context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// <copyright file="CabUnitTests.cs" company="DevAge, Vestris Inc. &amp; Contributors"> // Copyright (c) DevAge, Vestris Inc. &amp; Contributors. // </copyright> namespace dotNetInstallerUnitTests { using System; using System.IO; using dotNetUnitTestsRunner; using InstallerLib; using NUnit.Framework; [TestFixture] public class CabUnitTests { [Test] public void TestCabPathAutoDeleteFalse() { Console.WriteLine("TestCabPathAutoDeleteFalse"); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); setupConfiguration.cab_path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); setupConfiguration.cab_path_autodelete = false; Console.WriteLine("Creating '{0}'", setupConfiguration.cab_path); Directory.CreateDirectory(setupConfiguration.cab_path); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename)); File.Delete(configFilename); Assert.IsTrue(Directory.Exists(setupConfiguration.cab_path)); Directory.Delete(setupConfiguration.cab_path); } [Test] public void TestCabPathAutoDeleteTrue() { Console.WriteLine("TestCabPathAutoDeleteTrue"); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); setupConfiguration.cab_path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); setupConfiguration.cab_path_autodelete = true; Console.WriteLine("Creating '{0}'", setupConfiguration.cab_path); Directory.CreateDirectory(setupConfiguration.cab_path); File.WriteAllText(Path.Combine(setupConfiguration.cab_path, Guid.NewGuid().ToString()), Guid.NewGuid().ToString()); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename)); File.Delete(configFilename); Assert.IsFalse(Directory.Exists(setupConfiguration.cab_path)); } [Test] public void TestExtractCab() { Console.WriteLine("TestExtractCab"); // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.embedFiles = new string[] { Path.GetFileName(args.config) }; args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/ExtractCab")); // this should have created a directory called SupportFiles in the current directory string supportFilesPath = Path.Combine(Path.GetDirectoryName(args.output), "SupportFiles"); Console.WriteLine("Checking {0}", supportFilesPath); Assert.IsTrue(Directory.Exists(supportFilesPath), string.Format("Missing {0}", supportFilesPath)); File.Delete(args.config); File.Delete(args.output); Directory.Delete(supportFilesPath, true); } [Test] public void TestExtractCabPerComponent() { Console.WriteLine("TestExtractCabPerComponent"); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); ComponentCmd component = new ComponentCmd(); setupConfiguration.Children.Add(component); EmbedFile embedfile = new EmbedFile(); embedfile.sourcefilepath = args.config; embedfile.targetfilepath = Path.GetFileName(args.config); component.Children.Add(embedfile); configFile.SaveAs(args.config); Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/ExtractCab")); // this should have created a directory called SupportFiles in the current directory string supportFilesPath = Path.Combine(Path.GetDirectoryName(args.output), "SupportFiles"); Console.WriteLine("Checking {0}", supportFilesPath); Assert.IsTrue(Directory.Exists(supportFilesPath), string.Format("Missing {0}", supportFilesPath)); File.Delete(args.config); File.Delete(args.output); Directory.Delete(supportFilesPath, true); } [Test] public void TestExtractAndRunCabPerComponent() { Console.WriteLine("TestExtractAndRunCabPerComponent"); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); setupConfiguration.cab_path = Path.Combine(Path.GetTempPath(), "testExtractAndRunCabPerComponent"); setupConfiguration.cab_path_autodelete = false; configFile.Children.Add(setupConfiguration); ComponentCmd component = new ComponentCmd(); component.command = "cmd.exe /C copy \"#CABPATH\\component\\before.xml\" \"#CABPATH\\component\\after.xml\""; component.required_install = true; setupConfiguration.Children.Add(component); EmbedFile embedfile = new EmbedFile(); embedfile.sourcefilepath = args.config; embedfile.targetfilepath = @"component\before.xml"; component.Children.Add(embedfile); configFile.SaveAs(args.config); Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller string logfile = Path.Combine(Path.GetTempPath(), "testExtractAndRunCabPerComponent.log"); Console.WriteLine("Log: {0}", logfile); Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, string.Format("/qb /log /logfile \"{0}\"", logfile))); string extractedComponentPath = Path.Combine(setupConfiguration.cab_path, "component"); Console.WriteLine("Checking {0}", extractedComponentPath); Assert.IsTrue(Directory.Exists(extractedComponentPath), string.Format("Missing {0}", extractedComponentPath)); Assert.IsTrue(File.Exists(Path.Combine(Path.GetTempPath(), @"testExtractAndRunCabPerComponent\component\before.xml"))); Assert.IsTrue(File.Exists(Path.Combine(Path.GetTempPath(), @"testExtractAndRunCabPerComponent\component\after.xml"))); File.Delete(args.config); File.Delete(args.output); Directory.Delete(setupConfiguration.cab_path, true); File.Delete(logfile); } [Test] public void TestDisplayCab() { Console.WriteLine("TestDisplayCab"); // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); configFile.SaveAs(args.config); args.embed = true; args.apppath = Path.GetTempPath(); // args.embedFiles = new string[] { Path.GetFileName(args.config) }; args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/DisplayCab /qb")); File.Delete(args.config); File.Delete(args.output); } [Test] public void TestExtractCabTwoComponentsSameName() { Console.WriteLine("TestExtractCabTwoComponentsSameName"); InstallerLinkerArguments args = new InstallerLinkerArguments(); args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", args.config); args.embed = true; args.apppath = Path.GetTempPath(); args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe"); args.template = dotNetInstallerExeUtils.Executable; // create a self-extracting bootstrapper ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); configFile.Children.Add(setupConfiguration); for (int i = 0; i < 2; i++) { ComponentCmd component = new ComponentCmd(); component.id = "component"; setupConfiguration.Children.Add(component); EmbedFile embedfile = new EmbedFile(); embedfile.sourcefilepath = args.config; embedfile.targetfilepath = string.Format("component{0}\\file.xml", i); component.Children.Add(embedfile); } configFile.SaveAs(args.config); Console.WriteLine("Linking '{0}'", args.output); InstallerLinkerExeUtils.CreateInstaller(args); Assert.IsTrue(File.Exists(args.output)); // execute dotNetInstaller Assert.AreEqual(0, dotNetInstallerExeUtils.Run(args.output, "/ExtractCab")); // this should have created a directory called SupportFiles in the current directory string supportFilesPath = Path.Combine(Path.GetDirectoryName(args.output), "SupportFiles"); Console.WriteLine("Checking {0}", supportFilesPath); Assert.IsTrue(Directory.Exists(supportFilesPath), string.Format("Missing {0}", supportFilesPath)); Assert.IsTrue(Directory.Exists(supportFilesPath + @"\component0")); Assert.IsTrue(File.Exists(supportFilesPath + @"\component0\file.xml")); Assert.IsTrue(Directory.Exists(supportFilesPath + @"\component1")); Assert.IsTrue(File.Exists(supportFilesPath + @"\component1\file.xml")); File.Delete(args.config); File.Delete(args.output); Directory.Delete(supportFilesPath, true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Threading { // // Implementation of ThreadPoolBoundHandle that sits on top of the CLR's ThreadPool and Overlapped infrastructure // /// <summary> /// Represents an I/O handle that is bound to the system thread pool and enables low-level /// components to receive notifications for asynchronous I/O operations. /// </summary> public sealed partial class ThreadPoolBoundHandle : IDisposable { private readonly SafeHandle _handle; private bool _isDisposed; private ThreadPoolBoundHandle(SafeHandle handle) { _handle = handle; } /// <summary> /// Gets the bound operating system handle. /// </summary> /// <value> /// A <see cref="SafeHandle"/> object that holds the bound operating system handle. /// </value> public SafeHandle Handle { get { return _handle; } } /// <summary> /// Returns a <see cref="ThreadPoolBoundHandle"/> for the specific handle, /// which is bound to the system thread pool. /// </summary> /// <param name="handle"> /// A <see cref="SafeHandle"/> object that holds the operating system handle. The /// handle must have been opened for overlapped I/O on the unmanaged side. /// </param> /// <returns> /// <see cref="ThreadPoolBoundHandle"/> for <paramref name="handle"/>, which /// is bound to the system thread pool. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="handle"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="handle"/> has been disposed. /// <para> /// -or- /// </para> /// <paramref name="handle"/> does not refer to a valid I/O handle. /// <para> /// -or- /// </para> /// <paramref name="handle"/> refers to a handle that has not been opened /// for overlapped I/O. /// <para> /// -or- /// </para> /// <paramref name="handle"/> refers to a handle that has already been bound. /// </exception> /// <remarks> /// This method should be called once per handle. /// <para> /// -or- /// </para> /// <see cref="ThreadPoolBoundHandle"/> does not take ownership of <paramref name="handle"/>, /// it remains the responsibility of the caller to call <see cref="SafeHandle.Dispose"/>. /// </remarks> public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) { if (handle == null) throw new ArgumentNullException(nameof(handle)); if (handle.IsClosed || handle.IsInvalid) throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); try { // ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall // implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation. bool succeeded = ThreadPool.BindHandle(handle); Debug.Assert(succeeded); } catch (Exception ex) { // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR. // We do not let either of these leak and convert them to ArgumentException to // indicate that the specified handles are invalid. if (ex.HResult == System.HResults.E_HANDLE) // Bad handle throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle)); throw; } return new ThreadPoolBoundHandle(handle); } /// <summary> /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, specifying /// a delegate that is invoked when the asynchronous I/O operation is complete, a user-provided /// object providing context, and managed objects that serve as buffers. /// </summary> /// <param name="callback"> /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method /// invoked when the asynchronous I/O operation completes. /// </param> /// <param name="state"> /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> from other /// <see cref="NativeOverlapped"/> instances. Can be <see langword="null"/>. /// </param> /// <param name="pinData"> /// An object or array of objects representing the input or output buffer for the operation. Each /// object represents a buffer, for example an array of bytes. Can be <see langword="null"/>. /// </param> /// <returns> /// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure. /// </returns> /// <remarks> /// <para> /// The unmanaged pointer returned by this method can be passed to the operating system in /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in /// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called. /// </para> /// <para> /// The buffer or buffers specified in <paramref name="pinData"/> must be the same as those passed /// to the unmanaged operating system function that performs the asynchronous I/O. /// </para> /// <note> /// The buffers specified in <paramref name="pinData"/> are pinned for the duration of /// the I/O operation. /// </note> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="callback"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed. /// </exception> [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object state, object pinData) { if (callback == null) throw new ArgumentNullException(nameof(callback)); EnsureNotDisposed(); ThreadPoolBoundHandleOverlapped overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, preAllocated: null); overlapped._boundHandle = this; return overlapped._nativeOverlapped; } /// <summary> /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, using the callback, /// state, and buffers associated with the specified <see cref="PreAllocatedOverlapped"/> object. /// </summary> /// <param name="preAllocated"> /// A <see cref="PreAllocatedOverlapped"/> object from which to create the NativeOverlapped pointer. /// </param> /// <returns> /// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure. /// </returns> /// <remarks> /// <para> /// The unmanaged pointer returned by this method can be passed to the operating system in /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in /// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="preAllocated"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="preAllocated"/> is currently in use for another I/O operation. /// </exception> /// <exception cref="ObjectDisposedException"> /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed, or /// this method was called after <paramref name="preAllocated"/> was disposed. /// </exception> /// <seealso cref="PreAllocatedOverlapped"/> [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) { if (preAllocated == null) throw new ArgumentNullException(nameof(preAllocated)); EnsureNotDisposed(); preAllocated.AddRef(); try { ThreadPoolBoundHandleOverlapped overlapped = preAllocated._overlapped; if (overlapped._boundHandle != null) throw new ArgumentException(SR.Argument_PreAllocatedAlreadyAllocated, nameof(preAllocated)); overlapped._boundHandle = this; return overlapped._nativeOverlapped; } catch { preAllocated.Release(); throw; } } /// <summary> /// Frees the unmanaged memory associated with a <see cref="NativeOverlapped"/> structure /// allocated by the <see cref="AllocateNativeOverlapped"/> method. /// </summary> /// <param name="overlapped"> /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure to be freed. /// </param> /// <remarks> /// <note type="caution"> /// You must call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method exactly once /// on every <see cref="NativeOverlapped"/> unmanaged pointer allocated using the /// <see cref="AllocateNativeOverlapped"/> method. /// If you do not call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method, you will /// leak memory. If you call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method more /// than once on the same <see cref="NativeOverlapped"/> unmanaged pointer, memory will be corrupted. /// </note> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="overlapped"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed. /// </exception> [CLSCompliant(false)] public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { if (overlapped == null) throw new ArgumentNullException(nameof(overlapped)); // Note: we explicitly allow FreeNativeOverlapped calls after the ThreadPoolBoundHandle has been Disposed. ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped, this); if (wrapper._boundHandle != this) throw new ArgumentException(SR.Argument_NativeOverlappedWrongBoundHandle, nameof(overlapped)); if (wrapper._preAllocated != null) wrapper._preAllocated.Release(); else Overlapped.Free(overlapped); } /// <summary> /// Returns the user-provided object specified when the <see cref="NativeOverlapped"/> instance was /// allocated using the <see cref="AllocateNativeOverlapped(IOCompletionCallback, object, byte[])"/>. /// </summary> /// <param name="overlapped"> /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure from which to return the /// asscociated user-provided object. /// </param> /// <returns> /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> /// from other <see cref="NativeOverlapped"/> instances, otherwise, <see langword="null"/> if one was /// not specified when the instance was allocated using <see cref="AllocateNativeOverlapped"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="overlapped"/> is <see langword="null"/>. /// </exception> [CLSCompliant(false)] public unsafe static object GetNativeOverlappedState(NativeOverlapped* overlapped) { if (overlapped == null) throw new ArgumentNullException(nameof(overlapped)); ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped, null); Debug.Assert(wrapper._boundHandle != null); return wrapper._userState; } private static unsafe ThreadPoolBoundHandleOverlapped GetOverlappedWrapper(NativeOverlapped* overlapped, ThreadPoolBoundHandle expectedBoundHandle) { ThreadPoolBoundHandleOverlapped wrapper; try { wrapper = (ThreadPoolBoundHandleOverlapped)Overlapped.Unpack(overlapped); } catch (NullReferenceException ex) { throw new ArgumentException(SR.Argument_NativeOverlappedAlreadyFree, nameof(overlapped), ex); } return wrapper; } public void Dispose() { // .NET Native's version of ThreadPoolBoundHandle that wraps the Win32 ThreadPool holds onto // native resources so it needs to be disposable. To match the contract, we are also disposable. // We also implement a disposable state to mimic behavior between this implementation and // .NET Native's version (code written against us, will also work against .NET Native's version). _isDisposed = true; } private void EnsureNotDisposed() { if (_isDisposed) throw new ObjectDisposedException(GetType().ToString()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace App.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
//------------------------------------------------------------------------------- // <copyright file="MessageUnit.cs" company="MMS AG"> // Copyright (c) MMS AG, 2008-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus.Testing { using System; using System.Collections.Generic; using System.Threading.Tasks; using Dequeuing; using Pipeline; using Pipeline.Incoming; using Pipeline.Outgoing; public class MessageUnit : IBus { private readonly List<TransportMessage> outgoingTransport; private readonly List<TransportMessage> incomingTransport; private readonly List<LogicalMessage> incomingLogical; private readonly List<LogicalMessage> outgoingLogical; private readonly EndpointConfiguration configuration; private Bus unit; private MessageReceiverSimulator simulator; private Func<TransportMessage, Task> outgoing; public MessageUnit(EndpointConfiguration configuration) { this.configuration = configuration; this.outgoingTransport = new List<TransportMessage>(); this.incomingTransport = new List<TransportMessage>(); this.incomingLogical = new List<LogicalMessage>(); this.outgoingLogical = new List<LogicalMessage>(); } public Address Endpoint { get { return this.configuration.EndpointQueue; } } public List<TransportMessage> OutgoingTransport { get { return this.outgoingTransport; } } public List<TransportMessage> IncomingTransport { get { return this.incomingTransport; } } public List<LogicalMessage> IncomingLogical { get { return this.incomingLogical; } } public List<LogicalMessage> OutgoingLogical { get { return this.outgoingLogical; } } protected IHandlerRegistry Registry { get; set; } protected IMessageRouter Router { get; set; } public MessageUnit Use(HandlerRegistry registry) { this.Registry = registry; return this; } public MessageUnit Use(IMessageRouter router) { this.Router = router; return this; } public Task StartAsync() { this.simulator = new MessageReceiverSimulator(this.incomingTransport); IOutgoingPipelineFactory outgoingFactory = this.CreateOutgoingPipelineFactory(); IIncomingPipelineFactory incomingFactory = this.CreateIncomingPipelineFactory(); this.unit = this.CreateBus(this.simulator, outgoingFactory, incomingFactory); return this.unit.StartAsync(); } public Task StopAsync() { return this.unit.StopAsync(); } public void SetOutgoing(Func<TransportMessage, Task> outgoing) { this.outgoing = msg => { this.outgoingTransport.Add(msg); return outgoing(msg); }; } public Task SendLocal(object message) { return this.unit.SendLocal(message); } public Task HandOver(TransportMessage message) { return this.simulator.HandOver(message); } public Task Send(object message, SendOptions options = null) { return this.unit.Send(message, options); } public Task Publish(object message, PublishOptions options = null) { return this.unit.Publish(message, options); } protected virtual IIncomingPipelineFactory CreateIncomingPipelineFactory() { return new UnitIncomingPipelineFactory(this.Registry, this.IncomingLogical); } protected virtual IOutgoingPipelineFactory CreateOutgoingPipelineFactory() { return new UnitOutgoingPipelineFactory(this.outgoing, this.OutgoingLogical, this.Router); } protected virtual Bus CreateBus(IReceiveMessages receiver, IOutgoingPipelineFactory outgoingPipelineFactory, IIncomingPipelineFactory incomingPipelineFactory) { return new Bus(this.configuration, new DequeueStrategy(receiver), outgoingPipelineFactory, incomingPipelineFactory); } private class UnitOutgoingPipelineFactory : IOutgoingPipelineFactory { private readonly ICollection<LogicalMessage> outgoing; private readonly Func<TransportMessage, Task> onMessage; private readonly IMessageRouter router; public UnitOutgoingPipelineFactory(Func<TransportMessage, Task> onMessage, ICollection<LogicalMessage> outgoing, IMessageRouter router) { this.router = router; this.onMessage = onMessage; this.outgoing = outgoing; } public Task WarmupAsync() { return Task.FromResult(0); } public OutgoingPipeline Create() { var pipeline = new OutgoingPipeline(); var senderStep = new DispatchToTransportStep(new MessageSenderSimulator(this.onMessage), new MessagePublisherSimulator(this.onMessage)); pipeline.Logical .Register(new CreateTransportMessageStep()) .Register(new TraceOutgoingLogical(this.outgoing)); pipeline.Transport .Register(new SerializeMessageStep(new NewtonsoftJsonMessageSerializer())) .Register(new DetermineDestinationStep(this.router)) .Register(new EnrichTransportMessageWithDestinationAddress()) .Register(senderStep); return pipeline; } public Task CooldownAsync() { return Task.FromResult(0); } } private class UnitIncomingPipelineFactory : IIncomingPipelineFactory { private readonly IHandlerRegistry registry; private readonly ICollection<LogicalMessage> incoming; public UnitIncomingPipelineFactory(IHandlerRegistry registry, ICollection<LogicalMessage> incoming) { this.incoming = incoming; this.registry = registry; } public Task WarmupAsync() { return Task.FromResult(0); } public IncomingPipeline Create() { var pipeline = new IncomingPipeline(); pipeline.Transport .Register(new DeadLetterMessagesWhichCantBeDeserializedStep()) .Register(new DeserializeTransportMessageStep(new NewtonsoftJsonMessageSerializer())); pipeline.Logical .Register(new DeadLetterMessagesWhenRetryCountIsReachedStep()) .Register(new LoadMessageHandlersStep(this.registry)) .Register(new InvokeHandlerStep()) .Register(new TraceIncomingLogical(this.incoming)); return pipeline; } public Task CooldownAsync() { return Task.FromResult(0); } } private class MessageSenderSimulator : ISendMessages { private readonly Func<TransportMessage, Task> onMessage; public MessageSenderSimulator(Func<TransportMessage, Task> onMessage) { this.onMessage = onMessage; } public Task SendAsync(TransportMessage message, SendOptions options) { var brokeredMessage = message.ToBrokeredMessage(); var transportMessage = new TransportMessage(brokeredMessage); return this.onMessage(transportMessage); } } private class MessagePublisherSimulator : IPublishMessages { private readonly Func<TransportMessage, Task> onMessage; public MessagePublisherSimulator(Func<TransportMessage, Task> onMessage) { this.onMessage = onMessage; } public Task PublishAsync(TransportMessage message, PublishOptions options) { var brokeredMessage = message.ToBrokeredMessage(); var transportMessage = new TransportMessage(brokeredMessage); return this.onMessage(transportMessage); } } private class MessageReceiverSimulator : IReceiveMessages { private readonly ICollection<TransportMessage> collector; private Func<TransportMessage, Task> onMessage; public MessageReceiverSimulator(ICollection<TransportMessage> collector) { this.collector = collector; } public Task<AsyncClosable> StartAsync(EndpointConfiguration.ReadOnly configuration, Func<TransportMessage, Task> onMessage) { this.onMessage = onMessage; return Task.FromResult(new AsyncClosable(() => Task.FromResult(0))); } public Task HandOver(TransportMessage message) { this.collector.Add(message); return this.onMessage(message); } } private class TraceIncomingLogical : IIncomingLogicalStep { private readonly ICollection<LogicalMessage> collector; public TraceIncomingLogical(ICollection<LogicalMessage> collector) { this.collector = collector; } public Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next) { this.collector.Add(context.LogicalMessage); return next(); } } private class TraceOutgoingLogical : IOutgoingLogicalStep { private readonly ICollection<LogicalMessage> collector; public TraceOutgoingLogical(ICollection<LogicalMessage> collector) { this.collector = collector; } public Task Invoke(OutgoingLogicalContext context, Func<Task> next) { this.collector.Add(context.LogicalMessage); return next(); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for ProtectionContainersOperations. /// </summary> public static partial class ProtectionContainersOperationsExtensions { /// <summary> /// Gets details of the specific container registered to your Recovery /// Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Name of the fabric where the container belongs. /// </param> /// <param name='containerName'> /// Name of the container whose details need to be fetched. /// </param> public static ProtectionContainerResource Get(this IProtectionContainersOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectionContainersOperations)s).GetAsync(vaultName, resourceGroupName, fabricName, containerName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets details of the specific container registered to your Recovery /// Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Name of the fabric where the container belongs. /// </param> /// <param name='containerName'> /// Name of the container whose details need to be fetched. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ProtectionContainerResource> GetAsync(this IProtectionContainersOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the containers registered to Recovery Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static Microsoft.Rest.Azure.IPage<ProtectionContainerResource> List(this IProtectionContainersOperations operations, string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<BMSContainerQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<BMSContainerQueryObject>)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectionContainersOperations)s).ListAsync(vaultName, resourceGroupName, odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the containers registered to Recovery Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<ProtectionContainerResource>> ListAsync(this IProtectionContainersOperations operations, string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<BMSContainerQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<BMSContainerQueryObject>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(vaultName, resourceGroupName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Discovers all the containers in the subscription that can be backed up to /// Recovery Services Vault. This is an asynchronous operation. To know the /// status of the operation, call GetRefreshOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated the container. /// </param> public static void Refresh(this IProtectionContainersOperations operations, string vaultName, string resourceGroupName, string fabricName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectionContainersOperations)s).RefreshAsync(vaultName, resourceGroupName, fabricName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Discovers all the containers in the subscription that can be backed up to /// Recovery Services Vault. This is an asynchronous operation. To know the /// status of the operation, call GetRefreshOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated the container. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task RefreshAsync(this IProtectionContainersOperations operations, string vaultName, string resourceGroupName, string fabricName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.RefreshWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Unregisters the given container from your Recovery Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='identityName'> /// Name of the protection container to unregister. /// </param> public static void Unregister(this IProtectionContainersOperations operations, string resourceGroupName, string vaultName, string identityName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectionContainersOperations)s).UnregisterAsync(resourceGroupName, vaultName, identityName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unregisters the given container from your Recovery Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='identityName'> /// Name of the protection container to unregister. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task UnregisterAsync(this IProtectionContainersOperations operations, string resourceGroupName, string vaultName, string identityName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.UnregisterWithHttpMessagesAsync(resourceGroupName, vaultName, identityName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Lists the containers registered to Recovery Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<ProtectionContainerResource> ListNext(this IProtectionContainersOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectionContainersOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the containers registered to Recovery Services Vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<ProtectionContainerResource>> ListNextAsync(this IProtectionContainersOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.IO; namespace BizHawk.Emulation.DiscSystem { /// <summary> /// Indicates which part of a sector are needing to be synthesized. /// Sector synthesis may create too much data, but this is a hint as to what's needed /// TODO - add a flag indicating whether clearing has happened /// TODO - add output to the job indicating whether interleaving has happened. let the sector reader be responsible /// </summary> [Flags] enum ESectorSynthPart { /// <summary> /// The data sector header is required. There's no header for audio tracks/sectors. /// </summary> Header16 = 1, /// <summary> /// The main 2048 user data bytes are required /// </summary> User2048 = 2, /// <summary> /// The 276 bytes of error correction are required /// </summary> ECC276 = 4, /// <summary> /// The 12 bytes preceding the ECC section are required (usually EDC and zero but also userdata sometimes) /// </summary> EDC12 = 8, /// <summary> /// The entire possible 276+12=288 bytes of ECM data is required (ECC276|EDC12) /// </summary> ECM288Complete = (ECC276 | EDC12), /// <summary> /// An alias for ECM288Complete /// </summary> ECMAny = ECM288Complete, /// <summary> /// A mode2 userdata section is required: the main 2048 user bytes AND the ECC and EDC areas /// </summary> User2336 = (User2048 | ECM288Complete), /// <summary> /// The complete sector userdata (2352 bytes) is required /// </summary> UserComplete = 15, /// <summary> /// An alias for UserComplete /// </summary> UserAny = UserComplete, /// <summary> /// An alias for UserComplete /// </summary> User2352 = UserComplete, /// <summary> /// SubP is required /// </summary> SubchannelP = 16, /// <summary> /// SubQ is required /// </summary> SubchannelQ = 32, /// <summary> /// Subchannels R-W (all except for P and Q) /// </summary> Subchannel_RSTUVW = (64|128|256|512|1024|2048), /// <summary> /// Complete subcode is required /// </summary> SubcodeComplete = (SubchannelP | SubchannelQ | Subchannel_RSTUVW), /// <summary> /// Any of the subcode might be required (just another way of writing SubcodeComplete) /// </summary> SubcodeAny = SubcodeComplete, /// <summary> /// The subcode should be deinterleaved /// </summary> SubcodeDeinterleave = 4096, /// <summary> /// The 100% complete sector is required including 2352 bytes of userdata and 96 bytes of subcode /// </summary> Complete2448 = SubcodeComplete | User2352, } /// <summary> /// Basic unit of sector synthesis /// </summary> interface ISectorSynthJob2448 { /// <summary> /// Synthesizes a sctor with the given job parameters /// </summary> void Synth(SectorSynthJob job); } /// <summary> /// Not a proper job? maybe with additional flags, it could be /// </summary> class SectorSynthJob { public int LBA; public ESectorSynthPart Parts; public byte[] DestBuffer2448; public int DestOffset; public SectorSynthParams Params; public Disc Disc; } /// <summary> /// an ISectorSynthProvider that just returns a value from an array of pre-made sectors /// </summary> class ArraySectorSynthProvider : ISectorSynthProvider { public List<ISectorSynthJob2448> Sectors = new List<ISectorSynthJob2448>(); public int FirstLBA; public ISectorSynthJob2448 Get(int lba) { int index = lba - FirstLBA; if (index < 0) return null; if (index >= Sectors.Count) return null; return Sectors[index]; } } /// <summary> /// an ISectorSynthProvider that just returns a fixed synthesizer /// </summary> class SimpleSectorSynthProvider : ISectorSynthProvider { public ISectorSynthJob2448 SS; public ISectorSynthJob2448 Get(int lba) { return SS; } } /// <summary> /// Returns 'Patch' synth if the provided condition is met /// </summary> class ConditionalSectorSynthProvider : ISectorSynthProvider { Func<int,bool> Condition; ISectorSynthJob2448 Patch; ISectorSynthProvider Parent; public void Install(Disc disc, Func<int, bool> condition, ISectorSynthJob2448 patch) { Parent = disc.SynthProvider; disc.SynthProvider = this; Condition = condition; Patch = patch; } public ISectorSynthJob2448 Get(int lba) { if (Condition(lba)) return Patch; else return Parent.Get(lba); } } /// <summary> /// When creating a disc, this is set with a callback that can deliver an ISectorSynthJob2448 for the given LBA /// </summary> interface ISectorSynthProvider { /// <summary> /// Retrieves an ISectorSynthJob2448 for the given LBA /// </summary> ISectorSynthJob2448 Get(int lba); } /// <summary> /// Generic parameters for sector synthesis. /// To cut down on resource utilization, these can be stored in a disc and are tightly coupled to /// the SectorSynths that have been setup for it /// </summary> struct SectorSynthParams { //public long[] BlobOffsets; public MednaDisc MednaDisc; } class SS_PatchQ : ISectorSynthJob2448 { public ISectorSynthJob2448 Original; public byte[] Buffer_SubQ = new byte[12]; public void Synth(SectorSynthJob job) { Original.Synth(job); if ((job.Parts & ESectorSynthPart.SubchannelQ) == 0) return; //apply patched subQ for (int i = 0; i < 12; i++) job.DestBuffer2448[2352 + 12 + i] = Buffer_SubQ[i]; } } class SS_Leadout : ISectorSynthJob2448 { public int SessionNumber; public DiscMountPolicy Policy; public void Synth(SectorSynthJob job) { //be lazy, just generate the whole sector unconditionally //this is mostly based on mednafen's approach, which was probably finely tailored for PSX //heres the comments on the subject: // I'm not trusting that the "control" field for the TOC leadout entry will always be set properly, so | the control fields for the last track entry // and the leadout entry together before extracting the D2 bit. Audio track->data leadout is fairly benign though maybe noisy(especially if we ever implement // data scrambling properly), but data track->audio leadout could break things in an insidious manner for the more accurate drive emulation code). var ses = job.Disc.Structure.Sessions[SessionNumber]; int lba_relative = job.LBA - ses.LeadoutTrack.LBA; //data is zero int ts = lba_relative; int ats = job.LBA; const int ADR = 0x1; // Q channel data encodes position EControlQ control = ses.LeadoutTrack.Control; //ehhh? CDI? //if(toc.tracks[toc.last_track].valid) // control |= toc.tracks[toc.last_track].control & 0x4; //else if(toc.disc_type == DISC_TYPE_CD_I) // control |= 0x4; control |= (EControlQ)(((int)ses.LastInformationTrack.Control) & 4); SubchannelQ sq = new SubchannelQ(); sq.SetStatus(ADR, control); sq.q_tno.BCDValue = 0xAA; sq.q_index.BCDValue = 0x01; sq.Timestamp = ts; sq.AP_Timestamp = ats; sq.zero = 0; //finally, rely on a gap sector to do the heavy lifting to synthesize this CUE.CueTrackType TrackType = CUE.CueTrackType.Audio; if (ses.LeadoutTrack.IsData) { if (job.Disc.TOC.Session1Format == SessionFormat.Type20_CDXA || job.Disc.TOC.Session1Format == SessionFormat.Type10_CDI) TrackType = CUE.CueTrackType.Mode2_2352; else TrackType = CUE.CueTrackType.Mode1_2352; } CUE.SS_Gap ss_gap = new CUE.SS_Gap() { Policy = Policy, sq = sq, TrackType = TrackType, Pause = true //? }; ss_gap.Synth(job); } } }
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.Collections.Generic; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using System.Management.Automation.Remoting.Server; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// Handles all data structure handler communication with the client /// runspace pool /// </summary> internal class ServerRunspacePoolDataStructureHandler { #region Constructors /// <summary> /// Constructor which takes a server runspace pool driver and /// creates an associated ServerRunspacePoolDataStructureHandler /// </summary> /// <param name="driver"></param> /// <param name="transportManager"></param> internal ServerRunspacePoolDataStructureHandler(ServerRunspacePoolDriver driver, AbstractServerSessionTransportManager transportManager) { _clientRunspacePoolId = driver.InstanceId; _transportManager = transportManager; } #endregion Constructors #region Data Structure Handler Methods /// <summary> /// Send a message with application private data to the client /// </summary> /// <param name="applicationPrivateData">applicationPrivateData to send</param> /// <param name="serverCapability">server capability negotiated during initial exchange of remoting messages / session capabilities of client and server</param> internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability) { // make server's PSVersionTable available to the client using ApplicationPrivateData PSPrimitiveDictionary applicationPrivateDataWithVersionTable = PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData); // override the hardcoded version numbers with the stuff that was reported to the client during negotiation PSPrimitiveDictionary versionTable = (PSPrimitiveDictionary)applicationPrivateDataWithVersionTable[PSVersionInfo.PSVersionTableName]; versionTable[PSVersionInfo.PSRemotingProtocolVersionName] = serverCapability.ProtocolVersion; versionTable[PSVersionInfo.SerializationVersionName] = serverCapability.SerializationVersion; // Pass back the true PowerShell version to the client via application private data. versionTable[PSVersionInfo.PSVersionName] = PSVersionInfo.PSVersion; RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData( _clientRunspacePoolId, applicationPrivateDataWithVersionTable); SendDataAsync(data); } /// <summary> /// Send a message with the RunspacePoolStateInfo to the client /// </summary> /// <param name="stateInfo">state info to send</param> internal void SendStateInfoToClient(RunspacePoolStateInfo stateInfo) { RemoteDataObject data = RemotingEncoder.GenerateRunspacePoolStateInfo( _clientRunspacePoolId, stateInfo); SendDataAsync(data); } /// <summary> /// Send a message with the PSEventArgs to the client /// </summary> /// <param name="e">event to send</param> internal void SendPSEventArgsToClient(PSEventArgs e) { RemoteDataObject data = RemotingEncoder.GeneratePSEventArgs(_clientRunspacePoolId, e); SendDataAsync(data); } /// <summary> /// called when session is connected from a new client /// call into the sessionconnect handlers for each associated powershell dshandler /// </summary> internal void ProcessConnect() { List<ServerPowerShellDataStructureHandler> dsHandlers; lock (_associationSyncObject) { dsHandlers = new List<ServerPowerShellDataStructureHandler>(_associatedShells.Values); } foreach (var dsHandler in dsHandlers) { dsHandler.ProcessConnect(); } } /// <summary> /// Process the data received from the runspace pool on /// the server /// </summary> /// <param name="receivedData">data received</param> internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData) { if (receivedData == null) { throw PSTraceSource.NewArgumentNullException("receivedData"); } Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.RunspacePool, "RemotingTargetInterface must be Runspace"); switch (receivedData.DataType) { case RemotingDataType.CreatePowerShell: { Dbg.Assert(CreateAndInvokePowerShell != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); CreateAndInvokePowerShell.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData)); } break; case RemotingDataType.GetCommandMetadata: { Dbg.Assert(GetCommandMetadata != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); GetCommandMetadata.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData)); } break; case RemotingDataType.RemoteRunspaceHostResponseData: { Dbg.Assert(HostResponseReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data); //part of host message robustness algo. Now the host response is back, report to transport that // execution status is back to running _transportManager.ReportExecutionStatusAsRunning(); HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse)); } break; case RemotingDataType.SetMaxRunspaces: { Dbg.Assert(SetMaxRunspacesReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); SetMaxRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; case RemotingDataType.SetMinRunspaces: { Dbg.Assert(SetMinRunspacesReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); SetMinRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; case RemotingDataType.AvailableRunspaces: { Dbg.Assert(GetAvailableRunspacesReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); GetAvailableRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; case RemotingDataType.ResetRunspaceState: { Dbg.Assert(ResetRunspaceState != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events."); ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; } // switch... } /// <summary> /// Creates a powershell data structure handler from this runspace pool /// </summary> /// <param name="instanceId">powershell instance id</param> /// <param name="runspacePoolId">runspace pool id</param> /// <param name="remoteStreamOptions">remote stream options</param> /// <param name="localPowerShell">local PowerShell object</param> /// <returns>ServerPowerShellDataStructureHandler</returns> internal ServerPowerShellDataStructureHandler CreatePowerShellDataStructureHandler( Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, PowerShell localPowerShell) { // start with pool's transport manager. AbstractServerTransportManager cmdTransportManager = _transportManager; if (instanceId != Guid.Empty) { cmdTransportManager = _transportManager.GetCommandTransportManager(instanceId); Dbg.Assert(cmdTransportManager.TypeTable != null, "This should be already set in managed C++ code"); } ServerPowerShellDataStructureHandler dsHandler = new ServerPowerShellDataStructureHandler(instanceId, runspacePoolId, remoteStreamOptions, cmdTransportManager, localPowerShell); lock (_associationSyncObject) { _associatedShells.Add(dsHandler.PowerShellId, dsHandler); } dsHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); return dsHandler; } /// <summary> /// Returns the currently active PowerShell datastructure handler. /// </summary> /// <returns> /// ServerPowerShellDataStructureHandler if one is present, null otherwise. /// </returns> internal ServerPowerShellDataStructureHandler GetPowerShellDataStructureHandler() { lock (_associationSyncObject) { if (_associatedShells.Count > 0) { foreach (object o in _associatedShells.Values) { ServerPowerShellDataStructureHandler result = o as ServerPowerShellDataStructureHandler; if (result != null) { return result; } } } } return null; } /// <summary> /// dispatch the message to the associated powershell data structure handler /// </summary> /// <param name="rcvdData">message to dispatch</param> internal void DispatchMessageToPowerShell(RemoteDataObject<PSObject> rcvdData) { ServerPowerShellDataStructureHandler dsHandler = GetAssociatedPowerShellDataStructureHandler(rcvdData.PowerShellId); // if data structure handler is not found, then association has already been // removed, discard message if (dsHandler != null) { dsHandler.ProcessReceivedData(rcvdData); } } /// <summary> /// Send the specified response to the client. The client call will /// be blocked on the same /// </summary> /// <param name="callId">call id on the client</param> /// <param name="response">response to send</param> internal void SendResponseToClient(long callId, object response) { RemoteDataObject message = RemotingEncoder.GenerateRunspacePoolOperationResponse(_clientRunspacePoolId, response, callId); SendDataAsync(message); } /// <summary> /// TypeTable used for Serialization/Deserialization. /// </summary> internal TypeTable TypeTable { get { return _transportManager.TypeTable; } set { _transportManager.TypeTable = value; } } #endregion Data Structure Handler Methods #region Data Structure Handler events /// <summary> /// This event is raised whenever there is a request from the /// client to create a powershell on the server and invoke it /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> CreateAndInvokePowerShell; /// <summary> /// This event is raised whenever there is a request from the /// client to run command discovery pipeline /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> GetCommandMetadata; /// <summary> /// This event is raised when a host call response is received /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived; /// <summary> /// This event is raised when there is a request to modify the /// maximum runspaces in the runspace pool /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMaxRunspacesReceived; /// <summary> /// This event is raised when there is a request to modify the /// minimum runspaces in the runspace pool /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMinRunspacesReceived; /// <summary> /// This event is raised when there is a request to get the /// available runspaces in the runspace pool /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> GetAvailableRunspacesReceived; /// <summary> /// This event is raised when the client requests the runspace state /// to be reset. /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> ResetRunspaceState; #endregion Data Structure Handler events #region Private Methods /// <summary> /// Send the data specified as a RemoteDataObject asynchronously /// to the runspace pool on the remote session /// </summary> /// <param name="data">data to send</param> /// <remarks>This overload takes a RemoteDataObject and should /// be the one thats used to send data from within this /// data structure handler class</remarks> private void SendDataAsync(RemoteDataObject data) { Dbg.Assert(null != data, "Cannot send null object."); _transportManager.SendDataToClient(data, true); } /// <summary> /// Get the associated powershell data structure handler for the specified /// powershell id /// </summary> /// <param name="clientPowerShellId">powershell id for the /// powershell data structure handler</param> /// <returns>ServerPowerShellDataStructureHandler</returns> internal ServerPowerShellDataStructureHandler GetAssociatedPowerShellDataStructureHandler (Guid clientPowerShellId) { ServerPowerShellDataStructureHandler dsHandler = null; lock (_associationSyncObject) { bool success = _associatedShells.TryGetValue(clientPowerShellId, out dsHandler); if (!success) { dsHandler = null; } } return dsHandler; } /// <summary> /// Remove the association of the powershell from the runspace pool /// </summary> /// <param name="sender">sender of this event</param> /// <param name="e">unused</param> private void HandleRemoveAssociation(object sender, EventArgs e) { Dbg.Assert(sender is ServerPowerShellDataStructureHandler, @"sender of the event must be ServerPowerShellDataStructureHandler"); ServerPowerShellDataStructureHandler dsHandler = sender as ServerPowerShellDataStructureHandler; lock (_associationSyncObject) { _associatedShells.Remove(dsHandler.PowerShellId); } // let session transport manager remove its association of command transport manager. _transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId); } #endregion Private Methods #region Private Members private Guid _clientRunspacePoolId; // transport manager using which this // runspace pool driver handles all client // communication private AbstractServerSessionTransportManager _transportManager; private Dictionary<Guid, ServerPowerShellDataStructureHandler> _associatedShells = new Dictionary<Guid, ServerPowerShellDataStructureHandler>(); // powershell data structure handlers associated with this // runspace pool data structure handler private object _associationSyncObject = new object(); // object to synchronize operations to above #endregion Private Members } /// <summary> /// Handles all PowerShell data structure handler communication /// with the client side PowerShell /// </summary> internal class ServerPowerShellDataStructureHandler { #region Private Members // transport manager using which this // powershell driver handles all client // communication private AbstractServerTransportManager _transportManager; private Guid _clientRunspacePoolId; private Guid _clientPowerShellId; private RemoteStreamOptions _streamSerializationOptions; private Runspace _rsUsedToInvokePowerShell; #endregion Private Members #region Constructors /// <summary> /// Default constructor for creating ServerPowerShellDataStructureHandler /// instance /// </summary> /// <param name="instanceId">powershell instance id</param> /// <param name="runspacePoolId">runspace pool id</param> /// <param name="remoteStreamOptions">remote stream options</param> /// <param name="transportManager">transport manager</param> /// <param name="localPowerShell">local powershell object</param> internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, AbstractServerTransportManager transportManager, PowerShell localPowerShell) { _clientPowerShellId = instanceId; _clientRunspacePoolId = runspacePoolId; _transportManager = transportManager; _streamSerializationOptions = remoteStreamOptions; transportManager.Closing += HandleTransportClosing; if (localPowerShell != null) { localPowerShell.RunspaceAssigned += new EventHandler<PSEventArgs<Runspace>>(LocalPowerShell_RunspaceAssigned); } } private void LocalPowerShell_RunspaceAssigned(object sender, PSEventArgs<Runspace> e) { _rsUsedToInvokePowerShell = e.Args; } #endregion Constructors #region Data Structure Handler Methods /// <summary> /// Prepare transport manager to send data to client. /// </summary> internal void Prepare() { // When Guid.Empty is used, PowerShell must be using pool's transport manager // to send data to client. so we dont need to prepare command transport manager if (_clientPowerShellId != Guid.Empty) { _transportManager.Prepare(); } } /// <summary> /// Send the state information to the client /// </summary> /// <param name="stateInfo">state information to be /// sent to the client</param> internal void SendStateChangedInformationToClient(PSInvocationStateInfo stateInfo) { Dbg.Assert((stateInfo.State == PSInvocationState.Completed) || (stateInfo.State == PSInvocationState.Failed) || (stateInfo.State == PSInvocationState.Stopped), "SendStateChangedInformationToClient should be called to notify a termination state"); SendDataAsync(RemotingEncoder.GeneratePowerShellStateInfo( stateInfo, _clientPowerShellId, _clientRunspacePoolId)); // Close the transport manager only if the PowerShell Guid != Guid.Empty. // When Guid.Empty is used, PowerShell must be using pool's transport manager // to send data to client. if (_clientPowerShellId != Guid.Empty) { // no need to listen for closing events as we are initiating the close _transportManager.Closing -= HandleTransportClosing; // if terminal state is reached close the transport manager instead of letting // the client initiate the close. _transportManager.Close(null); } } /// <summary> /// Send the output data to the client /// </summary> /// <param name="data">data to send</param> internal void SendOutputDataToClient(PSObject data) { SendDataAsync(RemotingEncoder.GeneratePowerShellOutput(data, _clientPowerShellId, _clientRunspacePoolId)); } /// <summary> /// Send the error record to client /// </summary> /// <param name="errorRecord">error record to send</param> internal void SendErrorRecordToClient(ErrorRecord errorRecord) { errorRecord.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToErrorRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellError( errorRecord, _clientRunspacePoolId, _clientPowerShellId)); } /// <summary> /// Send the specified warning record to client /// </summary> /// <param name="record">warning record</param> internal void SendWarningRecordToClient(WarningRecord record) { record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToWarningRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellWarning)); } /// <summary> /// Send the specified debug record to client /// </summary> /// <param name="record">debug record</param> internal void SendDebugRecordToClient(DebugRecord record) { record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToDebugRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellDebug)); } /// <summary> /// Send the specified verbose record to client /// </summary> /// <param name="record">warning record</param> internal void SendVerboseRecordToClient(VerboseRecord record) { record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToVerboseRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellVerbose)); } /// <summary> /// Send the specified progress record to client /// </summary> /// <param name="record">progress record</param> internal void SendProgressRecordToClient(ProgressRecord record) { SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId)); } /// <summary> /// Send the specified information record to client /// </summary> /// <param name="record">information record</param> internal void SendInformationRecordToClient(InformationRecord record) { SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId)); } /// <summary> /// called when session is connected from a new client /// calls into observers of this event. /// observers include corresponding driver that shutdown /// input stream is present /// </summary> internal void ProcessConnect() { OnSessionConnected.SafeInvoke(this, EventArgs.Empty); } /// <summary> /// Process the data received from the powershell on /// the client /// </summary> /// <param name="receivedData">data received</param> internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData) { if (receivedData == null) { throw PSTraceSource.NewArgumentNullException("receivedData"); } Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.PowerShell, "RemotingTargetInterface must be PowerShell"); switch (receivedData.DataType) { case RemotingDataType.StopPowerShell: { Dbg.Assert(StopPowerShellReceived != null, "ServerPowerShellDriver should subscribe to all data structure handler events"); StopPowerShellReceived.SafeInvoke(this, EventArgs.Empty); } break; case RemotingDataType.PowerShellInput: { Dbg.Assert(InputReceived != null, "ServerPowerShellDriver should subscribe to all data structure handler events"); InputReceived.SafeInvoke(this, new RemoteDataEventArgs<object>(receivedData.Data)); } break; case RemotingDataType.PowerShellInputEnd: { Dbg.Assert(InputEndReceived != null, "ServerPowerShellDriver should subscribe to all data structure handler events"); InputEndReceived.SafeInvoke(this, EventArgs.Empty); } break; case RemotingDataType.RemotePowerShellHostResponseData: { Dbg.Assert(HostResponseReceived != null, "ServerPowerShellDriver should subscribe to all data structure handler events"); RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data); //part of host message robustness algo. Now the host response is back, report to transport that // execution status is back to running _transportManager.ReportExecutionStatusAsRunning(); HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse)); } break; } // switch ... } /// <summary> /// Raise a remove association event. This is raised /// when the powershell has gone into a terminal state /// and the runspace pool need not maintain any further /// associations /// </summary> internal void RaiseRemoveAssociationEvent() { Dbg.Assert(RemoveAssociation != null, @"The ServerRunspacePoolDataStructureHandler should subscribe to the RemoveAssociation event of ServerPowerShellDataStructureHandler"); RemoveAssociation.SafeInvoke(this, EventArgs.Empty); } /// <summary> /// Creates a ServerRemoteHost which is associated with this powershell. /// </summary> /// <param name="powerShellHostInfo">Host information about the host associated /// PowerShell object on the client.</param> /// <param name="runspaceServerRemoteHost">Host associated with the RunspacePool /// on the server.</param> /// <returns>A new ServerRemoteHost for the PowerShell.</returns> internal ServerRemoteHost GetHostAssociatedWithPowerShell( HostInfo powerShellHostInfo, ServerRemoteHost runspaceServerRemoteHost) { HostInfo hostInfo; // If host was null use the runspace's host for this powershell; otherwise, // use the HostInfo to create a proxy host of the powershell's host. if (powerShellHostInfo.UseRunspaceHost) { hostInfo = runspaceServerRemoteHost.HostInfo; } else { hostInfo = powerShellHostInfo; } // If the host was not null on the client, then the PowerShell object should // get a brand spanking new host. return new ServerRemoteHost(_clientRunspacePoolId, _clientPowerShellId, hostInfo, _transportManager, runspaceServerRemoteHost.Runspace, runspaceServerRemoteHost as ServerDriverRemoteHost); } #endregion Data Structure Handler Methods #region Data Structure Handler events /// <summary> /// this event is raised when the state of associated /// powershell is terminal and the runspace pool has /// to detach the association /// </summary> internal event EventHandler RemoveAssociation; /// <summary> /// this event is raised when the a message to stop the /// powershell is received from the client /// </summary> internal event EventHandler StopPowerShellReceived; /// <summary> /// This event is raised when an input object is received /// from the client /// </summary> internal event EventHandler<RemoteDataEventArgs<object>> InputReceived; /// <summary> /// This event is raised when end of input is received from /// the client /// </summary> internal event EventHandler InputEndReceived; /// <summary> /// raised when server session is connected from a new client /// </summary> internal event EventHandler OnSessionConnected; /// <summary> /// This event is raised when a host response is received /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived; #endregion Data Structure Handler events #region Internal Methods /// <summary> /// client powershell id /// </summary> internal Guid PowerShellId { get { return _clientPowerShellId; } } /// <summary> /// Runspace used to invoke PowerShell, this is used by the steppable /// pipeline driver. /// </summary> internal Runspace RunspaceUsedToInvokePowerShell { get { return _rsUsedToInvokePowerShell; } } #endregion Internal Methods #region Private Methods /// <summary> /// Send the data specified as a RemoteDataObject asynchronously /// to the runspace pool on the remote session /// </summary> /// <param name="data">data to send</param> /// <remarks>This overload takes a RemoteDataObject and should /// be the one thats used to send data from within this /// data structure handler class</remarks> private void SendDataAsync(RemoteDataObject data) { Dbg.Assert(null != data, "Cannot send null object."); // this is from a command execution..let transport manager collect // as much data as possible and send bigger buffer to client. _transportManager.SendDataToClient(data, false); } /// <summary> /// Handle transport manager's closing event. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void HandleTransportClosing(object sender, EventArgs args) { StopPowerShellReceived.SafeInvoke(this, args); } #endregion Private Methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using Xunit; using BitArrayTests.BitArray_BitArray_OperatorsTests; namespace BitArrayTests { public enum Operator { Xor, Or, And }; namespace BitArray_BitArray_OperatorsTests { public class BitArray_OperatorsTests { /// <summary> /// Test BitArray.And Operator /// </summary> [Fact] public static void BitArray_AndTest() { BitArray_Helper(Operator.And); // [] Test to make sure that 0 sized bit arrays can be And-ed BitArray b1 = new BitArray(0); BitArray b2 = new BitArray(0); b1.And(b2); } /// <summary> /// Test BitArray.Not Operator /// </summary> [Fact] public static void BitArray_NotTest() { // [] Standard cases BitArray ba2 = null; BitArray ba4 = null; ba2 = new BitArray(6, false); ba2.Set(0, true); ba2.Set(1, true); ba4 = ba2.Not(); for (int i = 0; i < ba4.Length; i++) { if (i <= 1) Assert.False(ba4.Get(i)); //"Err_2! ba4.Get(" + i + ") should be false" else Assert.True(ba4.Get(i)); //"Err_3! ba4.Get(" + i + ") should be true" } // [] Size stress cases. ba2 = new BitArray(0x1000F, false); ba2.Set(0, true); ba2.Set(1, true); ba2.Set(0x10000, true); ba2.Set(0x10001, true); ba4 = ba2.Not(); Assert.False(ba4.Get(1)); //"Err_4! ba4.Get(1) should be false" Assert.True(ba4.Get(2)); //"Err_5! ba4.Get(2) should be true" for (int i = 0x10000; i < ba2.Length; i++) { if (i <= 0x10001) Assert.False(ba4.Get(i)); //"Err_6! ba4.Get(" + i + ") should be false" else Assert.True(ba4.Get(i)); //"Err_7! ba4.Get(" + i + ") should be true" } } /// <summary> /// Test BitArray.Or Operator /// </summary> [Fact] public static void BitArray_OrTest() { BitArray_Helper(Operator.Or); } /// <summary> /// Test BitArray.Xor Operator /// </summary> [Fact] public static void BitArray_XorTest() { BitArray_Helper(Operator.Xor); } public static void BitArray_Helper(Operator op) { BitArray ba2 = null; BitArray ba3 = null; BitArray ba4 = null; // [] Standard cases (1,1) (1,0) (0,0). ba2 = new BitArray(6, false); ba3 = new BitArray(6, false); ba2.Set(0, true); ba2.Set(1, true); ba3.Set(1, true); ba3.Set(2, true); switch (op) { case Operator.Xor: ba4 = ba2.Xor(ba3); Assert.True(ba4.Get(0)); //"Err_8! Expected ba4.Get(0) to be true" Assert.False(ba4.Get(1)); //"Err_9! Expected ba4.Get(1) to be false" Assert.True(ba4.Get(2)); //"Err_10! Expected ba4.Get(2) to be true" Assert.False(ba4.Get(4)); //"Err_11! Expected ba4.Get(4) to be false" break; case Operator.And: ba4 = ba2.And(ba3); Assert.False(ba4.Get(0)); //"Err_12! Expected ba4.Get(0) to be false" Assert.True(ba4.Get(1)); //"Err_13! Expected ba4.Get(1) to be true" Assert.False(ba4.Get(2)); //"Err_14! Expected ba4.Get(2) to be false" Assert.False(ba4.Get(4)); //"Err_15! Expected ba4.Get(4) to be false" break; case Operator.Or: ba4 = ba2.Or(ba3); Assert.True(ba4.Get(0)); //"Err_16! Expected ba4.Get(0) to be true" Assert.True(ba4.Get(1)); //"Err_17! Expected ba4.Get(1) to be true" Assert.True(ba4.Get(2)); //"Err_18! Expected ba4.Get(2) to be true" Assert.False(ba4.Get(4)); //"Err_19! Expected ba4.Get(4) to be false" break; } // [] Size stress cases. ba2 = new BitArray(0x1000F, false); ba3 = new BitArray(0x1000F, false); ba2.Set(0x10000, true); // The bit for 1 (2^0). ba2.Set(0x10001, true); // The bit for 2 (2^1). ba3.Set(0x10001, true); // The bit for 2 (2^1). switch (op) { case Operator.Xor: ba4 = ba2.Xor(ba3); Assert.True(ba4.Get(0x10000)); //"Err_20! Expected ba4.Get(0x10000) to be true" Assert.False(ba4.Get(0x10001)); //"Err_21! Expected ba4.Get(0x10001) to be false" Assert.False(ba4.Get(0x10002)); //"Err_22! Expected ba4.Get(0x10002) to be false" Assert.False(ba4.Get(0x10004)); //"Err_23! Expected ba4.Get(0x10004) to be false" break; case Operator.And: ba4 = ba2.And(ba3); Assert.False(ba4.Get(0x10000)); //"Err_24! Expected ba4.Get(0x10000) to be false" Assert.True(ba4.Get(0x10001)); //"Err_25! Expected ba4.Get(0x10001) to be true" Assert.False(ba4.Get(0x10002)); //"Err_26! Expected ba4.Get(0x10002) to be false" Assert.False(ba4.Get(0x10004)); //"Err_27! Expected ba4.Get(0x10004) to be false" break; case Operator.Or: ba4 = ba2.Or(ba3); Assert.True(ba4.Get(0x10000)); //"Err_28! Expected ba4.Get(0x10000) to be true" Assert.True(ba4.Get(0x10001)); //"Err_29! Expected ba4.Get(0x10001) to be true" Assert.False(ba4.Get(0x10002)); //"Err_30! Expected ba4.Get(0x10002) to be false" Assert.False(ba4.Get(0x10004)); //"Err_31! Expected ba4.Get(0x10004) to be false" break; } } /// <summary> /// And negative test /// </summary> [Fact] public static void BitArray_AndTest_Negative() { // [] ArgumentException, length of arrays is different BitArray ba2 = new BitArray(11, false); BitArray ba3 = new BitArray(6, false); Assert.Throws<ArgumentException>(delegate { ba2.And(ba3); }); //"Err_32! wrong exception thrown." Assert.Throws<ArgumentException>(delegate { ba3.And(ba2); }); //"Err_33! wrong exception thrown." // [] ArgumentNullException, null. ba2 = new BitArray(6, false); ba3 = null; Assert.Throws<ArgumentNullException>(delegate { ba2.And(ba3); }); //"Err_34! wrong exception thrown." } /// <summary> /// Or negative test /// </summary> [Fact] public static void BitArray_OrTest_Negative() { // [] ArgumentException, length of arrays is different BitArray ba2 = new BitArray(11, false); BitArray ba3 = new BitArray(6, false); Assert.Throws<ArgumentException>(delegate { ba2.Or(ba3); }); //"Err_35! wrong exception thrown." // [] ArgumentNullException, null. ba2 = new BitArray(6, false); ba3 = null; Assert.Throws<ArgumentNullException>(delegate { ba2.Or(ba3); }); //"Err_36! wrong exception thrown." } /// <summary> /// Xor negative test /// </summary> [Fact] public static void BitArray_XorTest_Negative() { // [] ArgumentException, length of arrays is different BitArray ba2 = new BitArray(11, false); BitArray ba3 = new BitArray(6, false); Assert.Throws<ArgumentException>(delegate { ba2.Xor(ba3); }); //"Err_37! wrong exception thrown." // [] ArgumentNullException, null. ba2 = new BitArray(6, false); ba3 = null; Assert.Throws<ArgumentNullException>(delegate { ba2.Xor(ba3); }); //"Err_38! wrong exception thrown." } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; namespace System.Net.Http.Headers { public class RangeItemHeaderValue : ICloneable { private long? _from; private long? _to; public long? From { get { return _from; } } public long? To { get { return _to; } } public RangeItemHeaderValue(long? from, long? to) { if (!from.HasValue && !to.HasValue) { throw new ArgumentException("Invalid range. At least one of the two parameters must not be null."); } if (from.HasValue && (from.Value < 0)) { throw new ArgumentOutOfRangeException(nameof(from)); } if (to.HasValue && (to.Value < 0)) { throw new ArgumentOutOfRangeException(nameof(to)); } if (from.HasValue && to.HasValue && (from.Value > to.Value)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; } private RangeItemHeaderValue(RangeItemHeaderValue source) { Debug.Assert(source != null); _from = source._from; _to = source._to; } public override string ToString() { if (!_from.HasValue) { return "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo); } else if (!_to.HasValue) { return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-"; } return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo); } public override bool Equals(object obj) { RangeItemHeaderValue other = obj as RangeItemHeaderValue; if (other == null) { return false; } return ((_from == other._from) && (_to == other._to)); } public override int GetHashCode() { if (!_from.HasValue) { return _to.GetHashCode(); } else if (!_to.HasValue) { return _from.GetHashCode(); } return _from.GetHashCode() ^ _to.GetHashCode(); } // Returns the length of a range list. E.g. "1-2, 3-4, 5-6" adds 3 ranges to 'rangeCollection'. Note that empty // list segments are allowed, e.g. ",1-2, , 3-4,,". internal static int GetRangeItemListLength(string input, int startIndex, ICollection<RangeItemHeaderValue> rangeCollection) { Debug.Assert(rangeCollection != null); Debug.Assert(startIndex >= 0); if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length)) { return 0; } // Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,"). bool separatorFound = false; int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out separatorFound); // It's OK if we didn't find leading separator characters. Ignore 'separatorFound'. if (current == input.Length) { return 0; } RangeItemHeaderValue range = null; while (true) { int rangeLength = GetRangeItemLength(input, current, out range); if (rangeLength == 0) { return 0; } rangeCollection.Add(range); current = current + rangeLength; current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound); // If the string is not consumed, we must have a delimiter, otherwise the string is not a valid // range list. if ((current < input.Length) && !separatorFound) { return 0; } if (current == input.Length) { return current - startIndex; } } } internal static int GetRangeItemLength(string input, int startIndex, out RangeItemHeaderValue parsedValue) { Debug.Assert(startIndex >= 0); // This parser parses number ranges: e.g. '1-2', '1-', '-2'. parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespace. If not, we'll return 0. int current = startIndex; // Try parse the first value of a value pair. int fromStartIndex = current; int fromLength = HttpRuleParser.GetNumberLength(input, current, false); if (fromLength > HttpRuleParser.MaxInt64Digits) { return 0; } current = current + fromLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // After the first value, the '-' character must follow. if ((current == input.Length) || (input[current] != '-')) { // We need a '-' character otherwise this can't be a valid range. return 0; } current++; // skip the '-' character current = current + HttpRuleParser.GetWhitespaceLength(input, current); int toStartIndex = current; int toLength = 0; // If we didn't reach the end of the string, try parse the second value of the range. if (current < input.Length) { toLength = HttpRuleParser.GetNumberLength(input, current, false); if (toLength > HttpRuleParser.MaxInt64Digits) { return 0; } current = current + toLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); } if ((fromLength == 0) && (toLength == 0)) { return 0; // At least one value must be provided in order to be a valid range. } // Try convert first value to int64 long from = 0; if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from)) { return 0; } // Try convert second value to int64 long to = 0; if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to)) { return 0; } // 'from' must not be greater than 'to' if ((fromLength > 0) && (toLength > 0) && (from > to)) { return 0; } parsedValue = new RangeItemHeaderValue((fromLength == 0 ? (long?)null : (long?)from), (toLength == 0 ? (long?)null : (long?)to)); return current - startIndex; } object ICloneable.Clone() { return new RangeItemHeaderValue(this); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Management.Automation; using System.Net; using System.Net.Security; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using XenAPI; namespace Citrix.XenServer.Commands { [Cmdlet("Connect", "XenServer")] public class ConnectXenServerCommand : PSCmdlet { public ConnectXenServerCommand() { Port = 443; } #region Cmdlet Parameters [Parameter(ParameterSetName = "Url", Mandatory = true, Position = 0)] public string[] Url { get; set; } [Parameter(ParameterSetName = "ServerPort", Mandatory = true, Position = 0)] [Alias("svr")] public string[] Server { get; set; } [Parameter(ParameterSetName = "ServerPort")] public int Port { get; set; } [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [Alias("cred")] public PSCredential Creds { get; set; } [Parameter(Position = 1)] [Alias("user")] public string UserName { get; set; } [Parameter(Position = 2)] [Alias("pwd")] public string Password { get; set; } [Parameter] public string[] OpaqueRef { get; set; } [Parameter] public SwitchParameter PassThru { get; set; } [Parameter] public SwitchParameter NoWarnNewCertificates { get; set; } [Parameter] public SwitchParameter NoWarnCertificates { get; set; } [Parameter] public SwitchParameter SetDefaultSession { get; set; } [Parameter] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { if ((Url == null || Url.Length == 0) && (Server == null || Server.Length == 0)) { ThrowTerminatingError(new ErrorRecord( new Exception("You must provide a URL, Name or IP Address for the XenServer."), "", ErrorCategory.InvalidArgument, null)); } if (Creds == null && (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) && (OpaqueRef == null || OpaqueRef.Length == 0)) { Creds = Host.UI.PromptForCredential("XenServer Credential Request", "", string.IsNullOrEmpty(UserName) ? "root" : UserName, ""); if (Creds == null) { // Just bail out at this point, they've clicked cancel on the credentials pop up dialog ThrowTerminatingError(new ErrorRecord( new Exception("Credentials must be supplied when connecting to the XenServer."), "", ErrorCategory.InvalidArgument, null)); } } string connUser = ""; string connPassword = ""; if (OpaqueRef == null || OpaqueRef.Length == 0) { if (Creds == null) { connUser = UserName; connPassword = Password; SecureString secPwd = new SecureString(); foreach (char ch in connPassword) secPwd.AppendChar(ch); Creds = new PSCredential(UserName, secPwd); } else { connUser = Creds.UserName.StartsWith("\\") ? Creds.GetNetworkCredential().UserName : Creds.UserName; IntPtr ptrPassword = Marshal.SecureStringToBSTR(Creds.Password); connPassword = Marshal.PtrToStringBSTR(ptrPassword); Marshal.FreeBSTR(ptrPassword); } } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if (Url == null || Url.Length == 0) { Url = new string[Server.Length]; for (int i = 0; i < Server.Length; i++) Url[i] = CommonCmdletFunctions.GetUrl(Server[i], Port); } if (OpaqueRef == null) { OpaqueRef = new string[Url.Length]; } else { if (OpaqueRef.Length != Url.Length) ThrowTerminatingError(new ErrorRecord( new Exception("The number of opaque references provided should be the same as the number of xenservers."), "", ErrorCategory.InvalidArgument, null)); } Dictionary<string, Session> sessions = CommonCmdletFunctions.GetAllSessions(this); Dictionary<string, Session> newSessions = new Dictionary<string, Session>(); for (int i = 0; i < Url.Length; i++) { Session session; if (string.IsNullOrEmpty(OpaqueRef[i])) { session = new Session(Url[i]); var apiVersionString = XenAPI.Helper.APIVersionString(session.APIVersion); session.login_with_password(connUser, connPassword, apiVersionString, "XenServerPSModule/" + apiVersionString); } else { session = new Session(Url[i], OpaqueRef[i]); } session.Tag = Creds; session.opaque_ref = session.uuid; sessions[session.opaque_ref] = session; newSessions[session.opaque_ref] = session; if (i > 0) continue; //set the first of the specified connections as default if (SetDefaultSession) { WriteVerbose(string.Format("Setting connection {0} ({1}) as default.", session.Url, session.opaque_ref)); CommonCmdletFunctions.SetDefaultXenSession(this, session); } } CommonCmdletFunctions.SetAllSessions(this, sessions); if (PassThru) WriteObject(newSessions.Values, true); } #region Messages const string CERT_HAS_CHANGED_CAPTION = "Security Certificate Changed"; const string CERT_CHANGED = "The certificate fingerprint of the server you have connected to is:\n{0}\nBut was expected to be:\n{1}\n{2}\nDo you wish to continue?"; const string CERT_FOUND_CAPTION = "New Security Certificate"; const string CERT_FOUND = "The certificate fingerprint of the server you have connected to is :\n{0}\n{1}\nDo you wish to continue?"; const string CERT_TRUSTED = "The certificate on this server is trusted. It is recommended you re-issue this server's certificate."; const string CERT_NOT_TRUSTED = "The certificate on this server is not trusted."; #endregion private readonly object certificateValidationLock = new object(); private bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; lock(certificateValidationLock) { bool ignoreChanged = NoWarnCertificates || (bool)GetVariableValue("NoWarnCertificates", false); bool ignoreNew = ignoreChanged || NoWarnNewCertificates || (bool)GetVariableValue("NoWarnNewCertificates", false); HttpWebRequest webreq = (HttpWebRequest)sender; string hostname = webreq.Address.Host; string fingerprint = CommonCmdletFunctions.FingerprintPrettyString(certificate.GetCertHashString()); string trusted = VerifyInAllStores(new X509Certificate2(certificate)) ? CERT_TRUSTED : CERT_NOT_TRUSTED; var certificates = CommonCmdletFunctions.LoadCertificates(); bool ok; if (certificates.ContainsKey(hostname)) { string fingerprint_old = certificates[hostname]; if (fingerprint_old == fingerprint) return true; ok = Force || ignoreChanged || ShouldContinue(string.Format(CERT_CHANGED, fingerprint, fingerprint_old, trusted), CERT_HAS_CHANGED_CAPTION); } else { ok = Force || ignoreNew || ShouldContinue(string.Format(CERT_FOUND, fingerprint, trusted), CERT_FOUND_CAPTION); } if (ok) { certificates[hostname] = fingerprint; CommonCmdletFunctions.SaveCertificates(certificates); } return ok; } } private bool VerifyInAllStores(X509Certificate2 certificate2) { try { X509Chain chain = new X509Chain(true); return chain.Build(certificate2) || certificate2.Verify(); } catch (CryptographicException) { return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; /// <summary> /// System.Array.Sort(System.Array,System.Array,System.Int32,System.Int32,System.Collections.IComparer) /// </summary> public class ArrayIndexOf1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; retVal = NegTest8() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using default comparer "); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; int[] i1 = new int[6] { 24, 30, 28, 26, 32, 23 }; string[] s2 = new string[6]{"Jack", "Mary", "Mike", "Allin", "Peter", "Tom"}; int[] i2 = new int[6] { 24, 30, 28, 23, 26, 32 }; Array.Sort(s1, i1, 3, 3, null); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("002", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using comparer "); try { int length = TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetInt32(-55); i1[i] = value; i2[i] = value; } IComparer a1 = new A(); int startIdx = GetInt(0, length - 1); int endIdx = GetInt(startIdx, length - 1); int count = endIdx - startIdx; Array.Sort(i1, i2, startIdx, count, a1); for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("004", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer "); try { char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }; char[] d1 = new char[10] { 'a', 'e', 'd', 'c', 'b', 'f', 'g', 'h', 'i', 'j' }; int[] a1 = new int[10] { 2, 3, 4, 1, 0, 2, 12, 52, 31, 0 }; int[] b1 = new int[10] { 2, 0, 1, 4, 3, 2, 12, 52, 31, 0 }; IComparer b = new B(); Array.Sort(c1, a1, 1, 4, b); for (int i = 0; i < 10; i++) { if (c1[i] != d1[i]) { TestLibrary.TestFramework.LogError("006", "The result is not the value as expected"); retVal = false; } if (a1[i] != b1[i]) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Sort an int array and the items array is null "); try { int length = (int) TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetByte(-55); i1[i] = value; i2[i] = value; } int startIdx = GetInt(0, length - 2); int endIdx = GetInt(startIdx, length - 1); int count = endIdx - startIdx + 1; for (int i = startIdx; i < endIdx; i++) //manually quich sort { for (int j = i + 1; j <= endIdx; j++) { if (i2[i] > i2[j]) { int temp = i2[i]; i2[i] = i2[j]; i2[j] = temp; } } } Array.Sort(i1, null, startIdx, count, new A()); for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The first argument is null reference "); try { string[] s1 = null; int[] i1 = { 1, 2, 3, 4, 5 }; Array.Sort(s1, i1, 0, 2, null); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The keys array is not one dimension "); try { int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } }; int[] i2 = { 1, 2, 3, 4, 5 }; Array.Sort(i1, i2, 0, 3, null); TestLibrary.TestFramework.LogError("103", "The RankException is not throw as expected "); retVal = false; } catch (RankException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: The items array is not one dimension "); try { int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } }; int[] i2 = { 1, 2, 3, 4, 5 }; Array.Sort(i2, i1, 0, 2, null); TestLibrary.TestFramework.LogError("105", "The RankException is not throw as expected "); retVal = false; } catch (RankException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4:The length of items array is not equal to the length of keys array "); try { int length_array = TestLibrary.Generator.GetInt16(-55); int length_value = TestLibrary.Generator.GetByte(-55); string[] s1 = new string[length_array]; int[] i1 = new int[length_value]; for (int i = 0; i < length_array; i++) { string value = TestLibrary.Generator.GetString(-55, false, 0, 10); s1[i] = value; } for (int i = 0; i < length_value; i++) { int value = TestLibrary.Generator.GetInt32(-55); i1[i] = value; } int startIdx = GetInt(0, 255); int count = GetInt(256, length_array - 1); Array.Sort(s1, i1, startIdx, count, null); TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected "); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: The Icomparer is null and keys array does not implement the IComparer interface "); try { D d1 = new D(); D d2 = new D(); D d3 = new D(); D d4 = new D(); int[] i2 = { 1, 2, 3, 4 }; D[] d = new D[4] { d1, d2, d3, d4 }; Array.Sort(d, i2, 1, 3, null); TestLibrary.TestFramework.LogError("109", "The InvalidOperationException is not throw as expected "); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: The start index is less than the minimal bound of the array"); try { string[] s1 = new string[6]{"Jack", "Mary", "Peter", "Mike", "Tom", "Allin"}; int[] i1 = new int[6] { 24, 30, 28, 26, 32, 44 }; Array.Sort(s1, i1, -1, 4, null); TestLibrary.TestFramework.LogError("111", "The ArgumentOutOfRangeException is not throw as expected "); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest7: The length is less than zero"); try { string[] s1 = new string[6]{"Jack", "Mary", "Peter", "Mike", "Tom", "Allin"}; int[] i1 = new int[6] { 24, 30, 28, 26, 32, 44 }; Array.Sort(s1, i1, 3, -1, null); TestLibrary.TestFramework.LogError("111", "The ArgumentOutOfRangeException is not throw as expected "); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest8:The start index is greater than the max bound of the array"); try { int length = TestLibrary.Generator.GetInt16(-55); string[] s1 = new string[length]; int[] i1 = new int[length]; for (int i = 0; i < length; i++) { string value1 = TestLibrary.Generator.GetString(-55, false, 0, 10); int value2 = TestLibrary.Generator.GetInt32(-55); s1[i] = value1; i1[i] = value2; } Array.Sort(s1, i1, length + 1, 0, null); TestLibrary.TestFramework.LogError("113", "The ArgumentException is not throw as expected "); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("114", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayIndexOf1 test = new ArrayIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } class A : IComparer { #region IComparer Members public int Compare(object x, object y) { return ((int)x).CompareTo((int)y); } #endregion } class B : IComparer { #region IComparer Members public int Compare(object x, object y) { if (((char)x).CompareTo((char)y) > 0) return -1; else { if (x == y) { return 0; } else { return 1; } } } #endregion } class C : IComparer { protected int c_value; public C(int a) { this.c_value = a; } #region IComparer Members public int Compare(object x, object y) { return (x as C).c_value.CompareTo((y as C).c_value); } #endregion } class D : IComparer { #region IComparer Members public int Compare(object x, object y) { return 0; } #endregion } #region Help method for geting test data private Int32 GetInt(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
// Licensed to the .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.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Rules for the Hebrew calendar: // - The Hebrew calendar is both a Lunar (months) and Solar (years) // calendar, but allows for a week of seven days. // - Days begin at sunset. // - Leap Years occur in the 3, 6, 8, 11, 14, 17, & 19th years of a // 19-year cycle. Year = leap iff ((7y+1) mod 19 < 7). // - There are 12 months in a common year and 13 months in a leap year. // - In a common year, the 6th month, Adar, has 29 days. In a leap // year, the 6th month, Adar I, has 30 days and the leap month, // Adar II, has 29 days. // - Common years have 353-355 days. Leap years have 383-385 days. // - The Hebrew new year (Rosh HaShanah) begins on the 1st of Tishri, // the 7th month in the list below. // - The new year may not begin on Sunday, Wednesday, or Friday. // - If the new year would fall on a Tuesday and the conjunction of // the following year were at midday or later, the new year is // delayed until Thursday. // - If the new year would fall on a Monday after a leap year, the // new year is delayed until Tuesday. // - The length of the 8th and 9th months vary from year to year, // depending on the overall length of the year. // - The length of a year is determined by the dates of the new // years (Tishri 1) preceding and following the year in question. // - The 2th month is long (30 days) if the year has 355 or 385 days. // - The 3th month is short (29 days) if the year has 353 or 383 days. // - The Hebrew months are: // 1. Tishri (30 days) // 2. Heshvan (29 or 30 days) // 3. Kislev (29 or 30 days) // 4. Teveth (29 days) // 5. Shevat (30 days) // 6. Adar I (30 days) // 7. Adar {II} (29 days, this only exists if that year is a leap year) // 8. Nisan (30 days) // 9. Iyyar (29 days) // 10. Sivan (30 days) // 11. Tammuz (29 days) // 12. Av (30 days) // 13. Elul (29 days) // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1583/01/01 2239/09/29 ** Hebrew 5343/04/07 5999/13/29 */ // Includes CHebrew implemetation;i.e All the code necessary for converting // Gregorian to Hebrew Lunar from 1583 to 2239. [System.Runtime.InteropServices.ComVisible(true)] public class HebrewCalendar : Calendar { public static readonly int HebrewEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; internal const int DatePartDayOfWeek = 4; // // Hebrew Translation Table. // // This table is used to get the following Hebrew calendar information for a // given Gregorian year: // 1. The day of the Hebrew month corresponding to Gregorian January 1st // for a given Gregorian year. // 2. The month of the Hebrew month corresponding to Gregorian January 1st // for a given Gregorian year. // The information is not directly in the table. Instead, the info is decoded // by special values (numbers above 29 and below 1). // 3. The type of the Hebrew year for a given Gregorian year. // /* More notes: This table includes 2 numbers for each year. The offset into the table determines the year. (offset 0 is Gregorian year 1500) 1st number determines the day of the Hebrew month coresponeds to January 1st. 2nd number determines the type of the Hebrew year. (the type determines how many days are there in the year.) normal years : 1 = 353 days 2 = 354 days 3 = 355 days. Leap years : 4 = 383 5 384 6 = 385 days. A 99 means the year is not supported for translation. for convenience the table was defined for 750 year, but only 640 years are supported. (from 1583 to 2239) the years before 1582 (starting of Georgian calander) and after 2239, are filled with 99. Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. That's why, there no nead to specify the lunar month in the table. There are exceptions, these are coded by giving numbers above 29 and below 1. Actual decoding is takenig place whenever fetching information from the table. The function for decoding is in GetLunarMonthDay(). Example: The data for 2000 - 2005 A.D. is: 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004 For year 2000, we know it has a Hebrew year type 6, which means it has 385 days. And 1/1/2000 A.D. is Hebrew year 5760, 23rd day of 4th month. */ // // Jewish Era in use today is dated from the supposed year of the // Creation with its beginning in 3761 B.C. // // The Hebrew year of Gregorian 1st year AD. // 0001/01/01 AD is Hebrew 3760/01/01 private const int HebrewYearOf1AD = 3760; // The first Gregorian year in HebrewTable. private const int FirstGregorianTableYear = 1583; // == Hebrew Year 5343 // The last Gregorian year in HebrewTable. private const int LastGregorianTableYear = 2239; // == Hebrew Year 5999 private const int TABLESIZE = (LastGregorianTableYear - FirstGregorianTableYear); private const int MinHebrewYear = HebrewYearOf1AD + FirstGregorianTableYear; // == 5343 private const int MaxHebrewYear = HebrewYearOf1AD + LastGregorianTableYear; // == 5999 private static readonly byte[] s_hebrewTable = { 7,3,17,3, // 1583-1584 (Hebrew year: 5343 - 5344) 0,4,11,2,21,6,1,3,13,2, // 1585-1589 25,4,5,3,16,2,27,6,9,1, // 1590-1594 20,2,0,6,11,3,23,4,4,2, // 1595-1599 14,3,27,4,8,2,18,3,28,6, // 1600 11,1,22,5,2,3,12,3,25,4, // 1605 6,2,16,3,26,6,8,2,20,1, // 1610 0,6,11,2,24,4,4,3,15,2, // 1615 25,6,8,1,19,2,29,6,9,3, // 1620 22,4,3,2,13,3,25,4,6,3, // 1625 17,2,27,6,7,3,19,2,31,4, // 1630 11,3,23,4,5,2,15,3,25,6, // 1635 6,2,19,1,29,6,10,2,22,4, // 1640 3,3,14,2,24,6,6,1,17,3, // 1645 28,5,8,3,20,1,32,5,12,3, // 1650 22,6,4,1,16,2,26,6,6,3, // 1655 17,2,0,4,10,3,22,4,3,2, // 1660 14,3,24,6,5,2,17,1,28,6, // 1665 9,2,19,3,31,4,13,2,23,6, // 1670 3,3,15,1,27,5,7,3,17,3, // 1675 29,4,11,2,21,6,3,1,14,2, // 1680 25,6,5,3,16,2,28,4,9,3, // 1685 20,2,0,6,12,1,23,6,4,2, // 1690 14,3,26,4,8,2,18,3,0,4, // 1695 10,3,21,5,1,3,13,1,24,5, // 1700 5,3,15,3,27,4,8,2,19,3, // 1705 29,6,10,2,22,4,3,3,14,2, // 1710 26,4,6,3,18,2,28,6,10,1, // 1715 20,6,2,2,12,3,24,4,5,2, // 1720 16,3,28,4,8,3,19,2,0,6, // 1725 12,1,23,5,3,3,14,3,26,4, // 1730 7,2,17,3,28,6,9,2,21,4, // 1735 1,3,13,2,25,4,5,3,16,2, // 1740 27,6,9,1,19,3,0,5,11,3, // 1745 23,4,4,2,14,3,25,6,7,1, // 1750 18,2,28,6,9,3,21,4,2,2, // 1755 12,3,25,4,6,2,16,3,26,6, // 1760 8,2,20,1,0,6,11,2,22,6, // 1765 4,1,15,2,25,6,6,3,18,1, // 1770 29,5,9,3,22,4,2,3,13,2, // 1775 23,6,4,3,15,2,27,4,7,3, // 1780 19,2,31,4,11,3,21,6,3,2, // 1785 15,1,25,6,6,2,17,3,29,4, // 1790 10,2,20,6,3,1,13,3,24,5, // 1795 4,3,16,1,27,5,7,3,17,3, // 1800 0,4,11,2,21,6,1,3,13,2, // 1805 25,4,5,3,16,2,29,4,9,3, // 1810 19,6,30,2,13,1,23,6,4,2, // 1815 14,3,27,4,8,2,18,3,0,4, // 1820 11,3,22,5,2,3,14,1,26,5, // 1825 6,3,16,3,28,4,10,2,20,6, // 1830 30,3,11,2,24,4,4,3,15,2, // 1835 25,6,8,1,19,2,29,6,9,3, // 1840 22,4,3,2,13,3,25,4,7,2, // 1845 17,3,27,6,9,1,21,5,1,3, // 1850 11,3,23,4,5,2,15,3,25,6, // 1855 6,2,19,1,29,6,10,2,22,4, // 1860 3,3,14,2,24,6,6,1,18,2, // 1865 28,6,8,3,20,4,2,2,12,3, // 1870 24,4,4,3,16,2,26,6,6,3, // 1875 17,2,0,4,10,3,22,4,3,2, // 1880 14,3,24,6,5,2,17,1,28,6, // 1885 9,2,21,4,1,3,13,2,23,6, // 1890 5,1,15,3,27,5,7,3,19,1, // 1895 0,5,10,3,22,4,2,3,13,2, // 1900 24,6,4,3,15,2,27,4,8,3, // 1905 20,4,1,2,11,3,22,6,3,2, // 1910 15,1,25,6,7,2,17,3,29,4, // 1915 10,2,21,6,1,3,13,1,24,5, // 1920 5,3,15,3,27,4,8,2,19,6, // 1925 1,1,12,2,22,6,3,3,14,2, // 1930 26,4,6,3,18,2,28,6,10,1, // 1935 20,6,2,2,12,3,24,4,5,2, // 1940 16,3,28,4,9,2,19,6,30,3, // 1945 12,1,23,5,3,3,14,3,26,4, // 1950 7,2,17,3,28,6,9,2,21,4, // 1955 1,3,13,2,25,4,5,3,16,2, // 1960 27,6,9,1,19,6,30,2,11,3, // 1965 23,4,4,2,14,3,27,4,7,3, // 1970 18,2,28,6,11,1,22,5,2,3, // 1975 12,3,25,4,6,2,16,3,26,6, // 1980 8,2,20,4,30,3,11,2,24,4, // 1985 4,3,15,2,25,6,8,1,18,3, // 1990 29,5,9,3,22,4,3,2,13,3, // 1995 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004 20,4,1,2,11,3,23,4,5,2, // 2005 - 2009 15,3,25,6,6,2,19,1,29,6, // 2010 10,2,20,6,3,1,14,2,24,6, // 2015 4,3,17,1,28,5,8,3,20,4, // 2020 1,3,12,2,22,6,2,3,14,2, // 2025 26,4,6,3,17,2,0,4,10,3, // 2030 20,6,1,2,14,1,24,6,5,2, // 2035 15,3,28,4,9,2,19,6,1,1, // 2040 12,3,23,5,3,3,15,1,27,5, // 2045 7,3,17,3,29,4,11,2,21,6, // 2050 1,3,12,2,25,4,5,3,16,2, // 2055 28,4,9,3,19,6,30,2,12,1, // 2060 23,6,4,2,14,3,26,4,8,2, // 2065 18,3,0,4,10,3,22,5,2,3, // 2070 14,1,25,5,6,3,16,3,28,4, // 2075 9,2,20,6,30,3,11,2,23,4, // 2080 4,3,15,2,27,4,7,3,19,2, // 2085 29,6,11,1,21,6,3,2,13,3, // 2090 25,4,6,2,17,3,27,6,9,1, // 2095 20,5,30,3,10,3,22,4,3,2, // 2100 14,3,24,6,5,2,17,1,28,6, // 2105 9,2,21,4,1,3,13,2,23,6, // 2110 5,1,16,2,27,6,7,3,19,4, // 2115 30,2,11,3,23,4,3,3,14,2, // 2120 25,6,5,3,16,2,28,4,9,3, // 2125 21,4,2,2,12,3,23,6,4,2, // 2130 16,1,26,6,8,2,20,4,30,3, // 2135 11,2,22,6,4,1,14,3,25,5, // 2140 6,3,18,1,29,5,9,3,22,4, // 2145 2,3,13,2,23,6,4,3,15,2, // 2150 27,4,7,3,20,4,1,2,11,3, // 2155 21,6,3,2,15,1,25,6,6,2, // 2160 17,3,29,4,10,2,20,6,3,1, // 2165 13,3,24,5,4,3,17,1,28,5, // 2170 8,3,18,6,1,1,12,2,22,6, // 2175 2,3,14,2,26,4,6,3,17,2, // 2180 28,6,10,1,20,6,1,2,12,3, // 2185 24,4,5,2,15,3,28,4,9,2, // 2190 19,6,33,3,12,1,23,5,3,3, // 2195 13,3,25,4,6,2,16,3,26,6, // 2200 8,2,20,4,30,3,11,2,24,4, // 2205 4,3,15,2,25,6,8,1,18,6, // 2210 33,2,9,3,22,4,3,2,13,3, // 2215 25,4,6,3,17,2,27,6,9,1, // 2220 21,5,1,3,11,3,23,4,5,2, // 2225 15,3,25,6,6,2,19,4,33,3, // 2230 10,2,22,4,3,3,14,2,24,6, // 2235 6,1 // 2240 (Hebrew year: 6000) }; private const int MaxMonthPlusOne = 14; // // The lunar calendar has 6 different variations of month lengths // within a year. // private static readonly byte[] s_lunarMonthLen = { 0,00,00,00,00,00,00,00,00,00,00,00,00,0, 0,30,29,29,29,30,29,30,29,30,29,30,29,0, // 3 common year variations 0,30,29,30,29,30,29,30,29,30,29,30,29,0, 0,30,30,30,29,30,29,30,29,30,29,30,29,0, 0,30,29,29,29,30,30,29,30,29,30,29,30,29, // 3 leap year variations 0,30,29,30,29,30,30,29,30,29,30,29,30,29, 0,30,30,30,29,30,30,29,30,29,30,29,30,29 }; //internal static Calendar m_defaultInstance; internal static readonly DateTime calendarMinValue = new DateTime(1583, 1, 1); // Gregorian 2239/9/29 = Hebrew 5999/13/29 (last day in Hebrew year 5999). // We can only format/parse Hebrew numbers up to 999, so we limit the max range to Hebrew year 5999. internal static readonly DateTime calendarMaxValue = new DateTime((new DateTime(2239, 9, 29, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } public override DateTime MaxSupportedDateTime { get { return (calendarMaxValue); } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of HebrewCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ /* internal static Calendar GetDefaultInstance() { if (m_defaultInstance == null) { m_defaultInstance = new HebrewCalendar(); } return (m_defaultInstance); } */ // Construct an instance of gregorian calendar. public HebrewCalendar() { } internal override CalendarId ID { get { return (CalendarId.HEBREW); } } /*=================================CheckHebrewYearValue========================== **Action: Check if the Hebrew year value is supported in this class. **Returns: None. **Arguments: y Hebrew year value ** ear Hebrew era value **Exceptions: ArgumentOutOfRange_Range if the year value is not supported. **Note: ** We use a table for the Hebrew calendar calculation, so the year supported is limited. ============================================================================*/ static private void CheckHebrewYearValue(int y, int era, String varName) { CheckEraRange(era); if (y > MaxHebrewYear || y < MinHebrewYear) { throw new ArgumentOutOfRangeException( varName, String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear)); } } /*=================================CheckHebrewMonthValue========================== **Action: Check if the Hebrew month value is valid. **Returns: None. **Arguments: year Hebrew year value ** month Hebrew month value **Exceptions: ArgumentOutOfRange_Range if the month value is not valid. **Note: ** Call CheckHebrewYearValue() before calling this to verify the year value is supported. ============================================================================*/ private void CheckHebrewMonthValue(int year, int month, int era) { int monthsInYear = GetMonthsInYear(year, era); if (month < 1 || month > monthsInYear) { throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, monthsInYear)); } } /*=================================CheckHebrewDayValue========================== **Action: Check if the Hebrew day value is valid. **Returns: None. **Arguments: year Hebrew year value ** month Hebrew month value ** day Hebrew day value. **Exceptions: ArgumentOutOfRange_Range if the day value is not valid. **Note: ** Call CheckHebrewYearValue()/CheckHebrewMonthValue() before calling this to verify the year/month values are valid. ============================================================================*/ private void CheckHebrewDayValue(int year, int month, int day, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, daysInMonth)); } } static internal void CheckEraRange(int era) { if (era != CurrentEra && era != HebrewEra) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } } static private void CheckTicksRange(long ticks) { if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks) { throw new ArgumentOutOfRangeException( "time", // Print out the date in Gregorian using InvariantCulture since the DateTime is based on GreograinCalendar. String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, calendarMinValue, calendarMaxValue)); } } static internal int GetResult(__DateBuffer result, int part) { switch (part) { case DatePartYear: return (result.year); case DatePartMonth: return (result.month); case DatePartDay: return (result.day); } throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } /*=================================GetLunarMonthDay========================== **Action: Using the Hebrew table (HebrewTable) to get the Hebrew month/day value for Gregorian January 1st ** in a given Gregorian year. ** Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. ** That's why, there no nead to specify the lunar month in the table. There are exceptions, and these ** are coded by giving numbers above 29 and below 1. ** Actual decoding is takenig place in the switch statement below. **Returns: ** The Hebrew year type. The value is from 1 to 6. ** normal years : 1 = 353 days 2 = 354 days 3 = 355 days. ** Leap years : 4 = 383 5 384 6 = 385 days. **Arguments: ** gregorianYear The year value in Gregorian calendar. The value should be between 1500 and 2239. ** lunarDate Object to take the result of the Hebrew year/month/day. **Exceptions: ============================================================================*/ static internal int GetLunarMonthDay(int gregorianYear, __DateBuffer lunarDate) { // // Get the offset into the LunarMonthLen array and the lunar day // for January 1st. // int index = gregorianYear - FirstGregorianTableYear; if (index < 0 || index > TABLESIZE) { throw new ArgumentOutOfRangeException("gregorianYear"); } index *= 2; lunarDate.day = s_hebrewTable[index]; // Get the type of the year. The value is from 1 to 6 int LunarYearType = s_hebrewTable[index + 1]; // // Get the Lunar Month. // switch (lunarDate.day) { case (0): // 1/1 is on Shvat 1 lunarDate.month = 5; lunarDate.day = 1; break; case (30): // 1/1 is on Kislev 30 lunarDate.month = 3; break; case (31): // 1/1 is on Shvat 2 lunarDate.month = 5; lunarDate.day = 2; break; case (32): // 1/1 is on Shvat 3 lunarDate.month = 5; lunarDate.day = 3; break; case (33): // 1/1 is on Kislev 29 lunarDate.month = 3; lunarDate.day = 29; break; default: // 1/1 is on Tevet (This is the general case) lunarDate.month = 4; break; } return (LunarYearType); } // 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) { // The Gregorian year, month, day value for ticks. int gregorianYear, gregorianMonth, gregorianDay; int hebrewYearType; // lunar year type long AbsoluteDate; // absolute date - absolute date 1/1/1600 // // Make sure we have a valid Gregorian date that will fit into our // Hebrew conversion limits. // CheckTicksRange(ticks); DateTime time = new DateTime(ticks); // // Save the Gregorian date values. // gregorianYear = time.Year; gregorianMonth = time.Month; gregorianDay = time.Day; __DateBuffer lunarDate = new __DateBuffer(); // lunar month and day for Jan 1 // From the table looking-up value of HebrewTable[index] (stored in lunarDate.day), we get the the // lunar month and lunar day where the Gregorian date 1/1 falls. lunarDate.year = gregorianYear + HebrewYearOf1AD; hebrewYearType = GetLunarMonthDay(gregorianYear, lunarDate); // This is the buffer used to store the result Hebrew date. __DateBuffer result = new __DateBuffer(); // // Store the values for the start of the new year - 1/1. // result.year = lunarDate.year; result.month = lunarDate.month; result.day = lunarDate.day; // // Get the absolute date from 1/1/1600. // AbsoluteDate = GregorianCalendar.GetAbsoluteDate(gregorianYear, gregorianMonth, gregorianDay); // // If the requested date was 1/1, then we're done. // if ((gregorianMonth == 1) && (gregorianDay == 1)) { return (GetResult(result, part)); } // // Calculate the number of days between 1/1 and the requested date. // long NumDays; // number of days since 1/1 NumDays = AbsoluteDate - GregorianCalendar.GetAbsoluteDate(gregorianYear, 1, 1); // // If the requested date is within the current lunar month, then // we're done. // if ((NumDays + (long)lunarDate.day) <= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month])) { result.day += (int)NumDays; return (GetResult(result, part)); } // // Adjust for the current partial month. // result.month++; result.day = 1; // // Adjust the Lunar Month and Year (if necessary) based on the number // of days between 1/1 and the requested date. // // Assumes Jan 1 can never translate to the last Lunar month, which // is true. // NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day); Contract.Assert(NumDays >= 1, "NumDays >= 1"); // If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month // and day. if (NumDays > 1) { // // See if we're on the correct Lunar month. // while (NumDays > (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month])) { // // Adjust the number of days and move to the next month. // NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month++]); // // See if we need to adjust the Year. // Must handle both 12 and 13 month years. // if ((result.month > 13) || (s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month] == 0)) { // // Adjust the Year. // result.year++; hebrewYearType = s_hebrewTable[(gregorianYear + 1 - FirstGregorianTableYear) * 2 + 1]; // // Adjust the Month. // result.month = 1; } } // // Found the right Lunar month. // result.day += (int)(NumDays - 1); } return (GetResult(result, part)); } // 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 override DateTime AddMonths(DateTime time, int months) { try { int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int monthsInYear; int i; if (months >= 0) { i = m + months; while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra))) { y++; i -= monthsInYear; } } else { if ((i = m + months) <= 0) { months = -months; months -= m; y--; while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra))) { y--; months -= monthsInYear; } monthsInYear = GetMonthsInYear(y, CurrentEra); i = monthsInYear - months; } } int days = GetDaysInMonth(y, i); if (d > days) { d = days; } return (new DateTime(ToDateTime(y, i, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay))); } // We expect ArgumentException and ArgumentOutOfRangeException (which is subclass of ArgumentException) // If exception is thrown in the calls above, we are out of the supported range of this calendar. catch (ArgumentException) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_AddValue)); } } // 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 override DateTime AddYears(DateTime time, int years) { int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); y += years; CheckHebrewYearValue(y, Calendar.CurrentEra, "years"); int months = GetMonthsInYear(y, CurrentEra); if (m > months) { m = months; } int days = GetDaysInMonth(y, m); if (d > days) { d = days; } long ticks = ToDateTime(y, m, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override 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 override DayOfWeek GetDayOfWeek(DateTime time) { // If we calculate back, the Hebrew day of week for Gregorian 0001/1/1 is Monday (1). // Therfore, the fomula is: return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } static internal int GetHebrewYearType(int year, int era) { CheckHebrewYearValue(year, era, "year"); // The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear. // So we need to convert year (Hebrew year value) to Gregorian Year below. return (s_hebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1]); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { // Get Hebrew year value of the specified time. int year = GetYear(time); DateTime beginOfYearDate; if (year == 5343) { // Gregorian 1583/01/01 corresponds to Hebrew 5343/04/07 (MinSupportedDateTime) // To figure out the Gregorian date associated with Hebrew 5343/01/01, we need to // count the days from 5343/01/01 to 5343/04/07 and subtract that from Gregorian // 1583/01/01. // 1. Tishri (30 days) // 2. Heshvan (30 days since 5343 has 355 days) // 3. Kislev (30 days since 5343 has 355 days) // 96 days to get from 5343/01/01 to 5343/04/07 // Gregorian 1583/01/01 - 96 days = 1582/9/27 // the beginning of Hebrew year 5343 corresponds to Gregorian September 27, 1582. beginOfYearDate = new DateTime(1582, 9, 27); } else { // following line will fail when year is 5343 (first supported year) beginOfYearDate = ToDateTime(year, 1, 1, 0, 0, 0, 0, CurrentEra); } return ((int)((time.Ticks - beginOfYearDate.Ticks) / TicksPerDay) + 1); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { CheckEraRange(era); int hebrewYearType = GetHebrewYearType(year, era); CheckHebrewMonthValue(year, month, era); Contract.Assert(hebrewYearType >= 1 && hebrewYearType <= 6, "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year); int monthDays = s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + month]; if (monthDays == 0) { throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month); } return (monthDays); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { CheckEraRange(era); // normal years : 1 = 353 days 2 = 354 days 3 = 355 days. // Leap years : 4 = 383 5 384 6 = 385 days. // LunarYearType is from 1 to 6 int LunarYearType = GetHebrewYearType(year, era); if (LunarYearType < 4) { // common year: LunarYearType = 1, 2, 3 return (352 + LunarYearType); } return (382 + (LunarYearType - 3)); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (HebrewEra); } public override int[] Eras { get { return (new int[] { HebrewEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { return (IsLeapYear(year, era) ? 13 : 12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // 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 override bool IsLeapDay(int year, int month, int day, int era) { if (IsLeapMonth(year, month, era)) { // Every day in a leap month is a leap day. CheckHebrewDayValue(year, month, day, era); return (true); } else if (IsLeapYear(year, Calendar.CurrentEra)) { // There is an additional day in the 6th month in the leap year (the extra day is the 30th day in the 6th month), // so we should return true for 6/30 if that's in a leap year. if (month == 6 && day == 30) { return (true); } } CheckHebrewDayValue(year, month, day, era); 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 override int GetLeapMonth(int year, int era) { // Year/era values are checked in IsLeapYear(). if (IsLeapYear(year, era)) { // The 7th month in a leap year is a leap month. return (7); } 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 override bool IsLeapMonth(int year, int month, int era) { // Year/era values are checked in IsLeapYear(). bool isLeapYear = IsLeapYear(year, era); CheckHebrewMonthValue(year, month, era); // The 7th month in a leap year is a leap month. if (isLeapYear) { if (month == 7) { return (true); } } 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 override bool IsLeapYear(int year, int era) { CheckHebrewYearValue(year, era, "year"); return (((7 * (long)year + 1) % 19) < 7); } // (month1, day1) - (month2, day2) private static int GetDayDifference(int lunarYearType, int month1, int day1, int month2, int day2) { if (month1 == month2) { return (day1 - day2); } // Make sure that (month1, day1) < (month2, day2) bool swap = (month1 > month2); if (swap) { // (month1, day1) < (month2, day2). Swap the values. // The result will be a negative number. int tempMonth, tempDay; tempMonth = month1; tempDay = day1; month1 = month2; day1 = day2; month2 = tempMonth; day2 = tempDay; } // Get the number of days from (month1,day1) to (month1, end of month1) int days = s_lunarMonthLen[lunarYearType * MaxMonthPlusOne + month1] - day1; // Move to next month. month1++; // Add up the days. while (month1 < month2) { days += s_lunarMonthLen[lunarYearType * MaxMonthPlusOne + month1++]; } days += day2; return (swap ? days : -days); } /*=================================HebrewToGregorian========================== **Action: Convert Hebrew date to Gregorian date. **Returns: **Arguments: **Exceptions: ** The algorithm is like this: ** The hebrew year has an offset to the Gregorian year, so we can guess the Gregorian year for ** the specified Hebrew year. That is, GreogrianYear = HebrewYear - FirstHebrewYearOf1AD. ** ** From the Gregorian year and HebrewTable, we can get the Hebrew month/day value ** of the Gregorian date January 1st. Let's call this month/day value [hebrewDateForJan1] ** ** If the requested Hebrew month/day is less than [hebrewDateForJan1], we know the result ** Gregorian date falls in previous year. So we decrease the Gregorian year value, and ** retrieve the Hebrew month/day value of the Gregorian date january 1st again. ** ** Now, we get the answer of the Gregorian year. ** ** The next step is to get the number of days between the requested Hebrew month/day ** and [hebrewDateForJan1]. When we get that, we can create the DateTime by adding/subtracting ** the ticks value of the number of days. ** ============================================================================*/ private static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond) { // Get the rough Gregorian year for the specified hebrewYear. // int gregorianYear = hebrewYear - HebrewYearOf1AD; __DateBuffer hebrewDateOfJan1 = new __DateBuffer(); // year value is unused. int lunarYearType = GetLunarMonthDay(gregorianYear, hebrewDateOfJan1); if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day)) { return (new DateTime(gregorianYear, 1, 1, hour, minute, second, millisecond)); } int days = GetDayDifference(lunarYearType, hebrewMonth, hebrewDay, hebrewDateOfJan1.month, hebrewDateOfJan1.day); DateTime gregorianNewYear = new DateTime(gregorianYear, 1, 1); return (new DateTime(gregorianNewYear.Ticks + days * TicksPerDay + TimeToTicks(hour, minute, second, millisecond))); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckHebrewYearValue(year, era, "year"); CheckHebrewMonthValue(year, month, era); CheckHebrewDayValue(year, month, day, era); DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond); CheckTicksRange(dt.Ticks); return (dt); } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 5790; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value == 99) { // Do nothing here. Year 99 is allowed so that TwoDitYearMax is disabled. } else { CheckHebrewYearValue(value, HebrewEra, "value"); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return (base.ToFourDigitYear(year)); } if (year > MaxHebrewYear || year < MinHebrewYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear)); } return (year); } internal class __DateBuffer { internal int year; internal int month; internal int day; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015-2016 FUJIWARA, Yusuke and contributors // // 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. // // Contributors: // Samuel Cragg // #endregion -- License Terms -- using System; using System.Collections.Generic; #if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // FEATURE_MPCONTRACT using System.Linq; using System.Reflection; #if FEATURE_TAP using System.Threading; #endif // FEATURE_TAP namespace MsgPack.Serialization.AbstractSerializers { [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Well patterned" )] partial class SerializerBuilder<TContext, TConstruct> { private void BuildCollectionSerializer( TContext context, Type concreteType, PolymorphismSchema schema, out SerializationTarget targetInfo ) { #if DEBUG Contract.Assert( this.CollectionTraits.DetailedCollectionType != CollectionDetailedKind.Array ); #endif // DEBUG bool isUnpackFromRequired; bool isAddItemRequired; this.DetermineSerializationStrategy( context, concreteType, out targetInfo, out isUnpackFromRequired, out isAddItemRequired ); if ( typeof( IPackable ).IsAssignableFrom( this.TargetType ) ) { this.BuildIPackablePackTo( context ); } #if FEATURE_TAP if ( this.WithAsync( context ) ) { if ( typeof( IAsyncPackable ).IsAssignableFrom( this.TargetType ) ) { this.BuildIAsyncPackablePackTo( context ); } } #endif // FEATURE_TAP this.BuildCollectionCreateInstance( context, targetInfo.DeserializationConstructor, targetInfo.CanDeserialize ); var useUnpackable = false; if ( typeof( IUnpackable ).IsAssignableFrom( concreteType ?? this.TargetType ) ) { this.BuildIUnpackableUnpackFrom( context, this.GetUnpackableCollectionInstantiation( context ), targetInfo.CanDeserialize ); useUnpackable = true; } #if FEATURE_TAP if ( this.WithAsync( context ) ) { if ( typeof( IAsyncUnpackable ).IsAssignableFrom( concreteType ?? this.TargetType ) ) { this.BuildIAsyncUnpackableUnpackFrom( context, this.GetUnpackableCollectionInstantiation( context ), targetInfo.CanDeserialize ); useUnpackable = true; } } #endif // FEATURE_TAP if ( isAddItemRequired ) { if ( useUnpackable || !targetInfo.CanDeserialize ) { // AddItem should never called because UnpackFromCore calls IUnpackable/IAsyncUnpackable this.BuildCollectionAddItemNotImplemented( context ); } else { // For IEnumerable implements and IReadOnlyXXX implements this.BuildCollectionAddItem( context, this.CollectionTraits.AddMethod != null ? this.CollectionTraits // For declared collection. : ( concreteType ?? this.TargetType ).GetCollectionTraits( CollectionTraitOptions.Full, context.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) // For concrete collection. ); } } if ( isUnpackFromRequired && !useUnpackable ) { this.BuildCollectionUnpackFromCore( context, concreteType, schema, targetInfo.CanDeserialize, isAsync: false ); #if FEATURE_TAP if ( this.WithAsync( context ) ) { this.BuildCollectionUnpackFromCore( context, concreteType, schema, targetInfo.CanDeserialize, isAsync: true ); } #endif // FEATURE_TAP } this.BuildRestoreSchema( context, schema ); } private void DetermineSerializationStrategy( TContext context, Type concreteType, out SerializationTarget targetInfo, out bool isUnpackFromRequired, out bool isAddItemRequired ) { targetInfo = UnpackHelpers.DetermineCollectionSerializationStrategy( concreteType ?? this.TargetType, context.SerializationContext.CompatibilityOptions.AllowAsymmetricSerializer ); switch ( this.CollectionTraits.DetailedCollectionType ) { case CollectionDetailedKind.NonGenericEnumerable: case CollectionDetailedKind.NonGenericCollection: { isUnpackFromRequired = true; isAddItemRequired = true; break; } case CollectionDetailedKind.NonGenericList: { isUnpackFromRequired = false; isAddItemRequired = false; break; } case CollectionDetailedKind.NonGenericDictionary: { isUnpackFromRequired = false; isAddItemRequired = false; break; } case CollectionDetailedKind.GenericEnumerable: { isUnpackFromRequired = true; isAddItemRequired = true; break; } case CollectionDetailedKind.GenericDictionary: { isUnpackFromRequired = false; isAddItemRequired = false; break; } #if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyDictionary: { isUnpackFromRequired = false; isAddItemRequired = true; break; } case CollectionDetailedKind.GenericReadOnlyList: case CollectionDetailedKind.GenericReadOnlyCollection: { isUnpackFromRequired = false; isAddItemRequired = true; break; } #endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) default: { isUnpackFromRequired = false; isAddItemRequired = false; break; } } // switch } private TConstruct GetUnpackableCollectionInstantiation( TContext context ) { return this.EmitInvokeMethodExpression( context, this.EmitThisReferenceExpression( context ), context.GetDeclaredMethod( MethodName.CreateInstance ), this.MakeInt32Literal( context, 0 ) // Always 0 ); } #region -- AddItem -- private void BuildCollectionAddItem( TContext context, CollectionTraits traits ) { var addItem = this.BaseClass.GetRuntimeMethod( MethodName.AddItem ); var addItemParametersTypes = addItem.GetParameterTypes(); context.BeginMethodOverride( MethodName.AddItem ); context.EndMethodOverride( MethodName.AddItem, traits.CollectionType == CollectionKind.Map ? this.EmitAppendDictionaryItem( context, traits, context.CollectionToBeAdded, addItemParametersTypes[ 0 ], context.KeyToAdd, addItemParametersTypes[ 1 ], context.ValueToAdd, false ) : this.EmitAppendCollectionItem( context, null, traits, context.CollectionToBeAdded, context.ItemToAdd ) ); } private void BuildCollectionAddItemNotImplemented( TContext context ) { context.BeginMethodOverride( MethodName.AddItem ); context.EndMethodOverride( MethodName.AddItem, this.EmitSequentialStatements( context, TypeDefinition.VoidType ) // nop ); } #endregion -- AddItem -- #region -- UnpackFromCore -- private void BuildCollectionUnpackFromCore( TContext context, Type concreteType, PolymorphismSchema schema, bool canDeserialize, bool isAsync ) { var methodName = #if FEATURE_TAP isAsync ? MethodName.UnpackFromAsyncCore : #endif // FEATURE_TAP MethodName.UnpackFromCore; context.BeginMethodOverride( methodName ); var instanceType = concreteType ?? this.TargetType; context.EndMethodOverride( methodName, canDeserialize ? this.EmitSequentialStatements( context, this.TargetType, this.EmitCollectionUnpackFromStatements( context, instanceType, schema, isAsync ) ) : this.EmitThrowCannotUnpackFrom( context ) ); } private IEnumerable<TConstruct> EmitCollectionUnpackFromStatements( TContext context, Type instanceType, PolymorphismSchema schema, bool isAsync ) { // Header check yield return this.CollectionTraits.CollectionType == CollectionKind.Array ? this.EmitCheckIsArrayHeaderExpression( context, context.Unpacker ) : this.EmitCheckIsMapHeaderExpression( context, context.Unpacker ); var itemsCount = this.DeclareLocal( context, TypeDefinition.Int32Type, "itemsCount" ); // Unpack items count and store it yield return itemsCount; yield return this.EmitStoreVariableStatement( context, itemsCount, this.EmitGetItemsCountExpression( context, context.Unpacker ) ); var createInstance = this.EmitInvokeMethodExpression( context, this.EmitThisReferenceExpression( context ), context.GetDeclaredMethod( MethodName.CreateInstance ), itemsCount ); var collection = instanceType == this.TargetType ? createInstance : this.EmitUnboxAnyExpression( context, instanceType, createInstance ); // Get delegates to UnpackHelpers TConstruct iterative; TConstruct bulk; if ( this.CollectionTraits.CollectionType == CollectionKind.Array && this.CollectionTraits.AddMethod == null ) { // Try to use concrete collection's Add. var traitsOfTheCollection = instanceType.GetCollectionTraits( CollectionTraitOptions.Full, context.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes); bulk = this.MakeNullLiteral( context, #if FEATURE_TAP isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type, TypeDefinition.CancellationTokenType, TypeDefinition.TaskType ) : #endif // FEATURE_TAP TypeDefinition.GenericReferenceType( typeof( Action<,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type ) ); var indexOfItemParameter = context.IndexOfItem; var itemsCountParameter = context.ItemsCount; var appendToTargetParameter = context.CollectionToBeAdded; var unpackedItemParameter = context.DefineUnpackedItemParameterInSetValueMethods( this.CollectionTraits.ElementType ); var unpackItemValueArguments = new[] { context.Unpacker, context.UnpackToTarget, indexOfItemParameter, itemsCountParameter } #if FEATURE_TAP .Concat( isAsync ? new[] { this.ReferCancellationToken( context, 2 ) } : NoConstructs ).ToArray() #endif // FEATURE_TAP ; iterative = this.ExtractPrivateMethod( context, AdjustName( MethodName.UnpackCollectionItem, isAsync ), false, // isStatic #if FEATURE_TAP isAsync ? TypeDefinition.TaskType : #endif // FEATURE_TAP TypeDefinition.VoidType, () => this.EmitUnpackItemValueStatement( context, traitsOfTheCollection.ElementType, this.EmitInvariantStringFormat( context, "item{0}", indexOfItemParameter ), context.CollectionItemNilImplication, null, ( schema ?? PolymorphismSchema.Default ).ItemSchema, context.Unpacker, context.UnpackToTarget, indexOfItemParameter, itemsCountParameter, this.ExtractPrivateMethod( context, MethodName.AppendUnpackedItem, false, // isStatic TypeDefinition.VoidType, () => this.EmitAppendCollectionItem( context, null, traitsOfTheCollection, appendToTargetParameter, unpackedItemParameter ), appendToTargetParameter, unpackedItemParameter ), isAsync ), unpackItemValueArguments ); } else { // Invoke UnpackToCore because AddItem override/inheritance is available. bulk = this.EmitGetActionsExpression( context, ActionType.UnpackTo, isAsync ); context.IsUnpackToUsed = true; iterative = this.MakeNullLiteral( context, #if FEATURE_TAP isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type, TypeDefinition.Int32Type, TypeDefinition.CancellationTokenType, TypeDefinition.TaskType ) : #endif // FEATURE_TAP TypeDefinition.GenericReferenceType( typeof( Action<,,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type, TypeDefinition.Int32Type ) ); } var unpackHelperArguments = new Dictionary<string, TConstruct> { { "Unpacker", context.Unpacker }, { "ItemsCount", itemsCount }, { "Collection", collection }, { "BulkOperation", bulk }, { "EachOperation", iterative }, }; #if FEATURE_TAP if ( isAsync ) { unpackHelperArguments.Add( "CancellationToken", this.ReferCancellationToken( context, 2 ) ); } #endif // FEATURE_TAP var unpackHelperParametersType = ( #if FEATURE_TAP isAsync ? typeof( UnpackCollectionAsyncParameters<> ) : #endif // FEATURE_TAP typeof( UnpackCollectionParameters<> ) ).MakeGenericType( this.TargetType ); var unpackHelperParameters = this.DeclareLocal( context, unpackHelperParametersType, "unpackHelperParameters" ); yield return unpackHelperParameters; foreach ( var construct in this.CreatePackUnpackHelperArgumentInitialization( context, unpackHelperParameters, unpackHelperArguments ) ) { yield return construct; } // Call UnpackHelpers yield return this.EmitRetrunStatement( context, this.EmitInvokeMethodExpression( context, null, #if FEATURE_TAP isAsync ? Metadata._UnpackHelpers.UnpackCollectionAsync_1Method.MakeGenericMethod( this.TargetType ) : #endif // FEATURE_TAP Metadata._UnpackHelpers.UnpackCollection_1Method.MakeGenericMethod( this.TargetType ), this.EmitMakeRef( context, unpackHelperParameters ) ) ); } private TConstruct EmitGetItemsCountExpression( TContext context, TConstruct unpacker ) { return this.EmitInvokeMethodExpression( context, null, Metadata._UnpackHelpers.GetItemsCount, unpacker ); } #endregion -- UnpackFromCore -- #region -- CreateInstance -- private void BuildCollectionCreateInstance( TContext context, ConstructorInfo collectionConstructor, bool canDeserialize ) { context.BeginMethodOverride( MethodName.CreateInstance ); var collection = this.DeclareLocal( context, this.TargetType, "collection" ); context.EndMethodOverride( MethodName.CreateInstance, canDeserialize ? this.EmitSequentialStatements( context, this.TargetType, collection, this.EmitStoreVariableStatement( context, collection, this.EmitCreateNewObjectExpression( context, collection, collectionConstructor, this.DetermineCollectionConstructorArguments( context, collectionConstructor ) ) ), this.EmitRetrunStatement( context, this.EmitLoadVariableExpression( context, collection ) ) ) : this.EmitThrowCannotCreateInstance( context ) ); } #endregion -- CreateInstance -- #region -- RestoreSchema -- private void BuildRestoreSchema( TContext context, PolymorphismSchema schema ) { context.BeginPrivateMethod( MethodName.RestoreSchema, true, TypeDefinition.PolymorphismSchemaType ); var storage = this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType , "schema" ); context.EndPrivateMethod( MethodName.RestoreSchema, this.EmitSequentialStatements( context, TypeDefinition.PolymorphismSchemaType, new[] { storage } .Concat( this.EmitConstructPolymorphismSchema( context, storage, schema ) ) .Concat( new[] { this.EmitRetrunStatement( context, this.EmitLoadVariableExpression( context, storage ) ) } ) ) ); } #endregion -- RestoreSchema -- #region -- Constructor Helpers -- protected internal TConstruct EmitUnpackToInitialization( TContext context ) { // This method should be called at most once, so caching following array should be wasting. var parameterTypes = new[] { typeof( Unpacker ), this.TargetType, typeof( int ) }; var initUnpackTo = this.EmitSetField( context, this.EmitThisReferenceExpression( context ), context.GetDeclaredField( FieldName.UnpackTo ), this.EmitNewPrivateMethodDelegateExpression( context, this.BaseClass.GetRuntimeMethods().Single( m => m.Name == MethodName.UnpackToCore && m.GetParameterTypes().SequenceEqual( parameterTypes ) ) ) ); #if FEATURE_TAP if ( context.SerializationContext.SerializerOptions.WithAsync ) { // This method should be called at most once, so caching following array should be wasting. var asyncParameterTypes = new[] { typeof( Unpacker ), this.TargetType, typeof( int ), typeof( CancellationToken ) }; var initAsyncUnpackTo = this.EmitSetField( context, this.EmitThisReferenceExpression( context ), context.GetDeclaredField( FieldName.UnpackTo + "Async" ), this.EmitNewPrivateMethodDelegateExpression( context, this.BaseClass.GetRuntimeMethods().Single( m => m.Name == MethodName.UnpackToAsyncCore && m.GetParameterTypes().SequenceEqual( asyncParameterTypes ) ) ) ); return this.EmitSequentialStatements( context, TypeDefinition.VoidType, initUnpackTo, initAsyncUnpackTo ); } #endif // FEATURE_TAP return initUnpackTo; } #endregion -- Constructor Helpers -- } }
namespace java.util.concurrent { [global::MonoJavaBridge.JavaClass()] public partial class ThreadPoolExecutor : java.util.concurrent.AbstractExecutorService { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ThreadPoolExecutor(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class AbortPolicy : java.lang.Object, RejectedExecutionHandler { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected AbortPolicy(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void rejectedExecution(java.lang.Runnable arg0, java.util.concurrent.ThreadPoolExecutor arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.AbortPolicy.staticClass, "rejectedExecution", "(Ljava/lang/Runnable;Ljava/util/concurrent/ThreadPoolExecutor;)V", ref global::java.util.concurrent.ThreadPoolExecutor.AbortPolicy._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void rejectedExecution(global::java.lang.RunnableDelegate arg0, java.util.concurrent.ThreadPoolExecutor arg1) { rejectedExecution((global::java.lang.RunnableDelegateWrapper)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m1; public AbortPolicy() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor.AbortPolicy._m1.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor.AbortPolicy._m1 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.AbortPolicy.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.AbortPolicy.staticClass, global::java.util.concurrent.ThreadPoolExecutor.AbortPolicy._m1); Init(@__env, handle); } static AbortPolicy() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.concurrent.ThreadPoolExecutor.AbortPolicy.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/concurrent/ThreadPoolExecutor$AbortPolicy")); } } [global::MonoJavaBridge.JavaClass()] public partial class CallerRunsPolicy : java.lang.Object, RejectedExecutionHandler { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected CallerRunsPolicy(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void rejectedExecution(java.lang.Runnable arg0, java.util.concurrent.ThreadPoolExecutor arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy.staticClass, "rejectedExecution", "(Ljava/lang/Runnable;Ljava/util/concurrent/ThreadPoolExecutor;)V", ref global::java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void rejectedExecution(global::java.lang.RunnableDelegate arg0, java.util.concurrent.ThreadPoolExecutor arg1) { rejectedExecution((global::java.lang.RunnableDelegateWrapper)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m1; public CallerRunsPolicy() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy._m1.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy._m1 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy.staticClass, global::java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy._m1); Init(@__env, handle); } static CallerRunsPolicy() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/concurrent/ThreadPoolExecutor$CallerRunsPolicy")); } } [global::MonoJavaBridge.JavaClass()] public partial class DiscardOldestPolicy : java.lang.Object, RejectedExecutionHandler { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected DiscardOldestPolicy(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void rejectedExecution(java.lang.Runnable arg0, java.util.concurrent.ThreadPoolExecutor arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy.staticClass, "rejectedExecution", "(Ljava/lang/Runnable;Ljava/util/concurrent/ThreadPoolExecutor;)V", ref global::java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void rejectedExecution(global::java.lang.RunnableDelegate arg0, java.util.concurrent.ThreadPoolExecutor arg1) { rejectedExecution((global::java.lang.RunnableDelegateWrapper)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m1; public DiscardOldestPolicy() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy._m1.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy._m1 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy.staticClass, global::java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy._m1); Init(@__env, handle); } static DiscardOldestPolicy() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/concurrent/ThreadPoolExecutor$DiscardOldestPolicy")); } } [global::MonoJavaBridge.JavaClass()] public partial class DiscardPolicy : java.lang.Object, RejectedExecutionHandler { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected DiscardPolicy(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void rejectedExecution(java.lang.Runnable arg0, java.util.concurrent.ThreadPoolExecutor arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.DiscardPolicy.staticClass, "rejectedExecution", "(Ljava/lang/Runnable;Ljava/util/concurrent/ThreadPoolExecutor;)V", ref global::java.util.concurrent.ThreadPoolExecutor.DiscardPolicy._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void rejectedExecution(global::java.lang.RunnableDelegate arg0, java.util.concurrent.ThreadPoolExecutor arg1) { rejectedExecution((global::java.lang.RunnableDelegateWrapper)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m1; public DiscardPolicy() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor.DiscardPolicy._m1.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor.DiscardPolicy._m1 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.DiscardPolicy.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.DiscardPolicy.staticClass, global::java.util.concurrent.ThreadPoolExecutor.DiscardPolicy._m1); Init(@__env, handle); } static DiscardPolicy() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.concurrent.ThreadPoolExecutor.DiscardPolicy.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/concurrent/ThreadPoolExecutor$DiscardPolicy")); } } private static global::MonoJavaBridge.MethodId _m0; public override void shutdown() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "shutdown", "()V", ref global::java.util.concurrent.ThreadPoolExecutor._m0); } private static global::MonoJavaBridge.MethodId _m1; protected override void finalize() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "finalize", "()V", ref global::java.util.concurrent.ThreadPoolExecutor._m1); } private static global::MonoJavaBridge.MethodId _m2; public virtual bool remove(java.lang.Runnable arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "remove", "(Ljava/lang/Runnable;)Z", ref global::java.util.concurrent.ThreadPoolExecutor._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public bool remove(global::java.lang.RunnableDelegate arg0) { return remove((global::java.lang.RunnableDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m3; public override bool awaitTermination(long arg0, java.util.concurrent.TimeUnit arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "awaitTermination", "(JLjava/util/concurrent/TimeUnit;)Z", ref global::java.util.concurrent.ThreadPoolExecutor._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public override void execute(java.lang.Runnable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "execute", "(Ljava/lang/Runnable;)V", ref global::java.util.concurrent.ThreadPoolExecutor._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void execute(global::java.lang.RunnableDelegate arg0) { execute((global::java.lang.RunnableDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m5; public virtual void purge() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "purge", "()V", ref global::java.util.concurrent.ThreadPoolExecutor._m5); } private static global::MonoJavaBridge.MethodId _m6; public override global::java.util.List shutdownNow() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "shutdownNow", "()Ljava/util/List;", ref global::java.util.concurrent.ThreadPoolExecutor._m6) as java.util.List; } private static global::MonoJavaBridge.MethodId _m7; public override bool isShutdown() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "isShutdown", "()Z", ref global::java.util.concurrent.ThreadPoolExecutor._m7); } private static global::MonoJavaBridge.MethodId _m8; public override bool isTerminated() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "isTerminated", "()Z", ref global::java.util.concurrent.ThreadPoolExecutor._m8); } private static global::MonoJavaBridge.MethodId _m9; public virtual void allowCoreThreadTimeOut(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "allowCoreThreadTimeOut", "(Z)V", ref global::java.util.concurrent.ThreadPoolExecutor._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m10; public virtual bool isTerminating() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "isTerminating", "()Z", ref global::java.util.concurrent.ThreadPoolExecutor._m10); } private static global::MonoJavaBridge.MethodId _m11; public virtual void setThreadFactory(java.util.concurrent.ThreadFactory arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "setThreadFactory", "(Ljava/util/concurrent/ThreadFactory;)V", ref global::java.util.concurrent.ThreadPoolExecutor._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.util.concurrent.ThreadFactory ThreadFactory { get { return getThreadFactory(); } set { setThreadFactory(value); } } private static global::MonoJavaBridge.MethodId _m12; public virtual global::java.util.concurrent.ThreadFactory getThreadFactory() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.concurrent.ThreadFactory>(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getThreadFactory", "()Ljava/util/concurrent/ThreadFactory;", ref global::java.util.concurrent.ThreadPoolExecutor._m12) as java.util.concurrent.ThreadFactory; } private static global::MonoJavaBridge.MethodId _m13; public virtual void setRejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "setRejectedExecutionHandler", "(Ljava/util/concurrent/RejectedExecutionHandler;)V", ref global::java.util.concurrent.ThreadPoolExecutor._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.util.concurrent.RejectedExecutionHandler RejectedExecutionHandler { get { return getRejectedExecutionHandler(); } set { setRejectedExecutionHandler(value); } } private static global::MonoJavaBridge.MethodId _m14; public virtual global::java.util.concurrent.RejectedExecutionHandler getRejectedExecutionHandler() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.concurrent.RejectedExecutionHandler>(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getRejectedExecutionHandler", "()Ljava/util/concurrent/RejectedExecutionHandler;", ref global::java.util.concurrent.ThreadPoolExecutor._m14) as java.util.concurrent.RejectedExecutionHandler; } private static global::MonoJavaBridge.MethodId _m15; public virtual void setCorePoolSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "setCorePoolSize", "(I)V", ref global::java.util.concurrent.ThreadPoolExecutor._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int CorePoolSize { get { return getCorePoolSize(); } set { setCorePoolSize(value); } } private static global::MonoJavaBridge.MethodId _m16; public virtual int getCorePoolSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getCorePoolSize", "()I", ref global::java.util.concurrent.ThreadPoolExecutor._m16); } private static global::MonoJavaBridge.MethodId _m17; public virtual bool prestartCoreThread() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "prestartCoreThread", "()Z", ref global::java.util.concurrent.ThreadPoolExecutor._m17); } private static global::MonoJavaBridge.MethodId _m18; public virtual int prestartAllCoreThreads() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "prestartAllCoreThreads", "()I", ref global::java.util.concurrent.ThreadPoolExecutor._m18); } private static global::MonoJavaBridge.MethodId _m19; public virtual bool allowsCoreThreadTimeOut() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "allowsCoreThreadTimeOut", "()Z", ref global::java.util.concurrent.ThreadPoolExecutor._m19); } private static global::MonoJavaBridge.MethodId _m20; public virtual void setMaximumPoolSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "setMaximumPoolSize", "(I)V", ref global::java.util.concurrent.ThreadPoolExecutor._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int MaximumPoolSize { get { return getMaximumPoolSize(); } set { setMaximumPoolSize(value); } } private static global::MonoJavaBridge.MethodId _m21; public virtual int getMaximumPoolSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getMaximumPoolSize", "()I", ref global::java.util.concurrent.ThreadPoolExecutor._m21); } private static global::MonoJavaBridge.MethodId _m22; public virtual void setKeepAliveTime(long arg0, java.util.concurrent.TimeUnit arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "setKeepAliveTime", "(JLjava/util/concurrent/TimeUnit;)V", ref global::java.util.concurrent.ThreadPoolExecutor._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m23; public virtual long getKeepAliveTime(java.util.concurrent.TimeUnit arg0) { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getKeepAliveTime", "(Ljava/util/concurrent/TimeUnit;)J", ref global::java.util.concurrent.ThreadPoolExecutor._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.util.concurrent.BlockingQueue Queue { get { return getQueue(); } } private static global::MonoJavaBridge.MethodId _m24; public virtual global::java.util.concurrent.BlockingQueue getQueue() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.concurrent.BlockingQueue>(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getQueue", "()Ljava/util/concurrent/BlockingQueue;", ref global::java.util.concurrent.ThreadPoolExecutor._m24) as java.util.concurrent.BlockingQueue; } public new int PoolSize { get { return getPoolSize(); } } private static global::MonoJavaBridge.MethodId _m25; public virtual int getPoolSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getPoolSize", "()I", ref global::java.util.concurrent.ThreadPoolExecutor._m25); } public new int ActiveCount { get { return getActiveCount(); } } private static global::MonoJavaBridge.MethodId _m26; public virtual int getActiveCount() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getActiveCount", "()I", ref global::java.util.concurrent.ThreadPoolExecutor._m26); } public new int LargestPoolSize { get { return getLargestPoolSize(); } } private static global::MonoJavaBridge.MethodId _m27; public virtual int getLargestPoolSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getLargestPoolSize", "()I", ref global::java.util.concurrent.ThreadPoolExecutor._m27); } public new long TaskCount { get { return getTaskCount(); } } private static global::MonoJavaBridge.MethodId _m28; public virtual long getTaskCount() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getTaskCount", "()J", ref global::java.util.concurrent.ThreadPoolExecutor._m28); } public new long CompletedTaskCount { get { return getCompletedTaskCount(); } } private static global::MonoJavaBridge.MethodId _m29; public virtual long getCompletedTaskCount() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "getCompletedTaskCount", "()J", ref global::java.util.concurrent.ThreadPoolExecutor._m29); } private static global::MonoJavaBridge.MethodId _m30; protected virtual void beforeExecute(java.lang.Thread arg0, java.lang.Runnable arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "beforeExecute", "(Ljava/lang/Thread;Ljava/lang/Runnable;)V", ref global::java.util.concurrent.ThreadPoolExecutor._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } protected void beforeExecute(java.lang.Thread arg0, global::java.lang.RunnableDelegate arg1) { beforeExecute(arg0, (global::java.lang.RunnableDelegateWrapper)arg1); } private static global::MonoJavaBridge.MethodId _m31; protected virtual void afterExecute(java.lang.Runnable arg0, java.lang.Throwable arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "afterExecute", "(Ljava/lang/Runnable;Ljava/lang/Throwable;)V", ref global::java.util.concurrent.ThreadPoolExecutor._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } protected void afterExecute(global::java.lang.RunnableDelegate arg0, java.lang.Throwable arg1) { afterExecute((global::java.lang.RunnableDelegateWrapper)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m32; protected virtual void terminated() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.concurrent.ThreadPoolExecutor.staticClass, "terminated", "()V", ref global::java.util.concurrent.ThreadPoolExecutor._m32); } private static global::MonoJavaBridge.MethodId _m33; public ThreadPoolExecutor(int arg0, int arg1, long arg2, java.util.concurrent.TimeUnit arg3, java.util.concurrent.BlockingQueue arg4, java.util.concurrent.ThreadFactory arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor._m33.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor._m33 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.staticClass, "<init>", "(IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.staticClass, global::java.util.concurrent.ThreadPoolExecutor._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m34; public ThreadPoolExecutor(int arg0, int arg1, long arg2, java.util.concurrent.TimeUnit arg3, java.util.concurrent.BlockingQueue arg4, java.util.concurrent.RejectedExecutionHandler arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor._m34.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor._m34 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.staticClass, "<init>", "(IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/RejectedExecutionHandler;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.staticClass, global::java.util.concurrent.ThreadPoolExecutor._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m35; public ThreadPoolExecutor(int arg0, int arg1, long arg2, java.util.concurrent.TimeUnit arg3, java.util.concurrent.BlockingQueue arg4, java.util.concurrent.ThreadFactory arg5, java.util.concurrent.RejectedExecutionHandler arg6) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor._m35.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor._m35 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.staticClass, "<init>", "(IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/util/concurrent/RejectedExecutionHandler;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.staticClass, global::java.util.concurrent.ThreadPoolExecutor._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m36; public ThreadPoolExecutor(int arg0, int arg1, long arg2, java.util.concurrent.TimeUnit arg3, java.util.concurrent.BlockingQueue arg4) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.concurrent.ThreadPoolExecutor._m36.native == global::System.IntPtr.Zero) global::java.util.concurrent.ThreadPoolExecutor._m36 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.ThreadPoolExecutor.staticClass, "<init>", "(IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.concurrent.ThreadPoolExecutor.staticClass, global::java.util.concurrent.ThreadPoolExecutor._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); Init(@__env, handle); } static ThreadPoolExecutor() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.concurrent.ThreadPoolExecutor.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/concurrent/ThreadPoolExecutor")); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using Baseline; using Marten.Events.Projections; using Marten.Schema; using Marten.Storage; namespace Marten.Events { public class EventGraph : IFeatureSchema { private readonly ConcurrentDictionary<string, IAggregator> _aggregateByName = new ConcurrentDictionary<string, IAggregator>(); private readonly ConcurrentDictionary<Type, IAggregator> _aggregates = new ConcurrentDictionary<Type, IAggregator>(); private readonly ConcurrentCache<string, EventMapping> _byEventName = new ConcurrentCache<string, EventMapping>(); private readonly ConcurrentCache<Type, EventMapping> _events = new ConcurrentCache<Type, EventMapping>(); private IAggregatorLookup _aggregatorLookup; private string _databaseSchemaName; public EventGraph(StoreOptions options) { Options = options; _aggregatorLookup = new AggregatorLookup(); _events.OnMissing = eventType => { var mapping = typeof(EventMapping<>).CloseAndBuildAs<EventMapping>(this, eventType); Options.Storage.AddMapping(mapping); return mapping; }; _byEventName.OnMissing = name => { return AllEvents().FirstOrDefault(x => x.EventTypeName == name); }; InlineProjections = new ProjectionCollection(options); AsyncProjections = new ProjectionCollection(options); } internal StoreOptions Options { get; } internal DbObjectName Table => new DbObjectName(DatabaseSchemaName, "mt_events"); public EventMapping EventMappingFor(Type eventType) { return _events[eventType]; } public EventMapping EventMappingFor<T>() where T : class, new() { return EventMappingFor(typeof(T)); } public IEnumerable<EventMapping> AllEvents() { return _events; } public IEnumerable<IAggregator> AllAggregates() { return _aggregates.Values; } public EventMapping EventMappingFor(string eventType) { return _byEventName[eventType]; } public void AddEventType(Type eventType) { _events.FillDefault(eventType); } public void AddEventTypes(IEnumerable<Type> types) { types.Each(AddEventType); } public bool IsActive => _events.Any() || _aggregates.Any(); public string DatabaseSchemaName { get { return _databaseSchemaName ?? Options.DatabaseSchemaName; } set { _databaseSchemaName = value; } } public void AddAggregator<T>(IAggregator<T> aggregator) where T : class, new() { Options.Storage.MappingFor(typeof(T)); _aggregates.AddOrUpdate(typeof(T), aggregator, (type, previous) => aggregator); } public IAggregator<T> AggregateFor<T>() where T : class, new() { return _aggregates .GetOrAdd(typeof(T), type => { Options.Storage.MappingFor(typeof(T)); return _aggregatorLookup.Lookup<T>(); }) .As<IAggregator<T>>(); } public Type AggregateTypeFor(string aggregateTypeName) { if (_aggregateByName.ContainsKey(aggregateTypeName)) { return _aggregateByName[aggregateTypeName].AggregateType; } var aggregate = AllAggregates().FirstOrDefault(x => x.Alias == aggregateTypeName); if (aggregate == null) { throw new ArgumentOutOfRangeException(nameof(aggregateTypeName), $"Unknown aggregate type '{aggregateTypeName}'. You may need to register this aggregate type with StoreOptions.Events.AggregateFor<T>()"); } return _aggregateByName.GetOrAdd(aggregateTypeName, name => { return AllAggregates().FirstOrDefault(x => x.Alias == name); }).AggregateType; } public ProjectionCollection InlineProjections { get; } public ProjectionCollection AsyncProjections { get; } internal DbObjectName ProgressionTable => new DbObjectName(DatabaseSchemaName, "mt_event_progression"); public string AggregateAliasFor(Type aggregateType) { return _aggregates .GetOrAdd(aggregateType, type => _aggregatorLookup.Lookup(type)).Alias; } public IProjection ProjectionFor(Type viewType) { return AsyncProjections.ForView(viewType) ?? InlineProjections.ForView(viewType); } public ViewProjection<TView> ProjectView<TView>() where TView : class, new() { var projection = new ViewProjection<TView>(); InlineProjections.Add(projection); return projection; } /// <summary> /// Set default strategy to lookup IAggregator when no explicit IAggregator registration exists. /// </summary> /// <remarks>Unless called, <see cref="AggregatorLookup"/> is used</remarks> public void UseAggregatorLookup(IAggregatorLookup aggregatorLookup) { _aggregatorLookup = aggregatorLookup; } IEnumerable<Type> IFeatureSchema.DependentTypes() { yield break; } ISchemaObject[] IFeatureSchema.Objects { get { var eventsTable = new EventsTable(DatabaseSchemaName); var sequence = new Sequence(new DbObjectName(DatabaseSchemaName, "mt_events_sequence")) { Owner = eventsTable.Identifier, OwnerColumn = "seq_id" }; return new ISchemaObject[] { new StreamsTable(DatabaseSchemaName), eventsTable, new EventProgressionTable(DatabaseSchemaName), sequence, new SystemFunction(DatabaseSchemaName, "mt_append_event", "uuid, varchar, uuid[], varchar[], jsonb[]"), new SystemFunction(DatabaseSchemaName, "mt_mark_event_progression", "varchar, bigint"), }; } } Type IFeatureSchema.StorageType => typeof(EventGraph); public string Identifier { get; } = "eventstore"; public void WritePermissions(DdlRules rules, StringWriter writer) { // Nothing } } public class StreamsTable : Table { public StreamsTable(string schemaName) : base(new DbObjectName(schemaName, "mt_streams")) { AddPrimaryKey(new TableColumn("id", "uuid")); AddColumn("type", "varchar(100)", "NULL"); AddColumn("version", "integer", "NOT NULL"); AddColumn("timestamp", "timestamptz", "default (now()) NOT NULL"); AddColumn("snapshot", "jsonb"); AddColumn("snapshot_version", "integer"); } } public class EventsTable : Table { public EventsTable(string schemaName) : base(new DbObjectName(schemaName, "mt_events")) { AddPrimaryKey(new TableColumn("seq_id", "bigint")); AddColumn("id", "uuid", "NOT NULL"); AddColumn("stream_id", "uuid", $"REFERENCES {schemaName}.mt_streams ON DELETE CASCADE"); AddColumn("version", "integer", "NOT NULL"); AddColumn("data", "jsonb", "NOT NULL"); AddColumn("type", "varchar(100)", "NOT NULL"); AddColumn("timestamp", "timestamptz", "default (now()) NOT NULL"); Constraints.Add("CONSTRAINT pk_mt_events_stream_and_version UNIQUE(stream_id, version)"); Constraints.Add("CONSTRAINT pk_mt_events_id_unique UNIQUE(id)"); } } public class EventProgressionTable : Table { public EventProgressionTable(string schemaName) : base(new DbObjectName(schemaName, "mt_event_progression")) { AddPrimaryKey(new TableColumn("name", "varchar")); AddColumn("last_seq_id", "bigint", "NULL"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.libcurl.CURLAUTH; using CURLoption = Interop.libcurl.CURLoption; using CurlProtocols = Interop.libcurl.CURLPROTO_Definitions; using CURLProxyType = Interop.libcurl.curl_proxytype; using SafeCurlHandle = Interop.libcurl.SafeCurlHandle; using SafeCurlSlistHandle = Interop.libcurl.SafeCurlSlistHandle; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage> { internal readonly CurlHandler _handler; internal readonly HttpRequestMessage _requestMessage; internal readonly CurlResponseMessage _responseMessage; internal readonly CancellationToken _cancellationToken; internal readonly HttpContentAsyncStream _requestContentStream; internal SafeCurlHandle _easyHandle; private SafeCurlSlistHandle _requestHeaders; internal NetworkCredential _networkCredential; internal MultiAgent _associatedMultiAgent; internal SendTransferState _sendTransferState; internal bool _isRedirect = false; public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) : base(TaskCreationOptions.RunContinuationsAsynchronously) { _handler = handler; _requestMessage = requestMessage; _cancellationToken = cancellationToken; if (requestMessage.Content != null) { _requestContentStream = new HttpContentAsyncStream(requestMessage.Content); } _responseMessage = new CurlResponseMessage(this); } /// <summary> /// Initialize the underlying libcurl support for this EasyRequest. /// This is separated out of the constructor so that we can take into account /// any additional configuration needed based on the request message /// after the EasyRequest is configured and so that error handling /// can be better handled in the caller. /// </summary> internal void InitializeCurl() { // Create the underlying easy handle SafeCurlHandle easyHandle = Interop.libcurl.curl_easy_init(); if (easyHandle.IsInvalid) { throw new OutOfMemoryException(); } _easyHandle = easyHandle; // Configure the handle SetUrl(); SetDebugging(); SetMultithreading(); SetRedirection(); SetVerb(); SetDecompressionOptions(); SetProxyOptions(_requestMessage.RequestUri); SetCredentialsOptions(_handler.GetNetworkCredentials(_handler._serverCredentials,_requestMessage.RequestUri)); SetCookieOption(_requestMessage.RequestUri); SetRequestHeaders(); } public void EnsureResponseMessagePublished() { bool result = TrySetResult(_responseMessage); Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion, "If the task was already completed, it should have been completed succesfully; " + "we shouldn't be completing as successful after already completing as failed."); } public void FailRequest(Exception error) { Debug.Assert(error != null, "Expected non-null exception"); var oce = error as OperationCanceledException; if (oce != null) { TrySetCanceled(oce.CancellationToken); } else { if (error is IOException || error is CurlException || error == null) { error = CreateHttpRequestException(error); } TrySetException(error); } // There's not much we can reasonably assert here about the result of TrySet*. // It's possible that the task wasn't yet completed (e.g. a failure while initiating the request), // it's possible that the task was already completed as success (e.g. a failure sending back the response), // and it's possible that the task was already completed as failure (e.g. we handled the exception and // faulted the task, but then tried to fault it again while finishing processing in the main loop). // Make sure the exception is available on the response stream so that it's propagated // from any attempts to read from the stream. _responseMessage.ResponseStream.SignalComplete(error); } public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up { _responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data // Don't dispose of the ResponseMessage.ResponseStream as it may still be in use // by code reading data stored in the stream. // Dispose of the input content stream if there was one. Nothing should be using it any more. if (_requestContentStream != null) _requestContentStream.Dispose(); // Dispose of the underlying easy handle. We're no longer processing it. if (_easyHandle != null) _easyHandle.Dispose(); // Dispose of the request headers if we had any. We had to keep this handle // alive as long as the easy handle was using it. We didn't need to do any // ref counting on the safe handle, though, as the only processing happens // in Process, which ensures the handle will be rooted while libcurl is // doing any processing that assumes it's valid. if (_requestHeaders != null) _requestHeaders.Dispose(); } private void SetUrl() { VerboseTrace(_requestMessage.RequestUri.AbsoluteUri); SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri); SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS); } [Conditional(VerboseDebuggingConditional)] private void SetDebugging() { SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L); // In addition to CURLOPT_VERBOSE, CURLOPT_DEBUGFUNCTION could be used here in the future to: // - Route the verbose output to somewhere other than stderr // - Dump additional data related to CURLINFO_DATA_* and CURLINFO_SSL_DATA_* } private void SetMultithreading() { SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L); } private void SetRedirection() { if (!_handler._automaticRedirection) { return; } VerboseTrace(_handler._maxAutomaticRedirections.ToString()); SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L); long redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ? CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, redirectProtocols); SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections); } private void SetVerb() { VerboseTrace(_requestMessage.Method.Method); if (_requestMessage.Method == HttpMethod.Put) { SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L); if (_requestMessage.Content == null) { SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L); } } else if (_requestMessage.Method == HttpMethod.Head) { SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L); } else if (_requestMessage.Method == HttpMethod.Post) { SetCurlOption(CURLoption.CURLOPT_POST, 1L); if (_requestMessage.Content == null) { SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L); SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty); } } } private void SetDecompressionOptions() { if (!_handler.SupportsAutomaticDecompression) { return; } DecompressionMethods autoDecompression = _handler.AutomaticDecompression; bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0; bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0; if (gzip || deflate) { string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate : gzip ? EncodingNameGzip : EncodingNameDeflate; SetCurlOption(CURLoption.CURLOPT_ACCEPTENCODING, encoding); VerboseTrace(encoding); } } internal void SetProxyOptions(Uri requestUri) { if (_handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy) { SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); VerboseTrace("No proxy"); return; } if ((_handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) || (_handler.Proxy == null)) { VerboseTrace("Default proxy"); return; } Debug.Assert(_handler.Proxy != null, "proxy is null"); Debug.Assert(_handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy, "_proxyPolicy is not UseCustomProxy"); if (_handler.Proxy.IsBypassed(requestUri)) { SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); VerboseTrace("Bypassed proxy"); return; } var proxyUri = _handler.Proxy.GetProxy(requestUri); if (proxyUri == null) { VerboseTrace("No proxy URI"); return; } SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, CURLProxyType.CURLPROXY_HTTP); SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri); SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port); VerboseTrace("Set proxy: " + proxyUri.ToString()); NetworkCredential credentials = GetCredentials(_handler.Proxy.Credentials, _requestMessage.RequestUri); if (credentials != null) { if (string.IsNullOrEmpty(credentials.UserName)) { throw new ArgumentException(SR.net_http_argument_empty_string, "UserName"); } string credentialText = string.IsNullOrEmpty(credentials.Domain) ? string.Format("{0}:{1}", credentials.UserName, credentials.Password) : string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain); SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText); VerboseTrace("Set proxy credentials"); } } internal void SetCredentialsOptions(NetworkCredential credentials) { if (credentials == null) { _networkCredential = null; return; } string userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format("{0}\\{1}", credentials.Domain, credentials.UserName); SetCurlOption(CURLoption.CURLOPT_USERNAME, userName); SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, CURLAUTH.AuthAny); if (credentials.Password != null) { SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password); } _networkCredential = credentials; VerboseTrace("Set credentials options"); } internal void SetCookieOption(Uri uri) { if (!_handler._useCookie) { return; } string cookieValues = _handler.CookieContainer.GetCookieHeader(uri); if (cookieValues != null) { SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues); VerboseTrace("Set cookies"); } } private void SetRequestHeaders() { HttpContentHeaders contentHeaders = null; if (_requestMessage.Content != null) { SetChunkedModeForSend(_requestMessage); // TODO: Content-Length header isn't getting correctly placed using ToString() // This is a bug in HttpContentHeaders that needs to be fixed. if (_requestMessage.Content.Headers.ContentLength.HasValue) { long contentLength = _requestMessage.Content.Headers.ContentLength.Value; _requestMessage.Content.Headers.ContentLength = null; _requestMessage.Content.Headers.ContentLength = contentLength; } contentHeaders = _requestMessage.Content.Headers; } var slist = new SafeCurlSlistHandle(); // Add request and content request headers if (_requestMessage.Headers != null) { AddRequestHeaders(_requestMessage.Headers, slist); } if (contentHeaders != null) { AddRequestHeaders(contentHeaders, slist); if (contentHeaders.ContentType == null) { if (!Interop.libcurl.curl_slist_append(slist, NoContentType)) { throw CreateHttpRequestException(); } } } // Since libcurl always adds a Transfer-Encoding header, we need to explicitly block // it if caller specifically does not want to set the header if (_requestMessage.Headers.TransferEncodingChunked.HasValue && !_requestMessage.Headers.TransferEncodingChunked.Value) { if (!Interop.libcurl.curl_slist_append(slist, NoTransferEncoding)) { throw CreateHttpRequestException(); } } if (!slist.IsInvalid) { _requestHeaders = slist; SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist); VerboseTrace("Set headers"); } else { slist.Dispose(); } } private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSlistHandle handle) { foreach (KeyValuePair<string, IEnumerable<string>> header in headers) { string headerStr = header.Key + ": " + headers.GetHeaderString(header.Key); if (!Interop.libcurl.curl_slist_append(handle, headerStr)) { throw CreateHttpRequestException(); } } } internal void SetCurlOption(int option, string value) { ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value)); } internal void SetCurlOption(int option, long value) { ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value)); } internal void SetCurlOption(int option, ulong value) { ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value)); } internal void SetCurlOption(int option, IntPtr value) { ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value)); } internal void SetCurlOption(int option, Delegate value) { ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value)); } internal void SetCurlOption(int option, SafeHandle value) { ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value)); } internal sealed class SendTransferState { internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow internal int _offset; internal int _count; internal Task<int> _task; internal void SetTaskOffsetCount(Task<int> task, int offset, int count) { Debug.Assert(offset >= 0, "Offset should never be negative"); Debug.Assert(count >= 0, "Count should never be negative"); Debug.Assert(offset <= count, "Offset should never be greater than count"); _task = task; _offset = offset; _count = count; } } [Conditional(VerboseDebuggingConditional)] private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null) { CurlHandler.VerboseTrace(text, memberName, easy: this, agent: null); } } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering.PostProcessing; namespace UnityEditor.Rendering.PostProcessing { [PostProcessEditor(typeof(ColorGrading))] public sealed class ColorGradingEditor : PostProcessEffectEditor<ColorGrading> { SerializedParameterOverride m_GradingMode; static GUIContent[] s_Curves = { new GUIContent("Master"), new GUIContent("Red"), new GUIContent("Green"), new GUIContent("Blue"), new GUIContent("Hue Vs Hue"), new GUIContent("Hue Vs Sat"), new GUIContent("Sat Vs Sat"), new GUIContent("Lum Vs Sat") }; SerializedParameterOverride m_ExternalLut; SerializedParameterOverride m_Tonemapper; SerializedParameterOverride m_ToneCurveToeStrength; SerializedParameterOverride m_ToneCurveToeLength; SerializedParameterOverride m_ToneCurveShoulderStrength; SerializedParameterOverride m_ToneCurveShoulderLength; SerializedParameterOverride m_ToneCurveShoulderAngle; SerializedParameterOverride m_ToneCurveGamma; SerializedParameterOverride m_LdrLut; SerializedParameterOverride m_Temperature; SerializedParameterOverride m_Tint; SerializedParameterOverride m_ColorFilter; SerializedParameterOverride m_HueShift; SerializedParameterOverride m_Saturation; SerializedParameterOverride m_Brightness; SerializedParameterOverride m_PostExposure; SerializedParameterOverride m_Contrast; SerializedParameterOverride m_MixerRedOutRedIn; SerializedParameterOverride m_MixerRedOutGreenIn; SerializedParameterOverride m_MixerRedOutBlueIn; SerializedParameterOverride m_MixerGreenOutRedIn; SerializedParameterOverride m_MixerGreenOutGreenIn; SerializedParameterOverride m_MixerGreenOutBlueIn; SerializedParameterOverride m_MixerBlueOutRedIn; SerializedParameterOverride m_MixerBlueOutGreenIn; SerializedParameterOverride m_MixerBlueOutBlueIn; SerializedParameterOverride m_Lift; SerializedParameterOverride m_Gamma; SerializedParameterOverride m_Gain; SerializedParameterOverride m_MasterCurve; SerializedParameterOverride m_RedCurve; SerializedParameterOverride m_GreenCurve; SerializedParameterOverride m_BlueCurve; SerializedParameterOverride m_HueVsHueCurve; SerializedParameterOverride m_HueVsSatCurve; SerializedParameterOverride m_SatVsSatCurve; SerializedParameterOverride m_LumVsSatCurve; // Internal references to the actual animation curves // Needed for the curve editor SerializedProperty m_RawMasterCurve; SerializedProperty m_RawRedCurve; SerializedProperty m_RawGreenCurve; SerializedProperty m_RawBlueCurve; SerializedProperty m_RawHueVsHueCurve; SerializedProperty m_RawHueVsSatCurve; SerializedProperty m_RawSatVsSatCurve; SerializedProperty m_RawLumVsSatCurve; CurveEditor m_CurveEditor; Dictionary<SerializedProperty, Color> m_CurveDict; // Custom tone curve drawing const int k_CustomToneCurveResolution = 48; const float k_CustomToneCurveRangeY = 1.025f; readonly Vector3[] m_RectVertices = new Vector3[4]; readonly Vector3[] m_LineVertices = new Vector3[2]; readonly Vector3[] m_CurveVertices = new Vector3[k_CustomToneCurveResolution]; Rect m_CustomToneCurveRect; readonly HableCurve m_HableCurve = new HableCurve(); public override void OnEnable() { m_GradingMode = FindParameterOverride(x => x.gradingMode); m_ExternalLut = FindParameterOverride(x => x.externalLut); m_Tonemapper = FindParameterOverride(x => x.tonemapper); m_ToneCurveToeStrength = FindParameterOverride(x => x.toneCurveToeStrength); m_ToneCurveToeLength = FindParameterOverride(x => x.toneCurveToeLength); m_ToneCurveShoulderStrength = FindParameterOverride(x => x.toneCurveShoulderStrength); m_ToneCurveShoulderLength = FindParameterOverride(x => x.toneCurveShoulderLength); m_ToneCurveShoulderAngle = FindParameterOverride(x => x.toneCurveShoulderAngle); m_ToneCurveGamma = FindParameterOverride(x => x.toneCurveGamma); m_LdrLut = FindParameterOverride(x => x.ldrLut); m_Temperature = FindParameterOverride(x => x.temperature); m_Tint = FindParameterOverride(x => x.tint); m_ColorFilter = FindParameterOverride(x => x.colorFilter); m_HueShift = FindParameterOverride(x => x.hueShift); m_Saturation = FindParameterOverride(x => x.saturation); m_Brightness = FindParameterOverride(x => x.brightness); m_PostExposure = FindParameterOverride(x => x.postExposure); m_Contrast = FindParameterOverride(x => x.contrast); m_MixerRedOutRedIn = FindParameterOverride(x => x.mixerRedOutRedIn); m_MixerRedOutGreenIn = FindParameterOverride(x => x.mixerRedOutGreenIn); m_MixerRedOutBlueIn = FindParameterOverride(x => x.mixerRedOutBlueIn); m_MixerGreenOutRedIn = FindParameterOverride(x => x.mixerGreenOutRedIn); m_MixerGreenOutGreenIn = FindParameterOverride(x => x.mixerGreenOutGreenIn); m_MixerGreenOutBlueIn = FindParameterOverride(x => x.mixerGreenOutBlueIn); m_MixerBlueOutRedIn = FindParameterOverride(x => x.mixerBlueOutRedIn); m_MixerBlueOutGreenIn = FindParameterOverride(x => x.mixerBlueOutGreenIn); m_MixerBlueOutBlueIn = FindParameterOverride(x => x.mixerBlueOutBlueIn); m_Lift = FindParameterOverride(x => x.lift); m_Gamma = FindParameterOverride(x => x.gamma); m_Gain = FindParameterOverride(x => x.gain); m_MasterCurve = FindParameterOverride(x => x.masterCurve); m_RedCurve = FindParameterOverride(x => x.redCurve); m_GreenCurve = FindParameterOverride(x => x.greenCurve); m_BlueCurve = FindParameterOverride(x => x.blueCurve); m_HueVsHueCurve = FindParameterOverride(x => x.hueVsHueCurve); m_HueVsSatCurve = FindParameterOverride(x => x.hueVsSatCurve); m_SatVsSatCurve = FindParameterOverride(x => x.satVsSatCurve); m_LumVsSatCurve = FindParameterOverride(x => x.lumVsSatCurve); m_RawMasterCurve = FindProperty(x => x.masterCurve.value.curve); m_RawRedCurve = FindProperty(x => x.redCurve.value.curve); m_RawGreenCurve = FindProperty(x => x.greenCurve.value.curve); m_RawBlueCurve = FindProperty(x => x.blueCurve.value.curve); m_RawHueVsHueCurve = FindProperty(x => x.hueVsHueCurve.value.curve); m_RawHueVsSatCurve = FindProperty(x => x.hueVsSatCurve.value.curve); m_RawSatVsSatCurve = FindProperty(x => x.satVsSatCurve.value.curve); m_RawLumVsSatCurve = FindProperty(x => x.lumVsSatCurve.value.curve); m_CurveEditor = new CurveEditor(); m_CurveDict = new Dictionary<SerializedProperty, Color>(); // Prepare the curve editor SetupCurve(m_RawMasterCurve, new Color(1f, 1f, 1f), 2, false); SetupCurve(m_RawRedCurve, new Color(1f, 0f, 0f), 2, false); SetupCurve(m_RawGreenCurve, new Color(0f, 1f, 0f), 2, false); SetupCurve(m_RawBlueCurve, new Color(0f, 0.5f, 1f), 2, false); SetupCurve(m_RawHueVsHueCurve, new Color(1f, 1f, 1f), 0, true); SetupCurve(m_RawHueVsSatCurve, new Color(1f, 1f, 1f), 0, true); SetupCurve(m_RawSatVsSatCurve, new Color(1f, 1f, 1f), 0, false); SetupCurve(m_RawLumVsSatCurve, new Color(1f, 1f, 1f), 0, false); } public override void OnInspectorGUI() { PropertyField(m_GradingMode); var gradingMode = (GradingMode)m_GradingMode.value.intValue; // Check if we're in gamma or linear and display a warning if we're trying to do hdr // color grading while being in gamma mode if (gradingMode != GradingMode.LowDefinitionRange) { if (QualitySettings.activeColorSpace == ColorSpace.Gamma) EditorGUILayout.HelpBox("ColorSpace in project settings is set to Gamma, HDR color grading won't look correct. Switch to Linear or use LDR color grading mode instead.", MessageType.Warning); if (m_GradingMode.overrideState.boolValue) { if (!SystemInfo.supports3DRenderTextures || !SystemInfo.supportsComputeShaders) EditorGUILayout.HelpBox("HDR color grading requires compute shader & 3D render texture support.", MessageType.Warning); } } if (gradingMode == GradingMode.LowDefinitionRange) DoStandardModeGUI(false); else if (gradingMode == GradingMode.HighDefinitionRange) DoStandardModeGUI(true); else if (gradingMode == GradingMode.External) DoExternalModeGUI(); EditorGUILayout.Space(); } void SetupCurve(SerializedProperty prop, Color color, uint minPointCount, bool loop) { var state = CurveEditor.CurveState.defaultState; state.color = color; state.visible = false; state.minPointCount = minPointCount; state.onlyShowHandlesOnSelection = true; state.zeroKeyConstantValue = 0.5f; state.loopInBounds = loop; m_CurveEditor.Add(prop, state); m_CurveDict.Add(prop, color); } void DoExternalModeGUI() { PropertyField(m_ExternalLut); } void DoStandardModeGUI(bool hdr) { if (!hdr) { PropertyField(m_LdrLut); var lut = (target as ColorGrading).ldrLut.value; CheckLutImportSettings(lut); } if (hdr) { EditorGUILayout.Space(); EditorUtilities.DrawHeaderLabel("Tonemapping"); PropertyField(m_Tonemapper); if (m_Tonemapper.value.intValue == (int)Tonemapper.Custom) { DrawCustomToneCurve(); PropertyField(m_ToneCurveToeStrength); PropertyField(m_ToneCurveToeLength); PropertyField(m_ToneCurveShoulderStrength); PropertyField(m_ToneCurveShoulderLength); PropertyField(m_ToneCurveShoulderAngle); PropertyField(m_ToneCurveGamma); } } EditorGUILayout.Space(); EditorUtilities.DrawHeaderLabel("White Balance"); PropertyField(m_Temperature); PropertyField(m_Tint); EditorGUILayout.Space(); EditorUtilities.DrawHeaderLabel("Tone"); if (hdr) PropertyField(m_PostExposure); PropertyField(m_ColorFilter); PropertyField(m_HueShift); PropertyField(m_Saturation); if (!hdr) PropertyField(m_Brightness); PropertyField(m_Contrast); EditorGUILayout.Space(); int currentChannel = GlobalSettings.currentChannelMixer; using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel("Channel Mixer", GUIStyle.none, Styling.labelHeader); EditorGUI.BeginChangeCheck(); { using (new EditorGUILayout.HorizontalScope()) { GUILayoutUtility.GetRect(9f, 18f, GUILayout.ExpandWidth(false)); // Dirty hack to do proper right column alignement if (GUILayout.Toggle(currentChannel == 0, EditorUtilities.GetContent("Red|Red output channel."), EditorStyles.miniButtonLeft)) currentChannel = 0; if (GUILayout.Toggle(currentChannel == 1, EditorUtilities.GetContent("Green|Green output channel."), EditorStyles.miniButtonMid)) currentChannel = 1; if (GUILayout.Toggle(currentChannel == 2, EditorUtilities.GetContent("Blue|Blue output channel."), EditorStyles.miniButtonRight)) currentChannel = 2; } } if (EditorGUI.EndChangeCheck()) GUI.FocusControl(null); } GlobalSettings.currentChannelMixer = currentChannel; if (currentChannel == 0) { PropertyField(m_MixerRedOutRedIn); PropertyField(m_MixerRedOutGreenIn); PropertyField(m_MixerRedOutBlueIn); } else if (currentChannel == 1) { PropertyField(m_MixerGreenOutRedIn); PropertyField(m_MixerGreenOutGreenIn); PropertyField(m_MixerGreenOutBlueIn); } else { PropertyField(m_MixerBlueOutRedIn); PropertyField(m_MixerBlueOutGreenIn); PropertyField(m_MixerBlueOutBlueIn); } EditorGUILayout.Space(); EditorUtilities.DrawHeaderLabel("Trackballs"); using (new EditorGUILayout.HorizontalScope()) { PropertyField(m_Lift); GUILayout.Space(4f); PropertyField(m_Gamma); GUILayout.Space(4f); PropertyField(m_Gain); } EditorGUILayout.Space(); EditorUtilities.DrawHeaderLabel("Grading Curves"); DoCurvesGUI(hdr); } void CheckLutImportSettings(Texture lut) { if (lut != null) { var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(lut)) as TextureImporter; // Fails when using an internal texture as you can't change import settings on // builtin resources, thus the check for null if (importer != null) { bool valid = importer.anisoLevel == 0 && importer.mipmapEnabled == false && importer.sRGBTexture == false && importer.textureCompression == TextureImporterCompression.Uncompressed && importer.wrapMode == TextureWrapMode.Clamp; if (!valid) EditorUtilities.DrawFixMeBox("Invalid LUT import settings.", () => SetLutImportSettings(importer)); } } } void SetLutImportSettings(TextureImporter importer) { importer.textureType = TextureImporterType.Default; importer.mipmapEnabled = false; importer.anisoLevel = 0; importer.sRGBTexture = false; importer.npotScale = TextureImporterNPOTScale.None; importer.textureCompression = TextureImporterCompression.Uncompressed; importer.alphaSource = TextureImporterAlphaSource.None; importer.wrapMode = TextureWrapMode.Clamp; importer.SaveAndReimport(); AssetDatabase.Refresh(); } void DrawCustomToneCurve() { EditorGUILayout.Space(); // Reserve GUI space using (new GUILayout.HorizontalScope()) { GUILayout.Space(EditorGUI.indentLevel * 15f); m_CustomToneCurveRect = GUILayoutUtility.GetRect(128, 80); } if (Event.current.type != EventType.Repaint) return; // Prepare curve data float toeStrength = m_ToneCurveToeStrength.value.floatValue; float toeLength = m_ToneCurveToeLength.value.floatValue; float shoulderStrength = m_ToneCurveShoulderStrength.value.floatValue; float shoulderLength = m_ToneCurveShoulderLength.value.floatValue; float shoulderAngle = m_ToneCurveShoulderAngle.value.floatValue; float gamma = m_ToneCurveGamma.value.floatValue; m_HableCurve.Init( toeStrength, toeLength, shoulderStrength, shoulderLength, shoulderAngle, gamma ); float endPoint = m_HableCurve.whitePoint; // Background m_RectVertices[0] = PointInRect(0f, 0f, endPoint); m_RectVertices[1] = PointInRect(endPoint, 0f, endPoint); m_RectVertices[2] = PointInRect(endPoint, k_CustomToneCurveRangeY, endPoint); m_RectVertices[3] = PointInRect(0f, k_CustomToneCurveRangeY, endPoint); Handles.DrawSolidRectangleWithOutline(m_RectVertices, Color.white * 0.1f, Color.white * 0.4f); // Vertical guides if (endPoint < m_CustomToneCurveRect.width / 3) { int steps = Mathf.CeilToInt(endPoint); for (var i = 1; i < steps; i++) DrawLine(i, 0, i, k_CustomToneCurveRangeY, 0.4f, endPoint); } // Label Handles.Label(m_CustomToneCurveRect.position + Vector2.right, "Custom Tone Curve", EditorStyles.miniLabel); // Draw the acual curve var vcount = 0; while (vcount < k_CustomToneCurveResolution) { float x = endPoint * vcount / (k_CustomToneCurveResolution - 1); float y = m_HableCurve.Eval(x); if (y < k_CustomToneCurveRangeY) { m_CurveVertices[vcount++] = PointInRect(x, y, endPoint); } else { if (vcount > 1) { // Extend the last segment to the top edge of the rect. var v1 = m_CurveVertices[vcount - 2]; var v2 = m_CurveVertices[vcount - 1]; var clip = (m_CustomToneCurveRect.y - v1.y) / (v2.y - v1.y); m_CurveVertices[vcount - 1] = v1 + (v2 - v1) * clip; } break; } } if (vcount > 1) { Handles.color = Color.white * 0.9f; Handles.DrawAAPolyLine(2f, vcount, m_CurveVertices); } } void DrawLine(float x1, float y1, float x2, float y2, float grayscale, float rangeX) { m_LineVertices[0] = PointInRect(x1, y1, rangeX); m_LineVertices[1] = PointInRect(x2, y2, rangeX); Handles.color = Color.white * grayscale; Handles.DrawAAPolyLine(2f, m_LineVertices); } Vector3 PointInRect(float x, float y, float rangeX) { x = Mathf.Lerp(m_CustomToneCurveRect.x, m_CustomToneCurveRect.xMax, x / rangeX); y = Mathf.Lerp(m_CustomToneCurveRect.yMax, m_CustomToneCurveRect.y, y / k_CustomToneCurveRangeY); return new Vector3(x, y, 0); } void ResetVisibleCurves() { foreach (var curve in m_CurveDict) { var state = m_CurveEditor.GetCurveState(curve.Key); state.visible = false; m_CurveEditor.SetCurveState(curve.Key, state); } } void SetCurveVisible(SerializedProperty rawProp, SerializedProperty overrideProp) { var state = m_CurveEditor.GetCurveState(rawProp); state.visible = true; state.editable = overrideProp.boolValue; m_CurveEditor.SetCurveState(rawProp, state); } void CurveOverrideToggle(SerializedProperty overrideProp) { overrideProp.boolValue = GUILayout.Toggle(overrideProp.boolValue, EditorUtilities.GetContent("Override"), EditorStyles.toolbarButton); } static Material s_MaterialGrid; void DoCurvesGUI(bool hdr) { EditorGUILayout.Space(); ResetVisibleCurves(); using (new EditorGUI.DisabledGroupScope(serializedObject.isEditingMultipleObjects)) { int curveEditingId = 0; SerializedProperty currentCurveRawProp = null; // Top toolbar using (new GUILayout.HorizontalScope(EditorStyles.toolbar)) { curveEditingId = DoCurveSelectionPopup(GlobalSettings.currentCurve, hdr); curveEditingId = Mathf.Clamp(curveEditingId, hdr ? 4 : 0, 7); EditorGUILayout.Space(); switch (curveEditingId) { case 0: CurveOverrideToggle(m_MasterCurve.overrideState); SetCurveVisible(m_RawMasterCurve, m_MasterCurve.overrideState); currentCurveRawProp = m_RawMasterCurve; break; case 1: CurveOverrideToggle(m_RedCurve.overrideState); SetCurveVisible(m_RawRedCurve, m_RedCurve.overrideState); currentCurveRawProp = m_RawRedCurve; break; case 2: CurveOverrideToggle(m_GreenCurve.overrideState); SetCurveVisible(m_RawGreenCurve, m_GreenCurve.overrideState); currentCurveRawProp = m_RawGreenCurve; break; case 3: CurveOverrideToggle(m_BlueCurve.overrideState); SetCurveVisible(m_RawBlueCurve, m_BlueCurve.overrideState); currentCurveRawProp = m_RawBlueCurve; break; case 4: CurveOverrideToggle(m_HueVsHueCurve.overrideState); SetCurveVisible(m_RawHueVsHueCurve, m_HueVsHueCurve.overrideState); currentCurveRawProp = m_RawHueVsHueCurve; break; case 5: CurveOverrideToggle(m_HueVsSatCurve.overrideState); SetCurveVisible(m_RawHueVsSatCurve, m_HueVsSatCurve.overrideState); currentCurveRawProp = m_RawHueVsSatCurve; break; case 6: CurveOverrideToggle(m_SatVsSatCurve.overrideState); SetCurveVisible(m_RawSatVsSatCurve, m_SatVsSatCurve.overrideState); currentCurveRawProp = m_RawSatVsSatCurve; break; case 7: CurveOverrideToggle(m_LumVsSatCurve.overrideState); SetCurveVisible(m_RawLumVsSatCurve, m_LumVsSatCurve.overrideState); currentCurveRawProp = m_RawLumVsSatCurve; break; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Reset", EditorStyles.toolbarButton)) { switch (curveEditingId) { case 0: m_RawMasterCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); break; case 1: m_RawRedCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); break; case 2: m_RawGreenCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); break; case 3: m_RawBlueCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); break; case 4: m_RawHueVsHueCurve.animationCurveValue = new AnimationCurve(); break; case 5: m_RawHueVsSatCurve.animationCurveValue = new AnimationCurve(); break; case 6: m_RawSatVsSatCurve.animationCurveValue = new AnimationCurve(); break; case 7: m_RawLumVsSatCurve.animationCurveValue = new AnimationCurve(); break; } } GlobalSettings.currentCurve = curveEditingId; } // Curve area var settings = m_CurveEditor.settings; var rect = GUILayoutUtility.GetAspectRect(2f); var innerRect = settings.padding.Remove(rect); if (Event.current.type == EventType.Repaint) { // Background EditorGUI.DrawRect(rect, new Color(0.15f, 0.15f, 0.15f, 1f)); if (curveEditingId == 4 || curveEditingId == 5) DrawBackgroundTexture(innerRect, 0); else if (curveEditingId == 6 || curveEditingId == 7) DrawBackgroundTexture(innerRect, 1); // Bounds Handles.color = Color.white * (GUI.enabled ? 1f : 0.5f); Handles.DrawSolidRectangleWithOutline(innerRect, Color.clear, new Color(0.8f, 0.8f, 0.8f, 0.5f)); // Grid setup Handles.color = new Color(1f, 1f, 1f, 0.05f); int hLines = (int)Mathf.Sqrt(innerRect.width); int vLines = (int)(hLines / (innerRect.width / innerRect.height)); // Vertical grid int gridOffset = Mathf.FloorToInt(innerRect.width / hLines); int gridPadding = ((int)(innerRect.width) % hLines) / 2; for (int i = 1; i < hLines; i++) { var offset = i * Vector2.right * gridOffset; offset.x += gridPadding; Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.x, innerRect.yMax - 1) + offset); } // Horizontal grid gridOffset = Mathf.FloorToInt(innerRect.height / vLines); gridPadding = ((int)(innerRect.height) % vLines) / 2; for (int i = 1; i < vLines; i++) { var offset = i * Vector2.up * gridOffset; offset.y += gridPadding; Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.xMax - 1, innerRect.y) + offset); } } // Curve editor if (m_CurveEditor.OnGUI(rect)) { Repaint(); GUI.changed = true; } if (Event.current.type == EventType.Repaint) { // Borders Handles.color = Color.black; Handles.DrawLine(new Vector2(rect.x, rect.y - 18f), new Vector2(rect.xMax, rect.y - 18f)); Handles.DrawLine(new Vector2(rect.x, rect.y - 19f), new Vector2(rect.x, rect.yMax)); Handles.DrawLine(new Vector2(rect.x, rect.yMax), new Vector2(rect.xMax, rect.yMax)); Handles.DrawLine(new Vector2(rect.xMax, rect.yMax), new Vector2(rect.xMax, rect.y - 18f)); bool editable = m_CurveEditor.GetCurveState(currentCurveRawProp).editable; string editableString = editable ? string.Empty : "(Not Overriding)\n"; // Selection info var selection = m_CurveEditor.GetSelection(); var infoRect = innerRect; infoRect.x += 5f; infoRect.width = 100f; infoRect.height = 30f; if (selection.curve != null && selection.keyframeIndex > -1) { var key = selection.keyframe.Value; GUI.Label(infoRect, string.Format("{0}\n{1}", key.time.ToString("F3"), key.value.ToString("F3")), Styling.preLabel); } else { GUI.Label(infoRect, editableString, Styling.preLabel); } } } } void DrawBackgroundTexture(Rect rect, int pass) { if (s_MaterialGrid == null) s_MaterialGrid = new Material(Shader.Find("Hidden/PostProcessing/Editor/CurveGrid")) { hideFlags = HideFlags.HideAndDontSave }; float scale = EditorGUIUtility.pixelsPerPoint; var oldRt = RenderTexture.active; var rt = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); s_MaterialGrid.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f); s_MaterialGrid.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint); Graphics.Blit(null, rt, s_MaterialGrid, pass); RenderTexture.active = oldRt; GUI.DrawTexture(rect, rt); RenderTexture.ReleaseTemporary(rt); } int DoCurveSelectionPopup(int id, bool hdr) { GUILayout.Label(s_Curves[id], EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f)); var lastRect = GUILayoutUtility.GetLastRect(); var e = Event.current; if (e.type == EventType.MouseDown && e.button == 0 && lastRect.Contains(e.mousePosition)) { var menu = new GenericMenu(); for (int i = 0; i < s_Curves.Length; i++) { if (i == 4) menu.AddSeparator(""); if (hdr && i < 4) menu.AddDisabledItem(s_Curves[i]); else { int current = i; // Capture local for closure menu.AddItem(s_Curves[i], current == id, () => GlobalSettings.currentCurve = current); } } menu.DropDown(new Rect(lastRect.xMin, lastRect.yMax, 1f, 1f)); } return id; } } }
using System; using System.Linq; using Typewriter.TemplateEditor.Lexing.Braces; using Typewriter.TemplateEditor.Lexing.Contexts; using Typewriter.TemplateEditor.Lexing.Identifiers; using Typewriter.TemplateEditor.Lexing.Scopes; using Typewriter.TemplateEditor.Lexing.Tokens; namespace Typewriter.TemplateEditor.Lexing { public class Lexer { private static readonly char[] whitespaceChars = { ' ', '\t', '\r', '\n', '\f' }; private readonly string[] keywords = { "class", "module", "private", "public", "export", "if", "else" }; public TokenList Tokenize(string template) { //var x = ClassificationRegistry.GetClassificationType(Constants.KeywordClassificationType); var stream = new TemplateStream(template); var tokens = new TokenList(); var context = new ContextStack(tokens); var scope = new ScopeStack(); var brace = new BraceStack(); while (true) { if (ParseComment(stream, tokens, context)) continue; if (ParseDollar(stream, tokens, context, scope)) continue; if (ParseStatement(stream, tokens, context, scope)) continue; if (ParseFilter(stream, tokens, context, scope)) continue; if (ParseOther(stream, tokens, context, scope, brace)) continue; if (stream.Advance() == false) break; } context.Clear(stream.Position); return tokens; } private bool ParseComment(TemplateStream stream, TokenList tokens, ContextStack context) { if (stream.Current != '/' || stream.Peek() != '/') return false; var start = stream.Position; var line = stream.Line; while (stream.Advance()) { if (stream.Peek() == '\r') { stream.Advance(); break; } } tokens.Add(new Token(start, stream.Position - start, line, TokenType.Comment, context.Current)); return true; } private bool ParseDollar(TemplateStream stream, TokenList tokens, ContextStack context, ScopeStack scope) { if (stream.Current != '$' || scope.Current == Scope.Block) return false; var next = stream.Peek(); if (next == '$') { stream.Advance(2); return true; } if (char.IsLetter(next)) { scope.Push(Scope.Statement); stream.Advance(); return true; } if (next == '{') { scope.Push(Scope.Block); stream.Advance(); return true; } return false; } private bool ParseStatement(TemplateStream stream, TokenList tokens, ContextStack context, ScopeStack scope) { if (scope.Current == Scope.Statement) { scope.Pop(); } else if (scope.Current == Scope.Block) { var previous = stream.Peek(-1); if (previous == '$' || char.IsLetterOrDigit(previous)) return false; } else { return false; } var name = stream.PeekWord(); var identifier = context.Current.GetIdentifier(name); if (identifier != null) { tokens.Add(new Token(stream.Position, name.Length, stream.Line, TokenType.Identifier, context.Current, identifier.QuickInfo)); stream.Advance(name.Length); if (identifier.Type == IdentifierType.Indexed) { if (stream.Current == '(') scope.Push(Scope.Filter); if (stream.Current == '[') { scope.Push(Scope.Template); context.Push(name, stream.Position); } } else if (identifier.Type == IdentifierType.Boolean) { if (stream.Current == '[') scope.Push(Scope.True); } return true; } return false; } private bool ParseFilter(TemplateStream stream, TokenList tokens, ContextStack context, ScopeStack scope) { //if (scope.Current != Scope.Filter) return false; //scope.Pop(); //tokens.Add(new Token(stream.Position, 1, TokenType.OpenFunctionBrace, context.Current)); //while (stream.Current != ')') // if (stream.Advance() == false) return true; //tokens.Add(new Token(stream.Position, 1, TokenType.CloseFunctionBrace, context.Current)); //stream.Advance(); //if (stream.Current == '[') scope.Push(Scope.Template); //return true; return false; } private bool ParseOther(TemplateStream stream, TokenList tokens, ContextStack context, ScopeStack scope, BraceStack brace) { switch (stream.Current) { case '[': brace.Push(tokens.Add(new Token(stream.Position, 1, stream.Line, TokenType.OpenBrace, context.Current)), scope.Changed); stream.Advance(); return true; case ']': var openBrace = brace.Pop(TokenType.OpenBrace); var token = tokens.Add(new Token(stream.Position, 1, stream.Line, TokenType.CloseBrace, context.Current, null, openBrace.Token)); if (openBrace.Token != null) { openBrace.Token.MatchingToken = token; } stream.Advance(); if (openBrace.ScopeChanged) { var current = scope.Pop(); if (current == Scope.Template) { context.Pop(stream.Position); if (stream.Current == '[') scope.Push(Scope.Separator); } else if (current == Scope.True) { context.Pop(stream.Position); if (stream.Current == '[') scope.Push(Scope.False); } } return true; case '{': //tokens.Add(new Token(stream.Position - 1, 2, TokenType.OpenBlock, context.Current)); brace.Push(tokens.Add(new Token(stream.Position, 1, stream.Line, TokenType.OpenCurlyBrace, context.Current)), scope.Changed); stream.Advance(); return true; case '}': var openCurlyBrace = brace.Pop(TokenType.OpenCurlyBrace); token = tokens.Add(new Token(stream.Position, 1, stream.Line, TokenType.CloseCurlyBrace, context.Current, null, openCurlyBrace.Token)); if (openCurlyBrace.Token != null) { openCurlyBrace.Token.MatchingToken = token; } //tokens.Add(new Token(stream.Position, 1, TokenType.CloseBlock, context.Current)); stream.Advance(); if (openCurlyBrace.ScopeChanged) { scope.Pop(); } return true; case '(': brace.Push(tokens.Add(new Token(stream.Position, 1, stream.Line, TokenType.OpenFunctionBrace, context.Current)), scope.Changed); stream.Advance(); return true; case ')': var openFunctionBrace = brace.Pop(TokenType.OpenFunctionBrace); token = tokens.Add(new Token(stream.Position, 1, stream.Line, TokenType.CloseFunctionBrace, context.Current, null, openFunctionBrace.Token)); if (openFunctionBrace.Token != null) { openFunctionBrace.Token.MatchingToken = token; } stream.Advance(); if (openFunctionBrace.ScopeChanged) { scope.Pop(); } return true; } if (scope.Current == Scope.Block) return false; var name = stream.PeekWord(); if (name == null) return false; if (keywords.Contains(name)) { tokens.Add(new Token(stream.Position, name.Length, stream.Line, TokenType.Keyword, context.Current)); } stream.Advance(name.Length); return true; } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 Service Stack LLC. All Rights Reserved. // // Licensed under the same terms of ServiceStack. // using System; using System.Globalization; using System.IO; using System.Net; using System.Text; using ServiceStack.Text.Common; using ServiceStack.Text.Json; namespace ServiceStack.Text { /// <summary> /// Creates an instance of a Type from a string value /// </summary> public static class JsonSerializer { private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false); public static T DeserializeFromString<T>(string value) { if (string.IsNullOrEmpty(value)) return default(T); return (T)JsonReader<T>.Parse(value); } public static T DeserializeFromReader<T>(TextReader reader) { return DeserializeFromString<T>(reader.ReadToEnd()); } public static object DeserializeFromString(string value, Type type) { return string.IsNullOrEmpty(value) ? null : JsonReader.GetParseFn(type)(value); } public static object DeserializeFromReader(TextReader reader, Type type) { return DeserializeFromString(reader.ReadToEnd(), type); } [ThreadStatic] //Reuse the thread static StringBuilder when serializing to strings private static StringBuilderWriter LastWriter; internal class StringBuilderWriter : IDisposable { protected StringBuilder sb; protected StringWriter writer; public StringWriter Writer { get { return writer; } } public StringBuilderWriter() { this.sb = new StringBuilder(); this.writer = new StringWriter(sb, CultureInfo.InvariantCulture); } public static StringBuilderWriter Create() { var ret = LastWriter; if (JsConfig.ReuseStringBuffer && ret != null) { LastWriter = null; ret.sb.Clear(); return ret; } return new StringBuilderWriter(); } public override string ToString() { return sb.ToString(); } public void Dispose() { if (JsConfig.ReuseStringBuffer) { LastWriter = this; } else { Writer.Dispose(); } } } public static string SerializeToString<T>(T value) { if (value == null || value is Delegate) return null; if (typeof(T) == typeof(object)) { return SerializeToString(value, value.GetType()); } if (typeof(T).IsAbstract() || typeof(T).IsInterface()) { JsState.IsWritingDynamic = true; var result = SerializeToString(value, value.GetType()); JsState.IsWritingDynamic = false; return result; } using (var sb = StringBuilderWriter.Create()) { if (typeof(T) == typeof(string)) { JsonUtils.WriteString(sb.Writer, value as string); } else { JsonWriter<T>.WriteRootObject(sb.Writer, value); } return sb.ToString(); } } public static string SerializeToString(object value, Type type) { if (value == null) return null; using (var sb = StringBuilderWriter.Create()) { if (type == typeof(string)) { JsonUtils.WriteString(sb.Writer, value as string); } else { JsonWriter.GetWriteFn(type)(sb.Writer, value); } return sb.ToString(); } } public static void SerializeToWriter<T>(T value, TextWriter writer) { if (value == null) return; if (typeof(T) == typeof(string)) { writer.Write(value); } else if (typeof(T) == typeof(object)) { SerializeToWriter(value, value.GetType(), writer); } else if (typeof(T).IsAbstract() || typeof(T).IsInterface()) { JsState.IsWritingDynamic = false; SerializeToWriter(value, value.GetType(), writer); JsState.IsWritingDynamic = true; } else { JsonWriter<T>.WriteRootObject(writer, value); } } public static void SerializeToWriter(object value, Type type, TextWriter writer) { if (value == null) return; if (type == typeof(string)) { writer.Write(value); return; } JsonWriter.GetWriteFn(type)(writer, value); } public static void SerializeToStream<T>(T value, Stream stream) { if (value == null) return; if (typeof(T) == typeof(object)) { SerializeToStream(value, value.GetType(), stream); } else if (typeof(T).IsAbstract() || typeof(T).IsInterface()) { JsState.IsWritingDynamic = false; SerializeToStream(value, value.GetType(), stream); JsState.IsWritingDynamic = true; } else { var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsonWriter<T>.WriteRootObject(writer, value); writer.Flush(); } } public static void SerializeToStream(object value, Type type, Stream stream) { var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsonWriter.GetWriteFn(type)(writer, value); writer.Flush(); } public static T DeserializeFromStream<T>(Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString<T>(reader.ReadToEnd()); } } public static object DeserializeFromStream(Type type, Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString(reader.ReadToEnd(), type); } } public static T DeserializeResponse<T>(WebRequest webRequest) { using (var webRes = PclExport.Instance.GetResponse(webRequest)) { using (var stream = webRes.GetResponseStream()) { return DeserializeFromStream<T>(stream); } } } public static object DeserializeResponse<T>(Type type, WebRequest webRequest) { using (var webRes = PclExport.Instance.GetResponse(webRequest)) { using (var stream = webRes.GetResponseStream()) { return DeserializeFromStream(type, stream); } } } public static T DeserializeRequest<T>(WebRequest webRequest) { using (var webRes = PclExport.Instance.GetResponse(webRequest)) { return DeserializeResponse<T>(webRes); } } public static object DeserializeRequest(Type type, WebRequest webRequest) { using (var webRes = PclExport.Instance.GetResponse(webRequest)) { return DeserializeResponse(type, webRes); } } public static T DeserializeResponse<T>(WebResponse webResponse) { using (var stream = webResponse.GetResponseStream()) { return DeserializeFromStream<T>(stream); } } public static object DeserializeResponse(Type type, WebResponse webResponse) { using (var stream = webResponse.GetResponseStream()) { return DeserializeFromStream(type, stream); } } } public class JsonStringSerializer : IStringSerializer { public To DeserializeFromString<To>(string serializedText) { return JsonSerializer.DeserializeFromString<To>(serializedText); } public object DeserializeFromString(string serializedText, Type type) { return JsonSerializer.DeserializeFromString(serializedText, type); } public string SerializeToString<TFrom>(TFrom @from) { return JsonSerializer.SerializeToString(@from); } } }
// 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.Reflection.Internal; namespace System.Reflection.Metadata.Ecma335 { internal struct DocumentTableReader { internal readonly int NumberOfRows; private readonly bool _isGuidHeapRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int NameOffset = 0; private readonly int _hashAlgorithmOffset; private readonly int _hashOffset; private readonly int _languageOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal DocumentTableReader( int numberOfRows, int guidHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isGuidHeapRefSizeSmall = guidHeapRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _hashAlgorithmOffset = NameOffset + blobHeapRefSize; _hashOffset = _hashAlgorithmOffset + guidHeapRefSize; _languageOffset = _hashOffset + blobHeapRefSize; RowSize = _languageOffset + guidHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal DocumentNameBlobHandle GetName(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return DocumentNameBlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + NameOffset, _isBlobHeapRefSizeSmall)); } internal GuidHandle GetHashAlgorithm(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return GuidHandle.FromIndex(Block.PeekHeapReference(rowOffset + _hashAlgorithmOffset, _isGuidHeapRefSizeSmall)); } internal BlobHandle GetHash(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _hashOffset, _isBlobHeapRefSizeSmall)); } internal GuidHandle GetLanguage(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return GuidHandle.FromIndex(Block.PeekHeapReference(rowOffset + _languageOffset, _isGuidHeapRefSizeSmall)); } } internal struct MethodDebugInformationTableReader { internal readonly int NumberOfRows; private readonly bool _isDocumentRefSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int DocumentOffset = 0; private readonly int _sequencePointsOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal MethodDebugInformationTableReader( int numberOfRows, int documentRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isDocumentRefSmall = documentRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _sequencePointsOffset = DocumentOffset + documentRefSize; RowSize = _sequencePointsOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal DocumentHandle GetDocument(MethodDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return DocumentHandle.FromRowId(Block.PeekReference(rowOffset + DocumentOffset, _isDocumentRefSmall)); } internal BlobHandle GetSequencePoints(MethodDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _sequencePointsOffset, _isBlobHeapRefSizeSmall)); } } internal struct LocalScopeTableReader { internal readonly int NumberOfRows; private readonly bool _isMethodRefSmall; private readonly bool _isImportScopeRefSmall; private readonly bool _isLocalConstantRefSmall; private readonly bool _isLocalVariableRefSmall; private const int MethodOffset = 0; private readonly int _importScopeOffset; private readonly int _variableListOffset; private readonly int _constantListOffset; private readonly int _startOffsetOffset; private readonly int _lengthOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal LocalScopeTableReader( int numberOfRows, bool declaredSorted, int methodRefSize, int importScopeRefSize, int localVariableRefSize, int localConstantRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isMethodRefSmall = methodRefSize == 2; _isImportScopeRefSmall = importScopeRefSize == 2; _isLocalVariableRefSmall = localVariableRefSize == 2; _isLocalConstantRefSmall = localConstantRefSize == 2; _importScopeOffset = MethodOffset + methodRefSize; _variableListOffset = _importScopeOffset + importScopeRefSize; _constantListOffset = _variableListOffset + localVariableRefSize; _startOffsetOffset = _constantListOffset + localConstantRefSize; _lengthOffset = _startOffsetOffset + sizeof(uint); RowSize = _lengthOffset + sizeof(uint); Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); if (numberOfRows > 0 && !declaredSorted) { Throw.TableNotSorted(TableIndex.LocalScope); } } internal MethodDefinitionHandle GetMethod(int rowId) { int rowOffset = (rowId - 1) * RowSize; return MethodDefinitionHandle.FromRowId(Block.PeekReference(rowOffset + MethodOffset, _isMethodRefSmall)); } internal ImportScopeHandle GetImportScope(LocalScopeHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return ImportScopeHandle.FromRowId(Block.PeekReference(rowOffset + _importScopeOffset, _isImportScopeRefSmall)); } internal int GetVariableStart(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekReference(rowOffset + _variableListOffset, _isLocalVariableRefSmall); } internal int GetConstantStart(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekReference(rowOffset + _constantListOffset, _isLocalConstantRefSmall); } internal int GetStartOffset(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekInt32(rowOffset + _startOffsetOffset); } internal int GetLength(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekInt32(rowOffset + _lengthOffset); } internal int GetEndOffset(int rowId) { int rowOffset = (rowId - 1) * RowSize; long result = Block.PeekUInt32(rowOffset + _startOffsetOffset) + Block.PeekUInt32(rowOffset + _lengthOffset); if (unchecked((int)result) != result) { Throw.ValueOverflow(); } return (int)result; } internal void GetLocalScopeRange(int methodDefRid, out int firstScopeRowId, out int lastScopeRowId) { int startRowNumber, endRowNumber; Block.BinarySearchReferenceRange( NumberOfRows, RowSize, MethodOffset, (uint)methodDefRid, _isMethodRefSmall, out startRowNumber, out endRowNumber ); if (startRowNumber == -1) { firstScopeRowId = 1; lastScopeRowId = 0; } else { firstScopeRowId = startRowNumber + 1; lastScopeRowId = endRowNumber + 1; } } } internal struct LocalVariableTableReader { internal readonly int NumberOfRows; private readonly bool _isStringHeapRefSizeSmall; private readonly int _attributesOffset; private readonly int _indexOffset; private readonly int _nameOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal LocalVariableTableReader( int numberOfRows, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset ) { NumberOfRows = numberOfRows; _isStringHeapRefSizeSmall = stringHeapRefSize == 2; _attributesOffset = 0; _indexOffset = _attributesOffset + sizeof(ushort); _nameOffset = _indexOffset + sizeof(ushort); RowSize = _nameOffset + stringHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal LocalVariableAttributes GetAttributes(LocalVariableHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return (LocalVariableAttributes)Block.PeekUInt16(rowOffset + _attributesOffset); } internal ushort GetIndex(LocalVariableHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return Block.PeekUInt16(rowOffset + _indexOffset); } internal StringHandle GetName(LocalVariableHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return StringHandle.FromOffset(Block.PeekHeapReference(rowOffset + _nameOffset, _isStringHeapRefSizeSmall)); } } internal struct LocalConstantTableReader { internal readonly int NumberOfRows; private readonly bool _isStringHeapRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int NameOffset = 0; private readonly int _signatureOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal LocalConstantTableReader( int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isStringHeapRefSizeSmall = stringHeapRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _signatureOffset = NameOffset + stringHeapRefSize; RowSize = _signatureOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal StringHandle GetName(LocalConstantHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return StringHandle.FromOffset(Block.PeekHeapReference(rowOffset + NameOffset, _isStringHeapRefSizeSmall)); } internal BlobHandle GetSignature(LocalConstantHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _signatureOffset, _isBlobHeapRefSizeSmall)); } } internal struct StateMachineMethodTableReader { internal readonly int NumberOfRows; private readonly bool _isMethodRefSizeSmall; private const int MoveNextMethodOffset = 0; private readonly int _kickoffMethodOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal StateMachineMethodTableReader( int numberOfRows, bool declaredSorted, int methodRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isMethodRefSizeSmall = methodRefSize == 2; _kickoffMethodOffset = methodRefSize; RowSize = _kickoffMethodOffset + methodRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); if (numberOfRows > 0 && !declaredSorted) { Throw.TableNotSorted(TableIndex.StateMachineMethod); } } internal MethodDefinitionHandle FindKickoffMethod(int moveNextMethodRowId) { int foundRowNumber = this.Block.BinarySearchReference( this.NumberOfRows, this.RowSize, MoveNextMethodOffset, (uint)moveNextMethodRowId, _isMethodRefSizeSmall); if (foundRowNumber < 0) { return default(MethodDefinitionHandle); } return GetKickoffMethod(foundRowNumber + 1); } private MethodDefinitionHandle GetKickoffMethod(int rowId) { int rowOffset = (rowId - 1) * RowSize; return MethodDefinitionHandle.FromRowId(Block.PeekReference(rowOffset + _kickoffMethodOffset, _isMethodRefSizeSmall)); } } internal struct ImportScopeTableReader { internal readonly int NumberOfRows; private readonly bool _isImportScopeRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int ParentOffset = 0; private readonly int _importsOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal ImportScopeTableReader( int numberOfRows, int importScopeRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isImportScopeRefSizeSmall = importScopeRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _importsOffset = ParentOffset + importScopeRefSize; RowSize = _importsOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal ImportScopeHandle GetParent(ImportScopeHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return ImportScopeHandle.FromRowId(Block.PeekReference(rowOffset + ParentOffset, _isImportScopeRefSizeSmall)); } internal BlobHandle GetImports(ImportScopeHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _importsOffset, _isBlobHeapRefSizeSmall)); } } internal struct CustomDebugInformationTableReader { internal readonly int NumberOfRows; private readonly bool _isHasCustomDebugInformationRefSizeSmall; private readonly bool _isGuidHeapRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int ParentOffset = 0; private readonly int _kindOffset; private readonly int _valueOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal CustomDebugInformationTableReader( int numberOfRows, bool declaredSorted, int hasCustomDebugInformationRefSize, int guidHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isHasCustomDebugInformationRefSizeSmall = hasCustomDebugInformationRefSize == 2; _isGuidHeapRefSizeSmall = guidHeapRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _kindOffset = ParentOffset + hasCustomDebugInformationRefSize; _valueOffset = _kindOffset + guidHeapRefSize; RowSize = _valueOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); if (numberOfRows > 0 && !declaredSorted) { Throw.TableNotSorted(TableIndex.CustomDebugInformation); } } internal EntityHandle GetParent(CustomDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return HasCustomDebugInformationTag.ConvertToHandle(Block.PeekTaggedReference(rowOffset + ParentOffset, _isHasCustomDebugInformationRefSizeSmall)); } internal GuidHandle GetKind(CustomDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return GuidHandle.FromIndex(Block.PeekHeapReference(rowOffset + _kindOffset, _isGuidHeapRefSizeSmall)); } internal BlobHandle GetValue(CustomDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _valueOffset, _isBlobHeapRefSizeSmall)); } internal void GetRange(EntityHandle parentHandle, out int firstImplRowId, out int lastImplRowId) { int startRowNumber, endRowNumber; Block.BinarySearchReferenceRange( NumberOfRows, RowSize, ParentOffset, HasCustomDebugInformationTag.ConvertToTag(parentHandle), _isHasCustomDebugInformationRefSizeSmall, out startRowNumber, out endRowNumber ); if (startRowNumber == -1) { firstImplRowId = 1; lastImplRowId = 0; } else { firstImplRowId = startRowNumber + 1; lastImplRowId = endRowNumber + 1; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using GitSharp.Core; using Sep.Git.Tfs.Util; using StructureMap; using FileMode=GitSharp.Core.FileMode; namespace Sep.Git.Tfs.Core { public class GitRepository : GitHelpers, IGitRepository, IDisposable { private static readonly Regex configLineRegex = new Regex("^tfs-remote\\.(?<id>[^.]+)\\.(?<key>[^.=]+)=(?<value>.*)$"); private IDictionary<string, IGitTfsRemote> _cachedRemotes; private Repository _repository; public GitRepository(TextWriter stdout, string gitDir) : base(stdout) { GitDir = gitDir; _repository = new Repository(new DirectoryInfo(gitDir)); } private string GitDir { get; set; } public string WorkingCopyPath { get; set; } public string WorkingCopySubdir { get; set; } protected override Process Start(string [] command, Action<ProcessStartInfo> initialize) { return base.Start(command, initialize.And(SetUpPaths)); } private void SetUpPaths(ProcessStartInfo gitCommand) { if(GitDir != null) gitCommand.EnvironmentVariables["GIT_DIR"] = GitDir; if(WorkingCopyPath != null) gitCommand.WorkingDirectory = WorkingCopyPath; if(WorkingCopySubdir != null) gitCommand.WorkingDirectory = Path.Combine(gitCommand.WorkingDirectory, WorkingCopySubdir); } public IEnumerable<IGitTfsRemote> ReadAllTfsRemotes() { return GetTfsRemotes().Values; } public IGitTfsRemote ReadTfsRemote(string remoteId) { try { return GetTfsRemotes()[remoteId]; } catch(Exception e) { throw new Exception("Unable to locate git-tfs remote with id = " + remoteId, e); } } public IGitTfsRemote ReadTfsRemote(string tfsUrl, string tfsRepositoryPath) { try { var allRemotes = GetTfsRemotes(); return allRemotes.Values.First( remote => remote.Tfs.Url == tfsUrl && remote.TfsRepositoryPath == tfsRepositoryPath); } catch (Exception e) { throw new Exception("Unable to locate git-tfs remote with url = " + tfsUrl + ", repo = " + tfsRepositoryPath, e); } } private IDictionary<string, IGitTfsRemote> GetTfsRemotes() { return _cachedRemotes ?? (_cachedRemotes = ReadTfsRemotes()); } private IDictionary<string, IGitTfsRemote> ReadTfsRemotes() { var remotes = new Dictionary<string, IGitTfsRemote>(); CommandOutputPipe(stdout => ParseRemoteConfig(stdout, remotes), "config", "-l"); return remotes; } private void ParseRemoteConfig(TextReader stdout, IDictionary<string, IGitTfsRemote> remotes) { string line; while ((line = stdout.ReadLine()) != null) { TryParseRemoteConfigLine(line, remotes); } } private void TryParseRemoteConfigLine(string line, IDictionary<string, IGitTfsRemote> remotes) { var match = configLineRegex.Match(line); if (match.Success) { var key = match.Groups["key"].Value; var value = match.Groups["value"].Value; var remoteId = match.Groups["id"].Value; var remote = remotes.ContainsKey(remoteId) ? remotes[remoteId] : (remotes[remoteId] = CreateRemote(remoteId)); SetRemoteConfigValue(remote, key, value); } } private void SetRemoteConfigValue(IGitTfsRemote remote, string key, string value) { switch (key) { case "url": remote.Tfs.Url = value; break; case "username": remote.Tfs.Username = value; break; case "repository": remote.TfsRepositoryPath = value; break; case "ignore-paths": remote.IgnoreRegexExpression = value; break; //case "fetch": // remote.??? = value; // break; } } private IGitTfsRemote CreateRemote(string id) { var remote = ObjectFactory.GetInstance<IGitTfsRemote>(); remote.Repository = this; remote.Id = id; return remote; } public IEnumerable<TfsChangesetInfo> GetParentTfsCommits(string head) { return GetParentTfsCommits(head, new List<string>()); } public IEnumerable<TfsChangesetInfo> GetParentTfsCommits(string head, ICollection<string> localCommits) { var tfsCommits = new List<TfsChangesetInfo>(); try { CommandOutputPipe(stdout => FindTfsCommits(stdout, tfsCommits, localCommits), "log", "--no-color", "--pretty=medium", head); } catch (GitCommandException e) { Trace.WriteLine("An error occurred while loading head " + head + " (maybe it doesn't exist?): " + e); } return from commit in tfsCommits group commit by commit.Remote into remotes select remotes.OrderBy(commit => -commit.ChangesetId).First(); } private void FindTfsCommits(TextReader stdout, ICollection<TfsChangesetInfo> tfsCommits, ICollection<string> localCommits) { string currentCommit = null; string line; var commitRegex = new Regex("commit (" + GitTfsConstants.Sha1 + ")"); while (null != (line = stdout.ReadLine())) { var match = commitRegex.Match(line); if (match.Success) { if (currentCommit != null) localCommits.Add(currentCommit); currentCommit = match.Groups[1].Value; continue; } var changesetInfo = TryParseChangesetInfo(line, currentCommit); if (changesetInfo != null) { tfsCommits.Add(changesetInfo); currentCommit = null; } } //stdout.Close(); } private TfsChangesetInfo TryParseChangesetInfo(string gitTfsMetaInfo, string commit) { var match = GitTfsConstants.TfsCommitInfoRegex.Match(gitTfsMetaInfo); if (match.Success) { var commitInfo = ObjectFactory.GetInstance<TfsChangesetInfo>(); commitInfo.Remote = ReadTfsRemote(match.Groups["url"].Value, match.Groups["repository"].Value); commitInfo.ChangesetId = Convert.ToInt32(match.Groups["changeset"].Value); commitInfo.GitCommit = commit; return commitInfo; } return null; } public IDictionary<string, GitObject> GetObjects(string commit) { var entries = new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase); if (commit != null) { ParseEntries(entries, Command("ls-tree", "-r", "-z", commit), commit); ParseEntries(entries, Command("ls-tree", "-r", "-d", "-z", commit), commit); } return entries; } private void ParseEntries(IDictionary<string, GitObject> entries, string treeInfo, string commit) { foreach (var treeEntry in treeInfo.Split('\0')) { var gitObject = MakeGitObject(commit, treeEntry); if(gitObject != null) { entries[gitObject.Path] = gitObject; } } } private GitObject MakeGitObject(string commit, string treeInfo) { var treeRegex = new Regex(@"\A(?<mode>\d{6}) (?<type>blob|tree) (?<sha>" + GitTfsConstants.Sha1 + @")\t(?<path>.*)"); var match = treeRegex.Match(treeInfo); return !match.Success ? null : new GitObject { Mode = match.Groups["mode"].Value, Sha = match.Groups["sha"].Value, ObjectType = match.Groups["type"].Value, Path = match.Groups["path"].Value, Commit = commit }; } public IEnumerable<IGitChangedFile> GetChangedFiles(string from, string to) { using (var diffOutput = CommandOutputPipe("diff-tree", "-r", from, to)) { while (':' == diffOutput.Read()) { var builder = ObjectFactory.With("repository").EqualTo(this); builder = builder.With("oldMode").EqualTo(diffOutput.Read(6)); diffOutput.Read(1); // a space var newMode = diffOutput.Read(6); builder = builder.With("newMode").EqualTo(newMode); diffOutput.Read(1); // a space builder = builder.With("oldSha").EqualTo(diffOutput.Read(40)); diffOutput.Read(1); // a space builder = builder.With("newSha").EqualTo(diffOutput.Read(40)); diffOutput.Read(1); // a space var changeType = diffOutput.Read(1); diffOutput.Read(1); // tab builder = builder.With("path").EqualTo(diffOutput.ReadLine().Trim()); if(FileMode.GitLink == newMode.ToFileMode()) continue; IGitChangedFile change; try { change = builder.GetInstance<IGitChangedFile>(changeType); } catch (Exception e) { throw new Exception("Unable to handle change type " + changeType + ".", e); } yield return change; } } } public string GetChangeSummary(string from, string to) { string summary = ""; CommandOutputPipe(stdout => summary = stdout.ReadToEnd(), "diff-tree", "--shortstat", from, to); return summary; } public void GetBlob(string sha, string outputFile) { Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); CommandOutputPipe(stdout => Copy(stdout, outputFile), "cat-file", "-p", sha); } private void Copy(TextReader stdout, string file) { var stdoutStream = ((StreamReader) stdout).BaseStream; using(var destination = File.Create(file)) { stdoutStream.CopyTo(destination); } } public string HashAndInsertObject(string filename) { var writer = new ObjectWriter(_repository); var objectId = writer.WriteBlob(new FileInfo(filename)); return objectId.ToString(); } public string HashAndInsertObject(Stream file) { var writer = new ObjectWriter(_repository); var objectId = writer.WriteBlob(file.Length, file); return objectId.ToString(); } public string GetTreeForCommit(string commit) { if (string.IsNullOrEmpty(commit)) return null; string commitInfo = Command("cat-file", "-p", commit); foreach (var commitEntry in commitInfo.Split('\n')) { string[] elements = commitEntry.Split(' '); if (elements.Length == 2 && elements[0] == "tree") { return elements[1]; } } throw new Exception(String.Format("unable to find tree for commit {0}", commitInfo)); } public string GetNote(string reference) { string notes = null; try { notes = Command("notes", "show", reference); notes = notes.TrimEnd(new char[] {'\n'}); } catch(GitCommandException exception) { if (exception.ExitCode != 1) throw; } return notes; } public void SetNote(string reference, string value) { value = value.Replace("\"", "\\\""); Command("notes", "edit", "-m", value, reference); } public void Dispose() { if (_repository != null) _repository.Close(); } } }
// Created by Paul Gonzalez Becerra using System; using System.Runtime.InteropServices; using Saserdote.Mathematics.Collision; namespace Saserdote.Mathematics { [StructLayout(LayoutKind.Sequential)] public struct Vector2 { #region --- Field Variables --- // Variables public float x; public float y; public readonly static Vector2 ZERO= new Vector2(0f); public readonly static Vector2 UNIT_X= new Vector2(1f, 0f); public readonly static Vector2 UNIT_Y= new Vector2(0f, 1f); #endregion // Field Variables #region --- Constructors --- public Vector2(float pmX, float pmY) { x= pmX; y= pmY; } internal Vector2(float all):this(all, all) {} #endregion // Constructors #region --- Methods --- // Converts this vector into a 3d vector public Vector3 toVector3() { return new Vector3(x, y, 0f); } // Converts this vector into a 3d point public Point3f toPoint3f() { return new Point3f(x, y, 0f); } // Converts this vector into a 3d point public Point3i toPoint3i() { return new Point3i((int)x, (int)y, 0); } // Converts this vector into a 2d point public Point2f toPoint2f() { return new Point2f(x, y); } // Converts this vector into a 2d point public Point2i toPoint2i() { return new Point2i((int)x, (int)y); } // Adds the point with the vector to get a new point public Point3f add(Point3f pt) { return new Point3f(x+pt.x, y+pt.y, pt.z); } // Adds the point with the vector to get a new point public Point3i add(Point3i pt) { return new Point3i((int)x+pt.x, (int)y+pt.y, pt.z); } // Adds the point with the vector to get a new point public Point2f add(Point2f pt) { return new Point2f(x+pt.x, y+pt.y); } // Adds the point with the vector to get a new point public Point2i add(Point2i pt) { return new Point2i((int)x+pt.x, (int)y+pt.y); } // Adds the two vectors together public Vector2 add(Vector2 vec) { return new Vector2(x+vec.x, y+vec.y); } // Adds the two vectors together public Vector3 add(Vector3 vec) { return new Vector3(x+vec.x, y+vec.y, vec.z); } // Adds the vector to the point public System.Drawing.Point add(System.Drawing.Point pt) { return new System.Drawing.Point((int)(pt.X+x), (int)(pt.Y+y)); } // Subtracts the point with the vector to get a new point public Point3f subtract(Point3f pt) { return new Point3f(x-pt.x, y-pt.y, 0f-pt.z); } // Subtracts the point with the vector to get a new point public Point3i subtract(Point3i pt) { return new Point3i((int)x-pt.x, (int)y-pt.y, 0-pt.z); } // Subtracts the point with the vector to get a new point public Point2f subtract(Point2f pt) { return new Point2f(x-pt.x, y-pt.y); } // Subtracts the point with the vector to get a new point public Point2i subtract(Point2i pt) { return new Point2i((int)x-pt.x, (int)y-pt.y); } // Subtracts the two vectors together public Vector2 subtract(Vector2 vec) { return new Vector2(x-vec.x, y-vec.y); } // Subtracts the two vectors together public Vector3 subtract(Vector3 vec) { return new Vector3(x-vec.x, y-vec.y, 0f-vec.z); } // Subtracts the vector to the point public System.Drawing.Point subtract(System.Drawing.Point pt) { return new System.Drawing.Point((int)(pt.X-x), (int)(pt.Y-y)); } // Multiplies the 2d vector to get an appropriate scale public Vector2 multiply(float scale) { return new Vector2(x*scale, y*scale); } // Divides the 2d vector to get an appropriate scale public Vector2 divide(float scale) { if(scale== 0) throw new Exception("Dividing by Zero!"); return multiply(1f/scale); } // Gets the dot product of the two given vectors public float getDotProduct(Vector2 vec) { return (x*vec.x)+(y*vec.y); } // Gets the opposite of the current vector public Vector2 negate() { return new Vector2(-1f*x, -1f*y); } // Gets the vector's magnitude public float getMagnitude() { return (float)(Math.Sqrt(getMagnitudeSquared())); } // Gets the vector's magnitude before square rooting it public float getMagnitudeSquared() { return (x*x)+(y*y); } // Normalizes the vector, non-destructive public Vector2 normalize() { // Variables float mag= getMagnitude(); if(mag!= 0f) return new Vector2(x/mag, y/mag); else return Vector2.ZERO; } // Normalizes the vector, destructive public Vector2 normalizeDest() { // Variables float mag= getMagnitude(); if(mag!= 0f) { x/= mag; y/= mag; } return this; } // Finds if the two vectors are equal public bool equals(Vector2 vec) { return (x== vec.x && y== vec.y); } #endregion // Methods #region --- Inherited Methods --- // Finds if the given object is equal to this vector public override bool Equals(object obj) { if(obj== null) return false; if(obj is Vector2) return equals((Vector2)obj); return false; } // Prints out what are the x and y of the vector public override string ToString() { return "X:"+x+",Y:"+y; } // Gets the hash code public override int GetHashCode() { return (int)x^(int)y; } #endregion // Inherited Methods #region --- Operators --- // Equality operators public static bool operator ==(Vector2 left, Vector2 right) { return left.equals(right); } // Inequality operators public static bool operator !=(Vector2 left, Vector2 right) { return !left.equals(right); } // Less than operators public static bool operator <(Vector2 left, Vector2 right) { return (left.getMagnitudeSquared()< right.getMagnitudeSquared()); } public static bool operator <(Vector2 left, float right) { return (left.getMagnitude()< right); } public static bool operator <(float left, Vector2 right) { return (left< right.getMagnitude()); } // Less than or equal to operators public static bool operator <=(Vector2 left, Vector2 right) { return (left.getMagnitudeSquared()<= right.getMagnitudeSquared()); } public static bool operator <=(Vector2 left, float right) { return (left.getMagnitude()<= right); } public static bool operator <=(float left, Vector2 right) { return (left<= right.getMagnitude()); } // Greater than operators public static bool operator >(Vector2 left, Vector2 right) { return (left.getMagnitudeSquared()> right.getMagnitudeSquared()); } public static bool operator >(Vector2 left, float right) { return (left.getMagnitude()> right); } public static bool operator >(float left, Vector2 right) { return (left> right.getMagnitude()); } // Greater than or equal to operators public static bool operator >=(Vector2 left, Vector2 right) { return (left.getMagnitudeSquared()>= right.getMagnitudeSquared()); } public static bool operator >=(Vector2 left, float right) { return (left.getMagnitude()>= right); } public static bool operator >=(float left, Vector2 right) { return (left>= right.getMagnitude()); } // Addition operators public static Vector2 operator +(Vector2 left, Vector2 right) { return left.add(right); } public static Vector3 operator +(Vector2 left, Vector3 right) { return left.add(right); } public static Point3f operator +(Vector2 left, Point3f right) { return left.add(right); } public static Point3i operator +(Vector2 left, Point3i right) { return left.add(right); } public static Point2f operator +(Vector2 left, Point2f right) { return left.add(right); } public static Point2i operator +(Vector2 left, Point2i right) { return left.add(right); } public static System.Drawing.Point operator +(Vector2 left, System.Drawing.Point right) { return left.add(right); } public static System.Drawing.Point operator +(System.Drawing.Point left, Vector2 right) { return right.add(left); } // Subtraction operators public static Vector2 operator -(Vector2 left, Vector2 right) { return left.subtract(right); } public static Vector3 operator -(Vector2 left, Vector3 right) { return left.subtract(right); } public static Point3f operator -(Vector2 left, Point3f right) { return left.subtract(right); } public static Point3i operator -(Vector2 left, Point3i right) { return left.subtract(right); } public static Point2f operator -(Vector2 left, Point2f right) { return left.subtract(right); } public static Point2i operator -(Vector2 left, Point2i right) { return left.subtract(right); } public static System.Drawing.Point operator -(Vector2 left, System.Drawing.Point right) { return left.subtract(right); } public static System.Drawing.Point operator -(System.Drawing.Point left, Vector2 right) { return right.subtract(left); } // Multiplication operators public static float operator *(Vector2 left, Vector2 right) { return left.getDotProduct(right); } public static Vector2 operator *(Vector2 left, float right) { return left.multiply(right); } public static Vector2 operator *(float left, Vector2 right) { return right.multiply(left); } public static Vector2 operator *(Vector2 left, int right) { return left.multiply((float)right); } public static Vector2 operator *(int left, Vector2 right) { return right.multiply((float)left); } public static bool operator *(Vector2 left, BoundingVolume right) { return right.contains(left); } // Division operators public static Vector2 operator /(Vector2 left, float right) { return left.divide(right); } public static Vector2 operator /(Vector2 left, int right) { return left.divide((float)right); } // Uniary operators public static Vector2 operator -(Vector2 self) { return self.negate(); } public static Vector2 operator ~(Vector2 self) { return self.normalize(); } // Conversion operators // [Vector2 to Vector3] public static explicit operator Vector3(Vector2 castee) { return castee.toVector3(); } // [Vector2 to Point3f] public static explicit operator Point3f(Vector2 castee) { return castee.toPoint3f(); } // [Vector2 to Point3i] public static explicit operator Point3i(Vector2 castee) { return castee.toPoint3i(); } // [Vector2 to Point2f] public static explicit operator Point2f(Vector2 castee) { return castee.toPoint2f(); } // [Vector2 to Point2i] public static explicit operator Point2i(Vector2 castee) { return castee.toPoint2i(); } #endregion // Operators } } // End of File
using System; using System.Collections.Generic; using System.Text; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using System.Diagnostics; namespace Simbiosis { /// <summary> /// Optical Flow: measures the relative movement of objects and tiles in the vicinity (+/-90 degrees). /// Detects moving objects but also triggered when the creature itself moves. /// </summary> class OpticalFlow : Physiology { private const float RANGE = 30f; // visibility distance private SensorItem[] memories = null; // List of objects found at last search (positions tell us whether they've moved between updates) private int updateRate = 4; // only update once every second (efficient and gives any o/p time to be noticed) public OpticalFlow() { // Define my properties Mass = 0.2f; Resistance = 0.2f; Buoyancy = 0.0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] { new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 1, 0f, "Motion"), // output }, }; } public override void SlowUpdate() { if (--updateRate <= 0) { updateRate = 4; float signal = 0; SensorItem[] items = owner.GetObjectsInRange(0, RANGE, true, true, true); // Get a list of all visible creatures and tiles within range foreach (SensorItem item in items) { float angle = item.Angle(); // angle of obj from line of sight if (angle < (float)Math.PI / 2f) // if object is within sensor cone { foreach (SensorItem memory in memories) // search for same object in memory { if (item.Object == memory.Object) { float mvt = Vector3.LengthSq(memory.RelativePosition - item.RelativePosition); // how much object has moved relative to us in past 0.25 secs if (mvt != 0) // if moved, add abs distance to signal, modulated by how far downrange it is { signal += (float)Math.Sqrt(mvt) * item.Distance(RANGE); } break; } } } } memories = items; // store new list for next time Output(0, signal / 10f); // output a fraction of the accumulated motion } } } /// <summary> /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Speed sensor. Measures speed in the direction of its nose (away from the plug). /// Cell has 4 hairs, which stick out when still but flow backwards when cell is moving. /// A differentiator cell could be used to turn speed into acceleration. /// </summary> class Speed : Physiology { /// <summary> Last position of hair tip (hot4-7) </summary> private Vector3 lastPosn = new Vector3(); /// <summary> Moving average speed </summary> private float hairSpeed = 0; public Speed() { // Define my properties Mass = 0.2f; Resistance = 0.2f; Buoyancy = 0.0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] { new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 1, 0f, "Speed"), // output }, }; } /// <summary> /// Called every frame /// </summary> public override void FastUpdate(float elapsedTime) { // Make hairs flow Matrix hotMat = owner.GetHotspotNormalMatrix(0); // position and direction of hotspot hotMat.Invert(); Vector3 oldRelPos = Vector3.TransformCoordinate(lastPosn, hotMat); // transform previous position into new posn's frame float dist = -oldRelPos.Z; // distance hotspot has travelled along its normal axis lastPosn = owner.GetHotspotLocation(0); // remember latest position float speed = dist / elapsedTime / 4f; // Speed is distance / time hairSpeed = (hairSpeed * 31f + speed) / 32f; // keep a moving average for smooth animation if (hairSpeed < 0) hairSpeed = 0; JointOutput[0] = JointOutput[1] = JointOutput[2] = JointOutput[3] = hairSpeed; // drive hairs Output(0, hairSpeed); // output signal } } /// <summary> /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Passive sensor: detects narrow-spectrum bioluminescence emitted from special bioluminescence cells, /// allowing one creature to recognize another or detect the mood of another. /// Output is a pulse that decays over about a second /// </summary> class SpectralSensor : Physiology { /// <summary> Sensor range </summary> const float range = 60; /// <summary> Adjustable acceptance angle in radians either side of the line of sight </summary> const float halfAngle = (float)Math.PI / 4.0f; /// <summary> Current filter colour </summary> float r=0, g=0, b=0; /// <summary> instantaneous signal strength (received from stimuli) </summary> float incoming = 0; /// <summary> mean signal strength integrated over time </summary> float output = 0; public SpectralSensor() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Buoyancy = 0.0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] { // SOLE VARIANT new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 1, 0f, "Signal"), // output new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 0, 0f, "Filter colour"), // colour sensitivity }, }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { ReadFilter(); } public override void FastUpdate(float elapsedTime) { base.FastUpdate(elapsedTime); // If we have recently received a signal via a stimulus, add it to the output output += incoming; incoming = 0; output /= 1f + elapsedTime/1f; // output decays over time Output(0, output); } /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// Read/write/modify your sensory/motor nerves and/or chemicals, to implement your behaviour /// </summary> public override void SlowUpdate() { ReadFilter(); } /// <summary> /// Get the filter's RGB from the signal on input 1. /// The colours run smoothly from red, through yellow to green and cyan to blue (no magenta) /// </summary> private void ReadFilter() { float freq = Input(1); if (freq < 0.5f) { r = (0.5f - freq) * 2f; g = 1f - r; b = 0; } if (freq >= 0.5f) { r = 0; b = (freq - 0.5f) * 2f; g = 1f - b; } this.owner.SetAnimColour(0,new ColorValue(r, g, b), new ColorValue(0,0,0)); } /// <summary> We've been sent a Stimulus that our basic Cell object doesn't understand. /// This overload responds to the "bioluminescence" stimulus /// Parameter 0 will be a ColorValue containing the bioluminescent cell's current anim colour /// <param name="stimulus">The stimulus information</param> /// <returns>Return true if the stimulus was handled</returns> public override bool ReceiveStimulus(Stimulus stim) { if (stim.Type == "bioluminescence") { // Find out if the sender is within range/sight of our hotspot SensorItem sender = owner.TestStimulusVisibility(0, range, stim); float dist = sender.Distance(); if (dist<range) { float angle = sender.Angle(); if (angle < halfAngle) { // Parameter 0 will be a ColorValue containing the bioluminescent cell's current anim colour ColorValue light = (ColorValue)stim.Param0; // Compare the light to our filter colour float r1 = light.Red - r; // difference in RGB between filter and cell float g1 = light.Green - g; float b1 = light.Blue - b; float signal = 1f - (float)Math.Sqrt((r1 * r1 + g1 * g1 + b1 * b1) / 3f); // least squares measure of similarity (1=identical) signal *= 1f - angle / halfAngle; // scale by deviation from mid-line (so objects straight ahead have more effect) // NOTE: Removed this because bioluminescent cells are obviously tiny at long range //float apparentSize = sender.AngleSubtended(); // scale by angle subtended (depends on size and distance) //if (apparentSize < 0) apparentSize = 0; //signal *= apparentSize; // Add this signal to that waiting for inclusion in the output incoming += signal; } } return true; } else return false; } } /// <summary> /// /////////////////////////////////////////////////////////////////////////////////////// /// Colour-specific light sensor - Active sensor. Measures amount of a given colour (not counting terrain and water) within the field of view. /// Signal is a product of: /// - the closeness of the object /// - the size of the object /// - the similarity of the colour /// - the nearness to the centre of the field of view /// /// Channel 0 = output. Amount of current colour /// Channel 1 = optional input. Defines the colour of the filter (RGB values close to this will be detected) /// Channel 2 = optional input. Defines the selectivity of the filter (high values are broad; 0 is highly selective) /// /// </summary> class ColorSensitive : Physiology { /// <summary> Sensor range </summary> const float range = 40; /// <summary> Adjustable acceptance angle in radians either side of the line of sight </summary> const float halfAngle = (float)Math.PI / 4.0f; /// <summary> Current filter colour </summary> float r=0, g=0, b=0; public ColorSensitive() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Buoyancy = 0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] { // SOLE VARIANT new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 1, 0f, "Signal"), // output new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 0, 0f, "Filter colour"), // colour sensitivity }, }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } //public override void FastUpdate(float elapsedTime) //{ // base.FastUpdate(elapsedTime); //} /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// Read/write/modify your sensory/motor nerves and/or chemicals, to implement your behaviour /// </summary> public override void SlowUpdate() { ReadFilter(); ReadSignal(); } /// <summary> /// Get the filter's RGB from the signal on input 1. /// The colours run smoothly from red, through yellow to green and cyan to blue (no magenta) /// </summary> private void ReadFilter() { float freq = Input(1); if (freq < 0.5f) { r = (0.5f - freq) * 2f; g = 1f - r; b = 0; } if (freq >= 0.5f) { r = 0; b = (freq - 0.5f) * 2f; g = 1f - b; } this.owner.SetAnimColour(0,new ColorValue(r, g, b), new ColorValue(0,0,0)); } /// <summary> /// Read the sensor and output the signal /// </summary> private void ReadSignal() { float signal = 0; float total = 0; SensorItem[] items = owner.GetObjectsInRange(0, range, true, false, true); // Get a list of all visible creatures (but NOT tiles) within range foreach (SensorItem item in items) { float angle = item.Angle(); // angle of obj from line of sight if (angle < halfAngle) // if object is within sensor cone { List<ColorValue> colours = item.Object.ReqSpectrum(); // get the spectral response of the organism (its cell colours) // Measure the amount of light from each cell that will pass through the filter foreach (ColorValue c in colours) { float r1 = c.Red-r; // difference in RGB between filter and cell float g1 = c.Green-g; float b1 = c.Blue-b; signal += 1f - (float)Math.Sqrt((r1*r1 + g1*g1 + b1*b1)/3f); // least squares measure of similarity } signal /= colours.Count; // average by # colours signal *= 1f - angle/halfAngle; // scale by deviation from mid-line (so objects straight ahead have more effect) float apparentSize = item.AngleSubtended(); // scale by angle subtended (depends on size and distance) if (apparentSize < 0) apparentSize = 0; signal *= apparentSize; total++; // tally # objects found } } if (total > 0) // If we found one or more objects... { signal *= 1f - ((IDetectable)owner).ReqDepth(); // scale overall signal by the depth of the sensor (i.e. light level) signal *= 10f; // scale into a useful range if (signal < 0f) signal = 0f; // clamp output if (signal > 1f) signal = 1f; Output(0, signal); // signal is our primary output } else Output(0, 0); // ...else if no objects in sight, o/p will be zero } } /// <summary> /// /////////////////////////////////////////////////////////////////////////////////////// /// Sonar - Active sensor. Measures distance to nearest obstruction (terrain or creature). /// Equally sensitive to all obstructions less than given angle from the sensor axis. /// /// Channel 0 = output. Distance of nearest object /// Channel 1 = optional input. If connected, triggers a ping. If unconnected, pings are continuous but use more energy. /// /// </summary> class Sonar : Physiology { /// <summary> Adjustable range - default is 20 </summary> private float range = 20; /// <summary> Adjustable acceptance angle in radians either side of the line of sight </summary> private float halfAngle = (float)Math.PI / 4.0f; /// <summary> trigger signal must exceed this level to start a ping </summary> private const float TRIGGERTHRESHOLD = 0.5f; /// <summary> how many cycles of animation for a ping </summary> private const int PINGCYCLES = 2; /// <summary> state machine for handling pings & echoes </summary> private States state = States.Standby; private enum States { Standby, Pinging, }; /// <summary> Animated transducer </summary> private float animPosn = 0; // current angle private float animDelta = 0.9f; // rate of increase/decrease private int animCount = 0; // number of cycles to go public Sonar() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Buoyancy = 0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] { // SOLE VARIANT new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 1, 0f, "Distance"), // output - distance of nearest echo new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 0, 1f, "Trigger (optional)"), // triggers a "ping" }, }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } public override void FastUpdate(float elapsedTime) { base.FastUpdate(elapsedTime); // Update any ping animation if (state == States.Pinging) { animPosn += elapsedTime * animDelta; // if we're pinging, move the transducer JointOutput[0] = animPosn; if ((animPosn < 0) || (animPosn > 1.0f)) // if it has reached the limit { animDelta = -animDelta; // turn it around and bring back into range animPosn = (animPosn < 0) ? 0 : 1.0f; if (--animCount <= 0) // if this was the last cycle { ReadEcho(); // read the sensor state = States.Standby; // and go to standby } } } } /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// Read/write/modify your sensory/motor nerves and/or chemicals, to implement your behaviour /// </summary> public override void SlowUpdate() { // If we're in standby, decide if we should start a new ping (on trigger, or repeatedly if no trigger connection) if (state == States.Standby) { // if there's a trigger signal (constant or driven), start a ping if (Input(1) > TRIGGERTHRESHOLD) { state = States.Pinging; animCount = PINGCYCLES; } } } /// <summary> /// Read the sensor and output the distance /// </summary> private void ReadEcho() { float signal = 0; // largest 'sonar echo' so far found SensorItem[] items = owner.GetObjectsInRange(0, range, true, true, false); // Get a list of all creatures and tiles within range foreach (SensorItem item in items) { float angle = item.Angle(); // angle of obj from line of sight if (angle < halfAngle) // if object is within sensor cone { float dist = item.Distance(range); // get range-relative distance to obj if (dist > signal) signal = dist; // if this is closest so far, keep it } } Output(0, signal); // sonar signal is our primary output } } /// <summary> /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Vibration sensor. Passive. Detects ripples of disturbance from actuators (including the submarine fans) /// Has an acceptance angle of 180 degrees, so putting one on each side of a creature gives it an idea of the source direction. /// </summary> class Vibration : Physiology { /// <summary> Adjustable range - default is 20 </summary> private float range = 20; /// <summary> /// Acceptance angle in radians either side of the line of sight. /// (less than 180 degrees total, to shadow own body) /// </summary> private const float HALFANGLE = (float)Math.PI / 2.0f * 0.8f; public Vibration() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Buoyancy = 0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] // SOLE VARIANT { new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 1, 0f, "Signal strength"), // output channel to plug - distance }, }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } public override bool ReceiveStimulus(Stimulus stim) { switch (stim.Type) { // Potentially picked up a disturbance case "disturbance": SensorItem result = owner.TestStimulusVisibility(0, range, stim); // see if the source is within our acceptance angle if (result.Angle()<HALFANGLE) { Output(0,result.Distance(range)); // if so, output a signal as a fraction of the source range } return true; } Output(0,0); // if no valid sensation, clear the signal return false; } } }
// *********************************************************************** // Copyright (c) 2007 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 NUnit.Framework.Internal; using NUnit.Compatibility; using System.Collections; using System; using System.Reflection; namespace NUnit.Framework.Constraints { /// <summary> /// Delegate used to delay evaluation of the actual value /// to be used in evaluating a constraint /// </summary> public delegate TActual ActualValueDelegate<TActual>(); /// <summary> /// The Constraint class is the base of all built-in constraints /// within NUnit. It provides the operator overloads used to combine /// constraints. /// </summary> public abstract class Constraint : IConstraint { Lazy<string> _displayName; #region Constructor /// <summary> /// Construct a constraint with optional arguments /// </summary> /// <param name="args">Arguments to be saved</param> protected Constraint(params object[] args) { Arguments = args; _displayName = new Lazy<string>(() => { var type = this.GetType(); var displayName = type.Name; if (type.GetTypeInfo().IsGenericType) displayName = displayName.Substring(0, displayName.Length - 2); if (displayName.EndsWith("Constraint", StringComparison.Ordinal)) displayName = displayName.Substring(0, displayName.Length - 10); return displayName; }); } #endregion #region Properties /// <summary> /// The display name of this Constraint for use by ToString(). /// The default value is the name of the constraint with /// trailing "Constraint" removed. Derived classes may set /// this to another name in their constructors. /// </summary> public virtual string DisplayName { get { return _displayName.Value; } } /// <summary> /// The Description of what this constraint tests, for /// use in messages and in the ConstraintResult. /// </summary> public virtual string Description { get; protected set; } /// <summary> /// Arguments provided to this Constraint, for use in /// formatting the description. /// </summary> public object[] Arguments { get; private set; } /// <summary> /// The ConstraintBuilder holding this constraint /// </summary> public ConstraintBuilder Builder { get; set; } #endregion #region Abstract and Virtual Methods /// <summary> /// Applies the constraint to an actual value, returning a ConstraintResult. /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>A ConstraintResult</returns> public abstract ConstraintResult ApplyTo<TActual>(TActual actual); /// <summary> /// Applies the constraint to an ActualValueDelegate that returns /// the value to be tested. The default implementation simply evaluates /// the delegate but derived classes may override it to provide for /// delayed processing. /// </summary> /// <param name="del">An ActualValueDelegate</param> /// <returns>A ConstraintResult</returns> public virtual ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del) { #if ASYNC var invokeResult = GetTestObject(del); object awaitedResult; return ApplyTo(AwaitUtils.TryAwait(del, invokeResult, out awaitedResult) ? awaitedResult : invokeResult); #else return ApplyTo(GetTestObject(del)); #endif } #pragma warning disable 3006 /// <summary> /// Test whether the constraint is satisfied by a given reference. /// The default implementation simply dereferences the value but /// derived classes may override it to provide for delayed processing. /// </summary> /// <param name="actual">A reference to the value to be tested</param> /// <returns>A ConstraintResult</returns> public virtual ConstraintResult ApplyTo<TActual>(ref TActual actual) { return ApplyTo(actual); } #pragma warning restore 3006 /// <summary> /// Retrieves the value to be tested from an ActualValueDelegate. /// The default implementation simply evaluates the delegate but derived /// classes may override it to provide for delayed processing. /// </summary> /// <param name="del">An ActualValueDelegate</param> /// <returns>Delegate evaluation result</returns> protected virtual object GetTestObject<TActual>(ActualValueDelegate<TActual> del) { return del(); } #endregion #region ToString Override /// <summary> /// Default override of ToString returns the constraint DisplayName /// followed by any arguments within angle brackets. /// </summary> /// <returns></returns> public override string ToString() { string rep = GetStringRepresentation(); return this.Builder == null ? rep : string.Format("<unresolved {0}>", rep); } /// <summary> /// Returns the string representation of this constraint /// </summary> protected virtual string GetStringRepresentation() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("<"); sb.Append(DisplayName.ToLower()); foreach (object arg in Arguments) { sb.Append(" "); sb.Append(_displayable(arg)); } sb.Append(">"); return sb.ToString(); } private static string _displayable(object o) { if (o == null) return "null"; string fmt = o is string ? "\"{0}\"" : "{0}"; return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o); } #endregion #region Operator Overloads /// <summary> /// This operator creates a constraint that is satisfied only if both /// argument constraints are satisfied. /// </summary> public static Constraint operator &(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new AndConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if either /// of the argument constraints is satisfied. /// </summary> public static Constraint operator |(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new OrConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if the /// argument constraint is not satisfied. /// </summary> public static Constraint operator !(Constraint constraint) { IResolveConstraint r = (IResolveConstraint)constraint; return new NotConstraint(r.Resolve()); } #endregion #region Binary Operators /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression And { get { ConstraintBuilder builder = this.Builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new AndOperator()); return new ConstraintExpression(builder); } } /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression With { get { return this.And; } } /// <summary> /// Returns a ConstraintExpression by appending Or /// to the current constraint. /// </summary> public ConstraintExpression Or { get { ConstraintBuilder builder = this.Builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new OrOperator()); return new ConstraintExpression(builder); } } #endregion #region After Modifier #if !PORTABLE /// <summary> /// Returns a DelayedConstraint.WithRawDelayInterval with the specified delay time. /// </summary> /// <param name="delay">The delay, which defaults to milliseconds.</param> /// <returns></returns> public DelayedConstraint.WithRawDelayInterval After(int delay) { return new DelayedConstraint.WithRawDelayInterval(new DelayedConstraint( Builder == null ? this : Builder.Resolve(), delay)); } /// <summary> /// Returns a DelayedConstraint with the specified delay time /// and polling interval. /// </summary> /// <param name="delayInMilliseconds">The delay in milliseconds.</param> /// <param name="pollingInterval">The interval at which to test the constraint.</param> /// <returns></returns> public DelayedConstraint After(int delayInMilliseconds, int pollingInterval) { return new DelayedConstraint( Builder == null ? this : Builder.Resolve(), delayInMilliseconds, pollingInterval); } #endif #endregion #region IResolveConstraint Members /// <summary> /// Resolves any pending operators and returns the resolved constraint. /// </summary> IConstraint IResolveConstraint.Resolve() { return Builder == null ? this : Builder.Resolve(); } #endregion } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Xml; using Sce.Atf; using Sce.Atf.Applications; using Sce.Sled.Resources; using Sce.Sled.Shared; using Sce.Sled.Shared.Plugin; using Sce.Sled.Shared.Services; namespace Sce.Sled { public partial class SledTtyGui : UserControl, IInitializable { public SledTtyGui() { InitializeComponent(); var none = new ComboBoxItem(null); m_cmbLanguages.Items.Add(none); m_cmbLanguages.SelectedItem = none; } public void Initialize() { BuildControl(); var mainForm = SledServiceInstance.TryGet<MainForm>(); mainForm.Shown += MainFormShown; SkinService.ApplyActiveSkin(SledTtyMessageColorer.Instance); SkinService.SkinChangedOrApplied += SkinServiceSkinChangedOrApplied; } private void MainFormShown(object sender, EventArgs e) { if (m_splitterDistance == 0) return; try { m_split.SplitterDistance = m_splitterDistance; } catch (Exception ex) { SledOutDevice.OutLine( SledMessageType.Error, "SledTtyGui: Exception restoring splitter distance: {0}", ex.Message); } } public string[] ColumnNames { get { return m_columnNames; } set { m_columnNames = value; } } public IEnumerable<SledTtyMessage> Selection { get { if (SelectionCount == 0) yield break; foreach (int index in m_lstOutput.SelectedIndices) { yield return m_messages[index]; } } } public int SelectionCount { get { return m_lstOutput.SelectedIndices.Count; } } public string Settings { get { var xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", Encoding.UTF8.WebName, "yes")); var root = xmlDoc.CreateElement("Columns"); xmlDoc.AppendChild(root); // Save column widths foreach (var kv in m_columnWidths) { var columnElement = xmlDoc.CreateElement("Column"); root.AppendChild(columnElement); columnElement.SetAttribute("Name", kv.Key); columnElement.SetAttribute("Width", kv.Value.ToString()); } // Save splitter position var splitterElement = xmlDoc.CreateElement("Splitter"); splitterElement.SetAttribute("Distance", m_split.SplitterDistance.ToString()); root.AppendChild(splitterElement); return xmlDoc.InnerXml; } set { if (string.IsNullOrEmpty(value)) return; var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(value); var root = xmlDoc.DocumentElement; if ((root == null) || (root.Name != "Columns")) throw new Exception("Invalid SledTtyGui settings"); var columns = root.SelectNodes("Column"); if (columns != null) { foreach (XmlElement columnElement in columns) { var name = columnElement.GetAttribute("Name"); var widthString = columnElement.GetAttribute("Width"); int width; if (!string.IsNullOrEmpty(widthString) && int.TryParse(widthString, out width)) m_columnWidths[name] = width; } } var splitter = root.SelectNodes("Splitter"); if (splitter != null) { foreach (XmlElement splitterElement in splitter) { var distanceString = splitterElement.GetAttribute("Distance"); int distance; if (!string.IsNullOrEmpty(distanceString) && int.TryParse(distanceString, out distance)) m_splitterDistance = distance; break; } } if (columns == null) return; m_lstOutput.SuspendLayout(); foreach (ColumnHeader column in m_lstOutput.Columns) SetColumnWidth(column); m_lstOutput.ResumeLayout(); } } public void Clear() { try { m_lstOutput.VirtualListSize = 0; m_lstOutput.ResetWorkaroundList(); } finally { m_messages.Clear(); } } public bool SendEnabled { get { return m_btnSend.Enabled; } set { m_btnSend.Enabled = value; } } public void RegisterLanguage(ISledLanguagePlugin language) { var item = new ComboBoxItem(language); m_cmbLanguages.Items.Add(item); m_cmbLanguages.SelectedItem = item; } public void AppendMessages(List<SledTtyMessage> messages) { if (messages.Count <= 0) return; m_messages.AddRange(messages); m_lstOutput.VirtualListSize = m_messages.Count; m_lstOutput.EnsureVisible(m_messages.Count - 1); } public event EventHandler<SendClickedEventArgs> SendClicked; private void BuildControl() { if (m_bBuiltControl) return; try { m_lstOutput.Columns.Clear(); foreach (var name in m_columnNames) { var column = new ColumnHeader {Text = name}; SetColumnWidth(column); m_lstOutput.Columns.Add(column); } } finally { m_bBuiltControl = false; } } private void SetColumnWidth(ColumnHeader column) { int width; if (m_columnWidths.TryGetValue(column.Text, out width)) column.Width = width; else m_columnWidths[column.Text] = column.Width; } private void LstOutputColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) { var column = m_lstOutput.Columns[e.ColumnIndex]; m_columnWidths[column.Text] = column.Width; } private void LstOutputRetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) { var message = m_messages[e.ItemIndex]; // Show time with milliseconds included var time = message.Time.ToString("hh:mm:ss.fff"); var lstItem = new ListViewItem(time) {Tag = message}; lstItem.SubItems.Add(message.Message); e.Item = lstItem; } private void TxtInputKeyUp(object sender, KeyEventArgs e) { e.SuppressKeyPress = false; e.Handled = false; if (!e.Control || (e.KeyValue != 13)) return; if (!SendEnabled) return; if (StringUtil.IsNullOrEmptyOrWhitespace(m_txtInput.Text)) return; m_btnSend.PerformClick(); e.Handled = true; } private void BtnSendClick(object sender, EventArgs e) { var text = m_txtInput.Text; if (string.IsNullOrEmpty(text)) return; var item = m_cmbLanguages.SelectedItem as ComboBoxItem; if (item == null) return; var ea = new SendClickedEventArgs(item.Plugin, text); SendClicked.Raise(this, ea); if (ea.ClearText) m_txtInput.Text = string.Empty; } private void SkinServiceSkinChangedOrApplied(object sender, EventArgs e) { SkinService.ApplyActiveSkin(SledTtyMessageColorer.Instance); m_lstOutput.Invalidate(true); } private bool m_bBuiltControl; private string[] m_columnNames; private int m_splitterDistance; private readonly List<SledTtyMessage> m_messages = new List<SledTtyMessage>(); private readonly Dictionary<string, int> m_columnWidths = new Dictionary<string, int>(); #region Private Classes private class ComboBoxItem { public ComboBoxItem(ISledLanguagePlugin plugin) { Plugin = plugin; } public override string ToString() { return Plugin == null ? Localization.SledNone : Plugin.LanguageName; } public readonly ISledLanguagePlugin Plugin; } #endregion #region Public Classes public class SendClickedEventArgs : EventArgs { public SendClickedEventArgs(ISledLanguagePlugin plugin, string text) { Plugin = plugin; Text = text; ClearText = true; } public readonly ISledLanguagePlugin Plugin; public readonly string Text; public bool ClearText; } #endregion } }
namespace Epi.Windows.Analysis.Dialogs { partial class SelectDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SelectDialog)); this.btnHelp = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnFunctions = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.lblAvailableVar = new System.Windows.Forms.Label(); this.txtSelectCriteria = new System.Windows.Forms.TextBox(); this.lblSelectCriteria = new System.Windows.Forms.Label(); this.btnMissing = new System.Windows.Forms.Button(); this.btnNo = new System.Windows.Forms.Button(); this.btnYes = new System.Windows.Forms.Button(); this.btnOr = new System.Windows.Forms.Button(); this.btnAnd = new System.Windows.Forms.Button(); this.btnClosedParen = new System.Windows.Forms.Button(); this.btnOpenParen = new System.Windows.Forms.Button(); this.btnQuote = new System.Windows.Forms.Button(); this.btnAmpersand = new System.Windows.Forms.Button(); this.btnGreaterThan = new System.Windows.Forms.Button(); this.btnLessThan = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.btnMinus = new System.Windows.Forms.Button(); this.btnMultiply = new System.Windows.Forms.Button(); this.btnDivide = new System.Windows.Forms.Button(); this.btnEqual = new System.Windows.Forms.Button(); this.cmbAvailableVar = new System.Windows.Forms.ComboBox(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.btnFunction = new System.Windows.Forms.Button(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnFunctions // resources.ApplyResources(this.btnFunctions, "btnFunctions"); this.btnFunctions.Name = "btnFunctions"; this.btnFunctions.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnFunction_MouseDown); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // lblAvailableVar // this.lblAvailableVar.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblAvailableVar, "lblAvailableVar"); this.lblAvailableVar.Name = "lblAvailableVar"; // // txtSelectCriteria // resources.ApplyResources(this.txtSelectCriteria, "txtSelectCriteria"); this.txtSelectCriteria.Name = "txtSelectCriteria"; this.txtSelectCriteria.Leave += new System.EventHandler(this.txtSelectCriteria_Leave); // // lblSelectCriteria // this.lblSelectCriteria.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblSelectCriteria, "lblSelectCriteria"); this.lblSelectCriteria.Name = "lblSelectCriteria"; // // btnMissing // resources.ApplyResources(this.btnMissing, "btnMissing"); this.btnMissing.Name = "btnMissing"; this.btnMissing.Tag = "(.)"; this.btnMissing.Click += new System.EventHandler(this.ClickHandler); // // btnNo // resources.ApplyResources(this.btnNo, "btnNo"); this.btnNo.Name = "btnNo"; this.btnNo.Tag = "(-)"; this.btnNo.Click += new System.EventHandler(this.ClickHandler); // // btnYes // resources.ApplyResources(this.btnYes, "btnYes"); this.btnYes.Name = "btnYes"; this.btnYes.Tag = "(+)"; this.btnYes.Click += new System.EventHandler(this.ClickHandler); // // btnOr // resources.ApplyResources(this.btnOr, "btnOr"); this.btnOr.Name = "btnOr"; this.btnOr.Tag = "OR"; this.btnOr.Click += new System.EventHandler(this.ClickHandler); // // btnAnd // resources.ApplyResources(this.btnAnd, "btnAnd"); this.btnAnd.Name = "btnAnd"; this.btnAnd.Tag = "AND"; this.btnAnd.Click += new System.EventHandler(this.ClickHandler); // // btnClosedParen // resources.ApplyResources(this.btnClosedParen, "btnClosedParen"); this.btnClosedParen.Name = "btnClosedParen"; this.btnClosedParen.Click += new System.EventHandler(this.ClickHandler); // // btnOpenParen // resources.ApplyResources(this.btnOpenParen, "btnOpenParen"); this.btnOpenParen.Name = "btnOpenParen"; this.btnOpenParen.Click += new System.EventHandler(this.ClickHandler); // // btnQuote // resources.ApplyResources(this.btnQuote, "btnQuote"); this.btnQuote.Name = "btnQuote"; this.btnQuote.Click += new System.EventHandler(this.ClickHandler); // // btnAmpersand // resources.ApplyResources(this.btnAmpersand, "btnAmpersand"); this.btnAmpersand.Name = "btnAmpersand"; this.btnAmpersand.Tag = " & "; this.btnAmpersand.Click += new System.EventHandler(this.ClickHandler); // // btnGreaterThan // resources.ApplyResources(this.btnGreaterThan, "btnGreaterThan"); this.btnGreaterThan.Name = "btnGreaterThan"; this.btnGreaterThan.Click += new System.EventHandler(this.ClickHandler); // // btnLessThan // resources.ApplyResources(this.btnLessThan, "btnLessThan"); this.btnLessThan.Name = "btnLessThan"; this.btnLessThan.Click += new System.EventHandler(this.ClickHandler); // // btnAdd // resources.ApplyResources(this.btnAdd, "btnAdd"); this.btnAdd.Name = "btnAdd"; this.btnAdd.Click += new System.EventHandler(this.ClickHandler); // // btnMinus // resources.ApplyResources(this.btnMinus, "btnMinus"); this.btnMinus.Name = "btnMinus"; this.btnMinus.Click += new System.EventHandler(this.ClickHandler); // // btnMultiply // resources.ApplyResources(this.btnMultiply, "btnMultiply"); this.btnMultiply.Name = "btnMultiply"; this.btnMultiply.Click += new System.EventHandler(this.ClickHandler); // // btnDivide // resources.ApplyResources(this.btnDivide, "btnDivide"); this.btnDivide.Name = "btnDivide"; this.btnDivide.Click += new System.EventHandler(this.ClickHandler); // // btnEqual // resources.ApplyResources(this.btnEqual, "btnEqual"); this.btnEqual.Name = "btnEqual"; this.btnEqual.Click += new System.EventHandler(this.ClickHandler); // // cmbAvailableVar // resources.ApplyResources(this.cmbAvailableVar, "cmbAvailableVar"); this.cmbAvailableVar.Items.AddRange(new object[] { resources.GetString("cmbAvailableVar.Items"), resources.GetString("cmbAvailableVar.Items1"), resources.GetString("cmbAvailableVar.Items2")}); this.cmbAvailableVar.Name = "cmbAvailableVar"; // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // btnFunction // resources.ApplyResources(this.btnFunction, "btnFunction"); this.btnFunction.Name = "btnFunction"; this.btnFunction.UseVisualStyleBackColor = true; this.btnFunction.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnFunction_MouseDown); // // SelectDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.btnFunction); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnFunctions); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.lblAvailableVar); this.Controls.Add(this.lblSelectCriteria); this.Controls.Add(this.btnMissing); this.Controls.Add(this.btnNo); this.Controls.Add(this.btnYes); this.Controls.Add(this.btnOr); this.Controls.Add(this.btnAnd); this.Controls.Add(this.btnClosedParen); this.Controls.Add(this.btnOpenParen); this.Controls.Add(this.btnQuote); this.Controls.Add(this.btnAmpersand); this.Controls.Add(this.btnGreaterThan); this.Controls.Add(this.btnLessThan); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnMinus); this.Controls.Add(this.btnMultiply); this.Controls.Add(this.btnDivide); this.Controls.Add(this.btnEqual); this.Controls.Add(this.cmbAvailableVar); this.Controls.Add(this.txtSelectCriteria); this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SelectDialog"; this.Load += new System.EventHandler(this.SelectDialog_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblAvailableVar; private System.Windows.Forms.Button btnMissing; private System.Windows.Forms.Button btnNo; private System.Windows.Forms.Button btnYes; private System.Windows.Forms.Button btnOr; private System.Windows.Forms.Button btnAnd; private System.Windows.Forms.Button btnClosedParen; private System.Windows.Forms.Button btnOpenParen; private System.Windows.Forms.Button btnQuote; private System.Windows.Forms.Button btnAmpersand; private System.Windows.Forms.Button btnGreaterThan; private System.Windows.Forms.Button btnLessThan; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnMinus; private System.Windows.Forms.Button btnMultiply; private System.Windows.Forms.Button btnDivide; private System.Windows.Forms.Button btnEqual; private System.Windows.Forms.ComboBox cmbAvailableVar; private System.Windows.Forms.Button btnFunctions; private System.Windows.Forms.TextBox txtSelectCriteria; private System.Windows.Forms.Label lblSelectCriteria; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.Button btnFunction; } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Diagnostics; using System.Data.SqlServerCe; using System.IO; using ESRI.ArcLogistics.Utility; namespace ESRI.ArcLogistics.Data { /// <summary> /// DbArchiveResult class. /// </summary> internal class DbArchiveResult { #region constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public DbArchiveResult(string path, bool isCreated, DateTime? firstDate, DateTime? lastDate) { _path = path; _isCreated = isCreated; _firstDate = firstDate; _lastDate = lastDate; } #endregion constructors #region public properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets archive path. /// </summary> public string ArchivePath { get { return _path; } } /// <summary> /// Gets a value indicating if archive was created. /// False value means that original database does not contain data to archive. /// </summary> public bool IsArchiveCreated { get { return _isCreated; } } /// <summary> /// Gets oldest date with assigned schedule. /// </summary> public DateTime? FirstDateWithRoutes { get { return _firstDate; } } /// <summary> /// Gets newest date with assigned schedule. /// </summary> public DateTime? LastDateWithRoutes { get { return _lastDate; } } #endregion public properties #region private fields /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private string _path; private bool _isCreated; private DateTime? _firstDate; private DateTime? _lastDate; #endregion private fields } /// <summary> /// DatabaseArchiver class. /// </summary> internal class DatabaseArchiver { #region constants /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // date format for archive name private const string DATE_FORMAT = "yyyy-MM-dd"; // archive file name format private const string ARCH_NAME_FORMAT = "{0} {1}{2}"; private const string ARCH_NAME_EXT_FORMAT = "{0} {1} ({2}){3}"; #endregion constants #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Archives database. /// This method creates archive database if the original one contains /// data to archive and cleans original database (removes archived data). /// If method succeeds, archive will contain schedules older than /// specified date. /// If original database does not contain data to archive, archive file /// will not be created and DbArchiveResult.IsArchiveCreated property /// will be set to "false". /// Method throws an exception if failure occures. /// </summary> /// <param name="path"> /// File path of original database. /// </param> /// <param name="date"> /// Schedules older than this date will be archived. /// </param> /// <returns> /// DbArchiveResult object. /// </returns> public static DbArchiveResult ArchiveDatabase(string path, DateTime date) { Debug.Assert(path != null); bool isCreated = false; DateTime? firstDate = null; DateTime? lastDate = null; string baseConnStr = DatabaseHelper.BuildSqlConnString(path, true); string archPath = null; // check if database has schedules to archive if (_HasDataToArchive(baseConnStr, date)) { // make archive file path archPath = _BuildArchivePath(path); // copy original file File.Copy(path, archPath); try { string archConnStr = DatabaseHelper.BuildSqlConnString( archPath, true); // apply script to archive _ApplyScript(archConnStr, ResourceLoader.ReadFileAsString(ARCHIVE_SCRIPT_FILE_NAME), date); // query archive dates _QueryDates(archConnStr, out firstDate, out lastDate); // compact archive file SqlCeEngine engine = new SqlCeEngine(archConnStr); engine.Shrink(); // apply script to original database _ApplyScript(baseConnStr, ResourceLoader.ReadFileAsString(CLEAN_SCRIPT_FILE_NAME), date); isCreated = true; } catch { DatabaseEngine.DeleteDatabase(archPath); throw; } } return new DbArchiveResult(archPath, isCreated, firstDate, lastDate); } #endregion public methods #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private static void _ApplyScript(string connStr, string script, DateTime date) { Debug.Assert(connStr != null); Debug.Assert(script != null); // upgrade database if necessary DatabaseOpener.CheckForDbUpgrade(connStr); // script parameters SqlCeParameter[] paramArray = new SqlCeParameter[] { new SqlCeParameter("@date", date) }; // apply script DatabaseEngine.ExecuteScript(connStr, script, paramArray); } private static string _BuildArchivePath(string path) { Debug.Assert(path != null); string extension = Path.GetExtension(path); if (String.IsNullOrEmpty(extension)) throw new DataException(Properties.Messages.Error_GenDBArchiveName); string baseName = Path.GetFileNameWithoutExtension(path); if (String.IsNullOrEmpty(baseName)) throw new DataException(Properties.Messages.Error_GenDBArchiveName); string baseDir = Path.GetDirectoryName(path); if (String.IsNullOrEmpty(baseName)) throw new DataException(Properties.Messages.Error_GenDBArchiveName); string dateSuffix = DateTime.Now.ToString(DATE_FORMAT); string archName = String.Format(ARCH_NAME_FORMAT, baseName, dateSuffix, extension); string archPath = Path.Combine(baseDir, archName); bool exists = File.Exists(archPath); if (exists) { for (int count = 1; count < int.MaxValue; count++) { archName = String.Format(ARCH_NAME_EXT_FORMAT, baseName, dateSuffix, count, extension); archPath = Path.Combine(baseDir, archName); exists = File.Exists(archPath); if (!exists) break; } if (exists) throw new DataException(Properties.Messages.Error_GenDBArchiveName); } return archPath; } private static bool _HasDataToArchive(string connStr, DateTime date) { Debug.Assert(connStr != null); using (SqlCeConnection conn = new SqlCeConnection(connStr)) { conn.Open(); using (SqlCeCommand cmd = new SqlCeCommand( QUERY_STOPS_COUNT_BY_SCHEDULE_DATE, conn)) { cmd.Parameters.Add(new SqlCeParameter("@date", date)); int count = (int)cmd.ExecuteScalar(); return (count > 0); } } } private static void _QueryDates(string connStr, out DateTime? firstDate, out DateTime? lastDate) { Debug.Assert(connStr != null); using (SqlCeConnection conn = new SqlCeConnection(connStr)) { conn.Open(); firstDate = _QueryDate(conn, QUERY_OLDEST_SCHEDULE); lastDate = _QueryDate(conn, QUERY_OLDEST_SCHEDULE); } } private static DateTime? _QueryDate(SqlCeConnection conn, string query) { Debug.Assert(conn != null); Debug.Assert(query != null); using (SqlCeCommand cmd = new SqlCeCommand(query, conn)) { using (SqlCeDataReader reader = cmd.ExecuteReader()) { DateTime? date = null; if (reader.Read()) date = reader.GetDateTime(0); return date; } } } #endregion private methods #region Private constants /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Name of the file with archive script. /// </summary> private const string ARCHIVE_SCRIPT_FILE_NAME = "aldb_archive.sql"; /// <summary> /// Name of the file with cleaning script. /// </summary> private const string CLEAN_SCRIPT_FILE_NAME = "aldb_clean.sql"; /// <summary> /// Queries to DataBase. /// </summary> private const string QUERY_STOPS_COUNT_BY_SCHEDULE_DATE = @"select count(*) from [Stops] as st inner join [Routes] as rt on rt.[Id] = st.[RouteId] inner join [Schedules] as sch on sch.[Id] = rt.[ScheduleId] where rt.[Default] = 0 and sch.[PlannedDate] < @date"; private const string QUERY_NEWEST_SCHEDULE = @"select top(1) sch.[PlannedDate] from [Schedules] as sch inner join [Routes] as rt on sch.[Id] = rt.[ScheduleId] inner join [Stops] as st on rt.[Id] = st.[RouteId] where rt.[Default] = 0 order by sch.[PlannedDate] desc"; private const string QUERY_OLDEST_SCHEDULE = @"select top(1) sch.[PlannedDate] from [Schedules] as sch inner join [Routes] as rt on sch.[Id] = rt.[ScheduleId] inner join [Stops] as st on rt.[Id] = st.[RouteId] where rt.[Default] = 0 order by sch.[PlannedDate]"; #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using OpenMetaverse; using OpenSim.Region.Physics.Manager; using OpenSim.Region.Physics.Meshing; public class Vertex : IComparable<Vertex>, IEquatable<Vertex> { private OpenMetaverse.Vector3 _impl; public float X { get { return _impl.X; } set { _impl.X = value; } } public float Y { get { return _impl.Y; } set { _impl.Y = value; } } public float Z { get { return _impl.Z; } set { _impl.Z = value; } } public Vertex() { _impl = new Vector3(); } public Vertex(float x, float y, float z) { Set(x, y, z); } public Vector3 AsVector() { return _impl; } public void Set(float x, float y, float z) { if (float.IsInfinity(x) || float.IsNaN(x)) x = 0f; if (float.IsInfinity(y) || float.IsNaN(y)) y = 0f; if (float.IsInfinity(z) || float.IsNaN(z)) z = 0f; _impl = new Vector3(x, y, z); } public Vertex normalize() { float tlength = _impl.Length(); if (tlength != 0) { float mul = 1.0f / tlength; return new Vertex(X * mul, Y * mul, Z * mul); } else { return new Vertex(0, 0, 0); } } public Vertex cross(Vertex v) { return new Vertex(Y * v.Z - Z * v.Y, Z * v.X - X * v.Z, X * v.Y - Y * v.X); } // disable warning: mono compiler moans about overloading // operators hiding base operator but should not according to C# // language spec #pragma warning disable 0108 public static Vertex operator *(Vertex v, Quaternion q) { // From http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/ Vertex v2 = new Vertex(0f, 0f, 0f); v2.X = q.W * q.W * v.X + 2f * q.Y * q.W * v.Z - 2f * q.Z * q.W * v.Y + q.X * q.X * v.X + 2f * q.Y * q.X * v.Y + 2f * q.Z * q.X * v.Z - q.Z * q.Z * v.X - q.Y * q.Y * v.X; v2.Y = 2f * q.X * q.Y * v.X + q.Y * q.Y * v.Y + 2f * q.Z * q.Y * v.Z + 2f * q.W * q.Z * v.X - q.Z * q.Z * v.Y + q.W * q.W * v.Y - 2f * q.X * q.W * v.Z - q.X * q.X * v.Y; v2.Z = 2f * q.X * q.Z * v.X + 2f * q.Y * q.Z * v.Y + q.Z * q.Z * v.Z - 2f * q.W * q.Y * v.X - q.Y * q.Y * v.Z + 2f * q.W * q.X * v.Y - q.X * q.X * v.Z + q.W * q.W * v.Z; return v2; } public static Vertex operator +(Vertex v1, Vertex v2) { return new Vertex(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); } public static Vertex operator -(Vertex v1, Vertex v2) { return new Vertex(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z); } public static Vertex operator *(Vertex v1, Vertex v2) { return new Vertex(v1.X * v2.X, v1.Y * v2.Y, v1.Z * v2.Z); } public static Vertex operator +(Vertex v1, float am) { v1.X += am; v1.Y += am; v1.Z += am; return v1; } public static Vertex operator -(Vertex v1, float am) { v1.X -= am; v1.Y -= am; v1.Z -= am; return v1; } public static Vertex operator *(Vertex v1, float am) { v1.X *= am; v1.Y *= am; v1.Z *= am; return v1; } public static Vertex operator /(Vertex v1, float am) { if (am == 0f) { return new Vertex(0f,0f,0f); } float mul = 1.0f / am; v1.X *= mul; v1.Y *= mul; v1.Z *= mul; return v1; } #pragma warning restore 0108 public float dot(Vertex v) { return X * v.X + Y * v.Y + Z * v.Z; } public Vertex(OpenMetaverse.Vector3 v) { _impl = new Vector3(v); } public Vertex Clone() { return new Vertex(X, Y, Z); } public static Vertex FromAngle(double angle) { return new Vertex((float) Math.Cos(angle), (float) Math.Sin(angle), 0.0f); } public virtual bool Equals(Vertex v, float tolerance) { OpenMetaverse.Vector3 diff = this._impl - v._impl; float d = diff.Length(); if (d < tolerance) return true; return false; } public int CompareTo(Vertex other) { if (X < other.X) return -1; if (X > other.X) return 1; if (Y < other.Y) return -1; if (Y > other.Y) return 1; if (Z < other.Z) return -1; if (Z > other.Z) return 1; return 0; } public static bool operator >(Vertex me, Vertex other) { return me.CompareTo(other) > 0; } public static bool operator <(Vertex me, Vertex other) { return me.CompareTo(other) < 0; } public String ToRaw() { // Why this stuff with the number formatter? // Well, the raw format uses the english/US notation of numbers // where the "," separates groups of 1000 while the "." marks the border between 1 and 10E-1. // The german notation uses these characters exactly vice versa! // The Float.ToString() routine is a localized one, giving different results depending on the country // settings your machine works with. Unusable for a machine readable file format :-( NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; nfi.NumberDecimalDigits = 3; String s1 = X.ToString("N2", nfi) + " " + Y.ToString("N2", nfi) + " " + Z.ToString("N2", nfi); return s1; } #region IEquatable<Vertex> Members public bool Equals(Vertex other) { return this._impl.Equals(other._impl); } public override int GetHashCode() { return this._impl.GetHashCode(); } #endregion } public class Triangle : IEquatable<Triangle> { public Vertex v1; public Vertex v2; public Vertex v3; private float radius_square; private float cx; private float cy; public Triangle() { } public Triangle(Vertex _v1, Vertex _v2, Vertex _v3) { v1 = _v1; v2 = _v2; v3 = _v3; CalcCircle(); } public void Set(Vertex _v1, Vertex _v2, Vertex _v3) { v1 = _v1; v2 = _v2; v3 = _v3; CalcCircle(); } public bool isInCircle(float x, float y) { float dx, dy; float dd; dx = x - cx; dy = y - cy; dd = dx*dx + dy*dy; if (dd < radius_square) return true; else return false; } public bool isDegraded() { // This means, the vertices of this triangle are somewhat strange. // They either line up or at least two of them are identical return (radius_square == 0.0); } private void CalcCircle() { // Calculate the center and the radius of a circle given by three points p1, p2, p3 // It is assumed, that the triangles vertices are already set correctly double p1x, p2x, p1y, p2y, p3x, p3y; // Deviation of this routine: // A circle has the general equation (M-p)^2=r^2, where M and p are vectors // this gives us three equations f(p)=r^2, each for one point p1, p2, p3 // putting respectively two equations together gives two equations // f(p1)=f(p2) and f(p1)=f(p3) // bringing all constant terms to one side brings them to the form // M*v1=c1 resp.M*v2=c2 where v1=(p1-p2) and v2=(p1-p3) (still vectors) // and c1, c2 are scalars (Naming conventions like the variables below) // Now using the equations that are formed by the components of the vectors // and isolate Mx lets you make one equation that only holds My // The rest is straight forward and eaasy :-) // /* helping variables for temporary results */ double c1, c2; double v1x, v1y, v2x, v2y; double z, n; double rx, ry; // Readout the three points, the triangle consists of p1x = v1.X; p1y = v1.Y; p2x = v2.X; p2y = v2.Y; p3x = v3.X; p3y = v3.Y; /* calc helping values first */ c1 = (p1x*p1x + p1y*p1y - p2x*p2x - p2y*p2y)/2; c2 = (p1x*p1x + p1y*p1y - p3x*p3x - p3y*p3y)/2; v1x = p1x - p2x; v1y = p1y - p2y; v2x = p1x - p3x; v2y = p1y - p3y; z = (c1*v2x - c2*v1x); n = (v1y*v2x - v2y*v1x); if (n == 0.0) // This is no triangle, i.e there are (at least) two points at the same location { radius_square = 0.0f; return; } cy = (float) (z/n); if (v2x != 0.0) { cx = (float) ((c2 - v2y*cy)/v2x); } else if (v1x != 0.0) { cx = (float) ((c1 - v1y*cy)/v1x); } else { Debug.Assert(false, "Malformed triangle"); /* Both terms zero means nothing good */ } rx = (p1x - cx); ry = (p1y - cy); radius_square = (float) (rx*rx + ry*ry); } public override String ToString() { NumberFormatInfo nfi = new NumberFormatInfo(); nfi.CurrencyDecimalDigits = 2; nfi.CurrencyDecimalSeparator = "."; String s1 = "<" + v1.X.ToString(nfi) + "," + v1.Y.ToString(nfi) + "," + v1.Z.ToString(nfi) + ">"; String s2 = "<" + v2.X.ToString(nfi) + "," + v2.Y.ToString(nfi) + "," + v2.Z.ToString(nfi) + ">"; String s3 = "<" + v3.X.ToString(nfi) + "," + v3.Y.ToString(nfi) + "," + v3.Z.ToString(nfi) + ">"; return s1 + ";" + s2 + ";" + s3; } public OpenMetaverse.Vector3 getNormal() { // Vertices // Vectors for edges OpenMetaverse.Vector3 e1; OpenMetaverse.Vector3 e2; e1 = new OpenMetaverse.Vector3(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z); e2 = new OpenMetaverse.Vector3(v1.X - v3.X, v1.Y - v3.Y, v1.Z - v3.Z); // Cross product for normal OpenMetaverse.Vector3 n = OpenMetaverse.Vector3.Cross(e1, e2); // Length float l = n.Length(); // Normalized "normal" n = n/l; return n; } public void invertNormal() { Vertex vt; vt = v1; v1 = v2; v2 = vt; } // Dumps a triangle in the "raw faces" format, blender can import. This is for visualisation and // debugging purposes public String ToStringRaw() { String output = v1.ToRaw() + " " + v2.ToRaw() + " " + v3.ToRaw(); return output; } public bool Equals(Triangle other) { return this.v1.Equals(other.v1) && this.v2.Equals(other.v2) && this.v3.Equals(other.v3); } public override int GetHashCode() { return v1.GetHashCode() ^ v2.GetHashCode() ^ v3.GetHashCode(); } } public class IndexedTriangle : IEquatable<IndexedTriangle> { public int v1; public int v2; public int v3; public IndexedTriangle(int _v1, int _v2, int _v3) { int[] arr = new int[3] { _v1, _v2, _v3 }; Array.Sort(arr); v1 = arr[0]; v2 = arr[1]; v3 = arr[2]; } public override String ToString() { return "<" + v1.ToString() + "," + v2.ToString() + "," + v3.ToString() + ">"; } public bool Equals(IndexedTriangle other) { return this.v1.Equals(other.v1) && this.v2.Equals(other.v2) && this.v3.Equals(other.v3); } public override int GetHashCode() { return v1.GetHashCode() ^ v2.GetHashCode() ^ v3.GetHashCode(); } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using SchoolBusAPI.Models; namespace SchoolBusAPI.ViewModels { /// <summary> /// /// </summary> [DataContract] public partial class UserFavouriteViewModel : IEquatable<UserFavouriteViewModel> { /// <summary> /// Default constructor, required by entity framework /// </summary> public UserFavouriteViewModel() { } /// <summary> /// Initializes a new instance of the <see cref="UserFavouriteViewModel" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Name">Context Name.</param> /// <param name="Value">Saved search.</param> /// <param name="IsDefault">IsDefault.</param> /// <param name="FavouriteContextTypeId">FavouriteContextTypeId.</param> public UserFavouriteViewModel(int Id, string Name = null, string Value = null, bool? IsDefault = null, int? FavouriteContextTypeId = null) { this.Id = Id; this.Name = Name; this.Value = Value; this.IsDefault = IsDefault; this.FavouriteContextTypeId = FavouriteContextTypeId; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id")] public int Id { get; set; } /// <summary> /// Context Name /// </summary> /// <value>Context Name</value> [DataMember(Name="name")] [MetaDataExtension (Description = "Context Name")] public string Name { get; set; } /// <summary> /// Saved search /// </summary> /// <value>Saved search</value> [DataMember(Name="value")] [MetaDataExtension (Description = "Saved search")] public string Value { get; set; } /// <summary> /// Gets or Sets IsDefault /// </summary> [DataMember(Name="isDefault")] public bool? IsDefault { get; set; } /// <summary> /// Gets or Sets FavouriteContextTypeId /// </summary> [DataMember(Name="favouriteContextTypeId")] public int? FavouriteContextTypeId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UserFavouriteViewModel {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" IsDefault: ").Append(IsDefault).Append("\n"); sb.Append(" FavouriteContextTypeId: ").Append(FavouriteContextTypeId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((UserFavouriteViewModel)obj); } /// <summary> /// Returns true if UserFavouriteViewModel instances are equal /// </summary> /// <param name="other">Instance of UserFavouriteViewModel to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserFavouriteViewModel other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Value == other.Value || this.Value != null && this.Value.Equals(other.Value) ) && ( this.IsDefault == other.IsDefault || this.IsDefault != null && this.IsDefault.Equals(other.IsDefault) ) && ( this.FavouriteContextTypeId == other.FavouriteContextTypeId || this.FavouriteContextTypeId != null && this.FavouriteContextTypeId.Equals(other.FavouriteContextTypeId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks if (this.Id != null) { hash = hash * 59 + this.Id.GetHashCode(); } if (this.Name != null) { hash = hash * 59 + this.Name.GetHashCode(); } if (this.Value != null) { hash = hash * 59 + this.Value.GetHashCode(); } if (this.IsDefault != null) { hash = hash * 59 + this.IsDefault.GetHashCode(); } if (this.FavouriteContextTypeId != null) { hash = hash * 59 + this.FavouriteContextTypeId.GetHashCode(); } return hash; } } #region Operators public static bool operator ==(UserFavouriteViewModel left, UserFavouriteViewModel right) { return Equals(left, right); } public static bool operator !=(UserFavouriteViewModel left, UserFavouriteViewModel right) { return !Equals(left, right); } #endregion Operators } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal { public partial class WebApplicationGalleryParams { /// <summary> /// asyncTasks control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks; /// <summary> /// messageBox control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox; /// <summary> /// appHeader control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.WebApplicationGalleryHeader appHeader; /// <summary> /// urlPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl urlPanel; /// <summary> /// hlApplication control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink hlApplication; /// <summary> /// tempUrlPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl tempUrlPanel; /// <summary> /// tempUrl control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal tempUrl; /// <summary> /// secAppSettings control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secAppSettings; /// <summary> /// SettingsPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel SettingsPanel; /// <summary> /// lblInstallOnWebSite control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize lblInstallOnWebSite; /// <summary> /// locWebSiteDescription control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locWebSiteDescription; /// <summary> /// ddlWebSite control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlWebSite; /// <summary> /// valRequireWebSite control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator valRequireWebSite; /// <summary> /// lblInstallOnDirectory control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize lblInstallOnDirectory; /// <summary> /// directoryName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UsernameControl directoryName; /// <summary> /// lblLeaveThisFieldBlank control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize lblLeaveThisFieldBlank; /// <summary> /// divDatabase control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl divDatabase; /// <summary> /// databaseEngineBlock control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl databaseEngineBlock; /// <summary> /// locDatabaseType control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locDatabaseType; /// <summary> /// locDatabaseTypeDescr control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locDatabaseTypeDescr; /// <summary> /// databaseEngines control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList databaseEngines; /// <summary> /// databaseModeBlock control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl databaseModeBlock; /// <summary> /// locNewDatabase control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locNewDatabase; /// <summary> /// locNewDatabaseDescr control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locNewDatabaseDescr; /// <summary> /// databaseMode control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList databaseMode; /// <summary> /// repParams control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater repParams; /// <summary> /// InstallLogPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel InstallLogPanel; /// <summary> /// InstallLog control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl InstallLog; /// <summary> /// btnInstall control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnInstall; /// <summary> /// btnCancel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnCancel; /// <summary> /// btnOK control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnOK; } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 RazorDBx.C5; using NUnit.Framework; using SCG = System.Collections.Generic; namespace C5UnitTests.interfaces { [TestFixture] public class ICollectionsTests { public void TryC5Coll (ICollection<double> coll) { Assert.AreEqual (0, coll.Count); double[] arr = { }; coll.CopyTo(arr, 0); Assert.IsFalse(coll.IsReadOnly); coll.Add(2.3); coll.Add(3.2); Assert.AreEqual(2, coll.Count); Assert.IsTrue(coll.Contains(2.3)); Assert.IsFalse(coll.Contains(3.1)); Assert.IsFalse(coll.Remove(3.1)); Assert.IsTrue(coll.Remove(3.2)); Assert.IsFalse(coll.Contains(3.1)); Assert.AreEqual(1, coll.Count); coll.Clear(); Assert.AreEqual(0, coll.Count); Assert.IsFalse(coll.Remove(3.1)); } public void TrySCGColl(SCG.ICollection<double> coll) { // All members of SCG.ICollection<T> Assert.AreEqual(0, coll.Count); double[] arr = { }; coll.CopyTo(arr, 0); Assert.IsFalse(coll.IsReadOnly); coll.Add(2.3); coll.Add(3.2); Assert.AreEqual(2, coll.Count); Assert.IsTrue(coll.Contains(2.3)); Assert.IsFalse(coll.Contains(3.1)); Assert.IsFalse(coll.Remove(3.1)); Assert.IsTrue(coll.Remove(3.2)); Assert.IsFalse(coll.Contains(3.1)); Assert.AreEqual(1, coll.Count); coll.Clear(); Assert.AreEqual(0, coll.Count); Assert.IsFalse(coll.Remove(3.1)); } public void TryBothColl(ICollection<double> coll) { TryC5Coll(coll); TrySCGColl(coll); } [Test] public void Test1() { TryBothColl(new HashSet<double>()); TryBothColl(new HashBag<double>()); TryBothColl(new TreeSet<double>()); TryBothColl(new TreeBag<double>()); TryBothColl(new ArrayList<double>()); TryBothColl(new LinkedList<double>()); TryBothColl(new HashedArrayList<double>()); TryBothColl(new HashedLinkedList<double>()); TryBothColl(new SortedArray<double>()); } } [TestFixture] public class SCIListTests { class A { } class B : A { } class C : B { } public void TrySCIList(System.Collections.IList list) { // Should be called with a C5.IList<B> which is not a WrappedArray Assert.AreEqual(0, list.Count); list.CopyTo(new A[0], 0); list.CopyTo(new B[0], 0); list.CopyTo(new C[0], 0); Assert.IsTrue(!list.IsFixedSize); Assert.IsFalse(list.IsReadOnly); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Object b1 = new B(), b2 = new B(), c1 = new C(), c2 = new C(); Assert.AreEqual(0, list.Add(b1)); Assert.AreEqual(1, list.Add(c1)); Assert.AreEqual(2, list.Count); Assert.IsTrue(list.Contains(c1)); Assert.IsFalse(list.Contains(b2)); list[0] = b2; Assert.AreEqual(b2, list[0]); list[1] = c2; Assert.AreEqual(c2, list[1]); Assert.IsTrue(list.Contains(b2)); Assert.IsTrue(list.Contains(c2)); Array arrA = new A[2], arrB = new B[2]; list.CopyTo(arrA, 0); list.CopyTo(arrB, 0); Assert.AreEqual(b2, arrA.GetValue(0)); Assert.AreEqual(b2, arrB.GetValue(0)); Assert.AreEqual(c2, arrA.GetValue(1)); Assert.AreEqual(c2, arrB.GetValue(1)); Assert.AreEqual(0, list.IndexOf(b2)); Assert.AreEqual(-1, list.IndexOf(b1)); list.Remove(b1); list.Remove(b2); Assert.IsFalse(list.Contains(b2)); Assert.AreEqual(1, list.Count); // Contains c2 only list.Insert(0, b2); list.Insert(2, b1); Assert.AreEqual(b2, list[0]); Assert.AreEqual(c2, list[1]); Assert.AreEqual(b1, list[2]); list.Remove(c2); Assert.AreEqual(b2, list[0]); Assert.AreEqual(b1, list[1]); list.RemoveAt(1); Assert.AreEqual(b2, list[0]); list.Clear(); Assert.AreEqual(0, list.Count); list.Remove(b1); } [Test] public void Test1() { TrySCIList(new ArrayList<B>()); TrySCIList(new HashedArrayList<B>()); TrySCIList(new LinkedList<B>()); TrySCIList(new HashedLinkedList<B>()); } [Test] public void TryWrappedArrayAsSCIList1() { B[] myarray = new B[] { new B(), new B(), new C() }; System.Collections.IList list = new WrappedArray<B>(myarray); // Should be called with a three-element WrappedArray<B> Assert.AreEqual(3, list.Count); Assert.IsTrue(list.IsFixedSize); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Assert.AreEqual(myarray.SyncRoot, list.SyncRoot); Object b1 = new B(), b2 = new B(), c1 = new C(), c2 = new C(); list[0] = b2; Assert.AreEqual(b2, list[0]); list[1] = c2; Assert.AreEqual(c2, list[1]); Assert.IsTrue(list.Contains(b2)); Assert.IsTrue(list.Contains(c2)); Array arrA = new A[3], arrB = new B[3]; list.CopyTo(arrA, 0); list.CopyTo(arrB, 0); Assert.AreEqual(b2, arrA.GetValue(0)); Assert.AreEqual(b2, arrB.GetValue(0)); Assert.AreEqual(c2, arrA.GetValue(1)); Assert.AreEqual(c2, arrB.GetValue(1)); Assert.AreEqual(0, list.IndexOf(b2)); Assert.AreEqual(-1, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c1)); Assert.IsFalse(list.Contains(b1)); Assert.IsFalse(list.Contains(c1)); } [Test] public void TryWrappedArrayAsSCIList2() { B[] myarray = new B[] { }; System.Collections.IList list = new WrappedArray<B>(myarray); // Should be called with an empty WrappedArray<B> Assert.AreEqual(0, list.Count); list.CopyTo(new A[0], 0); list.CopyTo(new B[0], 0); list.CopyTo(new C[0], 0); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Object b1 = new B(), b2 = new B(), c1 = new C(), c2 = new C(); Assert.IsFalse(list.Contains(b2)); Assert.IsFalse(list.Contains(c2)); Assert.AreEqual(-1, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c1)); } [Test] public void TryGuardedListAsSCIList1() { B b1_ = new B(), b2_ = new B(); C c1_ = new C(), c2_ = new C(); ArrayList<B> mylist = new ArrayList<B>(); mylist.AddAll(new B[] { b1_, b2_, c1_ }); System.Collections.IList list = new GuardedList<B>(mylist); Object b1 = b1_, b2 = b2_, c1 = c1_, c2 = c2_; // Should be called with a three-element GuardedList<B> Assert.AreEqual(3, list.Count); Assert.IsTrue(list.IsFixedSize); Assert.IsTrue(list.IsReadOnly); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Assert.AreEqual(list.SyncRoot, ((System.Collections.IList)mylist).SyncRoot); Assert.IsTrue(list.Contains(b1)); Assert.IsTrue(list.Contains(b2)); Assert.IsTrue(list.Contains(c1)); Assert.IsFalse(list.Contains(c2)); Array arrA = new A[3], arrB = new B[3]; list.CopyTo(arrA, 0); list.CopyTo(arrB, 0); Assert.AreEqual(b1, arrA.GetValue(0)); Assert.AreEqual(b1, arrB.GetValue(0)); Assert.AreEqual(b2, arrA.GetValue(1)); Assert.AreEqual(b2, arrB.GetValue(1)); Assert.AreEqual(0, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c2)); } [Test] public void TryGuardedListAsSCIList2() { System.Collections.IList list = new GuardedList<B>(new ArrayList<B>()); // Should be called with an empty GuardedList<B> Assert.AreEqual(0, list.Count); list.CopyTo(new A[0], 0); list.CopyTo(new B[0], 0); list.CopyTo(new C[0], 0); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Object b1 = new B(), b2 = new B(), c1 = new C(), c2 = new C(); Assert.IsFalse(list.Contains(b2)); Assert.IsFalse(list.Contains(c2)); Assert.AreEqual(-1, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c1)); } [Test] public void TryViewOfGuardedListAsSCIList1() { B b1_ = new B(), b2_ = new B(); C c1_ = new C(), c2_ = new C(); ArrayList<B> mylist = new ArrayList<B>(); mylist.AddAll(new B[] { new B(), b1_, b2_, c1_, new B()}); System.Collections.IList list = new GuardedList<B>(mylist).View(1, 3); Object b1 = b1_, b2 = b2_, c1 = c1_, c2 = c2_; // Should be called with a three-element view of a GuardedList<B> Assert.AreEqual(3, list.Count); Assert.IsTrue(list.IsFixedSize); Assert.IsTrue(list.IsReadOnly); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Assert.AreEqual(list.SyncRoot, ((System.Collections.IList)mylist).SyncRoot); Assert.IsTrue(list.Contains(b1)); Assert.IsTrue(list.Contains(b2)); Assert.IsTrue(list.Contains(c1)); Assert.IsFalse(list.Contains(c2)); Array arrA = new A[3], arrB = new B[3]; list.CopyTo(arrA, 0); list.CopyTo(arrB, 0); Assert.AreEqual(b1, arrA.GetValue(0)); Assert.AreEqual(b1, arrB.GetValue(0)); Assert.AreEqual(b2, arrA.GetValue(1)); Assert.AreEqual(b2, arrB.GetValue(1)); Assert.AreEqual(0, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c2)); } [Test] public void TryViewOfGuardedListAsSCIList2() { System.Collections.IList list = new GuardedList<B>(new ArrayList<B>()).View(0, 0); Assert.AreEqual(0, list.Count); list.CopyTo(new A[0], 0); list.CopyTo(new B[0], 0); list.CopyTo(new C[0], 0); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Object b1 = new B(), b2 = new B(), c1 = new C(), c2 = new C(); Assert.IsFalse(list.Contains(b2)); Assert.IsFalse(list.Contains(c2)); Assert.AreEqual(-1, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c1)); } void TryListViewAsSCIList1(IList<B> mylist) { B b1_ = new B(), b2_ = new B(); C c1_ = new C(), c2_ = new C(); mylist.AddAll(new B[] { new B(), b1_, b2_, c1_, new B() }); System.Collections.IList list = mylist.View(1, 3); Object b1 = b1_, b2 = b2_, c1 = c1_, c2 = c2_; // Should be called with a three-element view on ArrayList<B> Assert.AreEqual(3, list.Count); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Assert.AreEqual(list.SyncRoot, mylist.SyncRoot); Assert.IsTrue(list.Contains(b1)); Assert.IsTrue(list.Contains(b2)); Assert.IsTrue(list.Contains(c1)); Assert.IsFalse(list.Contains(c2)); Array arrA = new A[3], arrB = new B[3]; list.CopyTo(arrA, 0); list.CopyTo(arrB, 0); Assert.AreEqual(b1, arrA.GetValue(0)); Assert.AreEqual(b1, arrB.GetValue(0)); Assert.AreEqual(b2, arrA.GetValue(1)); Assert.AreEqual(b2, arrB.GetValue(1)); Assert.AreEqual(0, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c2)); } void TryListViewAsSCIList2(IList<B> mylist) { System.Collections.IList list = mylist.View(0, 0); Assert.AreEqual(0, list.Count); list.CopyTo(new A[0], 0); list.CopyTo(new B[0], 0); list.CopyTo(new C[0], 0); Assert.IsFalse(list.IsSynchronized); Assert.AreNotEqual(null, list.SyncRoot); Assert.AreEqual(list.SyncRoot, mylist.SyncRoot); Object b1 = new B(), b2 = new B(), c1 = new C(), c2 = new C(); Assert.IsFalse(list.Contains(b2)); Assert.IsFalse(list.Contains(c2)); Assert.AreEqual(-1, list.IndexOf(b1)); Assert.AreEqual(-1, list.IndexOf(c1)); } [Test] public void TryArrayListViewAsSCIList() { TryListViewAsSCIList1(new ArrayList<B>()); TryListViewAsSCIList2(new ArrayList<B>()); } [Test] public void TryLinkedListViewAsSCIList() { TryListViewAsSCIList1(new LinkedList<B>()); TryListViewAsSCIList2(new LinkedList<B>()); } [Test] public void TryHashedArrayListViewAsSCIList() { TryListViewAsSCIList1(new HashedArrayList<B>()); TryListViewAsSCIList2(new HashedArrayList<B>()); } [Test] public void TryHashedLinkedListViewAsSCIList() { TryListViewAsSCIList1(new HashedLinkedList<B>()); TryListViewAsSCIList2(new HashedLinkedList<B>()); } [Test] public void TryGuardedViewAsSCIList() { ArrayList<B> mylist = new ArrayList<B>(); TryListViewAsSCIList2(new GuardedList<B>(mylist)); } } [TestFixture] public class IDictionaryTests { public void TryDictionary(IDictionary<string,string> dict) { Assert.AreEqual(0, dict.Count); Assert.IsTrue(dict.IsEmpty); Assert.IsFalse(dict.IsReadOnly); KeyValuePair<string,string>[] arr = { }; dict.CopyTo(arr, 0); dict["R"] = "A"; dict["S"] = "B"; dict["T"] = "C"; String old; Assert.IsTrue(dict.Update("R", "A1")); Assert.AreEqual("A1", dict["R"]); Assert.IsFalse(dict.Update("U", "D1")); Assert.IsFalse(dict.Contains("U")); Assert.IsTrue(dict.Update("R", "A2", out old)); Assert.AreEqual("A2", dict["R"]); Assert.AreEqual("A1", old); Assert.IsFalse(dict.Update("U", "D2", out old)); Assert.AreEqual(null, old); Assert.IsFalse(dict.Contains("U")); Assert.IsTrue(dict.UpdateOrAdd("R", "A3")); Assert.AreEqual("A3", dict["R"]); Assert.IsFalse(dict.UpdateOrAdd("U", "D3")); Assert.IsTrue(dict.Contains("U")); Assert.AreEqual("D3", dict["U"]); Assert.IsTrue(dict.UpdateOrAdd("R", "A4", out old)); Assert.AreEqual("A4", dict["R"]); Assert.AreEqual("A3", old); Assert.IsTrue(dict.UpdateOrAdd("U", "D4", out old)); Assert.IsTrue(dict.Contains("U")); Assert.AreEqual("D4", dict["U"]); Assert.AreEqual("D3", old); Assert.IsFalse(dict.UpdateOrAdd("V", "E1", out old)); Assert.IsTrue(dict.Contains("V")); Assert.AreEqual("E1", dict["V"]); Assert.AreEqual(null, old); } [Test] public void TestHashDictionary() { TryDictionary(new HashDictionary<string,string>()); } [Test] public void TestTreeDictionary() { TryDictionary(new TreeDictionary<string, string>()); } } }
// 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 Fixtures.PetstoreV2NoSync.Models { using PetstoreV2NoSync; using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; public partial class Pet { /// <summary> /// Initializes a new instance of the Pet class. /// </summary> public Pet() { } /// <summary> /// Initializes a new instance of the Pet class. /// </summary> /// <param name="status">pet status in the store. Possible values /// include: 'available', 'pending', 'sold'</param> public Pet(string name, IList<string> photoUrls, long? id = default(long?), Category category = default(Category), IList<Tag> tags = default(IList<Tag>), byte[] sByteProperty = default(byte[]), System.DateTime? birthday = default(System.DateTime?), IDictionary<string, Category> dictionary = default(IDictionary<string, Category>), string status = default(string)) { Id = id; Category = category; Name = name; PhotoUrls = photoUrls; Tags = tags; SByteProperty = sByteProperty; Birthday = birthday; Dictionary = dictionary; Status = status; } /// <summary> /// </summary> [JsonProperty(PropertyName = "id")] public long? Id { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "category")] public Category Category { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "photoUrls")] public IList<string> PhotoUrls { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "tags")] public IList<Tag> Tags { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sByte")] public byte[] SByteProperty { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "birthday")] public System.DateTime? Birthday { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "dictionary")] public IDictionary<string, Category> Dictionary { get; set; } /// <summary> /// Gets or sets pet status in the store. Possible values include: /// 'available', 'pending', 'sold' /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } if (PhotoUrls == null) { throw new ValidationException(ValidationRules.CannotBeNull, "PhotoUrls"); } } /// <summary> /// Serializes the object to an XML node /// </summary> internal XElement XmlSerialize(XElement result) { if( null != Id ) { result.Add(new XElement("id", Id) ); } if( null != Category ) { result.Add(Category.XmlSerialize(new XElement( "category" ))); } if( null != Name ) { result.Add(new XElement("name", Name) ); } if( null != PhotoUrls ) { var seq = new XElement("photoUrl"); foreach( var value in PhotoUrls ){ seq.Add(new XElement( "photoUrl", value ) ); } result.Add(seq); } if( null != Tags ) { var seq = new XElement("tag"); foreach( var value in Tags ){ seq.Add(value.XmlSerialize( new XElement( "tag") ) ); } result.Add(seq); } if( null != SByteProperty ) { result.Add(new XElement("sByte", SByteProperty) ); } if( null != Birthday ) { result.Add(new XElement("birthday", Birthday) ); } if( null != Dictionary ) { var dict = new XElement("dictionary"); foreach( var key in Dictionary.Keys ) { dict.Add(Dictionary[key].XmlSerialize(new XElement(key) ) ); } result.Add(dict); } if( null != Status ) { result.Add(new XElement("status", Status) ); } return result; } /// <summary> /// Deserializes an XML node to an instance of Pet /// </summary> internal static Pet XmlDeserialize(string payload) { // deserialize to xml and use the overload to do the work return XmlDeserialize( XElement.Parse( payload ) ); } internal static Pet XmlDeserialize(XElement payload) { var result = new Pet(); var deserializeId = XmlSerialization.ToDeserializer(e => (long?)e); long? resultId; if (deserializeId(payload, "id", out resultId)) { result.Id = resultId; } var deserializeCategory = XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e)); Category resultCategory; if (deserializeCategory(payload, "category", out resultCategory)) { result.Category = resultCategory; } var deserializeName = XmlSerialization.ToDeserializer(e => (string)e); string resultName; if (deserializeName(payload, "name", out resultName)) { result.Name = resultName; } var deserializePhotoUrls = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => (string)e), "photoUrl"); IList<string> resultPhotoUrls; if (deserializePhotoUrls(payload, "photoUrl", out resultPhotoUrls)) { result.PhotoUrls = resultPhotoUrls; } var deserializeTags = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => Tag.XmlDeserialize(e)), "tag"); IList<Tag> resultTags; if (deserializeTags(payload, "tag", out resultTags)) { result.Tags = resultTags; } var deserializeSByteProperty = XmlSerialization.ToDeserializer(e => System.Convert.FromBase64String(e.Value)); byte[] resultSByteProperty; if (deserializeSByteProperty(payload, "sByte", out resultSByteProperty)) { result.SByteProperty = resultSByteProperty; } var deserializeBirthday = XmlSerialization.ToDeserializer(e => (System.DateTime?)e); System.DateTime? resultBirthday; if (deserializeBirthday(payload, "birthday", out resultBirthday)) { result.Birthday = resultBirthday; } var deserializeDictionary = XmlSerialization.CreateDictionaryXmlDeserializer(XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e))); IDictionary<string, Category> resultDictionary; if (deserializeDictionary(payload, "dictionary", out resultDictionary)) { result.Dictionary = resultDictionary; } var deserializeStatus = XmlSerialization.ToDeserializer(e => (string)e); string resultStatus; if (deserializeStatus(payload, "status", out resultStatus)) { result.Status = resultStatus; } return result; } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Linq; using tk2dEditor.SpriteCollectionEditor; namespace tk2dEditor.SpriteCollectionEditor { public interface IEditorHost { void OnSpriteCollectionChanged(bool retainSelection); void OnSpriteCollectionSortChanged(); Texture2D GetTextureForSprite(int spriteId); SpriteCollectionProxy SpriteCollection { get; } int InspectorWidth { get; } SpriteView SpriteView { get; } void SelectSpritesFromList(int[] indices); void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds); void Commit(); } public class SpriteCollectionEditorEntry { public enum Type { None, Sprite, SpriteSheet, Font, MaxValue } public string name; public int index; public Type type; public bool selected = false; // list management public int listIndex; // index into the currently active list public int selectionKey; // a timestamp of when the entry was selected, to decide the last selected one } } public class tk2dSpriteCollectionEditorPopup : EditorWindow, IEditorHost { tk2dSpriteCollection _spriteCollection; // internal tmp var SpriteView spriteView; SettingsView settingsView; FontView fontView; SpriteSheetView spriteSheetView; // sprite collection we're editing SpriteCollectionProxy spriteCollectionProxy = null; public SpriteCollectionProxy SpriteCollection { get { return spriteCollectionProxy; } } public SpriteView SpriteView { get { return spriteView; } } // This lists all entries List<SpriteCollectionEditorEntry> entries = new List<SpriteCollectionEditorEntry>(); // This lists all selected entries List<SpriteCollectionEditorEntry> selectedEntries = new List<SpriteCollectionEditorEntry>(); // Callback when a sprite collection is changed and the selection needs to be refreshed public void OnSpriteCollectionChanged(bool retainSelection) { var oldSelection = selectedEntries.ToArray(); PopulateEntries(); if (retainSelection) { searchFilter = ""; // name may have changed foreach (var selection in oldSelection) { foreach (var entry in entries) { if (entry.type == selection.type && entry.index == selection.index) { entry.selected = true; break; } } } UpdateSelection(); } } public void SelectSpritesFromList(int[] indices) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); // Clear selection foreach (var entry in entries) entry.selected = false; // Create new selection foreach (var index in indices) { foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == index) { entry.selected = true; selectedEntries.Add(entry); break; } } } } public void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); foreach (var entry in entries) { entry.selected = (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == spriteSheetId); if (entry.selected) { spriteSheetView.Select(spriteCollectionProxy.spriteSheets[spriteSheetId], spriteIds); } } UpdateSelection(); } void UpdateSelection() { // clear settings view if its selected settingsView.show = false; selectedEntries = (from entry in entries where entry.selected == true orderby entry.selectionKey select entry).ToList(); } void ClearSelection() { entries.ForEach((a) => a.selected = false); UpdateSelection(); } // Callback when a sprite collection needs resorting public static bool Contains(string s, string text) { return s.ToLower().IndexOf(text.ToLower()) != -1; } // Callback when a sort criteria is changed public void OnSpriteCollectionSortChanged() { if (searchFilter.Length > 0) { // re-sort list entries = (from entry in entries where Contains(entry.name, searchFilter) select entry) .OrderBy( e => e.type ) .ThenBy( e => e.name, new tk2dEditor.Shared.NaturalComparer() ) .ToList(); } else { // re-sort list entries = (from entry in entries select entry) .OrderBy( e => e.type ) .ThenBy( e => e.name, new tk2dEditor.Shared.NaturalComparer() ) .ToList(); } for (int i = 0; i < entries.Count; ++i) entries[i].listIndex = i; } public int InspectorWidth { get { return tk2dPreferences.inst.spriteCollectionInspectorWidth; } } // populate the entries struct for display in the listbox void PopulateEntries() { entries = new List<SpriteCollectionEditorEntry>(); selectedEntries = new List<SpriteCollectionEditorEntry>(); if (spriteCollectionProxy == null) return; for (int spriteIndex = 0; spriteIndex < spriteCollectionProxy.textureParams.Count; ++spriteIndex) { var sprite = spriteCollectionProxy.textureParams[spriteIndex]; var spriteSourceTexture = sprite.texture; if (spriteSourceTexture == null && sprite.name.Length == 0) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = sprite.name; if (sprite.texture == null) { newEntry.name += " (missing)"; } newEntry.index = spriteIndex; newEntry.type = SpriteCollectionEditorEntry.Type.Sprite; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.spriteSheets.Count; ++i) { var spriteSheet = spriteCollectionProxy.spriteSheets[i]; if (!spriteSheet.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = spriteSheet.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.SpriteSheet; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.fonts.Count; ++i) { var font = spriteCollectionProxy.fonts[i]; if (!font.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = font.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.Font; entries.Add(newEntry); } OnSpriteCollectionSortChanged(); selectedEntries = new List<SpriteCollectionEditorEntry>(); } public void SetGenerator(tk2dSpriteCollection spriteCollection) { this._spriteCollection = spriteCollection; this.firstRun = true; spriteCollectionProxy = new SpriteCollectionProxy(spriteCollection); PopulateEntries(); } public void SetGeneratorAndSelectedSprite(tk2dSpriteCollection spriteCollection, int selectedSprite) { searchFilter = ""; SetGenerator(spriteCollection); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == selectedSprite) { entry.selected = true; break; } } UpdateSelection(); } int cachedSpriteId = -1; Texture2D cachedSpriteTexture = null; // Returns a texture for a given sprite, if the sprite is a region sprite, a new texture is returned public Texture2D GetTextureForSprite(int spriteId) { var param = spriteCollectionProxy.textureParams[spriteId]; if (spriteId != cachedSpriteId) { ClearTextureCache(); cachedSpriteId = spriteId; } if (param.extractRegion) { if (cachedSpriteTexture == null) { var tex = param.texture; cachedSpriteTexture = new Texture2D(param.regionW, param.regionH); for (int y = 0; y < param.regionH; ++y) { for (int x = 0; x < param.regionW; ++x) { cachedSpriteTexture.SetPixel(x, y, tex.GetPixel(param.regionX + x, param.regionY + y)); } } cachedSpriteTexture.Apply(); } return cachedSpriteTexture; } else { return param.texture; } } void ClearTextureCache() { if (cachedSpriteId != -1) cachedSpriteId = -1; if (cachedSpriteTexture != null) { DestroyImmediate(cachedSpriteTexture); cachedSpriteTexture = null; } } void OnEnable() { if (_spriteCollection != null) { SetGenerator(_spriteCollection); } spriteView = new SpriteView(this); settingsView = new SettingsView(this); fontView = new FontView(this); spriteSheetView = new SpriteSheetView(this); } void OnDisable() { ClearTextureCache(); _spriteCollection = null; } void OnDestroy() { tk2dSpriteThumbnailCache.Done(); tk2dEditorSkin.Done(); } string searchFilter = ""; void DrawToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); // LHS GUILayout.BeginHorizontal(GUILayout.Width(leftBarWidth - 6)); // Create Button GUIContent createButton = new GUIContent("Create"); Rect createButtonRect = GUILayoutUtility.GetRect(createButton, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false)); if (GUI.Button(createButtonRect, createButton, EditorStyles.toolbarDropDown)) { GUIUtility.hotControl = 0; GUIContent[] menuItems = new GUIContent[] { new GUIContent("Sprite Sheet"), new GUIContent("Font") }; EditorUtility.DisplayCustomMenu(createButtonRect, menuItems, -1, delegate(object userData, string[] options, int selected) { switch (selected) { case 0: int addedSpriteSheetIndex = spriteCollectionProxy.FindOrCreateEmptySpriteSheetSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == addedSpriteSheetIndex) entry.selected = true; } UpdateSelection(); break; case 1: if (SpriteCollection.allowMultipleAtlases) { EditorUtility.DisplayDialog("Create Font", "Adding fonts to sprite collections isn't allowed when multi atlas spanning is enabled. " + "Please disable it and try again.", "Ok"); } else { int addedFontIndex = spriteCollectionProxy.FindOrCreateEmptyFontSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Font && entry.index == addedFontIndex) entry.selected = true; } UpdateSelection(); } break; } } , null); } // Filter box GUILayout.Space(8); string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch, GUILayout.ExpandWidth(true)); if (newSearchFilter != searchFilter) { searchFilter = newSearchFilter; PopulateEntries(); } if (searchFilter.Length > 0) { if (GUILayout.Button("", tk2dEditorSkin.ToolbarSearchClear, GUILayout.ExpandWidth(false))) { searchFilter = ""; PopulateEntries(); } } else { GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap); } GUILayout.EndHorizontal(); // Label if (_spriteCollection != null) GUILayout.Label(_spriteCollection.name); // RHS GUILayout.FlexibleSpace(); // Always in settings view when empty if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { GUILayout.Toggle(true, "Settings", EditorStyles.toolbarButton); } else { bool newSettingsView = GUILayout.Toggle(settingsView.show, "Settings", EditorStyles.toolbarButton); if (newSettingsView != settingsView.show) { ClearSelection(); settingsView.show = newSettingsView; } } if (GUILayout.Button("Revert", EditorStyles.toolbarButton) && spriteCollectionProxy != null) { spriteCollectionProxy.CopyFromSource(); OnSpriteCollectionChanged(false); } if (GUILayout.Button("Commit", EditorStyles.toolbarButton) && spriteCollectionProxy != null) Commit(); GUILayout.EndHorizontal(); } public void Commit() { spriteCollectionProxy.DeleteUnusedData(); spriteCollectionProxy.CopyToTarget(); tk2dSpriteCollectionBuilder.ResetCurrentBuild(); if (!tk2dSpriteCollectionBuilder.Rebuild(_spriteCollection)) { EditorUtility.DisplayDialog("Failed to commit sprite collection", "Please check the console for more details.", "Ok"); } spriteCollectionProxy.CopyFromSource(); } void HandleListKeyboardShortcuts(int controlId) { Event ev = Event.current; if (ev.type == EventType.KeyDown && (GUIUtility.keyboardControl == controlId || GUIUtility.keyboardControl == 0) && entries != null && entries.Count > 0) { int selectedIndex = 0; foreach (var e in entries) { if (e.selected) break; selectedIndex++; } int newSelectedIndex = selectedIndex; switch (ev.keyCode) { case KeyCode.Home: newSelectedIndex = 0; break; case KeyCode.End: newSelectedIndex = entries.Count - 1; break; case KeyCode.UpArrow: newSelectedIndex = Mathf.Max(selectedIndex - 1, 0); break; case KeyCode.DownArrow: newSelectedIndex = Mathf.Min(selectedIndex + 1, entries.Count - 1); break; case KeyCode.PageUp: newSelectedIndex = Mathf.Max(selectedIndex - 10, 0); break; case KeyCode.PageDown: newSelectedIndex = Mathf.Min(selectedIndex + 10, entries.Count - 1); break; } if (newSelectedIndex != selectedIndex) { for (int i = 0; i < entries.Count; ++i) entries[i].selected = (i == newSelectedIndex); UpdateSelection(); Repaint(); ev.Use(); } } } Vector2 spriteListScroll = Vector2.zero; int spriteListSelectionKey = 0; void DrawSpriteList() { if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { DrawDropZone(); return; } int spriteListControlId = GUIUtility.GetControlID("tk2d.SpriteList".GetHashCode(), FocusType.Keyboard); HandleListKeyboardShortcuts(spriteListControlId); spriteListScroll = GUILayout.BeginScrollView(spriteListScroll, GUILayout.Width(leftBarWidth)); GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); bool multiSelectKey = (Application.platform == RuntimePlatform.OSXEditor)?Event.current.command:Event.current.control; bool shiftSelectKey = Event.current.shift; bool selectionChanged = false; SpriteCollectionEditorEntry.Type lastType = SpriteCollectionEditorEntry.Type.None; foreach (var entry in entries) { if (lastType != entry.type) { if (lastType != SpriteCollectionEditorEntry.Type.None) GUILayout.Space(8); else GUI.SetNextControlName("firstLabel"); GUILayout.Label(GetEntryTypeString(entry.type), tk2dEditorSkin.SC_ListBoxSectionHeader, GUILayout.ExpandWidth(true)); lastType = entry.type; } bool newSelected = GUILayout.Toggle(entry.selected, entry.name, tk2dEditorSkin.SC_ListBoxItem, GUILayout.ExpandWidth(true)); if (newSelected != entry.selected) { GUI.FocusControl("firstLabel"); entry.selectionKey = spriteListSelectionKey++; if (multiSelectKey) { // Only allow multiselection with sprites bool selectionAllowed = entry.type == SpriteCollectionEditorEntry.Type.Sprite; foreach (var e in entries) { if (e != entry && e.selected && e.type != entry.type) { selectionAllowed = false; break; } } if (selectionAllowed) { entry.selected = newSelected; selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } else if (shiftSelectKey) { // find first selected entry in list int firstSelection = int.MaxValue; foreach (var e in entries) { if (e.selected && e.listIndex < firstSelection) { firstSelection = e.listIndex; } } int lastSelection = entry.listIndex; if (lastSelection < firstSelection) { lastSelection = firstSelection; firstSelection = entry.listIndex; } // Filter for multiselection if (entry.type == SpriteCollectionEditorEntry.Type.Sprite) { for (int i = firstSelection; i <= lastSelection; ++i) { if (entries[i].type != entry.type) { firstSelection = entry.listIndex; lastSelection = entry.listIndex; } } } else { firstSelection = lastSelection = entry.listIndex; } foreach (var e in entries) { e.selected = (e.listIndex >= firstSelection && e.listIndex <= lastSelection); } selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } } if (selectionChanged) { GUIUtility.keyboardControl = spriteListControlId; UpdateSelection(); Repaint(); } GUILayout.EndVertical(); GUILayout.EndScrollView(); Rect viewRect = GUILayoutUtility.GetLastRect(); tk2dPreferences.inst.spriteCollectionListWidth = (int)tk2dGuiUtility.DragableHandle(4819283, viewRect, tk2dPreferences.inst.spriteCollectionListWidth, tk2dGuiUtility.DragDirection.Horizontal); } bool IsValidDragPayload() { int idx = 0; foreach (var v in DragAndDrop.objectReferences) { var type = v.GetType(); if (type == typeof(Texture2D)) return true; else if (type == typeof(Object) && System.IO.Directory.Exists(DragAndDrop.paths[idx])) return true; ++idx; } return false; } string GetEntryTypeString(SpriteCollectionEditorEntry.Type kind) { switch (kind) { case SpriteCollectionEditorEntry.Type.Sprite: return "Sprites"; case SpriteCollectionEditorEntry.Type.SpriteSheet: return "Sprite Sheets"; case SpriteCollectionEditorEntry.Type.Font: return "Fonts"; } Debug.LogError("Unhandled type"); return ""; } bool PromptImportDuplicate(string title, string message) { return EditorUtility.DisplayDialog(title, message, "Ignore", "Create Copy"); } void HandleDroppedPayload(Object[] objects) { bool hasDuplicates = false; foreach (var obj in objects) { Texture2D tex = obj as Texture2D; if (tex != null) { if (spriteCollectionProxy.FindSpriteBySource(tex) != -1) { hasDuplicates = true; } } } bool cloneDuplicates = false; if (hasDuplicates && EditorUtility.DisplayDialog("Duplicate textures detected.", "One or more textures is already in the collection. What do you want to do with the duplicates?", "Clone", "Ignore")) { cloneDuplicates = true; } List<int> addedIndices = new List<int>(); foreach (var obj in objects) { Texture2D tex = obj as Texture2D; if ((tex != null) && (cloneDuplicates || spriteCollectionProxy.FindSpriteBySource(tex) == -1)) { string name = spriteCollectionProxy.FindUniqueTextureName(tex.name); int slot = spriteCollectionProxy.FindOrCreateEmptySpriteSlot(); spriteCollectionProxy.textureParams[slot].name = name; spriteCollectionProxy.textureParams[slot].colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; spriteCollectionProxy.textureParams[slot].texture = (Texture2D)obj; addedIndices.Add(slot); } } // And now select them searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && addedIndices.IndexOf(entry.index) != -1) entry.selected = true; } UpdateSelection(); } // recursively find textures in path List<Object> AddTexturesInPath(string path) { List<Object> localObjects = new List<Object>(); foreach (var q in System.IO.Directory.GetFiles(path)) { string f = q.Replace('\\', '/'); System.IO.FileInfo fi = new System.IO.FileInfo(f); if (fi.Extension.ToLower() == ".meta") continue; Object obj = AssetDatabase.LoadAssetAtPath(f, typeof(Texture2D)); if (obj != null) localObjects.Add(obj); } foreach (var q in System.IO.Directory.GetDirectories(path)) { string d = q.Replace('\\', '/'); localObjects.AddRange(AddTexturesInPath(d)); } return localObjects; } int leftBarWidth { get { return tk2dPreferences.inst.spriteCollectionListWidth; } } Object[] deferredDroppedObjects; void DrawDropZone() { GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG, GUILayout.Width(leftBarWidth), GUILayout.ExpandHeight(true)); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (DragAndDrop.objectReferences.Length == 0 && !SpriteCollection.Empty) GUILayout.Label("Drop sprite here", tk2dEditorSkin.SC_DropBox); else GUILayout.Label("Drop sprites here", tk2dEditorSkin.SC_DropBox); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); Rect rect = new Rect(0, 0, leftBarWidth, Screen.height); if (rect.Contains(Event.current.mousePosition)) { switch (Event.current.type) { case EventType.DragUpdated: if (IsValidDragPayload()) DragAndDrop.visualMode = DragAndDropVisualMode.Copy; else DragAndDrop.visualMode = DragAndDropVisualMode.None; break; case EventType.DragPerform: var droppedObjectsList = new List<Object>(); for (int i = 0; i < DragAndDrop.objectReferences.Length; ++i) { var type = DragAndDrop.objectReferences[i].GetType(); if (type == typeof(Texture2D)) droppedObjectsList.Add(DragAndDrop.objectReferences[i]); else if (type == typeof(Object) && System.IO.Directory.Exists(DragAndDrop.paths[i])) droppedObjectsList.AddRange(AddTexturesInPath(DragAndDrop.paths[i])); } deferredDroppedObjects = droppedObjectsList.ToArray(); Repaint(); break; } } } bool dragging = false; bool currentDraggingValue = false; bool firstRun = true; List<UnityEngine.Object> assetsInResources = new List<UnityEngine.Object>(); bool InResources(UnityEngine.Object obj) { return AssetDatabase.GetAssetPath(obj).ToLower().IndexOf("/resources/") != -1; } void CheckForAssetsInResources() { assetsInResources.Clear(); foreach (tk2dSpriteCollectionDefinition tex in SpriteCollection.textureParams) { if (tex.texture == null) continue; if (InResources(tex.texture) && assetsInResources.IndexOf(tex.texture) == -1) assetsInResources.Add(tex.texture); } foreach (tk2dSpriteCollectionFont font in SpriteCollection.fonts) { if (font.texture != null && InResources(font.texture) && assetsInResources.IndexOf(font.texture) == -1) assetsInResources.Add(font.texture); if (font.bmFont != null && InResources(font.bmFont) && assetsInResources.IndexOf(font.bmFont) == -1) assetsInResources.Add(font.bmFont); } } Vector2 assetWarningScroll = Vector2.zero; bool HandleAssetsInResources() { if (firstRun && SpriteCollection != null) { CheckForAssetsInResources(); firstRun = false; } if (assetsInResources.Count > 0) { tk2dGuiUtility.InfoBox("Warning: The following assets are in one or more resources directories.\n" + "These files will be included in the build.", tk2dGuiUtility.WarningLevel.Warning); assetWarningScroll = GUILayout.BeginScrollView(assetWarningScroll, GUILayout.ExpandWidth(true)); foreach (UnityEngine.Object obj in assetsInResources) { EditorGUILayout.ObjectField(obj, typeof(UnityEngine.Object), false); } GUILayout.EndScrollView(); GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Ok", GUILayout.MinWidth(100))) { assetsInResources.Clear(); Repaint(); } GUILayout.EndHorizontal(); return true; } return false; } void OnGUI() { if (Event.current.type == EventType.DragUpdated) { if (IsValidDragPayload()) dragging = true; } else if (Event.current.type == EventType.DragExited) { dragging = false; Repaint(); } else { if (currentDraggingValue != dragging) { currentDraggingValue = dragging; } } if (Event.current.type == EventType.Layout && deferredDroppedObjects != null) { HandleDroppedPayload(deferredDroppedObjects); deferredDroppedObjects = null; } if (HandleAssetsInResources()) return; GUILayout.BeginVertical(); DrawToolbar(); GUILayout.BeginHorizontal(); if (currentDraggingValue) DrawDropZone(); else DrawSpriteList(); if (settingsView.show || (spriteCollectionProxy != null && spriteCollectionProxy.Empty)) settingsView.Draw(); else if (fontView.Draw(selectedEntries)) { } else if (spriteSheetView.Draw(selectedEntries)) { } else spriteView.Draw(selectedEntries); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } }
// // Client.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using DBus; using Hyena; using Banshee.Base; using Banshee.ServiceStack; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Collection.Indexer; namespace Halie { public static class Client { // NOTE: Interfaces are copied from Banshee.ThickClient/Banshee.Gui // since we don't want to link against any GUI assemblies for this // client. It's a simple interface [Interface ("org.bansheeproject.Banshee.ClientWindow")] public interface IClientWindow { void Present (); void Hide (); void Fullscreen (); } [Interface ("org.bansheeproject.Banshee.GlobalUIActions")] public interface IGlobalUIActions { void ShowImportDialog (); void ShowAboutDialog (); void ShowOpenLocationDialog (); void ShowPreferencesDialog (); } private static bool hide_field; private static DBusCommandService command; public static void Main () { if (!DBusConnection.ConnectTried) { DBusConnection.Connect (); } if (!DBusConnection.Enabled) { Error ("All commands ignored, DBus support is disabled"); return; } else if (!DBusConnection.ApplicationInstanceAlreadyRunning) { Error ("Banshee does not seem to be running"); return; } command = DBusServiceManager.FindInstance<DBusCommandService> ("/DBusCommandService"); hide_field = ApplicationContext.CommandLine.Contains ("hide-field"); bool present = HandlePlayerCommands () && HandleGlobalUIActions () && !ApplicationContext.CommandLine.Contains ("indexer"); HandleWindowCommands (present); HandleFiles (); } private static void HandleWindowCommands (bool present) { IClientWindow window = DBusServiceManager.FindInstance<IClientWindow> ("/ClientWindow"); if (window == null) { return; } foreach (KeyValuePair<string, string> arg in ApplicationContext.CommandLine.Arguments) { switch (arg.Key) { case "show": case "present": present = true; break; case "fullscreen": window.Fullscreen (); break; case "hide": present = false; window.Hide (); break; } } if (present && !ApplicationContext.CommandLine.Contains ("no-present")) { window.Present (); } } private static void HandleFiles () { foreach (string file in ApplicationContext.CommandLine.Files) { // If it looks like a URI with a protocol, leave it as is if (System.Text.RegularExpressions.Regex.IsMatch (file, "^\\w+\\:\\/")) { command.PushFile (file); } else { command.PushFile (Path.GetFullPath (file)); } } } private static bool HandleGlobalUIActions () { var global_ui_actions = DBusServiceManager.FindInstance<IGlobalUIActions> ("/GlobalUIActions"); var handled = false; if (ApplicationContext.CommandLine.Contains ("show-import-media")) { global_ui_actions.ShowImportDialog (); handled |= true; } if (ApplicationContext.CommandLine.Contains ("show-about")) { global_ui_actions.ShowAboutDialog (); handled |= true; } if (ApplicationContext.CommandLine.Contains ("show-preferences")) { global_ui_actions.ShowPreferencesDialog (); handled |= true; } if (ApplicationContext.CommandLine.Contains ("show-open-location")) { global_ui_actions.ShowOpenLocationDialog (); handled |= true; } return !handled; } private static bool HandlePlayerCommands () { IPlayerEngineService player = DBusServiceManager.FindInstance<IPlayerEngineService> ("/PlayerEngine"); IPlaybackControllerService controller = DBusServiceManager.FindInstance<IPlaybackControllerService> ("/PlaybackController"); IDictionary<string, object> track = null; int handled_count = 0; foreach (KeyValuePair<string, string> arg in ApplicationContext.CommandLine.Arguments) { handled_count++; switch (arg.Key) { // For the player engine case "play": player.Play (); break; case "pause": player.Pause (); break; case "stop": player.Close (); break; case "toggle-playing": player.TogglePlaying (); break; // For the playback controller case "first": controller.First (); break; case "next": controller.Next (ParseBool (arg.Value, "restart")); break; case "previous": controller.Previous (ParseBool (arg.Value, "restart")); break; case "restart-or-previous": controller.RestartOrPrevious (ParseBool (arg.Value, "restart")); break; case "stop-when-finished": controller.StopWhenFinished = !ParseBool (arg.Value); break; case "set-position": player.Position = (uint)Math.Round (Double.Parse (arg.Value) * 1000); break; case "set-volume": if (arg.Value.Length > 1) { if (arg.Value[0] == '+') { player.Volume += UInt16.Parse (arg.Value.Substring (1)); break; } if (arg.Value[0] == '-') { var dec = UInt16.Parse (arg.Value.Substring (1)); player.Volume = (ushort)(player.Volume > dec ? player.Volume - dec : 0); break; } } player.Volume = UInt16.Parse (arg.Value); break; case "set-rating": player.Rating = Byte.Parse (arg.Value); break; default: if (arg.Key.StartsWith ("query-")) { if (track == null) { try { track = player.CurrentTrack; } catch { } } HandleQuery (player, track, arg.Key.Substring (6)); } else { command.PushArgument (arg.Key, arg.Value ?? String.Empty); handled_count--; } break; } } return handled_count <= 0; } private static void HandleQuery (IPlayerEngineService player, IDictionary<string, object> track, string query) { // Translate legacy query arguments into new ones switch (query) { case "title": query = "name"; break; case "duration": query = "length"; break; case "uri": query = "URI"; break; } switch (query) { case "all": if (track != null) { foreach (KeyValuePair<string, object> field in track) { DisplayTrackField (field.Key, field.Value); } } HandleQuery (player, track, "position"); HandleQuery (player, track, "volume"); HandleQuery (player, track, "current-state"); HandleQuery (player, track, "last-state"); HandleQuery (player, track, "can-pause"); HandleQuery (player, track, "can-seek"); break; case "position": DisplayTrackField ("position", TimeSpan.FromMilliseconds (player.Position).TotalSeconds); break; case "volume": DisplayTrackField ("volume", player.Volume); break; case "current-state": DisplayTrackField ("current-state", player.CurrentState); break; case "last-state": DisplayTrackField ("last-state", player.LastState); break; case "can-pause": DisplayTrackField ("can-pause", player.CanPause); break; case "can-seek": DisplayTrackField ("can-seek", player.CanSeek); break; case "URI": case "artist": case "album": case "name": case "length": case "track-number": case "track-count": case "disc": case "year": case "rating": case "score": case "bit-rate": if (track == null) { Error ("not playing"); break; } DisplayTrackField (query, track.ContainsKey (query) ? track[query] : ""); break; default: Error ("'{0}' field unknown", query); break; } } private static void DisplayTrackField (string field, object value) { if (field == String.Empty) { return; } else if (field == "name") { field = "title"; } else if (field == "length") { field = "duration"; } string result = null; if (value is bool) { result = (bool)value ? "true" : "false"; } else { result = value.ToString (); } if (hide_field) { Console.WriteLine (result); } else { Console.WriteLine ("{0}: {1}", field.ToLower (), result); } } private static bool ParseBool (string value) { return ParseBool (value, "true", "yes"); } private static bool ParseBool (string value, params string [] trueValues) { if (String.IsNullOrEmpty (value)) { return false; } value = value.ToLower (); foreach (string trueValue in trueValues) { if (value == trueValue) { return true; } } return false; } private static void Error (string error, params object [] args) { Console.WriteLine ("Error: {0}", String.Format (error, args)); } } }
//// Copyright (c) 2013 Enrique Juan Gil Izquierdo //// //// 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.Collections.Generic; using UnityEngine; namespace iTweenFluent { /// <summary> /// Changes a GameObject's alpha value instantly then returns it to the /// provided alpha over time. If a Light, GUIText or GUITexture component /// is attached, it will become the target of the animation. /// Identical to using ColorFrom and using the "a" parameter. /// </summary> public class iTweenFadeFrom : iTweenFluent<iTweenFadeFrom> { public static iTweenFadeFrom Create(GameObject target) { return new iTweenFadeFrom( target ); } public iTweenFadeFrom(GameObject target) : base( target ) { } public override void Launch() { iTween.FadeFrom( Target, new System.Collections.Hashtable( Arguments ) ); } protected override iTweenFadeFrom ThisAsTSelf() { return this; } /// <summary> /// For the initial alpha value of the animation. /// </summary> /// <param name="alpha"></param> /// <returns></returns> public iTweenFadeFrom Alpha(float alpha) { return AddArgument( "alpha", alpha ); } /// <summary> /// For the initial alpha value of the animation. /// </summary> /// <param name="amount"></param> /// <returns></returns> public iTweenFadeFrom Amount(float amount) { return AddArgument( "amount", amount ); } /// <summary> /// For which color of a shader to use. Uses "_Color" by default. /// </summary> /// <param name="namedValueColor"></param> /// <returns></returns> public iTweenFadeFrom NamedValueColor(string namedValueColor) { return AddArgument( "NamedValueColor", namedValueColor ); } /// <summary> /// For whether or not to include children of this GameObject. True by default. /// </summary> /// <param name="includeChildren"></param> /// <returns></returns> public iTweenFadeFrom IncludeChildren(bool includeChildren) { return AddArgument( "includechildren", includeChildren ); } } /// <summary> /// Changes a GameObject's alpha value over time. If a Light, GUIText or /// GUITexture component is attached, it will become the target of the /// animation. Identical to using ColorTo and using the "a" parameter. /// </summary> public class iTweenFadeTo : iTweenFluent<iTweenFadeTo> { public static iTweenFadeTo Create(GameObject target) { return new iTweenFadeTo( target ); } public iTweenFadeTo(GameObject target) : base( target ) { } public override void Launch() { iTween.FadeTo( Target, new System.Collections.Hashtable( Arguments ) ); } protected override iTweenFadeTo ThisAsTSelf() { return this; } /// <summary> /// For the initial alpha value of the animation. /// </summary> /// <param name="alpha"></param> /// <returns></returns> public iTweenFadeTo Alpha(float alpha) { return AddArgument( "alpha", alpha ); } /// <summary> /// For the amount to change the alpha. /// </summary> /// <param name="amount"></param> /// <returns></returns> public iTweenFadeTo Amount(float amount) { return AddArgument( "amount", amount ); } /// <summary> /// For which color of a shader to use. Uses "_Color" by default. /// </summary> /// <param name="namedValueColor"></param> /// <returns></returns> public iTweenFadeTo NamedValueColor(string namedValueColor) { return AddArgument( "NamedValueColor", namedValueColor ); } /// <summary> /// For whether or not to include children of this GameObject. /// True by default. /// </summary> /// <param name="includeChildren"></param> /// <returns></returns> public iTweenFadeTo IncludeChildren(bool includeChildren) { return AddArgument( "includechildren", includeChildren ); } } /// <summary> /// Similar to FadeTo but incredibly less expensive for usage inside the /// Update function or similar looping situations involving a "live" set of /// changing values. Does not utilize an EaseType. /// </summary> public class iTweenFadeUpdate { private GameObject target; private Dictionary<string, object> arguments = new Dictionary<string, object>(); public static iTweenFadeUpdate Create(GameObject target) { return new iTweenFadeUpdate( target ); } public iTweenFadeUpdate(GameObject target) { this.target = target; } public void Launch() { iTween.FadeUpdate( target, new System.Collections.Hashtable( arguments ) ); } /// <summary> /// For the individual setting of the alpha. /// </summary> /// <param name="alpha"></param> /// <returns></returns> public iTweenFadeUpdate Alpha(float alpha) { return AddArgument( "alpha", alpha ); } /// <summary> /// For whether or not to include children of this GameObject. /// True by default. /// </summary> /// <param name="includeChildren"></param> /// <returns></returns> public iTweenFadeUpdate IncludeChildren(bool includeChildren) { return AddArgument( "includechildren", includeChildren ); } /// <summary> /// For the time in seconds the animation will take to complete. /// </summary> /// <param name="time"></param> /// <returns></returns> public iTweenFadeUpdate Time(float time) { return AddArgument( "time", time ); } protected iTweenFadeUpdate AddArgument(string arg, object value) { arguments[arg] = value; return this; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Xml; using System.Configuration; using System.Collections.Generic; using System.Text; using System.IO; namespace WebsitePanel.Setup { public sealed class AppConfig { public const string AppConfigFileNameWithoutExtension = "WebsitePanel.Installer.exe"; static AppConfig() { ConfigurationPath = DefaultConfigurationPath; } private AppConfig() { } private static Configuration appConfig = null; private static XmlDocument xmlConfig = null; public static string ConfigurationPath { get; set; } public static string DefaultConfigurationPath { get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppConfigFileNameWithoutExtension); } } public static void LoadConfiguration(ExeConfigurationFileMap FnMap = null, ConfigurationUserLevel CuLevel = ConfigurationUserLevel.None) { if (FnMap == null) appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationPath); else appConfig = ConfigurationManager.OpenMappedExeConfiguration(FnMap, CuLevel); ConfigurationSection section = appConfig.Sections["installer"]; if (section == null) throw new ConfigurationErrorsException("installer section not found in " + appConfig.FilePath); string strXml = section.SectionInformation.GetRawXml(); xmlConfig = new XmlDocument(); xmlConfig.LoadXml(strXml); } public static XmlDocument Configuration { get { return xmlConfig; } } public static void EnsureComponentConfig(string componentId) { var xmlConfigNode = GetComponentConfig(componentId); // if (xmlConfigNode != null) return; // CreateComponentConfig(componentId); } public static XmlNode CreateComponentConfig(string componentId) { XmlNode components = Configuration.SelectSingleNode("//components"); if (components == null) { components = Configuration.CreateElement("components"); Configuration.FirstChild.AppendChild(components); } XmlElement componentNode = Configuration.CreateElement("component"); componentNode.SetAttribute("id", componentId); components.AppendChild(componentNode); XmlElement settingsNode = Configuration.CreateElement("settings"); componentNode.AppendChild(settingsNode); return componentNode; } public static XmlNode GetComponentConfig(string componentId) { string xPath = string.Format("//component[@id=\"{0}\"]", componentId); return Configuration.SelectSingleNode(xPath); } public static void SaveConfiguration() { if (appConfig != null && xmlConfig != null) { ConfigurationSection section = appConfig.Sections["installer"]; section.SectionInformation.SetRawXml(xmlConfig.OuterXml); appConfig.Save(); } } public static void SetComponentSettingStringValue(string componentId, string settingName, string value) { XmlNode componentNode = GetComponentConfig(componentId); XmlNode settings = componentNode.SelectSingleNode("settings"); string xpath = string.Format("add[@key=\"{0}\"]", settingName); XmlNode settingNode = settings.SelectSingleNode(xpath); if (settingNode == null) { settingNode = Configuration.CreateElement("add"); XmlUtils.SetXmlAttribute(settingNode, "key", settingName); settings.AppendChild(settingNode); } XmlUtils.SetXmlAttribute(settingNode, "value", value); } public static void SetComponentSettingBooleanValue(string componentId, string settingName, bool value) { XmlNode componentNode = GetComponentConfig(componentId); XmlNode settings = componentNode.SelectSingleNode("settings"); string xpath = string.Format("add[@key=\"{0}\"]", settingName); XmlNode settingNode = settings.SelectSingleNode(xpath); if (settingNode == null) { settingNode = Configuration.CreateElement("add"); XmlUtils.SetXmlAttribute(settingNode, "key", settingName); settings.AppendChild(settingNode); } XmlUtils.SetXmlAttribute(settingNode, "value", value.ToString()); } public static void LoadComponentSettings(SetupVariables vars) { XmlNode componentNode = GetComponentConfig(vars.ComponentId); // if (componentNode != null) { var typeRef = vars.GetType(); // XmlNodeList settingNodes = componentNode.SelectNodes("settings/add"); // foreach (XmlNode item in settingNodes) { var sName = XmlUtils.GetXmlAttribute(item, "key"); var sValue = XmlUtils.GetXmlAttribute(item, "value"); // if (String.IsNullOrEmpty(sName)) continue; // var objProperty = typeRef.GetProperty(sName); // if (objProperty == null) continue; // Set property value objProperty.SetValue(vars, Convert.ChangeType(sValue, objProperty.PropertyType), null); } } } public static string GetComponentSettingStringValue(string componentId, string settingName) { string ret = null; XmlNode componentNode = GetComponentConfig(componentId); if (componentNode != null) { string xpath = string.Format("settings/add[@key=\"{0}\"]", settingName); XmlNode settingNode = componentNode.SelectSingleNode(xpath); if (settingNode != null) { ret = XmlUtils.GetXmlAttribute(settingNode, "value"); } } return ret; } internal static int GetComponentSettingInt32Value(string componentId, string settingName) { int ret = 0; XmlNode componentNode = GetComponentConfig(componentId); if (componentNode != null) { string xpath = string.Format("settings/add[@key=\"{0}\"]", settingName); XmlNode settingNode = componentNode.SelectSingleNode(xpath); string val = XmlUtils.GetXmlAttribute(settingNode, "value"); Int32.TryParse(val, out ret); } return ret; } internal static bool GetComponentSettingBooleanValue(string componentId, string settingName) { bool ret = false; XmlNode componentNode = GetComponentConfig(componentId); if (componentNode != null) { string xpath = string.Format("settings/add[@key=\"{0}\"]", settingName); XmlNode settingNode = componentNode.SelectSingleNode(xpath); string val = XmlUtils.GetXmlAttribute(settingNode, "value"); Boolean.TryParse(val, out ret); } return ret; } internal static string GetSettingStringValue(string settingName) { string ret = null; string xPath = string.Format("settings/add[@key=\"{0}\"]", settingName); XmlNode settingNode = Configuration.SelectSingleNode(xPath); if (settingNode != null) { ret = XmlUtils.GetXmlAttribute(settingNode, "value"); } return ret; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Monitor.Fluent { using Microsoft.Azure.Management.Monitor.Fluent.Models; internal partial class MetricAlertConditionImpl { /// <summary> /// Gets the criteria operator. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'. /// </summary> /// <summary> /// Gets the operator value. /// </summary> Models.MetricAlertRuleCondition Microsoft.Azure.Management.Monitor.Fluent.IMetricAlertCondition.Condition { get { return this.Condition(); } } /// <summary> /// Gets list of dimension conditions. /// </summary> /// <summary> /// Gets the dimensions value. /// </summary> System.Collections.Generic.IReadOnlyCollection<Models.MetricDimension> Microsoft.Azure.Management.Monitor.Fluent.IMetricAlertCondition.Dimensions { get { return this.Dimensions(); } } /// <summary> /// Gets name of the metric signal. /// </summary> /// <summary> /// Gets the metricName value. /// </summary> string Microsoft.Azure.Management.Monitor.Fluent.IMetricAlertCondition.MetricName { get { return this.MetricName(); } } /// <summary> /// Gets namespace of the metric. /// </summary> /// <summary> /// Gets the metricNamespace value. /// </summary> string Microsoft.Azure.Management.Monitor.Fluent.IMetricAlertCondition.MetricNamespace { get { return this.MetricNamespace(); } } /// <summary> /// Gets name of the criteria. /// </summary> /// <summary> /// Gets the name value. /// </summary> string Microsoft.Azure.Management.Monitor.Fluent.IMetricAlertCondition.Name { get { return this.Name(); } } /// <summary> /// Gets the parent of this child object. /// </summary> Microsoft.Azure.Management.Monitor.Fluent.IMetricAlert Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasParent<Microsoft.Azure.Management.Monitor.Fluent.IMetricAlert>.Parent { get { return this.Parent(); } } /// <summary> /// Gets the criteria threshold value that activates the alert. /// </summary> /// <summary> /// Gets the threshold value. /// </summary> double Microsoft.Azure.Management.Monitor.Fluent.IMetricAlertCondition.Threshold { get { return this.Threshold(); } } /// <summary> /// Gets the criteria time aggregation types. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total'. /// </summary> /// <summary> /// Gets the timeAggregation value. /// </summary> Models.MetricAlertRuleTimeAggregation Microsoft.Azure.Management.Monitor.Fluent.IMetricAlertCondition.TimeAggregation { get { return this.TimeAggregation(); } } /// <summary> /// Attaches the defined condition to the parent metric alert. /// </summary> /// <return>The next stage of metric alert definition.</return> MetricAlert.Update.IUpdate MetricAlertCondition.UpdateDefinition.IWithConditionAttach<MetricAlert.Update.IUpdate>.Attach() { return this.Attach(); } /// <summary> /// Attaches the defined condition to the parent metric alert. /// </summary> /// <return>The next stage of metric alert definition.</return> MetricAlert.Definition.IWithCreate MetricAlertCondition.Definition.IWithConditionAttach<MetricAlert.Definition.IWithCreate>.Attach() { return this.Attach(); } /// <summary> /// Returns back to the metric alert update flow. /// </summary> /// <return>The next stage of the metric alert update.</return> MetricAlert.Update.IUpdate MetricAlertCondition.Update.IUpdateStages.Parent() { return this.Parent(); } /// <summary> /// Sets the condition to monitor for the current metric alert. /// </summary> /// <param name="condition">The criteria operator. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.</param> /// <param name="timeAggregation">The criteria time aggregation types. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total'.</param> /// <param name="threshold">The criteria threshold value that activates the alert.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.UpdateDefinition.IWithConditionAttach<MetricAlert.Update.IUpdate> MetricAlertCondition.UpdateDefinition.IWithCriteriaOperator<MetricAlert.Update.IUpdate>.WithCondition(MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, double threshold) { return this.WithCondition(timeAggregation, condition, threshold); } /// <summary> /// Sets the condition to monitor for the current metric alert. /// </summary> /// <param name="condition">The criteria operator. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.</param> /// <param name="timeAggregation">The criteria time aggregation types. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total'.</param> /// <param name="threshold">The criteria threshold value that activates the alert.</param> /// <return>The next stage of the metric alert condition update.</return> MetricAlertCondition.Update.IUpdateStages MetricAlertCondition.Update.IUpdateStages.WithCondition(MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, double threshold) { return this.WithCondition(timeAggregation, condition, threshold); } /// <summary> /// Sets the condition to monitor for the current metric alert. /// </summary> /// <param name="condition">The criteria operator. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.</param> /// <param name="timeAggregation">The criteria time aggregation types. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total'.</param> /// <param name="threshold">The criteria threshold value that activates the alert.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.Definition.IWithConditionAttach<MetricAlert.Definition.IWithCreate> MetricAlertCondition.Definition.IWithCriteriaOperator<MetricAlert.Definition.IWithCreate>.WithCondition(MetricAlertRuleTimeAggregation timeAggregation, MetricAlertRuleCondition condition, double threshold) { return this.WithCondition(timeAggregation, condition, threshold); } /// <summary> /// Adds a metric dimension filter. /// </summary> /// <param name="dimensionName">The name of the dimension.</param> /// <param name="values">List of dimension values to alert on.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.UpdateDefinition.IWithConditionAttach<MetricAlert.Update.IUpdate> MetricAlertCondition.UpdateDefinition.IWithConditionAttach<MetricAlert.Update.IUpdate>.WithDimension(string dimensionName, params string[] values) { return this.WithDimension(dimensionName, values); } /// <summary> /// Adds a metric dimension filter. /// </summary> /// <param name="dimensionName">The name of the dimension.</param> /// <param name="values">List of dimension values to alert on.</param> /// <return>The next stage of the metric alert condition update.</return> MetricAlertCondition.Update.IUpdateStages MetricAlertCondition.Update.IUpdateStages.WithDimension(string dimensionName, params string[] values) { return this.WithDimension(dimensionName, values); } /// <summary> /// Adds a metric dimension filter. /// </summary> /// <param name="dimensionName">The name of the dimension.</param> /// <param name="values">List of dimension values to alert on.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.Definition.IWithConditionAttach<MetricAlert.Definition.IWithCreate> MetricAlertCondition.Definition.IWithConditionAttach<MetricAlert.Definition.IWithCreate>.WithDimension(string dimensionName, params string[] values) { return this.WithDimension(dimensionName, values); } /// <summary> /// Sets the name of the signal name to monitor. /// </summary> /// <param name="metricName">Metric name of the signal.</param> /// <param name="metricNamespace">The Namespace of the metric.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.Definition.IWithCriteriaOperator<MetricAlert.Definition.IWithCreate> MetricAlertCondition.Definition.Blank.MetricName.IMetricName<MetricAlert.Definition.IWithCreate>.WithMetricName(string metricName, string metricNamespace) { return this.WithMetricName(metricName, metricNamespace); } /// <summary> /// Sets the name of the signal name to monitor. /// </summary> /// <param name="metricName">Metric name of the signal.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.Definition.IWithCriteriaOperator<MetricAlert.Definition.IWithCreate> MetricAlertCondition.Definition.Blank.MetricName.IMetricName<MetricAlert.Definition.IWithCreate>.WithMetricName(string metricName) { return this.WithMetricName(metricName); } /// <summary> /// Sets the name of the signal name to monitor. /// </summary> /// <param name="metricName">Metric name of the signal.</param> /// <param name="metricNamespace">The Namespace of the metric.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.UpdateDefinition.IWithCriteriaOperator<MetricAlert.Update.IUpdate> MetricAlertCondition.UpdateDefinition.Blank.MetricName.IMetricName<MetricAlert.Update.IUpdate>.WithMetricName(string metricName, string metricNamespace) { return this.WithMetricName(metricName, metricNamespace); } /// <summary> /// Sets the name of the signal name to monitor. /// </summary> /// <param name="metricName">Metric name of the signal.</param> /// <return>The next stage of metric alert condition definition.</return> MetricAlertCondition.UpdateDefinition.IWithCriteriaOperator<MetricAlert.Update.IUpdate> MetricAlertCondition.UpdateDefinition.Blank.MetricName.IMetricName<MetricAlert.Update.IUpdate>.WithMetricName(string metricName) { return this.WithMetricName(metricName); } /// <summary> /// Removes the specified dimension filter. /// </summary> /// <param name="dimensionName">DimensionName the name of the dimension.</param> /// <return>The next stage of the metric alert condition update.</return> MetricAlertCondition.Update.IUpdateStages MetricAlertCondition.Update.IUpdateStages.WithoutDimension(string dimensionName) { return this.WithoutDimension(dimensionName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementDouble1() { var test = new VectorGetAndWithElement__GetAndWithElementDouble1(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementDouble1 { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector128<Double> value = Vector128.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { Double result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Double.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { Vector128<Double> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Double.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector128<Double> value = Vector128.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector128) .GetMethod(nameof(Vector128.GetElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Double)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Double.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { object result2 = typeof(Vector128) .GetMethod(nameof(Vector128.WithElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector128<Double>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Double.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Double result, Double[] values, [CallerMemberName] string method = "") { if (result != values[1]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector128<Double.GetElement(1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector128<Double> result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Double[] result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 1) && (result[i] != values[i])) { succeeded = false; break; } } if (result[1] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Double.WithElement(1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { //[TestCase(Name = "ReadToDescendant", Desc = "ReadToDescendant")] public partial class TCReadToDescendant : BridgeHelpers { #region XMLSTR private string _xmlStr = @"<?xml version='1.0'?> <root><!--Comment--> <elem><!-- Comment --> <child1 att='1'><?pi target?> <child2 xmlns='child2'> <child3/> blahblahblah<![CDATA[ blah ]]> <child4/> </child2> <?pi target1?> </child1> </elem> <elem att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah <child4/> </child2> <?pi target1?> </child1> </elem> <elem xmlns='elem'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <elem xmlns='elem' att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <e:elem xmlns:e='elem2'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> <e:elem xmlns:e='elem2' att='1'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> </root>"; #endregion //[Variation("Simple positive test", Priority = 0, Params = new object[] { "NNS" })] //[Variation("Simple positive test", Priority = 0, Params = new object[] { "DNS" })] //[Variation("Simple positive test", Priority = 0, Params = new object[] { "NS" })] public void v() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); TestLog.WriteIgnore(DataReader.ReadInnerXml() + "\n"); throw new TestException(TestResult.Failed, ""); } while (DataReader.Read()) ; DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on NS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } } //[Variation("Read on a deep tree atleast more than 4K boundary", Priority = 2)] public void v2() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (mnw.GetNodes().Length < 4096); mnw.PutText("<a/>"); mnw.Finish(); XmlReader DataReader = GetReader(new StringReader(mnw.GetNodes())); PositionOnElement(DataReader, "ELEMENT_1"); DataReader.ReadToDescendant("a"); TestLog.Compare(DataReader.Depth, count, "Depth is not correct"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NNS" })] //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "DNS" })] //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NS" })] public void v3() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); // Doing a sequential read. switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); int depth = DataReader.Depth; if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); throw new TestException(TestResult.Failed, ""); } TestLog.Compare(DataReader.ReadToDescendant("elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } TestLog.Compare(DataReader.ReadToDescendant("e:elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } } //[Variation("If name not found, stop at end element of the subtree", Priority = 1)] public void v4() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "elem"); TestLog.Compare(DataReader.ReadToDescendant("abc"), false, "Reader returned true for an invalid name"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); DataReader.Read(); TestLog.Compare(DataReader.ReadToDescendant("abc", "elem"), false, "reader returned true for an invalid name,ns combination"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Positioning on a level and try to find the name which is on a level higher", Priority = 1)] public void v5() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "child3"); TestLog.Compare(DataReader.ReadToDescendant("child1"), false, "Reader returned true for an invalid name"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type"); TestLog.Compare(DataReader.LocalName, "child3", "Wrong name"); PositionOnElement(DataReader, "child3"); TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), false, "Reader returned true for an invalid name,ns"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type for name,ns"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read to Descendant on one level and again to level below it", Priority = 1)] public void v6() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem"), true, "Cant find elem"); TestLog.Compare(DataReader.ReadToDescendant("child1"), true, "Cant find child1"); TestLog.Compare(DataReader.ReadToDescendant("child2"), true, "Cant find child2"); TestLog.Compare(DataReader.ReadToDescendant("child3"), true, "Cant find child3"); TestLog.Compare(DataReader.ReadToDescendant("child4"), false, "shouldnt find child4"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read to Descendant on one level and again to level below it, with namespace", Priority = 1)] public void v7() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Cant find elem"); TestLog.Compare(DataReader.ReadToDescendant("child1", "elem"), true, "Cant find child1"); TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Cant find child2"); TestLog.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Cant find child3"); TestLog.Compare(DataReader.ReadToDescendant("child4", "child2"), false, "shouldnt find child4"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read to Descendant on one level and again to level below it, with prefix", Priority = 1)] public void v8() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("e:elem"), true, "Cant find elem"); TestLog.Compare(DataReader.ReadToDescendant("e:child1"), true, "Cant find child1"); TestLog.Compare(DataReader.ReadToDescendant("e:child2"), true, "Cant find child2"); TestLog.Compare(DataReader.ReadToDescendant("e:child3"), true, "Cant find child3"); TestLog.Compare(DataReader.ReadToDescendant("e:child4"), false, "shouldnt find child4"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Multiple Reads to children and then next siblings, NNS", Priority = 2)] public void v9() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem"), true, "Read fails elem"); TestLog.Compare(DataReader.ReadToDescendant("child3"), true, "Read fails child3"); TestLog.Compare(DataReader.ReadToNextSibling("child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Multiple Reads to children and then next siblings, DNS", Priority = 2)] public void v10() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Read fails elem"); TestLog.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Read fails child3"); TestLog.Compare(DataReader.ReadToNextSibling("child4", "child2"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Multiple Reads to children and then next siblings, NS", Priority = 2)] public void v11() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("e:elem"), true, "Read fails elem"); TestLog.Compare(DataReader.ReadToDescendant("e:child3"), true, "Read fails child3"); TestLog.Compare(DataReader.ReadToNextSibling("e:child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Call from different nodetypes", Priority = 1)] public void v12() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { TestLog.Compare(DataReader.ReadToDescendant("child1"), false, "Fails on node"); } else { if (DataReader.HasAttributes) { while (DataReader.MoveToNextAttribute()) { TestLog.Compare(DataReader.ReadToDescendant("abc"), false, "Fails on attribute node"); } } } } DataReader.Dispose(); } //[Variation("Only child has namespaces and read to it", Priority = 2)] public void v14() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Fails on attribute node"); DataReader.Dispose(); } //[Variation("Pass null to both arguments throws ArgumentException", Priority = 2)] public void v15() { XmlReader DataReader = GetReader(new StringReader("<root><b/></root>")); DataReader.Read(); try { DataReader.ReadToDescendant(null); } catch (ArgumentNullException) { } try { DataReader.ReadToDescendant("b", null); } catch (ArgumentNullException) { } while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Different names, same uri works correctly", Priority = 2)] public void v17() { XmlReader DataReader = GetReader(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>")); DataReader.Read(); DataReader.ReadToDescendant("child1", "bar"); TestLog.Compare(DataReader.IsEmptyElement, false, "Not on the correct node"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("On Root Node", Priority = 0, Params = new object[] { "NNS" })] //[Variation("On Root Node", Priority = 0, Params = new object[] { "DNS" })] //[Variation("On Root Node", Priority = 0, Params = new object[] { "NS" })] public void v18() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); TestLog.WriteIgnore(DataReader.ReadInnerXml() + "\n"); throw new TestException(TestResult.Failed, ""); } while (DataReader.Read()) ; DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on NS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } } //[Variation("427176 Assertion failed when call XmlReader.ReadToDescendant() for non-existing node", Priority = 1)] public void v19() { XmlReader DataReader = GetReader(new StringReader("<a>b</a>")); TestLog.Compare(DataReader.ReadToDescendant("foo"), false, "Should fail without assert"); DataReader.Dispose(); } } } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; using SafeSslHandle = Interop.libssl.SafeSslHandle; internal static partial class Interop { internal static class OpenSsl { private static libssl.verify_callback s_verifyClientCertificate = VerifyClientCertificate; #region internal methods internal static SafeSslHandle AllocateSslContext(long options, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, string encryptionPolicy, bool isServer, bool remoteCertRequired) { SafeSslHandle context = null; IntPtr method = GetSslMethod(isServer, options); using (libssl.SafeSslContextHandle innerContext = Crypto.SslCtxCreate(method)) { if (innerContext.IsInvalid) { throw CreateSslException(SR.net_allocate_ssl_context_failed); } libssl.SSL_CTX_ctrl(innerContext, libssl.SSL_CTRL_OPTIONS, options, IntPtr.Zero); libssl.SSL_CTX_set_quiet_shutdown(innerContext, 1); libssl.SSL_CTX_set_cipher_list(innerContext, encryptionPolicy); if (certHandle != null && certKeyHandle != null) { SetSslCertificate(innerContext, certHandle, certKeyHandle); } if (remoteCertRequired) { Debug.Assert(isServer, "isServer flag should be true"); libssl.SSL_CTX_set_verify(innerContext, (int)libssl.ClientCertOption.SSL_VERIFY_PEER | (int)libssl.ClientCertOption.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, s_verifyClientCertificate); //update the client CA list UpdateCAListFromRootStore(innerContext); } context = SafeSslHandle.Create(innerContext, isServer); Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create"); if (context.IsInvalid) { context.Dispose(); throw CreateSslException(SR.net_allocate_ssl_context_failed); } } return context; } internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount) { sendBuf = null; sendCount = 0; if ((recvBuf != null) && (recvCount > 0)) { BioWrite(context.InputBio, recvBuf, recvOffset, recvCount); } libssl.SslErrorCode error; int retVal = libssl.SSL_do_handshake(context); if (retVal != 1) { error = GetSslError(context, retVal); if ((retVal != -1) || (error != libssl.SslErrorCode.SSL_ERROR_WANT_READ)) { throw CreateSslException(context, SR.net_ssl_handshake_failed_error, retVal); } } sendCount = libssl.BIO_ctrl_pending(context.OutputBio); if (sendCount > 0) { sendBuf = new byte[sendCount]; try { sendCount = BioRead(context.OutputBio, sendBuf, sendCount); } finally { if (sendCount <= 0) { sendBuf = null; sendCount = 0; } } } return ((libssl.SSL_state(context) == (int)libssl.SslState.SSL_ST_OK)); } internal static int Encrypt(SafeSslHandle context, byte[] buffer, int offset, int count, int bufferCapacity, out libssl.SslErrorCode errorCode) { errorCode = libssl.SslErrorCode.SSL_ERROR_NONE; int retVal; unsafe { fixed (byte* fixedBuffer = buffer) { retVal = Crypto.SslWrite(context, fixedBuffer + offset, count); } } if (retVal != count) { errorCode = GetSslError(context, retVal); retVal = 0; switch (errorCode) { // indicate end-of-file case libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: case libssl.SslErrorCode.SSL_ERROR_WANT_READ: break; default: throw CreateSslException(SR.net_ssl_encrypt_failed, errorCode); } } else { int capacityNeeded = libssl.BIO_ctrl_pending(context.OutputBio); Debug.Assert(bufferCapacity >= capacityNeeded, "Input buffer of size " + bufferCapacity + " bytes is insufficient since encryption needs " + capacityNeeded + " bytes."); retVal = BioRead(context.OutputBio, buffer, capacityNeeded); } return retVal; } internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out libssl.SslErrorCode errorCode) { errorCode = libssl.SslErrorCode.SSL_ERROR_NONE; int retVal = BioWrite(context.InputBio, outBuffer, 0, count); if (retVal == count) { retVal = Crypto.SslRead(context, outBuffer, retVal); if (retVal > 0) { count = retVal; } } if (retVal != count) { errorCode = GetSslError(context, retVal); retVal = 0; switch (errorCode) { // indicate end-of-file case libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: break; case libssl.SslErrorCode.SSL_ERROR_WANT_READ: // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ errorCode = libssl.SSL_renegotiate_pending(context) == 1 ? libssl.SslErrorCode.SSL_ERROR_RENEGOTIATE : libssl.SslErrorCode.SSL_ERROR_WANT_READ; break; default: throw CreateSslException(SR.net_ssl_decrypt_failed, errorCode); } } return retVal; } internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context) { return libssl.SSL_get_peer_certificate(context); } internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context) { return libssl.SSL_get_peer_cert_chain(context); } internal static libssl.SSL_CIPHER GetConnectionInfo(SafeSslHandle sslHandle, out string protocolVersion) { IntPtr cipherPtr = libssl.SSL_get_current_cipher(sslHandle); var cipher = new libssl.SSL_CIPHER(); if (IntPtr.Zero != cipherPtr) { cipher = Marshal.PtrToStructure<libssl.SSL_CIPHER>(cipherPtr); } IntPtr versionPtr = libssl.SSL_get_version(sslHandle); protocolVersion = Marshal.PtrToStringAnsi(versionPtr); return cipher; } internal static void FreeSslContext(SafeSslHandle context) { Debug.Assert((context != null) && !context.IsInvalid, "Expected a valid context in FreeSslContext"); Disconnect(context); context.Dispose(); } #endregion #region private methods private static IntPtr GetSslMethod(bool isServer, long options) { options &= libssl.ProtocolMask; Debug.Assert(options != libssl.ProtocolMask, "All protocols are disabled"); bool ssl2 = (options & libssl.Options.SSL_OP_NO_SSLv2) == 0; bool ssl3 = (options & libssl.Options.SSL_OP_NO_SSLv3) == 0; bool tls10 = (options & libssl.Options.SSL_OP_NO_TLSv1) == 0; bool tls11 = (options & libssl.Options.SSL_OP_NO_TLSv1_1) == 0; bool tls12 = (options & libssl.Options.SSL_OP_NO_TLSv1_2) == 0; IntPtr method = libssl.SslMethods.SSLv23_method; // default string methodName = "SSLv23_method"; if (!ssl2) { if (!ssl3) { if (!tls11 && !tls12) { method = libssl.SslMethods.TLSv1_method; methodName = "TLSv1_method"; } else if (!tls10 && !tls12) { method = libssl.SslMethods.TLSv1_1_method; methodName = "TLSv1_1_method"; } else if (!tls10 && !tls11) { method = libssl.SslMethods.TLSv1_2_method; methodName = "TLSv1_2_method"; } } else if (!tls10 && !tls11 && !tls12) { method = libssl.SslMethods.SSLv3_method; methodName = "SSLv3_method"; } } if (IntPtr.Zero == method) { throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName)); } return method; } private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr) { using (SafeX509StoreCtxHandle storeHandle = new SafeX509StoreCtxHandle(x509_ctx_ptr, false)) { using (var chain = new X509Chain()) { chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; using (SafeX509StackHandle chainStack = Crypto.X509StoreCtxGetChain(storeHandle)) { if (chainStack.IsInvalid) { Debug.Fail("Invalid chain stack handle"); return 0; } IntPtr certPtr = Crypto.GetX509StackField(chainStack, 0); if (IntPtr.Zero == certPtr) { return 0; } using (X509Certificate2 cert = new X509Certificate2(certPtr)) { return chain.Build(cert) ? 1 : 0; } } } } } private static void UpdateCAListFromRootStore(libssl.SafeSslContextHandle context) { using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack()) { //maintaining the HashSet of Certificate's issuer name to keep track of duplicates HashSet<string> issuerNameHashSet = new HashSet<string>(); //Enumerate Certificates from LocalMachine and CurrentUser root store AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet); AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet); libssl.SSL_CTX_set_client_CA_list(context, nameStack); // The handle ownership has been transferred into the CTX. nameStack.SetHandleAsInvalid(); } } private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet) { using (var store = new X509Store(StoreName.Root, storeLocation)) { store.Open(OpenFlags.ReadOnly); foreach (var certificate in store.Certificates) { //Check if issuer name is already present //Avoiding duplicate names if (!issuerNameHashSet.Add(certificate.Issuer)) { continue; } using (SafeX509Handle certHandle = Crypto.X509Duplicate(certificate.Handle)) { using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle))) { if (Crypto.PushX509NameStackField(nameStack, nameHandle)) { // The handle ownership has been transferred into the STACK_OF(X509_NAME). nameHandle.SetHandleAsInvalid(); } else { throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error); } } } } } } private static void Disconnect(SafeSslHandle context) { int retVal = libssl.SSL_shutdown(context); if (retVal < 0) { //TODO (Issue #3362) check this error libssl.SSL_get_error(context, retVal); } } //TODO (Issue #3362) should we check Bio should retry? private static int BioRead(SafeBioHandle bio, byte[] buffer, int count) { int bytes = Crypto.BioRead(bio, buffer, count); if (bytes != count) { throw CreateSslException(SR.net_ssl_read_bio_failed_error); } return bytes; } //TODO (Issue #3362) should we check Bio should retry? private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count) { int bytes; unsafe { fixed (byte* bufPtr = buffer) { bytes = Crypto.BioWrite(bio, bufPtr + offset, count); } } if (bytes != count) { throw CreateSslException(SR.net_ssl_write_bio_failed_error); } return bytes; } private static libssl.SslErrorCode GetSslError(SafeSslHandle context, int result) { libssl.SslErrorCode retVal = libssl.SSL_get_error(context, result); if (retVal == libssl.SslErrorCode.SSL_ERROR_SYSCALL) { retVal = (libssl.SslErrorCode)libssl.ERR_get_error(); } return retVal; } private static void SetSslCertificate(libssl.SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr) { Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid"); Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid"); int retVal = libssl.SSL_CTX_use_certificate(contextPtr, certPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_cert_failed); } retVal = libssl.SSL_CTX_use_PrivateKey(contextPtr, keyPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_private_key_failed); } //check private key retVal = libssl.SSL_CTX_check_private_key(contextPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_check_private_key_failed); } } private static SslException CreateSslException(string message) { ulong errorVal = libssl.ERR_get_error(); string msg = SR.Format(message, Marshal.PtrToStringAnsi(libssl.ERR_reason_error_string(errorVal))); return new SslException(msg, (int)errorVal); } private static SslException CreateSslException(string message, libssl.SslErrorCode error) { string msg = SR.Format(message, error); switch (error) { case libssl.SslErrorCode.SSL_ERROR_SYSCALL: return CreateSslException(msg); case libssl.SslErrorCode.SSL_ERROR_SSL: Exception innerEx = Interop.Crypto.CreateOpenSslCryptographicException(); return new SslException(innerEx.Message, innerEx); default: return new SslException(msg, error); } } private static SslException CreateSslException(SafeSslHandle context, string message, int error) { return CreateSslException(message, libssl.SSL_get_error(context, error)); } #endregion #region Internal class internal sealed class SslException : Exception { public SslException(string inputMessage) : base(inputMessage) { } public SslException(string inputMessage, Exception ex) : base(inputMessage, ex) { } public SslException(string inputMessage, libssl.SslErrorCode error) : this(inputMessage, (int)error) { } public SslException(string inputMessage, int error) : this(inputMessage) { HResult = error; } public SslException(int error) : this(SR.Format(SR.net_generic_operation_failed, error)) { HResult = error; } } #endregion } }
// // FeedUpdater.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Migo.Net; using Migo.TaskCore; using Migo.TaskCore.Collections; namespace Migo.Syndication { public class FeedManager { private bool disposed; private Dictionary<Feed, FeedUpdateTask> update_feed_map; private TaskList<FeedUpdateTask> update_task_list; private TaskGroup<FeedUpdateTask> update_task_group; #region Public Properties and Events public event Action<FeedItem> ItemAdded; public event Action<FeedItem> ItemChanged; public event Action<FeedItem> ItemRemoved; public event EventHandler FeedsChanged; #endregion #region Constructor public FeedManager () { update_feed_map = new Dictionary<Feed, FeedUpdateTask> (); update_task_list = new TaskList<FeedUpdateTask> (); // Limit to 4 feeds downloading at a time update_task_group = new TaskGroup<FeedUpdateTask> (2, update_task_list); update_task_group.TaskStopped += OnUpdateTaskStopped; update_task_group.TaskAssociated += OnUpdateTaskAdded; // TODO // Start timeout to refresh feeds every so often } #endregion #region Public Methods public bool IsUpdating (Feed feed) { return update_feed_map.ContainsKey (feed); } public Feed CreateFeed (string url, FeedAutoDownload autoDownload) { return CreateFeed (url, autoDownload, 0); } public Feed CreateFeed (string url, FeedAutoDownload autoDownload, int max_items) { return CreateFeed (url, null, autoDownload, max_items, true); } public Feed CreateFeed (string url, string title, FeedAutoDownload autoDownload, int max_items) { return CreateFeed (url, title, autoDownload, max_items, true); } public Feed CreateFeed (string url, string title, FeedAutoDownload autoDownload, int max_items, bool is_subscribed) { Feed feed = null; url = url.Trim ().TrimEnd ('/'); if (!Feed.Exists (url)) { feed = new Feed (url, autoDownload); feed.Title = title; feed.IsSubscribed = is_subscribed; feed.MaxItemCount = max_items; feed.Save (); feed.Update (); } return feed; } public void QueueUpdate (Feed feed) { lock (update_task_group.SyncRoot) { if (disposed) { return; } if (!update_feed_map.ContainsKey (feed)) { FeedUpdateTask task = new FeedUpdateTask (feed); update_feed_map[feed] = task; lock (update_task_list.SyncRoot) { update_task_list.Add (task); } } } } public void CancelUpdate (Feed feed) { lock (update_task_group.SyncRoot) { if (update_feed_map.ContainsKey (feed)) { update_feed_map[feed].CancelAsync (); } } } public void Dispose (System.Threading.AutoResetEvent disposeHandle) { lock (update_task_group.SyncRoot) { if (update_task_group != null) { //update_task_group.CancelAsync (); //update_task_group.Handle.WaitOne (); update_task_group.Dispose (); //disposeHandle.WaitOne (); update_task_group.TaskStopped -= OnUpdateTaskStopped; update_task_group.TaskAssociated -= OnUpdateTaskAdded; update_task_group = null; } update_task_list = null; disposed = true; } } #endregion #region Internal Methods internal void OnFeedsChanged () { EventHandler handler = FeedsChanged; if (handler != null) { handler (this, EventArgs.Empty); } } internal void OnItemAdded (FeedItem item) { Action<FeedItem> handler = ItemAdded; if (handler != null) { handler (item); } } internal void OnItemChanged (FeedItem item) { Action<FeedItem> handler = ItemChanged; if (handler != null) { handler (item); } } internal void OnItemRemoved (FeedItem item) { Action<FeedItem> handler = ItemRemoved; if (handler != null) { handler (item); } } #endregion #region Private Methods private void OnUpdateTaskAdded (object sender, TaskEventArgs<FeedUpdateTask> e) { lock (update_task_group.SyncRoot) { update_task_group.Execute (); } } private void OnUpdateTaskStopped (object sender, TaskEventArgs<FeedUpdateTask> e) { lock (update_task_group.SyncRoot) { FeedUpdateTask fut = e.Task as FeedUpdateTask; update_feed_map.Remove (fut.Feed); lock (update_task_list.SyncRoot) { update_task_list.Remove (e.Task); } } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Binary.Structure; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary writer implementation. /// </summary> internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter { /** Marshaller. */ private readonly Marshaller _marsh; /** Stream. */ private readonly IBinaryStream _stream; /** Builder (used only during build). */ private BinaryObjectBuilder _builder; /** Handles. */ private BinaryHandleDictionary<object, long> _hnds; /** Metadatas collected during this write session. */ private IDictionary<int, BinaryType> _metas; /** Current type ID. */ private int _curTypeId; /** Current name converter */ private IBinaryNameMapper _curConverter; /** Current mapper. */ private IBinaryIdMapper _curMapper; /** Current object start position. */ private int _curPos; /** Current raw position. */ private int _curRawPos; /** Whether we are currently detaching an object. */ private bool _detaching; /** Current type structure tracker, */ private BinaryStructureTracker _curStruct; /** Schema holder. */ private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current; /// <summary> /// Gets the marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Write named boolean value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean value.</param> public void WriteBoolean(string fieldName, bool val) { WriteFieldId(fieldName, BinaryUtils.TypeBool); WriteBooleanField(val); } /// <summary> /// Writes the boolean field. /// </summary> /// <param name="val">if set to <c>true</c> [value].</param> internal void WriteBooleanField(bool val) { _stream.WriteByte(BinaryUtils.TypeBool); _stream.WriteBool(val); } /// <summary> /// Write boolean value. /// </summary> /// <param name="val">Boolean value.</param> public void WriteBoolean(bool val) { _stream.WriteBool(val); } /// <summary> /// Write named boolean array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(string fieldName, bool[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayBool); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write boolean array. /// </summary> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(bool[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write named byte value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte value.</param> public void WriteByte(string fieldName, byte val) { WriteFieldId(fieldName, BinaryUtils.TypeBool); WriteByteField(val); } /// <summary> /// Write byte field value. /// </summary> /// <param name="val">Byte value.</param> internal void WriteByteField(byte val) { _stream.WriteByte(BinaryUtils.TypeByte); _stream.WriteByte(val); } /// <summary> /// Write byte value. /// </summary> /// <param name="val">Byte value.</param> public void WriteByte(byte val) { _stream.WriteByte(val); } /// <summary> /// Write named byte array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte array.</param> public void WriteByteArray(string fieldName, byte[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayByte); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write byte array. /// </summary> /// <param name="val">Byte array.</param> public void WriteByteArray(byte[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write named short value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short value.</param> public void WriteShort(string fieldName, short val) { WriteFieldId(fieldName, BinaryUtils.TypeShort); WriteShortField(val); } /// <summary> /// Write short field value. /// </summary> /// <param name="val">Short value.</param> internal void WriteShortField(short val) { _stream.WriteByte(BinaryUtils.TypeShort); _stream.WriteShort(val); } /// <summary> /// Write short value. /// </summary> /// <param name="val">Short value.</param> public void WriteShort(short val) { _stream.WriteShort(val); } /// <summary> /// Write named short array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short array.</param> public void WriteShortArray(string fieldName, short[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayShort); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write short array. /// </summary> /// <param name="val">Short array.</param> public void WriteShortArray(short[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write named char value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char value.</param> public void WriteChar(string fieldName, char val) { WriteFieldId(fieldName, BinaryUtils.TypeChar); WriteCharField(val); } /// <summary> /// Write char field value. /// </summary> /// <param name="val">Char value.</param> internal void WriteCharField(char val) { _stream.WriteByte(BinaryUtils.TypeChar); _stream.WriteChar(val); } /// <summary> /// Write char value. /// </summary> /// <param name="val">Char value.</param> public void WriteChar(char val) { _stream.WriteChar(val); } /// <summary> /// Write named char array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char array.</param> public void WriteCharArray(string fieldName, char[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayChar); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write char array. /// </summary> /// <param name="val">Char array.</param> public void WriteCharArray(char[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write named int value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int value.</param> public void WriteInt(string fieldName, int val) { WriteFieldId(fieldName, BinaryUtils.TypeInt); WriteIntField(val); } /// <summary> /// Writes the int field. /// </summary> /// <param name="val">The value.</param> internal void WriteIntField(int val) { _stream.WriteByte(BinaryUtils.TypeInt); _stream.WriteInt(val); } /// <summary> /// Write int value. /// </summary> /// <param name="val">Int value.</param> public void WriteInt(int val) { _stream.WriteInt(val); } /// <summary> /// Write named int array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int array.</param> public void WriteIntArray(string fieldName, int[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayInt); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write int array. /// </summary> /// <param name="val">Int array.</param> public void WriteIntArray(int[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write named long value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long value.</param> public void WriteLong(string fieldName, long val) { WriteFieldId(fieldName, BinaryUtils.TypeLong); WriteLongField(val); } /// <summary> /// Writes the long field. /// </summary> /// <param name="val">The value.</param> internal void WriteLongField(long val) { _stream.WriteByte(BinaryUtils.TypeLong); _stream.WriteLong(val); } /// <summary> /// Write long value. /// </summary> /// <param name="val">Long value.</param> public void WriteLong(long val) { _stream.WriteLong(val); } /// <summary> /// Write named long array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long array.</param> public void WriteLongArray(string fieldName, long[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayLong); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write long array. /// </summary> /// <param name="val">Long array.</param> public void WriteLongArray(long[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write named float value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float value.</param> public void WriteFloat(string fieldName, float val) { WriteFieldId(fieldName, BinaryUtils.TypeFloat); WriteFloatField(val); } /// <summary> /// Writes the float field. /// </summary> /// <param name="val">The value.</param> internal void WriteFloatField(float val) { _stream.WriteByte(BinaryUtils.TypeFloat); _stream.WriteFloat(val); } /// <summary> /// Write float value. /// </summary> /// <param name="val">Float value.</param> public void WriteFloat(float val) { _stream.WriteFloat(val); } /// <summary> /// Write named float array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float array.</param> public void WriteFloatArray(string fieldName, float[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayFloat); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write float array. /// </summary> /// <param name="val">Float array.</param> public void WriteFloatArray(float[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write named double value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double value.</param> public void WriteDouble(string fieldName, double val) { WriteFieldId(fieldName, BinaryUtils.TypeDouble); WriteDoubleField(val); } /// <summary> /// Writes the double field. /// </summary> /// <param name="val">The value.</param> internal void WriteDoubleField(double val) { _stream.WriteByte(BinaryUtils.TypeDouble); _stream.WriteDouble(val); } /// <summary> /// Write double value. /// </summary> /// <param name="val">Double value.</param> public void WriteDouble(double val) { _stream.WriteDouble(val); } /// <summary> /// Write named double array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double array.</param> public void WriteDoubleArray(string fieldName, double[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayDouble); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write double array. /// </summary> /// <param name="val">Double array.</param> public void WriteDoubleArray(double[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write named decimal value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal value.</param> public void WriteDecimal(string fieldName, decimal? val) { WriteFieldId(fieldName, BinaryUtils.TypeDecimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write decimal value. /// </summary> /// <param name="val">Decimal value.</param> public void WriteDecimal(decimal? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write named decimal array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(string fieldName, decimal?[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayDecimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write decimal array. /// </summary> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(decimal?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write named date value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date value.</param> public void WriteTimestamp(string fieldName, DateTime? val) { WriteFieldId(fieldName, BinaryUtils.TypeTimestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeTimestamp); BinaryUtils.WriteTimestamp(val.Value, _stream); } } /// <summary> /// Write date value. /// </summary> /// <param name="val">Date value.</param> public void WriteTimestamp(DateTime? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeTimestamp); BinaryUtils.WriteTimestamp(val.Value, _stream); } } /// <summary> /// Write named date array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date array.</param> public void WriteTimestampArray(string fieldName, DateTime?[] val) { WriteFieldId(fieldName, BinaryUtils.TypeTimestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream); } } /// <summary> /// Write date array. /// </summary> /// <param name="val">Date array.</param> public void WriteTimestampArray(DateTime?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream); } } /// <summary> /// Write named string value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String value.</param> public void WriteString(string fieldName, string val) { WriteFieldId(fieldName, BinaryUtils.TypeString); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write string value. /// </summary> /// <param name="val">String value.</param> public void WriteString(string val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write named string array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String array.</param> public void WriteStringArray(string fieldName, string[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayString); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write string array. /// </summary> /// <param name="val">String array.</param> public void WriteStringArray(string[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write named GUID value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID value.</param> public void WriteGuid(string fieldName, Guid? val) { WriteFieldId(fieldName, BinaryUtils.TypeGuid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write GUID value. /// </summary> /// <param name="val">GUID value.</param> public void WriteGuid(Guid? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write named GUID array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID array.</param> public void WriteGuidArray(string fieldName, Guid?[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayGuid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write GUID array. /// </summary> /// <param name="val">GUID array.</param> public void WriteGuidArray(Guid?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write named enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum value.</param> public void WriteEnum<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryUtils.TypeEnum); WriteEnum(val); } /// <summary> /// Write enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum value.</param> public void WriteEnum<T>(T val) { // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else { var desc = _marsh.GetDescriptor(val.GetType()); if (desc != null) { var metaHnd = _marsh.GetBinaryTypeHandler(desc); _stream.WriteByte(BinaryUtils.TypeEnum); BinaryUtils.WriteEnum(this, val); SaveMetadata(desc, metaHnd.OnObjectWriteFinished()); } else { // Unregistered enum, write as serializable Write(new SerializableObjectHolder(val)); } } } /// <summary> /// Write named enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayEnum); WriteEnumArray(val); } /// <summary> /// Write enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(T[] val) { WriteEnumArrayInternal(val, null); } /// <summary> /// Writes the enum array. /// </summary> /// <param name="val">The value.</param> /// <param name="elementTypeId">The element type id.</param> public void WriteEnumArrayInternal(Array val, int? elementTypeId) { if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayEnum); var elTypeId = elementTypeId ?? BinaryUtils.GetEnumTypeId(val.GetType().GetElementType(), Marshaller); BinaryUtils.WriteArray(val, this, elTypeId); } } /// <summary> /// Write named object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object value.</param> public void WriteObject<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryUtils.TypeObject); // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else Write(val); } /// <summary> /// Write object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Object value.</param> public void WriteObject<T>(T val) { Write(val); } /// <summary> /// Write named object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object array.</param> public void WriteArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArray); WriteArray(val); } /// <summary> /// Write object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="val">Object array.</param> public void WriteArray<T>(T[] val) { WriteArrayInternal(val); } /// <summary> /// Write object array. /// </summary> /// <param name="val">Object array.</param> public void WriteArrayInternal(Array val) { if (val == null) WriteNullRawField(); else { if (WriteHandle(_stream.Position, val)) return; _stream.WriteByte(BinaryUtils.TypeArray); BinaryUtils.WriteArray(val, this); } } /// <summary> /// Write named collection. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Collection.</param> public void WriteCollection(string fieldName, ICollection val) { WriteFieldId(fieldName, BinaryUtils.TypeCollection); WriteCollection(val); } /// <summary> /// Write collection. /// </summary> /// <param name="val">Collection.</param> public void WriteCollection(ICollection val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryUtils.TypeCollection); BinaryUtils.WriteCollection(val, this); } } /// <summary> /// Write named dictionary. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Dictionary.</param> public void WriteDictionary(string fieldName, IDictionary val) { WriteFieldId(fieldName, BinaryUtils.TypeDictionary); WriteDictionary(val); } /// <summary> /// Write dictionary. /// </summary> /// <param name="val">Dictionary.</param> public void WriteDictionary(IDictionary val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryUtils.TypeDictionary); BinaryUtils.WriteDictionary(val, this); } } /// <summary> /// Write NULL field. /// </summary> private void WriteNullField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Write NULL raw field. /// </summary> private void WriteNullRawField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Get raw writer. /// </summary> /// <returns> /// Raw writer. /// </returns> public IBinaryRawWriter GetRawWriter() { if (_curRawPos == 0) _curRawPos = _stream.Position; return this; } /// <summary> /// Set new builder. /// </summary> /// <param name="builder">Builder.</param> /// <returns>Previous builder.</returns> internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder) { BinaryObjectBuilder ret = _builder; _builder = builder; return ret; } /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="stream">Stream.</param> internal BinaryWriter(Marshaller marsh, IBinaryStream stream) { _marsh = marsh; _stream = stream; } /// <summary> /// Write object. /// </summary> /// <param name="obj">Object.</param> public void Write<T>(T obj) { // Handle special case for null. // ReSharper disable once CompareNonConstrainedGenericWithNull if (obj == null) { _stream.WriteByte(BinaryUtils.HdrNull); return; } // We use GetType() of a real object instead of typeof(T) to take advantage of // automatic Nullable'1 unwrapping. Type type = obj.GetType(); // Handle common case when primitive is written. if (type.IsPrimitive) { WritePrimitive(obj, type); return; } // Handle enums. if (type.IsEnum) { WriteEnum(obj); return; } // Handle special case for builder. if (WriteBuilderSpecials(obj)) return; // Suppose that we faced normal object and perform descriptor lookup. IBinaryTypeDescriptor desc = _marsh.GetDescriptor(type); if (desc != null) { // Writing normal object. var pos = _stream.Position; // Dealing with handles. if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj)) return; // Skip header length as not everything is known now _stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current); // Preserve old frame. int oldTypeId = _curTypeId; IBinaryNameMapper oldConverter = _curConverter; IBinaryIdMapper oldMapper = _curMapper; int oldRawPos = _curRawPos; var oldPos = _curPos; var oldStruct = _curStruct; // Push new frame. _curTypeId = desc.TypeId; _curConverter = desc.NameMapper; _curMapper = desc.IdMapper; _curRawPos = 0; _curPos = pos; _curStruct = new BinaryStructureTracker(desc, desc.WriterTypeStructure); var schemaIdx = _schema.PushSchema(); try { // Write object fields. desc.Serializer.WriteBinary(obj, this); var dataEnd = _stream.Position; // Write schema var schemaOffset = dataEnd - pos; int schemaId; var flags = desc.UserType ? BinaryObjectHeader.Flag.UserType : BinaryObjectHeader.Flag.None; if (Marshaller.CompactFooter && desc.UserType) flags |= BinaryObjectHeader.Flag.CompactFooter; var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags); if (hasSchema) { flags |= BinaryObjectHeader.Flag.HasSchema; // Calculate and write header. if (_curRawPos > 0) _stream.WriteInt(_curRawPos - pos); // raw offset is in the last 4 bytes // Update schema in type descriptor if (desc.Schema.Get(schemaId) == null) desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx)); } else schemaOffset = BinaryObjectHeader.Size; if (_curRawPos > 0) flags |= BinaryObjectHeader.Flag.HasRaw; var len = _stream.Position - pos; var hashCode = desc.EqualityComparer != null ? desc.EqualityComparer.GetHashCode(Stream, pos + BinaryObjectHeader.Size, dataEnd - pos - BinaryObjectHeader.Size, _schema, schemaIdx, _marsh, desc) : obj.GetHashCode(); var header = new BinaryObjectHeader(desc.TypeId, hashCode, len, schemaId, schemaOffset, flags); BinaryObjectHeader.Write(header, _stream, pos); Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end } finally { _schema.PopSchema(schemaIdx); } // Apply structure updates if any. _curStruct.UpdateWriterStructure(this); // Restore old frame. _curTypeId = oldTypeId; _curConverter = oldConverter; _curMapper = oldMapper; _curRawPos = oldRawPos; _curPos = oldPos; _curStruct = oldStruct; } else { // Are we dealing with a well-known type? var handler = BinarySystemHandlers.GetWriteHandler(type); if (handler == null) // We did our best, object cannot be marshalled. throw BinaryUtils.GetUnsupportedTypeException(type, obj); if (handler.SupportsHandles && WriteHandle(_stream.Position, obj)) return; handler.Write(this, obj); } } /// <summary> /// Write primitive type. /// </summary> /// <param name="val">Object.</param> /// <param name="type">Type.</param> private unsafe void WritePrimitive<T>(T val, Type type) { // .Net defines 14 primitive types. We support 12 - excluding IntPtr and UIntPtr. // Types check sequence is designed to minimize comparisons for the most frequent types. if (type == typeof(int)) WriteIntField(TypeCaster<int>.Cast(val)); else if (type == typeof(long)) WriteLongField(TypeCaster<long>.Cast(val)); else if (type == typeof(bool)) WriteBooleanField(TypeCaster<bool>.Cast(val)); else if (type == typeof(byte)) WriteByteField(TypeCaster<byte>.Cast(val)); else if (type == typeof(short)) WriteShortField(TypeCaster<short>.Cast(val)); else if (type == typeof(char)) WriteCharField(TypeCaster<char>.Cast(val)); else if (type == typeof(float)) WriteFloatField(TypeCaster<float>.Cast(val)); else if (type == typeof(double)) WriteDoubleField(TypeCaster<double>.Cast(val)); else if (type == typeof(sbyte)) { var val0 = TypeCaster<sbyte>.Cast(val); WriteByteField(*(byte*)&val0); } else if (type == typeof(ushort)) { var val0 = TypeCaster<ushort>.Cast(val); WriteShortField(*(short*) &val0); } else if (type == typeof(uint)) { var val0 = TypeCaster<uint>.Cast(val); WriteIntField(*(int*)&val0); } else if (type == typeof(ulong)) { var val0 = TypeCaster<ulong>.Cast(val); WriteLongField(*(long*)&val0); } else throw BinaryUtils.GetUnsupportedTypeException(type, val); } /// <summary> /// Try writing object as special builder type. /// </summary> /// <param name="obj">Object.</param> /// <returns>True if object was written, false otherwise.</returns> private bool WriteBuilderSpecials<T>(T obj) { if (_builder != null) { // Special case for binary object during build. BinaryObject portObj = obj as BinaryObject; if (portObj != null) { if (!WriteHandle(_stream.Position, portObj)) _builder.ProcessBinary(_stream, portObj); return true; } // Special case for builder during build. BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder; if (portBuilder != null) { if (!WriteHandle(_stream.Position, portBuilder)) _builder.ProcessBuilder(_stream, portBuilder); return true; } } return false; } /// <summary> /// Add handle to handles map. /// </summary> /// <param name="pos">Position in stream.</param> /// <param name="obj">Object.</param> /// <returns><c>true</c> if object was written as handle.</returns> private bool WriteHandle(long pos, object obj) { if (_hnds == null) { // Cache absolute handle position. _hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance); return false; } long hndPos; if (!_hnds.TryGetValue(obj, out hndPos)) { // Cache absolute handle position. _hnds.Add(obj, pos); return false; } _stream.WriteByte(BinaryUtils.HdrHnd); // Handle is written as difference between position before header and handle position. _stream.WriteInt((int)(pos - hndPos)); return true; } /// <summary> /// Perform action with detached semantics. /// </summary> /// <param name="a"></param> internal void WithDetach(Action<BinaryWriter> a) { if (_detaching) a(this); else { _detaching = true; BinaryHandleDictionary<object, long> oldHnds = _hnds; _hnds = null; try { a(this); } finally { _detaching = false; if (oldHnds != null) { // Merge newly recorded handles with old ones and restore old on the stack. // Otherwise we can use current handles right away. if (_hnds != null) oldHnds.Merge(_hnds); _hnds = oldHnds; } } } } /// <summary> /// Stream. /// </summary> internal IBinaryStream Stream { get { return _stream; } } /// <summary> /// Gets collected metadatas. /// </summary> /// <returns>Collected metadatas (if any).</returns> internal ICollection<BinaryType> GetBinaryTypes() { return _metas == null ? null : _metas.Values; } /// <summary> /// Write field ID. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="fieldTypeId">Field type ID.</param> private void WriteFieldId(string fieldName, byte fieldTypeId) { if (_curRawPos != 0) throw new BinaryObjectException("Cannot write named fields after raw data is written."); var fieldId = _curStruct.GetFieldId(fieldName, fieldTypeId); _schema.PushField(fieldId, _stream.Position - _curPos); } /// <summary> /// Saves metadata for this session. /// </summary> /// <param name="desc">The descriptor.</param> /// <param name="fields">Fields metadata.</param> internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, int> fields) { Debug.Assert(desc != null); if (_metas == null) { _metas = new Dictionary<int, BinaryType>(1) { {desc.TypeId, new BinaryType(desc, fields)} }; } else { BinaryType meta; if (_metas.TryGetValue(desc.TypeId, out meta)) meta.UpdateFields(fields); else _metas[desc.TypeId] = new BinaryType(desc, fields); } } } }
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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 the following location: * * 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. */ ////package org.jasig.cas.authentication.principal; ////import java.util.Collections; ////import java.util.HashMap; ////import java.util.Map; ////import org.jasig.cas.util.DefaultUniqueTicketIdGenerator; ////import org.jasig.cas.util.HttpClient; ////import org.jasig.cas.util.SamlUtils; ////import org.jasig.cas.util.UniqueTicketIdGenerator; ////import org.slf4j.Logger; ////import org.slf4j.LoggerFactory; /** * Abstract implementation of a WebApplicationService. * * @author Scott Battaglia * @version $Revision: 1.3 $ $Date: 2007/04/19 20:13:01 $ * @since 3.1 * */ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using NCAS.jasig.util; namespace NCAS.jasig.authentication.principal { public abstract class AbstractWebApplicationService : WebApplicationService { //protected static Logger LOG = LoggerFactory.getLogger(SamlService.class); private static Dictionary<string, Object> EMPTY_MAP = new Dictionary<string, object>(); private static UniqueTicketIdGenerator GENERATOR = new DefaultUniqueTicketIdGenerator(); /** The id of the service. */ private string id; /** The original url provided, used to reconstruct the redirect url. */ private string originalUrl; private string artifactId; private Principal principal; private bool loggedOutAlready = false; private HttpClient httpClient; protected AbstractWebApplicationService(string id, string originalUrl, string artifactId, HttpClient httpClient) { this.id = id; this.originalUrl = originalUrl; this.artifactId = artifactId; this.httpClient = httpClient; } public string toString() { return this.id; } public string getId() { return this.id; } public abstract Response getResponse(string ticketId); public string getArtifactId() { return this.artifactId; } public Dictionary<string, Object> getAttributes() { return EMPTY_MAP; } protected static string cleanupUrl(string url) { if (url == null) { return null; } int jsessionPosition = url.IndexOf(";jsession"); if (jsessionPosition == -1) { return url; } int questionMarkPosition = url.IndexOf("?"); if (questionMarkPosition < jsessionPosition) { return url.Substring(0, url.IndexOf(";jsession")); } return url.Substring(0, jsessionPosition) + url.Substring(questionMarkPosition); } protected string getOriginalUrl() { return this.originalUrl; } protected HttpClient getHttpClient() { return this.httpClient; } public bool equals(Object obj) { if (obj == null) { return false; } if (obj is Service) { Service service = (Service)obj; return this.getId().Equals(service.getId()); } return false; } public int hashCode() { int prime = 41; int result = 1; result = prime * result + ((this.id == null) ? 0 : this.id.GetHashCode()); return result; } protected Principal getPrincipal() { return this.principal; } public void setPrincipal(Principal principal) { this.principal = principal; } public bool matches(Service service) { return this.id.Equals(service.getId()); } [MethodImpl(MethodImplOptions.Synchronized)] public bool logOutOfService(string sessionIdentifier) { if (this.loggedOutAlready) { return true; } Dev.Log.Loger.Debug("Sending logout request for: " + this.getId()); string logoutRequest = "<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\"" + GENERATOR.getNewTicketId("LR") + "\" Version=\"2.0\" IssueInstant=\"" + SamlUtils.getCurrentDateAndTime() + "\"><saml:NameID xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\">@NOT_USED@</saml:NameID><samlp:SessionIndex>" + sessionIdentifier + "</samlp:SessionIndex></samlp:LogoutRequest>"; this.loggedOutAlready = true; if (this.httpClient != null) { return this.httpClient.sendMessageToEndPoint(this.getOriginalUrl(), logoutRequest, true); } return false; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapDITStructureRuleSchema.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using SchemaParser = Novell.Directory.Ldap.Utilclass.SchemaParser; using AttributeQualifier = Novell.Directory.Ldap.Utilclass.AttributeQualifier; namespace Novell.Directory.Ldap { /// <summary> Represents the definition of a specific DIT (Directory Information Tree) /// structure rule in the directory schema. /// /// The LdapDITStructureRuleSchema class represents the definition of a DIT /// Structure Rule. It is used to discover or modify which /// object classes a particular object class may be subordinate to in the DIT. /// /// </summary> public class LdapDITStructureRuleSchema:LdapSchemaElement { /// <summary> Returns the rule ID for this structure rule. /// /// The getRuleID method returns an integer rather than a dotted /// decimal OID. Objects of this class do not have an OID, /// thus getID can return null. /// /// /// </summary> /// <returns> The rule ID for this structure rule. /// </returns> virtual public int RuleID { get { return ruleID; } } /// <summary> Returns the NameForm that this structure rule controls. /// /// You can get the actual object class that this structure rule controls /// by calling the getNameForm.getObjectClass method. /// /// </summary> /// <returns> The NameForm that this structure rule controls. /// </returns> virtual public System.String NameForm { get { return nameForm; } } /// <summary> Returns a list of all structure rules that are superior to this /// structure rule. /// /// To resolve to an object class, you need to first /// resolve the superior ID to another structure rule, then call /// the getNameForm.getObjectClass method on that structure rule. /// /// </summary> /// <returns> A list of all structure rules that are superior to this structure rule. /// </returns> virtual public System.String[] Superiors { get { return superiorIDs; } } private int ruleID = 0; private System.String nameForm = ""; private System.String[] superiorIDs = new System.String[]{""}; /// <summary>Constructs a DIT structure rule for adding to or deleting from the /// schema. /// /// </summary> /// <param name="names"> The names of the structure rule. /// /// </param> /// <param name="ruleID"> The unique identifier of the structure rule. NOTE: /// this is an integer, not a dotted numerical /// identifier. Structure rules aren't identified /// by OID. /// /// </param> /// <param name="description">An optional description of the structure rule. /// /// </param> /// <param name="obsolete"> True if the structure rule is obsolete. /// /// </param> /// <param name="nameForm"> Either the identifier or name of a name form. /// This is used to indirectly refer to the object /// class that this structure rule applies to. /// /// </param> /// <param name="superiorIDs">A list of superior structure rules - specified /// by their integer ID. The object class /// specified by this structure rule (via the /// nameForm parameter) may only be subordinate in /// the DIT to object classes of those represented /// by the structure rules here; it may be null. /// /// </param> public LdapDITStructureRuleSchema(System.String[] names, int ruleID, System.String description, bool obsolete, System.String nameForm, System.String[] superiorIDs):base(LdapSchema.schemaTypeNames[LdapSchema.DITSTRUCTURE]) { base.names = new System.String[names.Length]; names.CopyTo(base.names, 0); this.ruleID = ruleID; base.description = description; base.obsolete = obsolete; this.nameForm = nameForm; this.superiorIDs = superiorIDs; base.Value = formatString(); return ; } /// <summary> Constructs a DIT structure rule from the raw string value returned from /// a schema query for dITStructureRules. /// /// </summary> /// <param name="raw"> The raw string value returned from a schema /// query for dITStructureRules. /// </param> public LdapDITStructureRuleSchema(System.String raw):base(LdapSchema.schemaTypeNames[LdapSchema.DITSTRUCTURE]) { base.obsolete = false; try { SchemaParser parser = new SchemaParser(raw); if (parser.Names != null) { base.names = new System.String[parser.Names.Length]; parser.Names.CopyTo(base.names, 0); } if ((System.Object) parser.ID != null) ruleID = System.Int32.Parse(parser.ID); if ((System.Object) parser.Description != null) base.description = parser.Description; if (parser.Superiors != null) { superiorIDs = new System.String[parser.Superiors.Length]; parser.Superiors.CopyTo(superiorIDs, 0); } if ((System.Object) parser.NameForm != null) nameForm = parser.NameForm; base.obsolete = parser.Obsolete; System.Collections.IEnumerator qualifiers = parser.Qualifiers; AttributeQualifier attrQualifier; while (qualifiers.MoveNext()) { attrQualifier = (AttributeQualifier) qualifiers.Current; setQualifier(attrQualifier.Name, attrQualifier.Values); } base.Value = formatString(); } catch (System.IO.IOException e) { } return ; } /// <summary> Returns a string in a format suitable for directly adding to a /// directory, as a value of the particular schema element class. /// /// </summary> /// <returns> A string representation of the class' definition. /// </returns> protected internal override System.String formatString() { System.Text.StringBuilder valueBuffer = new System.Text.StringBuilder("( "); System.String token; System.String[] strArray; token = RuleID.ToString(); valueBuffer.Append(token); strArray = Names; if (strArray != null) { valueBuffer.Append(" NAME "); if (strArray.Length == 1) { valueBuffer.Append("'" + strArray[0] + "'"); } else { valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { valueBuffer.Append(" '" + strArray[i] + "'"); } valueBuffer.Append(" )"); } } if ((System.Object) (token = Description) != null) { valueBuffer.Append(" DESC "); valueBuffer.Append("'" + token + "'"); } if (Obsolete) { valueBuffer.Append(" OBSOLETE"); } if ((System.Object) (token = NameForm) != null) { valueBuffer.Append(" FORM "); valueBuffer.Append("'" + token + "'"); } if ((strArray = Superiors) != null) { valueBuffer.Append(" SUP "); if (strArray.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } System.Collections.IEnumerator en; if ((en = QualifierNames) != null) { System.String qualName; System.String[] qualValue; while (en.MoveNext()) { qualName = ((System.String) en.Current); valueBuffer.Append(" " + qualName + " "); if ((qualValue = getQualifier(qualName)) != null) { if (qualValue.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < qualValue.Length; i++) { if (i > 0) valueBuffer.Append(" "); valueBuffer.Append("'" + qualValue[i] + "'"); } if (qualValue.Length > 1) valueBuffer.Append(" )"); } } } valueBuffer.Append(" )"); return valueBuffer.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.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public static class ExceptTests { private const int DuplicateFactor = 4; private static IEnumerable<int> RightCounts(int leftCount) { int upperBound = Math.Max(DuplicateFactor, leftCount); return new[] { 0, 1, upperBound, upperBound * 2 }.Distinct(); } public static IEnumerable<object[]> ExceptUnorderedData(int[] leftCounts) { foreach (int leftCount in leftCounts.DefaultIfEmpty(Sources.OuterLoopCount / 4)) { foreach (int rightCount in RightCounts(leftCount)) { int rightStart = 0 - rightCount / 2; yield return new object[] { leftCount, rightStart, rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) }; } } } public static IEnumerable<object[]> ExceptData(int[] leftCounts) { foreach (int leftCount in leftCounts.DefaultIfEmpty(Sources.OuterLoopCount / 4)) { foreach (int rightCount in RightCounts(leftCount)) { int rightStart = 0 - rightCount / 2; foreach (object[] left in Sources.Ranges(new[] { leftCount })) { yield return left.Concat(new object[] { UnorderedSources.Default(rightStart, rightCount), rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) }).ToArray(); } } } } public static IEnumerable<object[]> ExceptSourceMultipleData(int[] counts) { foreach (int leftCount in counts.DefaultIfEmpty(Sources.OuterLoopCount / DuplicateFactor / 2)) { ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered(); foreach (int rightCount in RightCounts(leftCount)) { int rightStart = 0 - rightCount / 2; yield return new object[] { left, leftCount, UnorderedSources.Default(rightStart, rightCount), rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) }; } } } // // Except // [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })] public static void Except_Unordered(int leftCount, int rightStart, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount); IntegerRangeSet seen = new IntegerRangeSet(start, count); foreach (int i in leftQuery.Except(rightQuery)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Unordered_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count) { Except_Unordered(leftCount, rightStart, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })] public static void Except(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; int seen = start; foreach (int i in leftQuery.Except(rightQuery)) { Assert.Equal(seen++, i); } Assert.Equal(count + start, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except(left, leftCount, rightQuery, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })] public static void Except_Unordered_NotPipelined(int leftCount, int rightStart, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount); IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(leftQuery.Except(rightQuery).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Unordered_NotPipelined_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count) { Except_Unordered_NotPipelined(leftCount, rightStart, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })] public static void Except_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; int seen = start; Assert.All(leftQuery.Except(rightQuery).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(count + start, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_NotPipelined(left, leftCount, rightQuery, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })] public static void Except_Unordered_Distinct(int leftCount, int rightStart, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount); leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount); foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2))) { seen.Add(i % (DuplicateFactor * 2)); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Unordered_Distinct_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count) { Except_Unordered_Distinct(leftCount, rightStart, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })] public static void Except_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); int seen = expectedCount == 0 ? 0 : leftCount - expectedCount; foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2))) { Assert.Equal(seen++, i); } Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_Distinct(left, leftCount, rightQuery, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })] public static void Except_Unordered_Distinct_NotPipelined(int leftCount, int rightStart, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount); leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount); Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Unordered_Distinct_NotPipelined_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count) { Except_Unordered_Distinct_NotPipelined(leftCount, rightStart, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })] public static void Except_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); int seen = expectedCount == 0 ? 0 : leftCount - expectedCount; Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_Distinct_NotPipelined(left, leftCount, rightQuery, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptSourceMultipleData), new[] { 0, 1, 2, 16 })] public static void Except_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { // The difference between this test and the previous, is that it's not possible to // get non-unique results from ParallelEnumerable.Range()... // Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar, // or via a comparator that considers some elements equal. IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(leftQuery.AsUnordered().Except(rightQuery), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptSourceMultipleData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptSourceMultipleData), new[] { 0, 1, 2, 16 })] public static void Except_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { int seen = start; Assert.All(leftQuery.Except(rightQuery), x => Assert.Equal(seen++, x)); Assert.Equal(start + count, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptSourceMultipleData), new int[] { /* Sources.OuterLoopCount */ })] public static void Except_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count); } [Fact] public static void Except_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void Except_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Except(ParallelEnumerable.Range(0, 1).WithCancellation(t))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Except(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Except(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Except(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default))); } [Fact] public static void Except_ArgumentNullException() { Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Except(null)); Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Except(null, EqualityComparer<int>.Default)); } } }
//******************************************************************************************************************************************************************************************// // Public Domain // // // // Written by Peter O. in 2014. // // // // Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ // // // // If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ // //******************************************************************************************************************************************************************************************// using System; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers { // <summary>Implements arithmetic methods that support // traps.</summary> // <typeparam name='T'>Data type for a numeric value in a particular // radix.</typeparam> internal class TrappableRadixMath<T> : IRadixMath<T> { private readonly IRadixMath<T> math; public TrappableRadixMath(IRadixMath<T> math) { #if DEBUG if (math == null) { throw new ArgumentNullException(nameof(math)); } #endif this.math = math; } public T DivideToIntegerNaturalScale( T thisValue, T divisor, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.DivideToIntegerNaturalScale( thisValue, divisor, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T DivideToIntegerZeroScale( T thisValue, T divisor, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.DivideToIntegerZeroScale(thisValue, divisor, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Abs(T value, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Abs(value, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Negate(T value, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Negate(value, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Remainder( T thisValue, T divisor, EContext ctx, bool roundAfterDivide) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Remainder( thisValue, divisor, tctx, roundAfterDivide); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public IRadixMathHelper<T> GetHelper() { return this.math.GetHelper(); } public T RemainderNear(T thisValue, T divisor, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.RemainderNear(thisValue, divisor, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Pi(EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Pi(tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Power(T thisValue, T pow, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Power(thisValue, pow, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Ln(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Ln(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Exp(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Exp(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T SquareRoot(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.SquareRoot(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T NextMinus(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.NextMinus(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T NextToward(T thisValue, T otherValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.NextToward(thisValue, otherValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T NextPlus(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.NextPlus(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T DivideToExponent( T thisValue, T divisor, EInteger desiredExponent, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.DivideToExponent( thisValue, divisor, desiredExponent, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Divide(T thisValue, T divisor, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Divide(thisValue, divisor, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T MinMagnitude(T a, T b, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.MinMagnitude(a, b, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T MaxMagnitude(T a, T b, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.MaxMagnitude(a, b, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Max(T a, T b, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Max(a, b, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Min(T a, T b, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Min(a, b, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Multiply(T thisValue, T other, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Multiply(thisValue, other, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T MultiplyAndAdd( T thisValue, T multiplicand, T augend, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.MultiplyAndAdd( thisValue, multiplicand, augend, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Plus(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Plus(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T RoundToPrecision(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.RoundToPrecision(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Quantize(T thisValue, T otherValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Quantize(thisValue, otherValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T RoundToExponentExact( T thisValue, EInteger expOther, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.RoundToExponentExact(thisValue, expOther, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T RoundToExponentSimple( T thisValue, EInteger expOther, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.RoundToExponentSimple(thisValue, expOther, ctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T RoundToExponentNoRoundedFlag( T thisValue, EInteger exponent, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.RoundToExponentNoRoundedFlag( thisValue, exponent, ctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Reduce(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Reduce(thisValue, ctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T Add(T thisValue, T other, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.Add(thisValue, other, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T CompareToWithContext( T thisValue, T otherValue, bool treatQuietNansAsSignaling, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.CompareToWithContext( thisValue, otherValue, treatQuietNansAsSignaling, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } // <summary>Compares a T object with this instance.</summary> // <param name='thisValue'></param> // <returns>Zero if the values are equal; a negative number if this // instance is less, or a positive number if this instance is // greater.</returns> public int CompareTo(T thisValue, T otherValue) { return this.math.CompareTo(thisValue, otherValue); } public T RoundAfterConversion(T thisValue, EContext ctx) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.RoundAfterConversion(thisValue, tctx); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T SignalOverflow(EContext ctx, bool neg) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.SignalOverflow(tctx, neg); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } public T AddEx( T thisValue, T other, EContext ctx, bool roundToOperandPrecision) { EContext tctx = (ctx == null) ? ctx : ctx.GetNontrapping(); T result = this.math.AddEx( thisValue, other, ctx, roundToOperandPrecision); return ctx == null ? result : ctx.TriggerTraps(result, tctx); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Orleans.CodeGeneration; using Orleans.Runtime.Configuration; using Orleans.Serialization; namespace Orleans.Runtime { internal class Message : IOutgoingMessage { public static int LargeMessageSizeThreshold { get; set; } public const int LENGTH_HEADER_SIZE = 8; public const int LENGTH_META_HEADER = 4; #region metadata [NonSerialized] private string _targetHistory; [NonSerialized] private DateTime? _queuedTime; [NonSerialized] private int? _retryCount; [NonSerialized] private int? _maxRetries; public string TargetHistory { get { return _targetHistory; } set { _targetHistory = value; } } public DateTime? QueuedTime { get { return _queuedTime; } set { _queuedTime = value; } } public int? RetryCount { get { return _retryCount; } set { _retryCount = value; } } public int? MaxRetries { get { return _maxRetries; } set { _maxRetries = value; } } #endregion /// <summary> /// NOTE: The contents of bodyBytes should never be modified /// </summary> private List<ArraySegment<byte>> bodyBytes; private List<ArraySegment<byte>> headerBytes; private object bodyObject; // Cache values of TargetAddess and SendingAddress as they are used very frequently private ActivationAddress targetAddress; private ActivationAddress sendingAddress; private static readonly Logger logger; static Message() { logger = LogManager.GetLogger("Message", LoggerType.Runtime); } public enum Categories { Ping, System, Application, } public enum Directions { Request, Response, OneWay } public enum ResponseTypes { Success, Error, Rejection } public enum RejectionTypes { Transient, Overloaded, DuplicateRequest, Unrecoverable, GatewayTooBusy, } internal HeadersContainer Headers { get; set; } = new HeadersContainer(); public Categories Category { get { return Headers.Category; } set { Headers.Category = value; } } public Directions Direction { get { return Headers.Direction ?? default(Directions); } set { Headers.Direction = value; } } public bool HasDirection => Headers.Direction.HasValue; public bool IsReadOnly { get { return Headers.IsReadOnly; } set { Headers.IsReadOnly = value; } } public bool IsAlwaysInterleave { get { return Headers.IsAlwaysInterleave; } set { Headers.IsAlwaysInterleave = value; } } public bool IsUnordered { get { return Headers.IsUnordered; } set { Headers.IsUnordered = value; } } public bool IsReturnedFromRemoteCluster { get { return Headers.IsReturnedFromRemoteCluster; } set { Headers.IsReturnedFromRemoteCluster = value; } } public CorrelationId Id { get { return Headers.Id; } set { Headers.Id = value; } } public int ResendCount { get { return Headers.ResendCount; } set { Headers.ResendCount = value; } } public int ForwardCount { get { return Headers.ForwardCount; } set { Headers.ForwardCount = value; } } public SiloAddress TargetSilo { get { return Headers.TargetSilo; } set { Headers.TargetSilo = value; targetAddress = null; } } public GrainId TargetGrain { get { return Headers.TargetGrain; } set { Headers.TargetGrain = value; targetAddress = null; } } public ActivationId TargetActivation { get { return Headers.TargetActivation; } set { Headers.TargetActivation = value; targetAddress = null; } } public ActivationAddress TargetAddress { get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); } set { TargetGrain = value.Grain; TargetActivation = value.Activation; TargetSilo = value.Silo; targetAddress = value; } } public GuidId TargetObserverId { get { return Headers.TargetObserverId; } set { Headers.TargetObserverId = value; targetAddress = null; } } public SiloAddress SendingSilo { get { return Headers.SendingSilo; } set { Headers.SendingSilo = value; sendingAddress = null; } } public GrainId SendingGrain { get { return Headers.SendingGrain; } set { Headers.SendingGrain = value; sendingAddress = null; } } public ActivationId SendingActivation { get { return Headers.SendingActivation; } set { Headers.SendingActivation = value; sendingAddress = null; } } public ActivationAddress SendingAddress { get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); } set { SendingGrain = value.Grain; SendingActivation = value.Activation; SendingSilo = value.Silo; sendingAddress = value; } } public bool IsNewPlacement { get { return Headers.IsNewPlacement; } set { Headers.IsNewPlacement = value; } } public ResponseTypes Result { get { return Headers.Result; } set { Headers.Result = value; } } public DateTime? Expiration { get { return Headers.Expiration; } set { Headers.Expiration = value; } } public bool IsExpired => Expiration.HasValue && DateTime.UtcNow > Expiration.Value; public bool IsExpirableMessage(IMessagingConfiguration config) { if (!config.DropExpiredMessages) return false; GrainId id = TargetGrain; if (id == null) return false; // don't set expiration for one way, system target and system grain messages. return Direction != Directions.OneWay && !id.IsSystemTarget && !Constants.IsSystemGrain(id); } public string DebugContext { get { return GetNotNullString(Headers.DebugContext); } set { Headers.DebugContext = value; } } public List<ActivationAddress> CacheInvalidationHeader { get { return Headers.CacheInvalidationHeader; } set { Headers.CacheInvalidationHeader = value; } } internal void AddToCacheInvalidationHeader(ActivationAddress address) { var list = new List<ActivationAddress>(); if (CacheInvalidationHeader != null) { list.AddRange(CacheInvalidationHeader); } list.Add(address); CacheInvalidationHeader = list; } // Resends are used by the sender, usualy due to en error to send or due to a transient rejection. public bool MayResend(IMessagingConfiguration config) { return ResendCount < config.MaxResendCount; } // Forwardings are used by the receiver, usualy when it cannot process the message and forwars it to another silo to perform the processing // (got here due to outdated cache, silo is shutting down/overloaded, ...). public bool MayForward(GlobalConfiguration config) { return ForwardCount < config.MaxForwardCount; } /// <summary> /// Set by sender's placement logic when NewPlacementRequested is true /// so that receiver knows desired grain type /// </summary> public string NewGrainType { get { return GetNotNullString(Headers.NewGrainType); } set { Headers.NewGrainType = value; } } /// <summary> /// Set by caller's grain reference /// </summary> public string GenericGrainType { get { return GetNotNullString(Headers.GenericGrainType); } set { Headers.GenericGrainType = value; } } public RejectionTypes RejectionType { get { return Headers.RejectionType; } set { Headers.RejectionType = value; } } public string RejectionInfo { get { return GetNotNullString(Headers.RejectionInfo); } set { Headers.RejectionInfo = value; } } public Dictionary<string, object> RequestContextData { get { return Headers.RequestContextData; } set { Headers.RequestContextData = value; } } public object BodyObject { get { if (bodyObject != null) { return bodyObject; } try { bodyObject = DeserializeBody(bodyBytes); } finally { if (bodyBytes != null) { BufferPool.GlobalPool.Release(bodyBytes); bodyBytes = null; } } return bodyObject; } set { bodyObject = value; if (bodyBytes == null) return; BufferPool.GlobalPool.Release(bodyBytes); bodyBytes = null; } } private static object DeserializeBody(List<ArraySegment<byte>> bytes) { if (bytes == null) { return null; } try { var stream = new BinaryTokenStreamReader(bytes); return SerializationManager.Deserialize(stream); } catch (Exception ex) { logger.Error(ErrorCode.Messaging_UnableToDeserializeBody, "Exception deserializing message body", ex); throw; } } public Message() { bodyObject = null; bodyBytes = null; headerBytes = null; } private Message(Categories type, Directions subtype) : this() { Category = type; Direction = subtype; } internal static Message CreateMessage(InvokeMethodRequest request, InvokeMethodOptions options) { var message = new Message( Categories.Application, (options & InvokeMethodOptions.OneWay) != 0 ? Directions.OneWay : Directions.Request) { Id = CorrelationId.GetNext(), IsReadOnly = (options & InvokeMethodOptions.ReadOnly) != 0, IsUnordered = (options & InvokeMethodOptions.Unordered) != 0, BodyObject = request }; if ((options & InvokeMethodOptions.AlwaysInterleave) != 0) message.IsAlwaysInterleave = true; var contextData = RequestContext.Export(); if (contextData != null) { message.RequestContextData = contextData; } return message; } // Initializes body and header but does not take ownership of byte. // Caller must clean up bytes public Message(List<ArraySegment<byte>> header, List<ArraySegment<byte>> body, bool deserializeBody = false) { var input = new BinaryTokenStreamReader(header); Headers = SerializationManager.DeserializeMessageHeaders(input); if (deserializeBody) { bodyObject = DeserializeBody(body); } else { bodyBytes = body; } } public Message CreateResponseMessage() { var response = new Message(this.Category, Directions.Response) { Id = this.Id, IsReadOnly = this.IsReadOnly, IsAlwaysInterleave = this.IsAlwaysInterleave, TargetSilo = this.SendingSilo }; if (SendingGrain != null) { response.TargetGrain = SendingGrain; if (SendingActivation != null) { response.TargetActivation = SendingActivation; } } response.SendingSilo = this.TargetSilo; if (TargetGrain != null) { response.SendingGrain = TargetGrain; if (TargetActivation != null) { response.SendingActivation = TargetActivation; } else if (this.TargetGrain.IsSystemTarget) { response.SendingActivation = ActivationId.GetSystemActivation(TargetGrain, TargetSilo); } } if (DebugContext != null) { response.DebugContext = DebugContext; } response.CacheInvalidationHeader = CacheInvalidationHeader; response.Expiration = Expiration; var contextData = RequestContext.Export(); if (contextData != null) { response.RequestContextData = contextData; } return response; } public Message CreateRejectionResponse(RejectionTypes type, string info, OrleansException ex = null) { var response = CreateResponseMessage(); response.Result = ResponseTypes.Rejection; response.RejectionType = type; response.RejectionInfo = info; response.BodyObject = ex; if (logger.IsVerbose) logger.Verbose("Creating {0} rejection with info '{1}' for {2} at:" + Environment.NewLine + "{3}", type, info, this, Utils.GetStackTrace()); return response; } public Message CreatePromptExceptionResponse(Exception exception) { return new Message(Category, Directions.Response) { Result = ResponseTypes.Error, BodyObject = Response.ExceptionResponse(exception) }; } public void ClearTargetAddress() { targetAddress = null; } private static string GetNotNullString(string s) { return s ?? string.Empty; } /// <summary> /// Tell whether two messages are duplicates of one another /// </summary> /// <param name="other"></param> /// <returns></returns> public bool IsDuplicate(Message other) { return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id); } #region Serialization public List<ArraySegment<byte>> Serialize(out int headerLength) { int dummy; return Serialize_Impl(out headerLength, out dummy); } private List<ArraySegment<byte>> Serialize_Impl(out int headerLengthOut, out int bodyLengthOut) { var headerStream = new BinaryTokenStreamWriter(); SerializationManager.SerializeMessageHeaders(Headers, headerStream); if (bodyBytes == null) { var bodyStream = new BinaryTokenStreamWriter(); SerializationManager.Serialize(bodyObject, bodyStream); // We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message // being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the // serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually // pretty high (an array allocation plus a bunch of copying). bodyBytes = bodyStream.ToBytes() as List<ArraySegment<byte>>; } if (headerBytes != null) { BufferPool.GlobalPool.Release(headerBytes); } headerBytes = headerStream.ToBytes() as List<ArraySegment<byte>>; int headerLength = headerBytes.Sum(ab => ab.Count); int bodyLength = bodyBytes.Sum(ab => ab.Count); var bytes = new List<ArraySegment<byte>>(); bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength))); bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength))); bytes.AddRange(headerBytes); bytes.AddRange(bodyBytes); if (headerLength + bodyLength > LargeMessageSizeThreshold) { logger.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}", headerLength + bodyLength + LENGTH_HEADER_SIZE, headerLength, bodyLength, bytes.Count, this.ToString()); if (logger.IsVerbose3) logger.Verbose3("Sending large message {0}", this.ToLongString()); } headerLengthOut = headerLength; bodyLengthOut = bodyLength; return bytes; } public void ReleaseBodyAndHeaderBuffers() { ReleaseHeadersOnly(); ReleaseBodyOnly(); } public void ReleaseHeadersOnly() { if (headerBytes == null) return; BufferPool.GlobalPool.Release(headerBytes); headerBytes = null; } public void ReleaseBodyOnly() { if (bodyBytes == null) return; BufferPool.GlobalPool.Release(bodyBytes); bodyBytes = null; } #endregion // For testing and logging/tracing public string ToLongString() { var sb = new StringBuilder(); string debugContex = DebugContext; if (!string.IsNullOrEmpty(debugContex)) { // if DebugContex is present, print it first. sb.Append(debugContex).Append("."); } AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader); AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category); AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction); AppendIfExists(HeadersContainer.Headers.EXPIRATION, sb, (m) => m.Expiration); AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount); AppendIfExists(HeadersContainer.Headers.GENERIC_GRAIN_TYPE, sb, (m) => m.GenericGrainType); AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id); AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave); AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement); AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly); AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered); AppendIfExists(HeadersContainer.Headers.IS_RETURNED_FROM_REMOTE_CLUSTER, sb, (m) => m.IsReturnedFromRemoteCluster); AppendIfExists(HeadersContainer.Headers.NEW_GRAIN_TYPE, sb, (m) => m.NewGrainType); AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo); AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType); AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData); AppendIfExists(HeadersContainer.Headers.RESEND_COUNT, sb, (m) => m.ResendCount); AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result); AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation); AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain); AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo); AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation); AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain); AppendIfExists(HeadersContainer.Headers.TARGET_OBSERVER, sb, (m) => m.TargetObserverId); AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo); return sb.ToString(); } private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider) { // used only under log3 level if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE) { sb.AppendFormat("{0}={1};", header, valueProvider(this)); sb.AppendLine(); } } public override string ToString() { string response = String.Empty; if (Direction == Directions.Response) { switch (Result) { case ResponseTypes.Error: response = "Error "; break; case ResponseTypes.Rejection: response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo); break; default: break; } } return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}{9}: {10}", IsReadOnly ? "ReadOnly " : "", //0 IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1 IsNewPlacement ? "NewPlacement " : "", // 2 response, //3 Direction, //4 String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5 String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6 Id, //7 ResendCount > 0 ? "[ResendCount=" + ResendCount + "]" : "", //8 ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //9 DebugContext); //10 } internal void SetTargetPlacement(PlacementResult value) { TargetActivation = value.Activation; TargetSilo = value.Silo; if (value.IsNewPlacement) IsNewPlacement = true; if (!String.IsNullOrEmpty(value.GrainType)) NewGrainType = value.GrainType; } public string GetTargetHistory() { var history = new StringBuilder(); history.Append("<"); if (TargetSilo != null) { history.Append(TargetSilo).Append(":"); } if (TargetGrain != null) { history.Append(TargetGrain).Append(":"); } if (TargetActivation != null) { history.Append(TargetActivation); } history.Append(">"); if (!string.IsNullOrEmpty(TargetHistory)) { history.Append(" ").Append(TargetHistory); } return history.ToString(); } public bool IsSameDestination(IOutgoingMessage other) { var msg = (Message)other; return msg != null && Object.Equals(TargetSilo, msg.TargetSilo); } // For statistical measuring of time spent in queues. private ITimeInterval timeInterval; public void Start() { timeInterval = TimeIntervalFactory.CreateTimeInterval(true); timeInterval.Start(); } public void Stop() { timeInterval.Stop(); } public void Restart() { timeInterval.Restart(); } public TimeSpan Elapsed { get { return timeInterval.Elapsed; } } internal void DropExpiredMessage(MessagingStatisticsGroup.Phase phase) { MessagingStatisticsGroup.OnMessageExpired(phase); if (logger.IsVerbose2) logger.Verbose2("Dropping an expired message: {0}", this); ReleaseBodyAndHeaderBuffers(); } [Serializable] public class HeadersContainer { [Flags] public enum Headers { NONE = 0, ALWAYS_INTERLEAVE = 1 << 0, CACHE_INVALIDATION_HEADER = 1 << 1, CATEGORY = 1 << 2, CORRELATION_ID = 1 << 3, DEBUG_CONTEXT = 1 << 4, DIRECTION = 1 << 5, EXPIRATION = 1 << 6, FORWARD_COUNT = 1 << 7, NEW_GRAIN_TYPE = 1 << 8, GENERIC_GRAIN_TYPE = 1 << 9, RESULT = 1 << 10, REJECTION_INFO = 1 << 11, REJECTION_TYPE = 1 << 12, READ_ONLY = 1 << 13, RESEND_COUNT = 1 << 14, SENDING_ACTIVATION = 1 << 15, SENDING_GRAIN = 1 <<16, SENDING_SILO = 1 << 17, IS_NEW_PLACEMENT = 1 << 18, TARGET_ACTIVATION = 1 << 19, TARGET_GRAIN = 1 << 20, TARGET_SILO = 1 << 21, TARGET_OBSERVER = 1 << 22, IS_UNORDERED = 1 << 23, REQUEST_CONTEXT = 1 << 24, IS_RETURNED_FROM_REMOTE_CLUSTER = 1 << 25, // Do not add over int.MaxValue of these. } private Categories _category; private Directions? _direction; private bool _isReadOnly; private bool _isAlwaysInterleave; private bool _isUnordered; private bool _isReturnedFromRemoteCluster; private CorrelationId _id; private int _resendCount; private int _forwardCount; private SiloAddress _targetSilo; private GrainId _targetGrain; private ActivationId _targetActivation; private GuidId _targetObserverId; private SiloAddress _sendingSilo; private GrainId _sendingGrain; private ActivationId _sendingActivation; private bool _isNewPlacement; private ResponseTypes _result; private DateTime? _expiration; private string _debugContext; private List<ActivationAddress> _cacheInvalidationHeader; private string _newGrainType; private string _genericGrainType; private RejectionTypes _rejectionType; private string _rejectionInfo; private Dictionary<string, object> _requestContextData; public Categories Category { get { return _category; } set { _category = value; } } public Directions? Direction { get { return _direction; } set { _direction = value; } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; } } public bool IsAlwaysInterleave { get { return _isAlwaysInterleave; } set { _isAlwaysInterleave = value; } } public bool IsUnordered { get { return _isUnordered; } set { _isUnordered = value; } } public bool IsReturnedFromRemoteCluster { get { return _isReturnedFromRemoteCluster; } set { _isReturnedFromRemoteCluster = value; } } public CorrelationId Id { get { return _id; } set { _id = value; } } public int ResendCount { get { return _resendCount; } set { _resendCount = value; } } public int ForwardCount { get { return _forwardCount; } set { _forwardCount = value; } } public SiloAddress TargetSilo { get { return _targetSilo; } set { _targetSilo = value; } } public GrainId TargetGrain { get { return _targetGrain; } set { _targetGrain = value; } } public ActivationId TargetActivation { get { return _targetActivation; } set { _targetActivation = value; } } public GuidId TargetObserverId { get { return _targetObserverId; } set { _targetObserverId = value; } } public SiloAddress SendingSilo { get { return _sendingSilo; } set { _sendingSilo = value; } } public GrainId SendingGrain { get { return _sendingGrain; } set { _sendingGrain = value; } } public ActivationId SendingActivation { get { return _sendingActivation; } set { _sendingActivation = value; } } public bool IsNewPlacement { get { return _isNewPlacement; } set { _isNewPlacement = value; } } public ResponseTypes Result { get { return _result; } set { _result = value; } } public DateTime? Expiration { get { return _expiration; } set { _expiration = value; } } public string DebugContext { get { return _debugContext; } set { _debugContext = value; } } public List<ActivationAddress> CacheInvalidationHeader { get { return _cacheInvalidationHeader; } set { _cacheInvalidationHeader = value; } } /// <summary> /// Set by sender's placement logic when NewPlacementRequested is true /// so that receiver knows desired grain type /// </summary> public string NewGrainType { get { return _newGrainType; } set { _newGrainType = value; } } /// <summary> /// Set by caller's grain reference /// </summary> public string GenericGrainType { get { return _genericGrainType; } set { _genericGrainType = value; } } public RejectionTypes RejectionType { get { return _rejectionType; } set { _rejectionType = value; } } public string RejectionInfo { get { return _rejectionInfo; } set { _rejectionInfo = value; } } public Dictionary<string, object> RequestContextData { get { return _requestContextData; } set { _requestContextData = value; } } internal Headers GetHeadersMask() { Headers headers = Headers.NONE; if(Category != default(Categories)) headers = headers | Headers.CATEGORY; headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION; if (IsReadOnly) headers = headers | Headers.READ_ONLY; if (IsAlwaysInterleave) headers = headers | Headers.ALWAYS_INTERLEAVE; if(IsUnordered) headers = headers | Headers.IS_UNORDERED; headers = _id == null ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID; if (_resendCount != default(int)) headers = headers | Headers.RESEND_COUNT; if(_forwardCount != default (int)) headers = headers | Headers.FORWARD_COUNT; headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO; headers = _targetGrain == null ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN; headers = _targetActivation == null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION; headers = _targetObserverId == null ? headers & ~Headers.TARGET_OBSERVER : headers | Headers.TARGET_OBSERVER; headers = _sendingSilo == null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO; headers = _sendingGrain == null ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN; headers = _sendingActivation == null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION; headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT; headers = _result == default(ResponseTypes)? headers & ~Headers.RESULT : headers | Headers.RESULT; headers = _expiration == null ? headers & ~Headers.EXPIRATION : headers | Headers.EXPIRATION; headers = string.IsNullOrEmpty(_debugContext) ? headers & ~Headers.DEBUG_CONTEXT : headers | Headers.DEBUG_CONTEXT; headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER; headers = string.IsNullOrEmpty(_newGrainType) ? headers & ~Headers.NEW_GRAIN_TYPE : headers | Headers.NEW_GRAIN_TYPE; headers = string.IsNullOrEmpty(GenericGrainType) ? headers & ~Headers.GENERIC_GRAIN_TYPE : headers | Headers.GENERIC_GRAIN_TYPE; headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE; headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO; headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT; return headers; } static HeadersContainer() { Register(); } [Orleans.CodeGeneration.CopierMethodAttribute] public static System.Object DeepCopier(System.Object original) { return original; } [Orleans.CodeGeneration.SerializerMethodAttribute] public static void Serializer(System.Object untypedInput, BinaryTokenStreamWriter stream, System.Type expected) { HeadersContainer input = (HeadersContainer)untypedInput; var headers = input.GetHeadersMask(); stream.Write((int)headers); if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE) { var count = input.CacheInvalidationHeader.Count; stream.Write(input.CacheInvalidationHeader.Count); for (int i = 0; i < count; i++) { WriteObj(stream, typeof(ActivationAddress), input.CacheInvalidationHeader[i]); } } if ((headers & Headers.CATEGORY) != Headers.NONE) { stream.Write((byte)input.Category); } if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE) stream.Write(input.DebugContext); if ((headers & Headers.DIRECTION) != Headers.NONE) stream.Write((byte)input.Direction.Value); if ((headers & Headers.EXPIRATION) != Headers.NONE) stream.Write(input.Expiration.Value); if ((headers & Headers.FORWARD_COUNT) != Headers.NONE) stream.Write(input.ForwardCount); if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE) stream.Write(input.GenericGrainType); if ((headers & Headers.CORRELATION_ID) != Headers.NONE) stream.Write(input.Id); if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE) stream.Write(input.IsAlwaysInterleave); if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE) stream.Write(input.IsNewPlacement); if ((headers & Headers.READ_ONLY) != Headers.NONE) stream.Write(input.IsReadOnly); if ((headers & Headers.IS_UNORDERED) != Headers.NONE) stream.Write(input.IsUnordered); if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE) stream.Write(input.NewGrainType); if ((headers & Headers.REJECTION_INFO) != Headers.NONE) stream.Write(input.RejectionInfo); if ((headers & Headers.REJECTION_TYPE) != Headers.NONE) stream.Write((byte)input.RejectionType); if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE) { var requestData = input.RequestContextData; var count = requestData.Count; stream.Write(count); foreach (var d in requestData) { stream.Write(d.Key); SerializationManager.SerializeInner(d.Value, stream, typeof(object)); } } if ((headers & Headers.RESEND_COUNT) != Headers.NONE) stream.Write(input.ResendCount); if ((headers & Headers.RESULT) != Headers.NONE) stream.Write((byte)input.Result); if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE) { stream.Write(input.SendingActivation); } if ((headers & Headers.SENDING_GRAIN) != Headers.NONE) { stream.Write(input.SendingGrain); } if ((headers & Headers.SENDING_SILO) != Headers.NONE) { stream.Write(input.SendingSilo); } if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE) { stream.Write(input.TargetActivation); } if ((headers & Headers.TARGET_GRAIN) != Headers.NONE) { stream.Write(input.TargetGrain); } if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE) { WriteObj(stream, typeof(GuidId), input.TargetObserverId); } if ((headers & Headers.TARGET_SILO) != Headers.NONE) { stream.Write(input.TargetSilo); } } [Orleans.CodeGeneration.DeserializerMethodAttribute] public static System.Object Deserializer(System.Type expected, BinaryTokenStreamReader stream) { var result = new HeadersContainer(); Orleans.Serialization.DeserializationContext.Current.RecordObject(result); var headers = (Headers)stream.ReadInt(); if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE) { var n = stream.ReadInt(); if (n > 0) { var list = result.CacheInvalidationHeader = new List<ActivationAddress>(n); for (int i = 0; i < n; i++) { list.Add((ActivationAddress)ReadObj(typeof(ActivationAddress), stream)); } } } if ((headers & Headers.CATEGORY) != Headers.NONE) result.Category = (Categories)stream.ReadByte(); if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE) result.DebugContext = stream.ReadString(); if ((headers & Headers.DIRECTION) != Headers.NONE) result.Direction = (Message.Directions)stream.ReadByte(); if ((headers & Headers.EXPIRATION) != Headers.NONE) result.Expiration = stream.ReadDateTime(); if ((headers & Headers.FORWARD_COUNT) != Headers.NONE) result.ForwardCount = stream.ReadInt(); if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE) result.GenericGrainType = stream.ReadString(); if ((headers & Headers.CORRELATION_ID) != Headers.NONE) result.Id = (Orleans.Runtime.CorrelationId)ReadObj(typeof(Orleans.Runtime.CorrelationId), stream); if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE) result.IsAlwaysInterleave = ReadBool(stream); if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE) result.IsNewPlacement = ReadBool(stream); if ((headers & Headers.READ_ONLY) != Headers.NONE) result.IsReadOnly = ReadBool(stream); if ((headers & Headers.IS_UNORDERED) != Headers.NONE) result.IsUnordered = ReadBool(stream); if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE) result.NewGrainType = stream.ReadString(); if ((headers & Headers.REJECTION_INFO) != Headers.NONE) result.RejectionInfo = stream.ReadString(); if ((headers & Headers.REJECTION_TYPE) != Headers.NONE) result.RejectionType = (RejectionTypes)stream.ReadByte(); if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE) { var c = stream.ReadInt(); var requestData = new Dictionary<string, object>(c); for (int i = 0; i < c; i++) { requestData[stream.ReadString()] = SerializationManager.DeserializeInner(null, stream); } result.RequestContextData = requestData; } if ((headers & Headers.RESEND_COUNT) != Headers.NONE) result.ResendCount = stream.ReadInt(); if ((headers & Headers.RESULT) != Headers.NONE) result.Result = (Orleans.Runtime.Message.ResponseTypes)stream.ReadByte(); if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE) result.SendingActivation = stream.ReadActivationId(); if ((headers & Headers.SENDING_GRAIN) != Headers.NONE) result.SendingGrain = stream.ReadGrainId(); if ((headers & Headers.SENDING_SILO) != Headers.NONE) result.SendingSilo = stream.ReadSiloAddress(); if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE) result.TargetActivation = stream.ReadActivationId(); if ((headers & Headers.TARGET_GRAIN) != Headers.NONE) result.TargetGrain = stream.ReadGrainId(); if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE) result.TargetObserverId = (Orleans.Runtime.GuidId)ReadObj(typeof(Orleans.Runtime.GuidId), stream); if ((headers & Headers.TARGET_SILO) != Headers.NONE) result.TargetSilo = stream.ReadSiloAddress(); return (HeadersContainer)result; } private static bool ReadBool(BinaryTokenStreamReader stream) { return stream.ReadByte() == (byte) SerializationTokenType.True; } private static void WriteObj(BinaryTokenStreamWriter stream, Type type, object input) { var ser = SerializationManager.GetSerializer(type); ser.Invoke(input, stream, type); } private static object ReadObj(Type t, BinaryTokenStreamReader stream) { var des = SerializationManager.GetDeserializer(t); return des.Invoke(t, stream); } public static void Register() { SerializationManager.Register(typeof(HeadersContainer), DeepCopier, Serializer, Deserializer); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.Models; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public static partial class ResourceProviderOperationsExtensions { /// <summary> /// Backs up an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Backup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse Backup(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).BackupAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Backs up an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Backup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> BackupAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return operations.BackupAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Begin backup operation of an Api Management service.To determine /// whether the operation has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the BeginBackup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse BeginBackup(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).BeginBackupAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin backup operation of an Api Management service.To determine /// whether the operation has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the BeginBackup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> BeginBackupAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return operations.BeginBackupAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Begins creating new or updating existing Api Management service.To /// determine whether the operation has finished processing the /// request, call GetApiServiceLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CreateOrUpdate Api Management /// service operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse BeginCreatingOrUpdating(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).BeginCreatingOrUpdatingAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins creating new or updating existing Api Management service.To /// determine whether the operation has finished processing the /// request, call GetApiServiceLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CreateOrUpdate Api Management /// service operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> BeginCreatingOrUpdatingAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceCreateOrUpdateParameters parameters) { return operations.BeginCreatingOrUpdatingAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Begin to manage (CUD) deployments of an Api Management service.To /// determine whether the operation has finished processing the /// request, call GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageDeployments operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse BeginManagingDeployments(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageDeploymentsParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).BeginManagingDeploymentsAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin to manage (CUD) deployments of an Api Management service.To /// determine whether the operation has finished processing the /// request, call GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageDeployments operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> BeginManagingDeploymentsAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageDeploymentsParameters parameters) { return operations.BeginManagingDeploymentsAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Begin to manage (CUD) VPN configuration of an Api Management /// service.To determine whether the operation has finished processing /// the request, call GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageVirtualNetworks /// operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse BeginManagingVirtualNetworks(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageVirtualNetworksParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).BeginManagingVirtualNetworksAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin to manage (CUD) VPN configuration of an Api Management /// service.To determine whether the operation has finished processing /// the request, call GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageVirtualNetworks /// operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> BeginManagingVirtualNetworksAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageVirtualNetworksParameters parameters) { return operations.BeginManagingVirtualNetworksAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Begin restore from backup operation of an Api Management service.To /// determine whether the operation has finished processing the /// request, call GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Restore Api Management service /// from backup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse BeginRestoring(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).BeginRestoringAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin restore from backup operation of an Api Management service.To /// determine whether the operation has finished processing the /// request, call GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Restore Api Management service /// from backup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> BeginRestoringAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return operations.BeginRestoringAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Begin updating hostname of an Api Management service.To determine /// whether the operation has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the UpdateHostname operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse BeginUpdatingHostname(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceUpdateHostnameParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).BeginUpdatingHostnameAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin updating hostname of an Api Management service.To determine /// whether the operation has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the UpdateHostname operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> BeginUpdatingHostnameAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceUpdateHostnameParameters parameters) { return operations.BeginUpdatingHostnameAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Checks whether the custom host name maps to an Api Management /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CheckCustomHostname operation. /// </param> /// <returns> /// The response of the CheckCustomHostname operation. /// </returns> public static ApiServiceCheckCustomHostnameResponse CheckCustomHostname(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceCheckCustomHostnameParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).CheckCustomHostnameAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether the custom host name maps to an Api Management /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CheckCustomHostname operation. /// </param> /// <returns> /// The response of the CheckCustomHostname operation. /// </returns> public static Task<ApiServiceCheckCustomHostnameResponse> CheckCustomHostnameAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceCheckCustomHostnameParameters parameters) { return operations.CheckCustomHostnameAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Checks availability and correctness of a name for an Api Management /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CheckServiceNameAvailability /// operation. /// </param> /// <returns> /// Response of the CheckServiceNameAvailability operation. /// </returns> public static ApiServiceCheckNameAvailabilityResponse CheckServiceNameAvailability(this IResourceProviderOperations operations, ApiServiceCheckNameAvailabilityParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).CheckServiceNameAvailabilityAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks availability and correctness of a name for an Api Management /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CheckServiceNameAvailability /// operation. /// </param> /// <returns> /// Response of the CheckServiceNameAvailability operation. /// </returns> public static Task<ApiServiceCheckNameAvailabilityResponse> CheckServiceNameAvailabilityAsync(this IResourceProviderOperations operations, ApiServiceCheckNameAvailabilityParameters parameters) { return operations.CheckServiceNameAvailabilityAsync(parameters, CancellationToken.None); } /// <summary> /// Creates new or updates existing Api Management service /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CreateOrUpdate Api Management /// service operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse CreateOrUpdate(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).CreateOrUpdateAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates new or updates existing Api Management service /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the CreateOrUpdate Api Management /// service operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> CreateOrUpdateAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Deletes existing Api Management service /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IResourceProviderOperations operations, string resourceGroupName, string name) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).DeleteAsync(resourceGroupName, name); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes existing Api Management service /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IResourceProviderOperations operations, string resourceGroupName, string name) { return operations.DeleteAsync(resourceGroupName, name, CancellationToken.None); } /// <summary> /// Get an Api Management service resource description. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// The response of the Get Api Management service operation. /// </returns> public static ApiServiceGetResponse Get(this IResourceProviderOperations operations, string resourceGroupName, string name) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).GetAsync(resourceGroupName, name); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get an Api Management service resource description. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// The response of the Get Api Management service operation. /// </returns> public static Task<ApiServiceGetResponse> GetAsync(this IResourceProviderOperations operations, string resourceGroupName, string name) { return operations.GetAsync(resourceGroupName, name, CancellationToken.None); } /// <summary> /// The Get ApiService Operation Status operation returns the status of /// the create or update operation. After calling the operation, you /// can call Get ApiService Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. This /// method differs GetLongRunningOperationStatus in providing Api /// Management service resource description. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse GetApiServiceLongRunningOperationStatus(this IResourceProviderOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).GetApiServiceLongRunningOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get ApiService Operation Status operation returns the status of /// the create or update operation. After calling the operation, you /// can call Get ApiService Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. This /// method differs GetLongRunningOperationStatus in providing Api /// Management service resource description. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> GetApiServiceLongRunningOperationStatusAsync(this IResourceProviderOperations operations, string operationStatusLink) { return operations.GetApiServiceLongRunningOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <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='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetLongRunningOperationStatus(this IResourceProviderOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).GetLongRunningOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <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='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(this IResourceProviderOperations operations, string operationStatusLink) { return operations.GetLongRunningOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Gets SsoToken for an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// The response of the GetSsoToken operation. /// </returns> public static ApiServiceGetSsoTokenResponse GetSsoToken(this IResourceProviderOperations operations, string resourceGroupName, string name) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).GetSsoTokenAsync(resourceGroupName, name); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets SsoToken for an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// The response of the GetSsoToken operation. /// </returns> public static Task<ApiServiceGetSsoTokenResponse> GetSsoTokenAsync(this IResourceProviderOperations operations, string resourceGroupName, string name) { return operations.GetSsoTokenAsync(resourceGroupName, name, CancellationToken.None); } /// <summary> /// List all Api Management services within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group. If resourceGroupName /// value is null the method lists all Api Management services within /// subscription /// </param> /// <returns> /// The response of the List Api Management services operation. /// </returns> public static ApiServiceListResponse List(this IResourceProviderOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List all Api Management services within a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group. If resourceGroupName /// value is null the method lists all Api Management services within /// subscription /// </param> /// <returns> /// The response of the List Api Management services operation. /// </returns> public static Task<ApiServiceListResponse> ListAsync(this IResourceProviderOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Manage (CUD) deployments of an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageDeployments operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse ManageDeployments(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageDeploymentsParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).ManageDeploymentsAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Manage (CUD) deployments of an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageDeployments operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> ManageDeploymentsAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageDeploymentsParameters parameters) { return operations.ManageDeploymentsAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Manage (CUD) VPN configuration of an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageVirtualNetworks /// operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse ManageVirtualNetworks(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageVirtualNetworksParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).ManageVirtualNetworksAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Manage (CUD) VPN configuration of an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the ManageVirtualNetworks /// operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> ManageVirtualNetworksAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceManageVirtualNetworksParameters parameters) { return operations.ManageVirtualNetworksAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Restore an Api Management service from backup. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Restore Api Management service /// from backup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse Restore(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).RestoreAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Restore an Api Management service from backup. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Restore Api Management service /// from backup operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> RestoreAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceBackupRestoreParameters parameters) { return operations.RestoreAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Update hostname of an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the UpdateHostname operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static ApiServiceLongRunningOperationResponse UpdateHostname(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceUpdateHostnameParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).UpdateHostnameAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update hostname of an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the UpdateHostname operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<ApiServiceLongRunningOperationResponse> UpdateHostnameAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceUpdateHostnameParameters parameters) { return operations.UpdateHostnameAsync(resourceGroupName, name, parameters, CancellationToken.None); } /// <summary> /// Upload SSL certificate for an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Upload SSL certificate for an /// Api Management service operation. /// </param> /// <returns> /// The response of the Upload SSL certificate for an Api Management /// service operation. /// </returns> public static ApiServiceUploadCertificateResponse UploadCertificate(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceUploadCertificateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceProviderOperations)s).UploadCertificateAsync(resourceGroupName, name, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Upload SSL certificate for an Api Management service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='name'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Upload SSL certificate for an /// Api Management service operation. /// </param> /// <returns> /// The response of the Upload SSL certificate for an Api Management /// service operation. /// </returns> public static Task<ApiServiceUploadCertificateResponse> UploadCertificateAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceUploadCertificateParameters parameters) { return operations.UploadCertificateAsync(resourceGroupName, name, parameters, CancellationToken.None); } } }
using AjaxControlToolkit.Design; using AjaxControlToolkit.HtmlEditor.Sanitizer; using AjaxControlToolkit.HtmlEditor.ToolbarButtons; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; namespace AjaxControlToolkit.HtmlEditor { [Obsolete("HtmlEditor is obsolete. Use HtmlEditorExtender instead.")] [Designer("AjaxControlToolkit.Design.EditorDesigner, AjaxControlToolkit")] [ToolboxItem(false)] [ValidationPropertyAttribute("Content")] [ClientCssResource(Constants.HtmlEditorEditorName)] [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Enums))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BackColorClear))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BackColorSelector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Bold))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BoxButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BulletedList))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ColorButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ColorSelector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.CommonButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Copy))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Cut))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DecreaseIndent))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignMode))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModeBoxButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModeImageButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModePopupImageButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModeSelectButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.EditorToggleButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FixedBackColor))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FixedColorButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FixedForeColor))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FontName))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FontSize))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ForeColor))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ForeColorClear))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ForeColorSelector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.HorizontalSeparator))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.HtmlMode))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ImageButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.IncreaseIndent))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.InsertHR))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.InsertLink))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Italic))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyCenter))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyFull))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyLeft))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyRight))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Ltr))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.MethodButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ModeButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.OkCancelPopupButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.OrderedList))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Paragraph))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Paste))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.PasteText))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.PasteWord))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.PreviewMode))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Redo))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.RemoveAlignment))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.RemoveLink))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.RemoveStyles))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Rtl))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SelectButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SelectOption))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Selector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.StrikeThrough))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SubScript))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SuperScript))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Underline))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Undo))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.AttachedPopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.AttachedTemplatePopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.BaseColorsPopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.LinkProperties))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.OkCancelAttachedTemplatePopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.Popup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.PopupBGIButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.PopupBoxButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.PopupCommonButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.RegisteredField))] [ClientScriptResource("Sys.Extended.UI.HtmlEditor.Editor", Constants.HtmlEditorEditorName)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.HtmlEditorName + Constants.IconPostfix)] public class Editor : ScriptControlBase { internal Toolbar _bottomToolbar; internal Toolbar _topToolbar; EditPanel _editPanel; Toolbar _changingToolbar; TableCell _editPanelCell; TableRow _topToolbarRow; TableRow _bottomToolbarRow; bool _wasPreRender; public Editor() : base(false, HtmlTextWriterTag.Div) { } /// <summary> /// Determines whether or not to use HTML-sanitization before data transfer to the server /// </summary> [Browsable(true)] [DefaultValue(true)] public bool EnableSanitization { get { return EditPanel.EnableSanitization; } set { EditPanel.EnableSanitization = value; } } [Category("Behavior")] public event ContentChangedEventHandler ContentChanged { add { EditPanel.Events.AddHandler(EditPanel.EventContentChanged, value); } remove { EditPanel.Events.RemoveHandler(EditPanel.EventContentChanged, value); } } protected bool IsDesign { get { try { var isd = false; if(Context == null) isd = true; else if(Site != null) isd = Site.DesignMode; else isd = false; return isd; } catch { return true; } } } [DefaultValue(false)] [Category("Behavior")] public virtual bool SuppressTabInDesignMode { get { return EditPanel.SuppressTabInDesignMode; } set { EditPanel.SuppressTabInDesignMode = value; } } [DefaultValue(false)] public virtual bool TopToolbarPreservePlace { get { return (bool)(ViewState["TopToolbarPreservePlace"] ?? false); } set { ViewState["TopToolbarPreservePlace"] = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool IgnoreTab { get { return (bool)(ViewState["IgnoreTab"] ?? false); } set { ViewState["IgnoreTab"] = value; } } [DefaultValue("")] [Category("Appearance")] [Description("Folder used for toolbar's buttons' images")] public virtual string ButtonImagesFolder { get { return (String)(ViewState["ButtonImagesFolder"] ?? String.Empty); } set { ViewState["ButtonImagesFolder"] = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool NoUnicode { get { return EditPanel.NoUnicode; } set { EditPanel.NoUnicode = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool NoScript { get { return EditPanel.NoScript; } set { EditPanel.NoScript = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool InitialCleanUp { get { return EditPanel.InitialCleanUp; } set { EditPanel.InitialCleanUp = value; } } [DefaultValue("ajax__htmleditor_htmlpanel_default")] [Category("Appearance")] public virtual string HtmlPanelCssClass { get { return EditPanel.HtmlPanelCssClass; } set { EditPanel.HtmlPanelCssClass = value; } } [DefaultValue("")] [Category("Appearance")] public virtual string DocumentCssPath { get { return EditPanel.DocumentCssPath; } set { EditPanel.DocumentCssPath = value; } } [DefaultValue("")] [Category("Appearance")] public virtual string DesignPanelCssPath { get { return EditPanel.DesignPanelCssPath; } set { EditPanel.DesignPanelCssPath = value; } } [DefaultValue(true)] [Category("Behavior")] public virtual bool AutoFocus { get { return EditPanel.AutoFocus; } set { EditPanel.AutoFocus = value; } } [DefaultValue("")] [Category("Appearance")] public virtual string Content { get { return EditPanel.Content; } set { EditPanel.Content = value; } } [DefaultValue(ActiveModeType.Design)] [Category("Behavior")] public virtual ActiveModeType ActiveMode { get { return EditPanel.ActiveMode; } set { EditPanel.ActiveMode = value; } } [DefaultValue("")] [Category("Behavior")] public virtual string OnClientActiveModeChanged { get { return EditPanel.OnClientActiveModeChanged; } set { EditPanel.OnClientActiveModeChanged = value; } } [DefaultValue("")] [Category("Behavior")] public virtual string OnClientBeforeActiveModeChanged { get { return EditPanel.OnClientBeforeActiveModeChanged; } set { EditPanel.OnClientBeforeActiveModeChanged = value; } } [DefaultValue(typeof(Unit), "")] [Category("Appearance")] public override Unit Height { get { return base.Height; } set { base.Height = value; } } [DefaultValue(typeof(Unit), "")] [Category("Appearance")] public override Unit Width { get { return base.Width; } set { base.Width = value; } } [DefaultValue("ajax__htmleditor_editor_default")] [Category("Appearance")] public override string CssClass { get { return base.CssClass; } set { base.CssClass = value; } } internal EditPanel EditPanel { get { if(_editPanel == null) _editPanel = new EditPanelInstance(); return _editPanel; } } protected Toolbar BottomToolbar { get { if(_bottomToolbar == null) _bottomToolbar = new ToolbarInstance(); return _bottomToolbar; } } protected Toolbar TopToolbar { get { if(_topToolbar == null) _topToolbar = new ToolbarInstance(); return _topToolbar; } } protected override Style CreateControlStyle() { var style = new EditorStyle(ViewState); style.CssClass = "ajax__htmleditor_editor_default"; return style; } protected override void AddAttributesToRender(HtmlTextWriter writer) { if(!ControlStyleCreated || IsDesign) { writer.AddAttribute(HtmlTextWriterAttribute.Class, (IsDesign ? "ajax__htmleditor_editor_base " : "") + "ajax__htmleditor_editor_default"); } base.AddAttributesToRender(writer); } protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); descriptor.AddComponentProperty("editPanel", EditPanel.ClientID); if(_changingToolbar != null) descriptor.AddComponentProperty("changingToolbar", _changingToolbar.ClientID); } protected override void OnInit(EventArgs e) { base.OnInit(e); EditPanel.Toolbars.Add(BottomToolbar); _changingToolbar = TopToolbar; EditPanel.Toolbars.Add(TopToolbar); var table = new Table(); TableRow row; TableCell cell; table.CellPadding = 0; table.CellSpacing = 0; table.CssClass = "ajax__htmleditor_editor_container"; table.Style[HtmlTextWriterStyle.BorderCollapse] = "separate"; _topToolbarRow = row = new TableRow(); cell = new TableCell(); cell.Controls.Add(TopToolbar); cell.CssClass = "ajax__htmleditor_editor_toptoolbar"; row.Cells.Add(cell); table.Rows.Add(row); row = new TableRow(); _editPanelCell = cell = new TableCell(); cell.CssClass = "ajax__htmleditor_editor_editpanel"; cell.Controls.Add(EditPanel); row.Cells.Add(cell); table.Rows.Add(row); _bottomToolbarRow = row = new TableRow(); cell = new TableCell(); cell.Controls.Add(BottomToolbar); cell.CssClass = "ajax__htmleditor_editor_bottomtoolbar"; row.Cells.Add(cell); table.Rows.Add(row); Controls.Add(table); } protected virtual void FillBottomToolbar() { BottomToolbar.Buttons.Add(new DesignMode()); BottomToolbar.Buttons.Add(new HtmlMode()); BottomToolbar.Buttons.Add(new PreviewMode()); } protected virtual void FillTopToolbar() { Collection<SelectOption> options; SelectOption option; TopToolbar.Buttons.Add(new ToolbarButtons.Undo()); TopToolbar.Buttons.Add(new ToolbarButtons.Redo()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Bold()); TopToolbar.Buttons.Add(new ToolbarButtons.Italic()); TopToolbar.Buttons.Add(new ToolbarButtons.Underline()); TopToolbar.Buttons.Add(new ToolbarButtons.StrikeThrough()); TopToolbar.Buttons.Add(new ToolbarButtons.SubScript()); TopToolbar.Buttons.Add(new ToolbarButtons.SuperScript()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Ltr()); TopToolbar.Buttons.Add(new ToolbarButtons.Rtl()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var FixedForeColor = new ToolbarButtons.FixedForeColor(); TopToolbar.Buttons.Add(FixedForeColor); var ForeColorSelector = new ToolbarButtons.ForeColorSelector(); ForeColorSelector.FixedColorButtonId = FixedForeColor.ID = "FixedForeColor"; TopToolbar.Buttons.Add(ForeColorSelector); TopToolbar.Buttons.Add(new ToolbarButtons.ForeColorClear()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var FixedBackColor = new ToolbarButtons.FixedBackColor(); TopToolbar.Buttons.Add(FixedBackColor); var BackColorSelector = new ToolbarButtons.BackColorSelector(); BackColorSelector.FixedColorButtonId = FixedBackColor.ID = "FixedBackColor"; TopToolbar.Buttons.Add(BackColorSelector); TopToolbar.Buttons.Add(new ToolbarButtons.BackColorClear()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.RemoveStyles()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var fontName = new FontName(); TopToolbar.Buttons.Add(fontName); options = fontName.Options; option = new SelectOption { Text = "Arial", Value = "arial,helvetica,sans-serif" }; options.Add(option); option = new SelectOption { Text = "Courier New", Value = "courier new,courier,monospace" }; options.Add(option); option = new SelectOption { Text = "Georgia", Value = "georgia,times new roman,times,serif" }; options.Add(option); option = new SelectOption { Text = "Tahoma", Value = "tahoma,arial,helvetica,sans-serif" }; options.Add(option); option = new SelectOption { Text = "Times New Roman", Value = "times new roman,times,serif" }; options.Add(option); option = new SelectOption { Text = "Verdana", Value = "verdana,arial,helvetica,sans-serif" }; options.Add(option); option = new SelectOption { Text = "Impact", Value = "impact" }; options.Add(option); option = new SelectOption { Text = "WingDings", Value = "wingdings" }; options.Add(option); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var fontSize = new ToolbarButtons.FontSize(); TopToolbar.Buttons.Add(fontSize); options = fontSize.Options; option = new SelectOption { Text = "1 ( 8 pt)", Value = "8pt" }; options.Add(option); option = new SelectOption { Text = "2 (10 pt)", Value = "10pt" }; options.Add(option); option = new SelectOption { Text = "3 (12 pt)", Value = "12pt" }; options.Add(option); option = new SelectOption { Text = "4 (14 pt)", Value = "14pt" }; options.Add(option); option = new SelectOption { Text = "5 (18 pt)", Value = "18pt" }; options.Add(option); option = new SelectOption { Text = "6 (24 pt)", Value = "24pt" }; options.Add(option); option = new SelectOption { Text = "7 (36 pt)", Value = "36pt" }; options.Add(option); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Cut()); TopToolbar.Buttons.Add(new ToolbarButtons.Copy()); TopToolbar.Buttons.Add(new ToolbarButtons.Paste()); TopToolbar.Buttons.Add(new ToolbarButtons.PasteText()); TopToolbar.Buttons.Add(new ToolbarButtons.PasteWord()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.DecreaseIndent()); TopToolbar.Buttons.Add(new ToolbarButtons.IncreaseIndent()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Paragraph()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyLeft()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyCenter()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyRight()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyFull()); TopToolbar.Buttons.Add(new ToolbarButtons.RemoveAlignment()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.OrderedList()); TopToolbar.Buttons.Add(new ToolbarButtons.BulletedList()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.InsertHR()); TopToolbar.Buttons.Add(new ToolbarButtons.InsertLink()); TopToolbar.Buttons.Add(new ToolbarButtons.RemoveLink()); } protected override void CreateChildControls() { BottomToolbar.Buttons.Clear(); FillBottomToolbar(); if(BottomToolbar.Buttons.Count == 0) { if(EditPanel.Toolbars.Contains(BottomToolbar)) EditPanel.Toolbars.Remove(BottomToolbar); _bottomToolbarRow.Visible = false; (EditPanel.Parent as TableCell).Style["border-bottom-width"] = "0"; } else { BottomToolbar.AlwaysVisible = true; BottomToolbar.ButtonImagesFolder = ButtonImagesFolder; for(var i = 0; i < BottomToolbar.Buttons.Count; i++) BottomToolbar.Buttons[i].IgnoreTab = IgnoreTab; } TopToolbar.Buttons.Clear(); FillTopToolbar(); if(TopToolbar.Buttons.Count == 0) { if(EditPanel.Toolbars.Contains(TopToolbar)) EditPanel.Toolbars.Remove(TopToolbar); _topToolbarRow.Visible = false; (EditPanel.Parent as TableCell).Style["border-top-width"] = "0"; _changingToolbar = null; } else { TopToolbar.ButtonImagesFolder = ButtonImagesFolder; for(var i = 0; i < TopToolbar.Buttons.Count; i++) { TopToolbar.Buttons[i].IgnoreTab = IgnoreTab; TopToolbar.Buttons[i].PreservePlace = TopToolbarPreservePlace; } } if(!Height.IsEmpty) (Controls[0] as Table).Style.Add(HtmlTextWriterStyle.Height, Height.ToString()); if(!Width.IsEmpty) (Controls[0] as Table).Style.Add(HtmlTextWriterStyle.Width, Width.ToString()); if(EditPanel.IE(Page) && !IsDesign) { _editPanelCell.Style[HtmlTextWriterStyle.Height] = "expression(Sys.Extended.UI.HtmlEditor.Editor.MidleCellHeightForIE(this.parentNode.parentNode.parentNode,this.parentNode))"; } EditPanel.IgnoreTab = IgnoreTab; } protected override void OnPreRender(EventArgs e) { try { base.OnPreRender(e); } catch { } _wasPreRender = true; } protected override void Render(HtmlTextWriter writer) { if(!_wasPreRender) OnPreRender(new EventArgs()); base.Render(writer); } internal void CreateChilds(DesignerWithMapPath designer) { CreateChildControls(); TopToolbar.CreateChilds(designer); BottomToolbar.CreateChilds(designer); EditPanel.SetDesigner(designer); } private sealed class EditorStyle : Style { public EditorStyle(StateBag state) : base(state) { } protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { base.FillStyleAttributes(attributes, urlResolver); attributes.Remove(HtmlTextWriterStyle.Height); attributes.Remove(HtmlTextWriterStyle.Width); } } } }
using ClosedXML.Excel.CalcEngine; using ClosedXML.Excel.Drawings; using ClosedXML.Excel.Misc; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; namespace ClosedXML.Excel { internal class XLWorksheet : XLRangeBase, IXLWorksheet { #region Events public XLReentrantEnumerableSet<XLCallbackAction> RangeShiftedRows; public XLReentrantEnumerableSet<XLCallbackAction> RangeShiftedColumns; #endregion Events #region Fields private readonly Dictionary<Int32, Int32> _columnOutlineCount = new Dictionary<Int32, Int32>(); private readonly Dictionary<Int32, Int32> _rowOutlineCount = new Dictionary<Int32, Int32>(); internal Int32 ZOrder = 1; private String _name; internal Int32 _position; private Double _rowHeight; private Boolean _tabActive; internal Boolean EventTrackingEnabled; #endregion Fields #region Constructor public XLWorksheet(String sheetName, XLWorkbook workbook) : base( new XLRangeAddress( new XLAddress(null, XLHelper.MinRowNumber, XLHelper.MinColumnNumber, false, false), new XLAddress(null, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber, false, false))) { EventTrackingEnabled = workbook.EventTracking == XLEventTracking.Enabled; RangeShiftedRows = new XLReentrantEnumerableSet<XLCallbackAction>(); RangeShiftedColumns = new XLReentrantEnumerableSet<XLCallbackAction>(); RangeAddress.Worksheet = this; RangeAddress.FirstAddress.Worksheet = this; RangeAddress.LastAddress.Worksheet = this; NamedRanges = new XLNamedRanges(workbook); SheetView = new XLSheetView(); Tables = new XLTables(); Hyperlinks = new XLHyperlinks(); DataValidations = new XLDataValidations(); PivotTables = new XLPivotTables(); Protection = new XLSheetProtection(); AutoFilter = new XLAutoFilter(); ConditionalFormats = new XLConditionalFormats(); Workbook = workbook; SetStyle(workbook.Style); Internals = new XLWorksheetInternals(new XLCellsCollection(), new XLColumnsCollection(), new XLRowsCollection(), new XLRanges()); PageSetup = new XLPageSetup((XLPageSetup)workbook.PageOptions, this); Outline = new XLOutline(workbook.Outline); _columnWidth = workbook.ColumnWidth; _rowHeight = workbook.RowHeight; RowHeightChanged = Math.Abs(workbook.RowHeight - XLWorkbook.DefaultRowHeight) > XLHelper.Epsilon; Name = sheetName; SubscribeToShiftedRows((range, rowsShifted) => this.WorksheetRangeShiftedRows(range, rowsShifted)); SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted)); Charts = new XLCharts(); ShowFormulas = workbook.ShowFormulas; ShowGridLines = workbook.ShowGridLines; ShowOutlineSymbols = workbook.ShowOutlineSymbols; ShowRowColHeaders = workbook.ShowRowColHeaders; ShowRuler = workbook.ShowRuler; ShowWhiteSpace = workbook.ShowWhiteSpace; ShowZeros = workbook.ShowZeros; RightToLeft = workbook.RightToLeft; TabColor = XLColor.NoColor; SelectedRanges = new XLRanges(); Author = workbook.Author; } #endregion Constructor //private IXLStyle _style; private const String InvalidNameChars = @":\/?*[]"; public string LegacyDrawingId; public Boolean LegacyDrawingIsNew; private Double _columnWidth; public XLWorksheetInternals Internals { get; private set; } public override IEnumerable<IXLStyle> Styles { get { UpdatingStyle = true; yield return GetStyle(); foreach (XLCell c in Internals.CellsCollection.GetCells()) yield return c.Style; UpdatingStyle = false; } } public override Boolean UpdatingStyle { get; set; } public override IXLStyle InnerStyle { get { return GetStyle(); } set { SetStyle(value); } } internal Boolean RowHeightChanged { get; set; } internal Boolean ColumnWidthChanged { get; set; } public Int32 SheetId { get; set; } internal String RelId { get; set; } public XLDataValidations DataValidations { get; private set; } public IXLCharts Charts { get; private set; } public XLSheetProtection Protection { get; private set; } public XLAutoFilter AutoFilter { get; private set; } #region IXLWorksheet Members public XLWorkbook Workbook { get; private set; } public override IXLStyle Style { get { return GetStyle(); } set { SetStyle(value); foreach (XLCell cell in Internals.CellsCollection.GetCells()) cell.Style = value; } } public Double ColumnWidth { get { return _columnWidth; } set { ColumnWidthChanged = true; _columnWidth = value; } } public Double RowHeight { get { return _rowHeight; } set { RowHeightChanged = true; _rowHeight = value; } } public String Name { get { return _name; } set { if (value.IndexOfAny(InvalidNameChars.ToCharArray()) != -1) throw new ArgumentException("Worksheet names cannot contain any of the following characters: " + InvalidNameChars); if (XLHelper.IsNullOrWhiteSpace(value)) throw new ArgumentException("Worksheet names cannot be empty"); if (value.Length > 31) throw new ArgumentException("Worksheet names cannot be more than 31 characters"); Workbook.WorksheetsInternal.Rename(_name, value); _name = value; } } public Int32 Position { get { return _position; } set { if (value > Workbook.WorksheetsInternal.Count + Workbook.UnsupportedSheets.Count + 1) throw new IndexOutOfRangeException("Index must be equal or less than the number of worksheets + 1."); if (value < _position) { Workbook.WorksheetsInternal .Where<XLWorksheet>(w => w.Position >= value && w.Position < _position) .ForEach(w => w._position += 1); } if (value > _position) { Workbook.WorksheetsInternal .Where<XLWorksheet>(w => w.Position <= value && w.Position > _position) .ForEach(w => (w)._position -= 1); } _position = value; } } public IXLPageSetup PageSetup { get; private set; } public IXLOutline Outline { get; private set; } IXLRow IXLWorksheet.FirstRowUsed() { return FirstRowUsed(); } IXLRow IXLWorksheet.FirstRowUsed(Boolean includeFormats) { return FirstRowUsed(includeFormats); } IXLRow IXLWorksheet.LastRowUsed() { return LastRowUsed(); } IXLRow IXLWorksheet.LastRowUsed(Boolean includeFormats) { return LastRowUsed(includeFormats); } IXLColumn IXLWorksheet.LastColumn() { return LastColumn(); } IXLColumn IXLWorksheet.FirstColumn() { return FirstColumn(); } IXLRow IXLWorksheet.FirstRow() { return FirstRow(); } IXLRow IXLWorksheet.LastRow() { return LastRow(); } IXLColumn IXLWorksheet.FirstColumnUsed() { return FirstColumnUsed(); } IXLColumn IXLWorksheet.FirstColumnUsed(Boolean includeFormats) { return FirstColumnUsed(includeFormats); } IXLColumn IXLWorksheet.LastColumnUsed() { return LastColumnUsed(); } IXLColumn IXLWorksheet.LastColumnUsed(Boolean includeFormats) { return LastColumnUsed(includeFormats); } public IXLColumns Columns() { var retVal = new XLColumns(this); var columnList = new List<Int32>(); if (Internals.CellsCollection.Count > 0) columnList.AddRange(Internals.CellsCollection.ColumnsUsed.Keys); if (Internals.ColumnsCollection.Count > 0) columnList.AddRange(Internals.ColumnsCollection.Keys.Where(c => !columnList.Contains(c))); foreach (int c in columnList) retVal.Add(Column(c)); return retVal; } public IXLColumns Columns(String columns) { var retVal = new XLColumns(null); var columnPairs = columns.Split(','); foreach (string tPair in columnPairs.Select(pair => pair.Trim())) { String firstColumn; String lastColumn; if (tPair.Contains(':') || tPair.Contains('-')) { var columnRange = XLHelper.SplitRange(tPair); firstColumn = columnRange[0]; lastColumn = columnRange[1]; } else { firstColumn = tPair; lastColumn = tPair; } Int32 tmp; if (Int32.TryParse(firstColumn, out tmp)) { foreach (IXLColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn))) retVal.Add((XLColumn)col); } else { foreach (IXLColumn col in Columns(firstColumn, lastColumn)) retVal.Add((XLColumn)col); } } return retVal; } public IXLColumns Columns(String firstColumn, String lastColumn) { return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn), XLHelper.GetColumnNumberFromLetter(lastColumn)); } public IXLColumns Columns(Int32 firstColumn, Int32 lastColumn) { var retVal = new XLColumns(null); for (int co = firstColumn; co <= lastColumn; co++) retVal.Add(Column(co)); return retVal; } public IXLRows Rows() { var retVal = new XLRows(this); var rowList = new List<Int32>(); if (Internals.CellsCollection.Count > 0) rowList.AddRange(Internals.CellsCollection.RowsUsed.Keys); if (Internals.RowsCollection.Count > 0) rowList.AddRange(Internals.RowsCollection.Keys.Where(r => !rowList.Contains(r))); foreach (int r in rowList) retVal.Add(Row(r)); return retVal; } public IXLRows Rows(String rows) { var retVal = new XLRows(null); var rowPairs = rows.Split(','); foreach (string tPair in rowPairs.Select(pair => pair.Trim())) { String firstRow; String lastRow; if (tPair.Contains(':') || tPair.Contains('-')) { var rowRange = XLHelper.SplitRange(tPair); firstRow = rowRange[0]; lastRow = rowRange[1]; } else { firstRow = tPair; lastRow = tPair; } foreach (IXLRow row in Rows(Int32.Parse(firstRow), Int32.Parse(lastRow))) retVal.Add((XLRow)row); } return retVal; } public IXLRows Rows(Int32 firstRow, Int32 lastRow) { var retVal = new XLRows(null); for (int ro = firstRow; ro <= lastRow; ro++) retVal.Add(Row(ro)); return retVal; } IXLRow IXLWorksheet.Row(Int32 row) { return Row(row); } IXLColumn IXLWorksheet.Column(Int32 column) { return Column(column); } IXLColumn IXLWorksheet.Column(String column) { return Column(column); } IXLCell IXLWorksheet.Cell(int row, int column) { return Cell(row, column); } IXLCell IXLWorksheet.Cell(string cellAddressInRange) { return Cell(cellAddressInRange); } IXLCell IXLWorksheet.Cell(int row, string column) { return Cell(row, column); } IXLCell IXLWorksheet.Cell(IXLAddress cellAddressInRange) { return Cell(cellAddressInRange); } IXLRange IXLWorksheet.Range(IXLRangeAddress rangeAddress) { return Range(rangeAddress); } IXLRange IXLWorksheet.Range(string rangeAddress) { return Range(rangeAddress); } IXLRange IXLWorksheet.Range(IXLCell firstCell, IXLCell lastCell) { return Range(firstCell, lastCell); } IXLRange IXLWorksheet.Range(string firstCellAddress, string lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLWorksheet.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLWorksheet.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn) { return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn); } public IXLWorksheet CollapseRows() { Enumerable.Range(1, 8).ForEach(i => CollapseRows(i)); return this; } public IXLWorksheet CollapseColumns() { Enumerable.Range(1, 8).ForEach(i => CollapseColumns(i)); return this; } public IXLWorksheet ExpandRows() { Enumerable.Range(1, 8).ForEach(i => ExpandRows(i)); return this; } public IXLWorksheet ExpandColumns() { Enumerable.Range(1, 8).ForEach(i => ExpandRows(i)); return this; } public IXLWorksheet CollapseRows(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Collapse()); return this; } public IXLWorksheet CollapseColumns(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Collapse()); return this; } public IXLWorksheet ExpandRows(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Expand()); return this; } public IXLWorksheet ExpandColumns(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Expand()); return this; } public void Delete() { Workbook.WorksheetsInternal.Delete(Name); } public IXLNamedRanges NamedRanges { get; private set; } public IXLNamedRange NamedRange(String rangeName) { return NamedRanges.NamedRange(rangeName); } public IXLSheetView SheetView { get; private set; } public IXLTables Tables { get; private set; } public IXLTable Table(Int32 index) { return Tables.Table(index); } public IXLTable Table(String name) { return Tables.Table(name); } public IXLWorksheet CopyTo(String newSheetName) { return CopyTo(Workbook, newSheetName, Workbook.WorksheetsInternal.Count + 1); } public IXLWorksheet CopyTo(String newSheetName, Int32 position) { return CopyTo(Workbook, newSheetName, position); } public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName) { return CopyTo(workbook, newSheetName, workbook.WorksheetsInternal.Count + 1); } public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName, Int32 position) { var targetSheet = (XLWorksheet)workbook.WorksheetsInternal.Add(newSheetName, position); Internals.ColumnsCollection.ForEach(kp => targetSheet.Internals.ColumnsCollection.Add(kp.Key, new XLColumn(kp.Value))); Internals.RowsCollection.ForEach(kp => targetSheet.Internals.RowsCollection.Add(kp.Key, new XLRow(kp.Value))); Internals.CellsCollection.GetCells().ForEach(c => targetSheet.Cell(c.Address).CopyFrom(c, false)); DataValidations.ForEach(dv => targetSheet.DataValidations.Add(new XLDataValidation(dv))); targetSheet.Visibility = Visibility; targetSheet.ColumnWidth = ColumnWidth; targetSheet.ColumnWidthChanged = ColumnWidthChanged; targetSheet.RowHeight = RowHeight; targetSheet.RowHeightChanged = RowHeightChanged; targetSheet.SetStyle(Style); targetSheet.PageSetup = new XLPageSetup((XLPageSetup)PageSetup, targetSheet); (targetSheet.PageSetup.Header as XLHeaderFooter).Changed = true; (targetSheet.PageSetup.Footer as XLHeaderFooter).Changed = true; targetSheet.Outline = new XLOutline(Outline); targetSheet.SheetView = new XLSheetView(SheetView); Internals.MergedRanges.ForEach( kp => targetSheet.Internals.MergedRanges.Add(targetSheet.Range(kp.RangeAddress.ToString()))); foreach (var picture in Pictures) { var newPic = targetSheet.AddPicture(picture.ImageStream, picture.Format, picture.Name) .WithPlacement(picture.Placement) .WithSize(picture.Width, picture.Height); switch (picture.Placement) { case XLPicturePlacement.FreeFloating: newPic.MoveTo(picture.Left, picture.Top); break; case XLPicturePlacement.Move: var newAddress = new XLAddress(targetSheet, picture.TopLeftCellAddress.RowNumber, picture.TopLeftCellAddress.ColumnNumber, false, false); newPic.MoveTo(newAddress, picture.GetOffset(XLMarkerPosition.TopLeft)); break; case XLPicturePlacement.MoveAndSize: var newFromAddress = new XLAddress(targetSheet, picture.TopLeftCellAddress.RowNumber, picture.TopLeftCellAddress.ColumnNumber, false, false); var newToAddress = new XLAddress(targetSheet, picture.BottomRightCellAddress.RowNumber, picture.BottomRightCellAddress.ColumnNumber, false, false); newPic.MoveTo(newFromAddress, picture.GetOffset(XLMarkerPosition.TopLeft), newToAddress, picture.GetOffset(XLMarkerPosition.BottomRight)); break; } } foreach (IXLNamedRange r in NamedRanges) { var ranges = new XLRanges(); r.Ranges.ForEach(ranges.Add); targetSheet.NamedRanges.Add(r.Name, ranges); } foreach (XLTable t in Tables.Cast<XLTable>()) { String tableName = t.Name; var table = targetSheet.Tables.Any(tt => tt.Name == tableName) ? new XLTable(targetSheet.Range(t.RangeAddress.ToString()), true) : new XLTable(targetSheet.Range(t.RangeAddress.ToString()), tableName, true); table.RelId = t.RelId; table.EmphasizeFirstColumn = t.EmphasizeFirstColumn; table.EmphasizeLastColumn = t.EmphasizeLastColumn; table.ShowRowStripes = t.ShowRowStripes; table.ShowColumnStripes = t.ShowColumnStripes; table.ShowAutoFilter = t.ShowAutoFilter; table.Theme = t.Theme; table._showTotalsRow = t.ShowTotalsRow; table._uniqueNames.Clear(); t._uniqueNames.ForEach(n => table._uniqueNames.Add(n)); Int32 fieldCount = t.ColumnCount(); for (Int32 f = 0; f < fieldCount; f++) { var tableField = table.Field(f) as XLTableField; var tField = t.Field(f) as XLTableField; tableField.Index = tField.Index; tableField.Name = tField.Name; tableField.totalsRowLabel = tField.totalsRowLabel; tableField.totalsRowFunction = tField.totalsRowFunction; } } if (AutoFilter.Enabled) targetSheet.Range(AutoFilter.Range.RangeAddress).SetAutoFilter(); return targetSheet; } private String ReplaceRelativeSheet(string newSheetName, String value) { if (XLHelper.IsNullOrWhiteSpace(value)) return value; var newValue = new StringBuilder(); var addresses = value.Split(','); foreach (var address in addresses) { var pair = address.Split('!'); if (pair.Length == 2) { String sheetName = pair[0]; if (sheetName.StartsWith("'")) sheetName = sheetName.Substring(1, sheetName.Length - 2); String name = sheetName.ToLower().Equals(Name.ToLower()) ? newSheetName : sheetName; newValue.Append(String.Format("'{0}'!{1}", name, pair[1])); } else { newValue.Append(address); } } return newValue.ToString(); } public new IXLHyperlinks Hyperlinks { get; private set; } IXLDataValidations IXLWorksheet.DataValidations { get { return DataValidations; } } private XLWorksheetVisibility _visibility; public XLWorksheetVisibility Visibility { get { return _visibility; } set { if (value != XLWorksheetVisibility.Visible) TabSelected = false; _visibility = value; } } public IXLWorksheet Hide() { Visibility = XLWorksheetVisibility.Hidden; return this; } public IXLWorksheet Unhide() { Visibility = XLWorksheetVisibility.Visible; return this; } IXLSheetProtection IXLWorksheet.Protection { get { return Protection; } } public IXLSheetProtection Protect() { return Protection.Protect(); } public IXLSheetProtection Protect(String password) { return Protection.Protect(password); } public IXLSheetProtection Unprotect() { return Protection.Unprotect(); } public IXLSheetProtection Unprotect(String password) { return Protection.Unprotect(password); } public new IXLRange Sort() { return GetRangeForSort().Sort(); } public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks); } public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks); } public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().SortLeftToRight(sortOrder, matchCase, ignoreBlanks); } public Boolean ShowFormulas { get; set; } public Boolean ShowGridLines { get; set; } public Boolean ShowOutlineSymbols { get; set; } public Boolean ShowRowColHeaders { get; set; } public Boolean ShowRuler { get; set; } public Boolean ShowWhiteSpace { get; set; } public Boolean ShowZeros { get; set; } public IXLWorksheet SetShowFormulas() { ShowFormulas = true; return this; } public IXLWorksheet SetShowFormulas(Boolean value) { ShowFormulas = value; return this; } public IXLWorksheet SetShowGridLines() { ShowGridLines = true; return this; } public IXLWorksheet SetShowGridLines(Boolean value) { ShowGridLines = value; return this; } public IXLWorksheet SetShowOutlineSymbols() { ShowOutlineSymbols = true; return this; } public IXLWorksheet SetShowOutlineSymbols(Boolean value) { ShowOutlineSymbols = value; return this; } public IXLWorksheet SetShowRowColHeaders() { ShowRowColHeaders = true; return this; } public IXLWorksheet SetShowRowColHeaders(Boolean value) { ShowRowColHeaders = value; return this; } public IXLWorksheet SetShowRuler() { ShowRuler = true; return this; } public IXLWorksheet SetShowRuler(Boolean value) { ShowRuler = value; return this; } public IXLWorksheet SetShowWhiteSpace() { ShowWhiteSpace = true; return this; } public IXLWorksheet SetShowWhiteSpace(Boolean value) { ShowWhiteSpace = value; return this; } public IXLWorksheet SetShowZeros() { ShowZeros = true; return this; } public IXLWorksheet SetShowZeros(Boolean value) { ShowZeros = value; return this; } public XLColor TabColor { get; set; } public IXLWorksheet SetTabColor(XLColor color) { TabColor = color; return this; } public Boolean TabSelected { get; set; } public Boolean TabActive { get { return _tabActive; } set { if (value && !_tabActive) { foreach (XLWorksheet ws in Worksheet.Workbook.WorksheetsInternal) ws._tabActive = false; } _tabActive = value; } } public IXLWorksheet SetTabSelected() { TabSelected = true; return this; } public IXLWorksheet SetTabSelected(Boolean value) { TabSelected = value; return this; } public IXLWorksheet SetTabActive() { TabActive = true; return this; } public IXLWorksheet SetTabActive(Boolean value) { TabActive = value; return this; } IXLPivotTable IXLWorksheet.PivotTable(String name) { return PivotTable(name); } public IXLPivotTables PivotTables { get; private set; } public Boolean RightToLeft { get; set; } public IXLWorksheet SetRightToLeft() { RightToLeft = true; return this; } public IXLWorksheet SetRightToLeft(Boolean value) { RightToLeft = value; return this; } public new IXLRanges Ranges(String ranges) { var retVal = new XLRanges(); foreach (string rangeAddressStr in ranges.Split(',').Select(s => s.Trim())) { if (XLHelper.IsValidRangeAddress(rangeAddressStr)) retVal.Add(Range(new XLRangeAddress(Worksheet, rangeAddressStr))); else if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0)) NamedRange(rangeAddressStr).Ranges.ForEach(retVal.Add); else { Workbook.NamedRanges.First(n => String.Compare(n.Name, rangeAddressStr, true) == 0 && n.Ranges.First().Worksheet == this) .Ranges.ForEach(retVal.Add); } } return retVal; } IXLBaseAutoFilter IXLWorksheet.AutoFilter { get { return AutoFilter; } } public IXLRows RowsUsed(Boolean includeFormats = false, Func<IXLRow, Boolean> predicate = null) { var rows = new XLRows(Worksheet); var rowsUsed = new HashSet<Int32>(); Internals.RowsCollection.Keys.ForEach(r => rowsUsed.Add(r)); Internals.CellsCollection.RowsUsed.Keys.ForEach(r => rowsUsed.Add(r)); foreach (var rowNum in rowsUsed) { var row = Row(rowNum); if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row))) rows.Add(row); else row.Dispose(); } return rows; } public IXLRows RowsUsed(Func<IXLRow, Boolean> predicate = null) { return RowsUsed(false, predicate); } public IXLColumns ColumnsUsed(Boolean includeFormats = false, Func<IXLColumn, Boolean> predicate = null) { var columns = new XLColumns(Worksheet); var columnsUsed = new HashSet<Int32>(); Internals.ColumnsCollection.Keys.ForEach(r => columnsUsed.Add(r)); Internals.CellsCollection.ColumnsUsed.Keys.ForEach(r => columnsUsed.Add(r)); foreach (var columnNum in columnsUsed) { var column = Column(columnNum); if (!column.IsEmpty(includeFormats) && (predicate == null || predicate(column))) columns.Add(column); else column.Dispose(); } return columns; } public IXLColumns ColumnsUsed(Func<IXLColumn, Boolean> predicate = null) { return ColumnsUsed(false, predicate); } public new void Dispose() { if (AutoFilter != null) AutoFilter.Dispose(); Internals.Dispose(); foreach (var picture in this.Pictures) picture.Dispose(); base.Dispose(); } #endregion IXLWorksheet Members #region Outlines public void IncrementColumnOutline(Int32 level) { if (level <= 0) return; if (!_columnOutlineCount.ContainsKey(level)) _columnOutlineCount.Add(level, 0); _columnOutlineCount[level]++; } public void DecrementColumnOutline(Int32 level) { if (level <= 0) return; if (!_columnOutlineCount.ContainsKey(level)) _columnOutlineCount.Add(level, 0); if (_columnOutlineCount[level] > 0) _columnOutlineCount[level]--; } public Int32 GetMaxColumnOutline() { var list = _columnOutlineCount.Where(kp => kp.Value > 0).ToList(); return list.Count == 0 ? 0 : list.Max(kp => kp.Key); } public void IncrementRowOutline(Int32 level) { if (level <= 0) return; if (!_rowOutlineCount.ContainsKey(level)) _rowOutlineCount.Add(level, 0); _rowOutlineCount[level]++; } public void DecrementRowOutline(Int32 level) { if (level <= 0) return; if (!_rowOutlineCount.ContainsKey(level)) _rowOutlineCount.Add(level, 0); if (_rowOutlineCount[level] > 0) _rowOutlineCount[level]--; } public Int32 GetMaxRowOutline() { return _rowOutlineCount.Count == 0 ? 0 : _rowOutlineCount.Where(kp => kp.Value > 0).Max(kp => kp.Key); } #endregion Outlines public HashSet<Int32> GetStyleIds() { return Internals.CellsCollection.GetStyleIds(GetStyleId()); } public XLRow FirstRowUsed() { return FirstRowUsed(false); } public XLRow FirstRowUsed(Boolean includeFormats) { using (var asRange = AsRange()) using (var rngRow = asRange.FirstRowUsed(includeFormats)) return rngRow != null ? Row(rngRow.RangeAddress.FirstAddress.RowNumber) : null; } public XLRow LastRowUsed() { return LastRowUsed(false); } public XLRow LastRowUsed(Boolean includeFormats) { using (var asRange = AsRange()) using (var rngRow = asRange.LastRowUsed(includeFormats)) return rngRow != null ? Row(rngRow.RangeAddress.LastAddress.RowNumber) : null; } public XLColumn LastColumn() { return Column(XLHelper.MaxColumnNumber); } public XLColumn FirstColumn() { return Column(1); } public XLRow FirstRow() { return Row(1); } public XLRow LastRow() { return Row(XLHelper.MaxRowNumber); } public XLColumn FirstColumnUsed() { return FirstColumnUsed(false); } public XLColumn FirstColumnUsed(Boolean includeFormats) { using (var asRange = AsRange()) using (var rngColumn = asRange.FirstColumnUsed(includeFormats)) return rngColumn != null ? Column(rngColumn.RangeAddress.FirstAddress.ColumnNumber) : null; } public XLColumn LastColumnUsed() { return LastColumnUsed(false); } public XLColumn LastColumnUsed(Boolean includeFormats) { using (var asRange = AsRange()) using (var rngColumn = asRange.LastColumnUsed(includeFormats)) return rngColumn != null ? Column(rngColumn.RangeAddress.LastAddress.ColumnNumber) : null; } public XLRow Row(Int32 row) { return Row(row, true); } public XLColumn Column(Int32 column) { if (column <= 0 || column > XLHelper.MaxColumnNumber) throw new IndexOutOfRangeException(String.Format("Column number must be between 1 and {0}", XLHelper.MaxColumnNumber)); Int32 thisStyleId = GetStyleId(); if (!Internals.ColumnsCollection.ContainsKey(column)) { // This is a new row so we're going to reference all // cells in this row to preserve their formatting Internals.RowsCollection.Keys.ForEach(r => Cell(r, column)); Internals.ColumnsCollection.Add(column, new XLColumn(column, new XLColumnParameters(this, thisStyleId, false))); } return new XLColumn(column, new XLColumnParameters(this, thisStyleId, true)); } public IXLColumn Column(String column) { return Column(XLHelper.GetColumnNumberFromLetter(column)); } public override XLRange AsRange() { return Range(1, 1, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber); } public void Clear() { Internals.CellsCollection.Clear(); Internals.ColumnsCollection.Clear(); Internals.MergedRanges.Clear(); Internals.RowsCollection.Clear(); } private void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted) { var newMerge = new XLRanges(); foreach (IXLRange rngMerged in Internals.MergedRanges) { if (range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.FirstAddress.ColumnNumber && rngMerged.RangeAddress.FirstAddress.RowNumber >= range.RangeAddress.FirstAddress.RowNumber && rngMerged.RangeAddress.LastAddress.RowNumber <= range.RangeAddress.LastAddress.RowNumber) { var newRng = Range( rngMerged.RangeAddress.FirstAddress.RowNumber, rngMerged.RangeAddress.FirstAddress.ColumnNumber + columnsShifted, rngMerged.RangeAddress.LastAddress.RowNumber, rngMerged.RangeAddress.LastAddress.ColumnNumber + columnsShifted); newMerge.Add(newRng); } else if ( !(range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.FirstAddress.ColumnNumber && range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.LastAddress.RowNumber)) newMerge.Add(rngMerged); } Internals.MergedRanges = newMerge; Workbook.Worksheets.ForEach(ws => MoveNamedRangesColumns(range, columnsShifted, ws.NamedRanges)); MoveNamedRangesColumns(range, columnsShifted, Workbook.NamedRanges); ShiftConditionalFormattingColumns(range, columnsShifted); ShiftPageBreaksColumns(range, columnsShifted); } private void ShiftPageBreaksColumns(XLRange range, int columnsShifted) { for (var i = 0; i < PageSetup.ColumnBreaks.Count; i++) { int br = PageSetup.ColumnBreaks[i]; if (range.RangeAddress.FirstAddress.ColumnNumber <= br) { PageSetup.ColumnBreaks[i] = br + columnsShifted; } } } private void ShiftConditionalFormattingColumns(XLRange range, int columnsShifted) { Int32 firstColumn = range.RangeAddress.FirstAddress.ColumnNumber; if (firstColumn == 1) return; Int32 lastColumn = range.RangeAddress.FirstAddress.ColumnNumber + columnsShifted - 1; Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber; Int32 lastRow = range.RangeAddress.LastAddress.RowNumber; var insertedRange = Range(firstRow, firstColumn, lastRow, lastColumn); var fc = insertedRange.FirstColumn(); var model = fc.ColumnLeft(); Int32 modelFirstRow = model.RangeAddress.FirstAddress.RowNumber; if (ConditionalFormats.Any(cf => cf.Range.Intersects(model))) { for (Int32 ro = firstRow; ro <= lastRow; ro++) { var cellModel = model.Cell(ro - modelFirstRow + 1); foreach (var cf in ConditionalFormats.Where(cf => cf.Range.Intersects(cellModel.AsRange())).ToList()) { Range(ro, firstColumn, ro, lastColumn).AddConditionalFormat(cf); } } } insertedRange.Dispose(); model.Dispose(); fc.Dispose(); } private void WorksheetRangeShiftedRows(XLRange range, int rowsShifted) { var newMerge = new XLRanges(); foreach (IXLRange rngMerged in Internals.MergedRanges) { if (range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.FirstAddress.RowNumber && rngMerged.RangeAddress.FirstAddress.ColumnNumber >= range.RangeAddress.FirstAddress.ColumnNumber && rngMerged.RangeAddress.LastAddress.ColumnNumber <= range.RangeAddress.LastAddress.ColumnNumber) { var newRng = Range( rngMerged.RangeAddress.FirstAddress.RowNumber + rowsShifted, rngMerged.RangeAddress.FirstAddress.ColumnNumber, rngMerged.RangeAddress.LastAddress.RowNumber + rowsShifted, rngMerged.RangeAddress.LastAddress.ColumnNumber); newMerge.Add(newRng); } else if (!(range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.FirstAddress.RowNumber && range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.LastAddress.ColumnNumber)) newMerge.Add(rngMerged); } Internals.MergedRanges = newMerge; Workbook.Worksheets.ForEach(ws => MoveNamedRangesRows(range, rowsShifted, ws.NamedRanges)); MoveNamedRangesRows(range, rowsShifted, Workbook.NamedRanges); ShiftConditionalFormattingRows(range, rowsShifted); ShiftPageBreaksRows(range, rowsShifted); } private void ShiftPageBreaksRows(XLRange range, int rowsShifted) { for (var i = 0; i < PageSetup.RowBreaks.Count; i++) { int br = PageSetup.RowBreaks[i]; if (range.RangeAddress.FirstAddress.RowNumber <= br) { PageSetup.RowBreaks[i] = br + rowsShifted; } } } private void ShiftConditionalFormattingRows(XLRange range, int rowsShifted) { Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber; if (firstRow == 1) return; SuspendEvents(); var rangeUsed = range.Worksheet.RangeUsed(true); IXLRangeAddress usedAddress; if (rangeUsed == null) usedAddress = range.RangeAddress; else usedAddress = rangeUsed.RangeAddress; ResumeEvents(); if (firstRow < usedAddress.FirstAddress.RowNumber) firstRow = usedAddress.FirstAddress.RowNumber; Int32 lastRow = range.RangeAddress.FirstAddress.RowNumber + rowsShifted - 1; if (lastRow > usedAddress.LastAddress.RowNumber) lastRow = usedAddress.LastAddress.RowNumber; Int32 firstColumn = range.RangeAddress.FirstAddress.ColumnNumber; if (firstColumn < usedAddress.FirstAddress.ColumnNumber) firstColumn = usedAddress.FirstAddress.ColumnNumber; Int32 lastColumn = range.RangeAddress.LastAddress.ColumnNumber; if (lastColumn > usedAddress.LastAddress.ColumnNumber) lastColumn = usedAddress.LastAddress.ColumnNumber; var insertedRange = Range(firstRow, firstColumn, lastRow, lastColumn); var fr = insertedRange.FirstRow(); var model = fr.RowAbove(); Int32 modelFirstColumn = model.RangeAddress.FirstAddress.ColumnNumber; if (ConditionalFormats.Any(cf => cf.Range.Intersects(model))) { for (Int32 co = firstColumn; co <= lastColumn; co++) { var cellModel = model.Cell(co - modelFirstColumn + 1); foreach (var cf in ConditionalFormats.Where(cf => cf.Range.Intersects(cellModel.AsRange())).ToList()) { Range(firstRow, co, lastRow, co).AddConditionalFormat(cf); } } } insertedRange.Dispose(); model.Dispose(); fr.Dispose(); } internal void BreakConditionalFormatsIntoCells(List<IXLAddress> addresses) { var newConditionalFormats = new XLConditionalFormats(); SuspendEvents(); foreach (var conditionalFormat in ConditionalFormats) { foreach (XLCell cell in conditionalFormat.Range.Cells(c => !addresses.Contains(c.Address))) { var row = cell.Address.RowNumber; var column = cell.Address.ColumnLetter; var newConditionalFormat = new XLConditionalFormat(cell.AsRange(), true); newConditionalFormat.CopyFrom(conditionalFormat); newConditionalFormat.Values.Values.Where(f => f.IsFormula) .ForEach(f => f._value = XLHelper.ReplaceRelative(f.Value, row, column)); newConditionalFormats.Add(newConditionalFormat); } conditionalFormat.Range.Dispose(); } ResumeEvents(); ConditionalFormats = newConditionalFormats; } private void MoveNamedRangesRows(XLRange range, int rowsShifted, IXLNamedRanges namedRanges) { foreach (XLNamedRange nr in namedRanges) { var newRangeList = nr.RangeList.Select(r => XLCell.ShiftFormulaRows(r, this, range, rowsShifted)).Where( newReference => newReference.Length > 0).ToList(); nr.RangeList = newRangeList; } } private void MoveNamedRangesColumns(XLRange range, int columnsShifted, IXLNamedRanges namedRanges) { foreach (XLNamedRange nr in namedRanges) { var newRangeList = nr.RangeList.Select(r => XLCell.ShiftFormulaColumns(r, this, range, columnsShifted)).Where( newReference => newReference.Length > 0).ToList(); nr.RangeList = newRangeList; } } public void NotifyRangeShiftedRows(XLRange range, Int32 rowsShifted) { if (RangeShiftedRows != null) { foreach (var item in RangeShiftedRows) { item.Action(range, rowsShifted); } } } public void NotifyRangeShiftedColumns(XLRange range, Int32 columnsShifted) { if (RangeShiftedColumns != null) { foreach (var item in RangeShiftedColumns) { item.Action(range, columnsShifted); } } } public XLRow Row(Int32 row, Boolean pingCells) { if (row <= 0 || row > XLHelper.MaxRowNumber) throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}", XLHelper.MaxRowNumber)); Int32 styleId; XLRow rowToUse; if (Internals.RowsCollection.TryGetValue(row, out rowToUse)) styleId = rowToUse.GetStyleId(); else { if (pingCells) { // This is a new row so we're going to reference all // cells in columns of this row to preserve their formatting var usedColumns = from c in Internals.ColumnsCollection join dc in Internals.CellsCollection.ColumnsUsed.Keys on c.Key equals dc where !Internals.CellsCollection.Contains(row, dc) select dc; usedColumns.ForEach(c => Cell(row, c)); } styleId = GetStyleId(); Internals.RowsCollection.Add(row, new XLRow(row, new XLRowParameters(this, styleId, false))); } return new XLRow(row, new XLRowParameters(this, styleId)); } private IXLRange GetRangeForSort() { var range = RangeUsed(); SortColumns.ForEach(e => range.SortColumns.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase)); SortRows.ForEach(e => range.SortRows.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase)); return range; } public XLPivotTable PivotTable(String name) { return (XLPivotTable)PivotTables.PivotTable(name); } public new IXLCells Cells() { return Cells(true, true); } public new IXLCells Cells(Boolean usedCellsOnly) { if (usedCellsOnly) return Cells(true, true); else return Range(FirstCellUsed(), LastCellUsed()).Cells(false, true); } public new XLCell Cell(String cellAddressInRange) { if (XLHelper.IsValidA1Address(cellAddressInRange)) return Cell(XLAddress.Create(this, cellAddressInRange)); if (NamedRanges.Any(n => String.Compare(n.Name, cellAddressInRange, true) == 0)) return (XLCell)NamedRange(cellAddressInRange).Ranges.First().FirstCell(); var namedRanges = Workbook.NamedRanges.FirstOrDefault(n => String.Compare(n.Name, cellAddressInRange, true) == 0 && n.Ranges.Count == 1); if (namedRanges == null || !namedRanges.Ranges.Any()) return null; return (XLCell)namedRanges.Ranges.First().FirstCell(); } internal XLCell CellFast(String cellAddressInRange) { return Cell(XLAddress.Create(this, cellAddressInRange)); } public override XLRange Range(String rangeAddressStr) { if (XLHelper.IsValidRangeAddress(rangeAddressStr)) return Range(new XLRangeAddress(Worksheet, rangeAddressStr)); if (rangeAddressStr.Contains("[")) return Table(rangeAddressStr.Substring(0, rangeAddressStr.IndexOf("["))) as XLRange; if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0)) return (XLRange)NamedRange(rangeAddressStr).Ranges.First(); var namedRanges = Workbook.NamedRanges.FirstOrDefault(n => String.Compare(n.Name, rangeAddressStr, true) == 0 && n.Ranges.Count == 1 ); if (namedRanges == null || !namedRanges.Ranges.Any()) return null; return (XLRange)namedRanges.Ranges.First(); } public IXLRanges MergedRanges { get { return Internals.MergedRanges; } } public IXLConditionalFormats ConditionalFormats { get; private set; } private Boolean _eventTracking; public void SuspendEvents() { _eventTracking = EventTrackingEnabled; EventTrackingEnabled = false; } public void ResumeEvents() { EventTrackingEnabled = _eventTracking; } public IXLRanges SelectedRanges { get; internal set; } public IXLCell ActiveCell { get; set; } private XLCalcEngine _calcEngine; private XLCalcEngine CalcEngine { get { return _calcEngine ?? (_calcEngine = new XLCalcEngine(this)); } } public Object Evaluate(String expression) { return CalcEngine.Evaluate(expression); } public String Author { get; set; } public IList<Drawings.IXLPicture> Pictures { get; private set; } = new List<Drawings.IXLPicture>(); private String GetNextPictureName() { var pictureNumber = this.Pictures.Count; while (Pictures.Any(p => p.Name == $"Picture {pictureNumber}")) { pictureNumber++; } return $"Picture {pictureNumber}"; } public IXLPicture AddPicture(Stream stream) { var picture = new XLPicture(this, stream); Pictures.Add(picture); picture.Name = GetNextPictureName(); return picture; } public IXLPicture AddPicture(Stream stream, string name) { var picture = AddPicture(stream); picture.Name = name; return picture; } public Drawings.IXLPicture AddPicture(Stream stream, XLPictureFormat format) { var picture = new XLPicture(this, stream, format); Pictures.Add(picture); picture.Name = GetNextPictureName(); return picture; } public IXLPicture AddPicture(Stream stream, XLPictureFormat format, string name) { var picture = AddPicture(stream, format); picture.Name = name; return picture; } public IXLPicture AddPicture(Bitmap bitmap) { var picture = new XLPicture(this, bitmap); Pictures.Add(picture); picture.Name = GetNextPictureName(); return picture; } public IXLPicture AddPicture(Bitmap bitmap, string name) { var picture = AddPicture(bitmap); this.Name = name; return picture; } public IXLPicture AddPicture(string imageFile) { using (var bitmap = Image.FromFile(imageFile) as Bitmap) { var picture = new XLPicture(this, bitmap); Pictures.Add(picture); picture.Name = GetNextPictureName(); return picture; } } public IXLPicture AddPicture(string imageFile, string name) { var picture = AddPicture(imageFile); picture.Name = name; return picture; } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Razor.TagHelpers; namespace OrchardCore.ResourceManagement.TagHelpers { [HtmlTargetElement("script", Attributes = NameAttributeName)] [HtmlTargetElement("script", Attributes = SrcAttributeName)] [HtmlTargetElement("script", Attributes = AtAttributeName)] public class ScriptTagHelper : TagHelper { private const string NameAttributeName = "asp-name"; private const string SrcAttributeName = "asp-src"; private const string AtAttributeName = "at"; private const string AppendVersionAttributeName = "asp-append-version"; [HtmlAttributeName(NameAttributeName)] public string Name { get; set; } [HtmlAttributeName(SrcAttributeName)] public string Src { get; set; } [HtmlAttributeName(AppendVersionAttributeName)] public bool? AppendVersion { get; set; } public string CdnSrc { get; set; } public string DebugSrc { get; set; } public string DebugCdnSrc { get; set; } public bool? UseCdn { get; set; } public string Condition { get; set; } public string Culture { get; set; } public bool? Debug { get; set; } public string DependsOn { get; set; } public string Version { get; set; } [HtmlAttributeName(AtAttributeName)] public ResourceLocation At { get; set; } private readonly IResourceManager _resourceManager; public ScriptTagHelper(IResourceManager resourceManager) { _resourceManager = resourceManager; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.SuppressOutput(); if (String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Src)) { RequireSettings setting; if (String.IsNullOrEmpty(DependsOn)) { // Include custom script url setting = _resourceManager.RegisterUrl("script", Src, DebugSrc); } else { // Anonymous declaration with dependencies, then display // Using the source as the name to prevent duplicate references to the same file var name = Src.ToLowerInvariant(); var definition = _resourceManager.InlineManifest.DefineScript(name); definition.SetUrl(Src, DebugSrc); if (!String.IsNullOrEmpty(Version)) { definition.SetVersion(Version); } if (!String.IsNullOrEmpty(CdnSrc)) { definition.SetCdn(CdnSrc, DebugCdnSrc); } if (!String.IsNullOrEmpty(Culture)) { definition.SetCultures(Culture.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); } if (!String.IsNullOrEmpty(DependsOn)) { definition.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); } if (AppendVersion.HasValue) { definition.ShouldAppendVersion(AppendVersion); } if (!String.IsNullOrEmpty(Version)) { definition.SetVersion(Version); } setting = _resourceManager.RegisterResource("script", name); } if (At != ResourceLocation.Unspecified) { setting.AtLocation(At); } if (!String.IsNullOrEmpty(Condition)) { setting.UseCondition(Condition); } if (Debug != null) { setting.UseDebugMode(Debug.Value); } if (!String.IsNullOrEmpty(Culture)) { setting.UseCulture(Culture); } if (AppendVersion.HasValue) { setting.ShouldAppendVersion(AppendVersion); } foreach (var attribute in output.Attributes) { setting.SetAttribute(attribute.Name, attribute.Value.ToString()); } if (At == ResourceLocation.Unspecified) { _resourceManager.RenderLocalScript(setting, output.Content); } } else if (!String.IsNullOrEmpty(Name) && String.IsNullOrEmpty(Src)) { // Resource required var setting = _resourceManager.RegisterResource("script", Name); if (At != ResourceLocation.Unspecified) { setting.AtLocation(At); } if (UseCdn != null) { setting.UseCdn(UseCdn.Value); } if (!String.IsNullOrEmpty(Condition)) { setting.UseCondition(Condition); } if (Debug != null) { setting.UseDebugMode(Debug.Value); } if (!String.IsNullOrEmpty(Culture)) { setting.UseCulture(Culture); } if (AppendVersion.HasValue) { setting.ShouldAppendVersion(AppendVersion); } if (!String.IsNullOrEmpty(Version)) { setting.UseVersion(Version); } // This allows additions to the pre registered scripts dependencies. if (!String.IsNullOrEmpty(DependsOn)) { setting.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); } if (At == ResourceLocation.Unspecified) { _resourceManager.RenderLocalScript(setting, output.Content); } else { var childContent = await output.GetChildContentAsync(); if (!childContent.IsEmptyOrWhiteSpace) { // Inline content definition _resourceManager.InlineManifest.DefineScript(Name) .SetInnerContent(childContent.GetContent()); } } } else if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Src)) { // Inline declaration var definition = _resourceManager.InlineManifest.DefineScript(Name); definition.SetUrl(Src, DebugSrc); if (!String.IsNullOrEmpty(Version)) { definition.SetVersion(Version); } if (!String.IsNullOrEmpty(CdnSrc)) { definition.SetCdn(CdnSrc, DebugCdnSrc); } if (!String.IsNullOrEmpty(Culture)) { definition.SetCultures(Culture.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); } if (!String.IsNullOrEmpty(DependsOn)) { definition.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)); } if (AppendVersion.HasValue) { definition.ShouldAppendVersion(AppendVersion); } if (!String.IsNullOrEmpty(Version)) { definition.SetVersion(Version); } // If At is specified then we also render it if (At != ResourceLocation.Unspecified) { var setting = _resourceManager.RegisterResource("script", Name); setting.AtLocation(At); if (UseCdn != null) { setting.UseCdn(UseCdn.Value); } if (!String.IsNullOrEmpty(Condition)) { setting.UseCondition(Condition); } if (Debug != null) { setting.UseDebugMode(Debug.Value); } if (!String.IsNullOrEmpty(Culture)) { setting.UseCulture(Culture); } foreach (var attribute in output.Attributes) { setting.SetAttribute(attribute.Name, attribute.Value.ToString()); } } } else if (String.IsNullOrEmpty(Name) && String.IsNullOrEmpty(Src)) { // Custom script content var childContent = await output.GetChildContentAsync(); var builder = new TagBuilder("script"); builder.InnerHtml.AppendHtml(childContent); builder.TagRenderMode = TagRenderMode.Normal; foreach (var attribute in output.Attributes) { builder.Attributes.Add(attribute.Name, attribute.Value.ToString()); } // If no type was specified, define a default one if (!builder.Attributes.ContainsKey("type")) { builder.Attributes.Add("type", "text/javascript"); } if (At == ResourceLocation.Head) { _resourceManager.RegisterHeadScript(builder); } else { _resourceManager.RegisterFootScript(builder); } } } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Xml; using System.Text; using System.Collections; using OpenSource.UPnP; namespace UPnPStackBuilder { /// <summary> /// Summary description for DeviceObjectGenerator. /// </summary> public class DeviceObjectGenerator { public static void InjectBytes(out string byteString, byte[] inVal, string newLine, bool withTypeCast) { CodeProcessor cs = new CodeProcessor(new StringBuilder(),false); cs.NewLine = newLine; cs.Append("{"+cs.NewLine); bool _first = true; int _ctr=0; foreach(byte b in inVal) { if (_first==false) { cs.Append(","); } else { _first = false; } string hx = b.ToString("X"); if (withTypeCast) { cs.Append("(char)"); } cs.Append("0x"); if (hx.Length==1){cs.Append("0");} cs.Append(hx); ++_ctr; if (_ctr%(withTypeCast?10:20)==0) { cs.Append(cs.NewLine); } } cs.Append(cs.NewLine+"}"); byteString = cs.ToString(); } public static void InjectCompressedString(out string CompressedString, out int CompressedStringLength, string InVal, string newLine) { UTF8Encoding U = new UTF8Encoding(); byte[] stringX = OpenSource.Utilities.StringCompressor.CompressString(InVal); CompressedStringLength = stringX.Length; InjectBytes(out CompressedString,stringX,newLine,true); } protected static void LabelDevices(Hashtable t, UPnPDevice d) { string deviceName = d.DeviceURN_Prefix; string useName; int counter = 2; deviceName = deviceName.Substring(0,deviceName.Length-1); deviceName = deviceName.Substring(1+deviceName.LastIndexOf(":")); useName = deviceName; while(t.ContainsKey(useName)) { useName = deviceName + counter.ToString(); ++counter; } t[useName] = d; d.User2 = useName; foreach(UPnPDevice ed in d.EmbeddedDevices) { LabelDevices(t,ed); } } protected static void GenerateStateVariableLookupTable_Service(UPnPService s, Hashtable t) { Hashtable lookupTable = new Hashtable(); t[s] = lookupTable; int i=0; foreach(UPnPStateVariable v in s.GetStateVariables()) { StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); UPnPDebugObject dobj = new UPnPDebugObject(v); dobj.InvokeNonStaticMethod("GetStateVariableXML",new object[1]{X}); lookupTable[v] = new object[3]{i,sb.Length,sb.ToString()}; i+=sb.Length; } } public static void GenerateStateVariableLookupTable(UPnPDevice d, Hashtable t) { foreach(UPnPDevice ed in d.EmbeddedDevices) { GenerateStateVariableLookupTable(ed,t); } foreach(UPnPService s in d.Services) { GenerateStateVariableLookupTable_Service(s,t); } } protected static void GenerateActionLookupTable_Service(UPnPService s, Hashtable t) { Hashtable lookupTable = new Hashtable(); t[s] = lookupTable; int i=0; foreach(UPnPAction a in s.Actions) { StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); UPnPDebugObject dobj = new UPnPDebugObject(a); dobj.InvokeNonStaticMethod("GetXML",new object[1]{X}); lookupTable[a] = new object[2]{i,sb.Length}; i+=sb.Length; } } public static void GenerateActionLookupTable(UPnPDevice d, Hashtable t) { foreach(UPnPDevice ed in d.EmbeddedDevices) { GenerateActionLookupTable(ed,t); } foreach(UPnPService s in d.Services) { GenerateActionLookupTable_Service(s,t); } } protected static void PopulateStateVariableStructs(CodeProcessor cs, UPnPDevice d, Hashtable VarTable) { foreach(UPnPDevice ed in d.EmbeddedDevices) { PopulateStateVariableStructs(cs,ed,VarTable); } foreach(UPnPService s in d.Services) { cs.Append("struct UPnP_StateVariableTable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+" UPnP_StateVariableTable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_Impl = "+cs.NewLine); cs.Append("{"+cs.NewLine); string stringX; int stringXLen; StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); foreach(UPnPStateVariable v in s.GetStateVariables()) { UPnPDebugObject dobj = new UPnPDebugObject(v); dobj.InvokeNonStaticMethod("GetStateVariableXML",new object[1]{X}); } X.Flush(); InjectCompressedString(out stringX,out stringXLen,sb.ToString(),cs.NewLine); cs.Append(" "+stringX+","+cs.NewLine); cs.Append(" "+stringXLen.ToString()+","+cs.NewLine); cs.Append(" "+sb.Length.ToString()+cs.NewLine); cs.Append("};"+cs.NewLine); foreach(UPnPStateVariable v in s.GetStateVariables()) { Hashtable t = (Hashtable)VarTable[s]; int startingIndex = (int)((object[])t[v])[0]; string varString = (string)((object[])t[v])[2]; cs.Append("struct UPnP_StateVariable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+v.Name+" UPnP_StateVariable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+v.Name+"_Impl = "+cs.NewLine); cs.Append("{"+cs.NewLine); cs.Append(" "+startingIndex.ToString()+","+cs.NewLine); // Start Index cs.Append(" "+(varString.IndexOf("</dataType>")+11).ToString()+","+cs.NewLine); if (v.AllowedStringValues!=null) { int avlen=0; foreach(string avs in v.AllowedStringValues) { avlen += avs.Length; } cs.Append(" "+(varString.IndexOf("<allowedValueList>")+startingIndex).ToString()+","+cs.NewLine); // Start of Allowed Value List cs.Append(" 18,"+cs.NewLine); // Length of allowedValueList cs.Append(" "+(varString.IndexOf("</allowedValueList>")+startingIndex).ToString()+","+cs.NewLine); // Start of endTag cs.Append(" 19,"+cs.NewLine); // Length of end tag cs.Append(" {"); foreach(string av in v.AllowedStringValues) { cs.Append("\""+av+"\","); } cs.Append("NULL"); cs.Append("}"); } if (v.Minimum!=null || v.Maximum!=null) { if (v.AllowedStringValues!=null) { cs.Append(","+cs.NewLine); } cs.Append(" "+(startingIndex+varString.IndexOf("<allowedValueRange>")).ToString()+","+cs.NewLine); cs.Append(" 19,"+cs.NewLine); cs.Append(" "+(startingIndex+varString.IndexOf("</allowedValueRange>")).ToString()+","+cs.NewLine); cs.Append(" 20,"+cs.NewLine); cs.Append(" {"); if (v.Minimum!=null) { cs.Append("\""+v.Minimum.ToString()+"\","); } else { cs.Append("NULL,"); } if (v.Maximum!=null) { cs.Append("\""+v.Maximum.ToString()+"\","); } else { cs.Append("NULL,"); } if (v.Step!=null) { cs.Append("\""+v.Step.ToString()+"\""); } else { cs.Append("NULL"); } cs.Append("}"); } if (v.DefaultValue!=null) { if (v.AllowedStringValues!=null || v.Maximum!=null || v.Maximum!=null) { cs.Append(","+cs.NewLine); } cs.Append(" "+(startingIndex+varString.IndexOf("<defaultValue>")).ToString()+","+cs.NewLine); cs.Append(" 14,"+cs.NewLine); cs.Append(" "+(startingIndex+varString.IndexOf("</defaultValue>")).ToString()+","+cs.NewLine); cs.Append(" 15,"+cs.NewLine); cs.Append("\""+UPnPService.SerializeObjectInstance(v.DefaultValue)+"\""); } if (v.DefaultValue!=null || v.AllowedStringValues!=null || v.Maximum!=null || v.Maximum!=null) { cs.Append(","+cs.NewLine); } cs.Append((varString.IndexOf("</stateVariable>")+startingIndex).ToString()+","+cs.NewLine); cs.Append(" 16"+cs.NewLine); cs.Append("};"+cs.NewLine); } } } protected static void BuildStateVariableStructs(CodeProcessor cs, UPnPDevice d) { foreach(UPnPDevice ed in d.EmbeddedDevices) { BuildStateVariableStructs(cs,ed); } foreach(UPnPService s in d.Services) { string stringX; int stringXLen; StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); foreach(UPnPStateVariable v in s.GetStateVariables()) { UPnPDebugObject dobj = new UPnPDebugObject(v); dobj.InvokeNonStaticMethod("GetStateVariableXML",new object[1]{X}); } InjectCompressedString(out stringX,out stringXLen,sb.ToString(),cs.NewLine); cs.Append("struct UPnP_StateVariableTable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+cs.NewLine); cs.Append("{"+cs.NewLine); cs.Append(" char Reserved["+stringXLen.ToString()+"];"+cs.NewLine); cs.Append(" int ReservedXL;"+cs.NewLine); cs.Append(" int ReservedUXL;"+cs.NewLine); cs.Append("};"+cs.NewLine); foreach(UPnPStateVariable v in s.GetStateVariables()) { cs.Append("struct UPnP_StateVariable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+v.Name+cs.NewLine); cs.Append("{"+cs.NewLine); cs.Append(" int Reserved1;"+cs.NewLine); cs.Append(" int Reserved1L;"+cs.NewLine); if (v.AllowedStringValues!=null) { cs.Append(" int Reserved2;"+cs.NewLine); cs.Append(" int Reserved2L;"+cs.NewLine); cs.Append(" int Reserved3;"+cs.NewLine); cs.Append(" int Reserved3L;"+cs.NewLine); cs.Append(" char *AllowedValues[UPnP_StateVariable_AllowedValues_MAX];"+cs.NewLine); } if (v.Minimum!=null || v.Maximum!=null) { cs.Append(" int Reserved4;"+cs.NewLine); cs.Append(" int Reserved4L;"+cs.NewLine); cs.Append(" int Reserved5;"+cs.NewLine); cs.Append(" int Reserved5L;"+cs.NewLine); cs.Append(" char *MinMaxStep[3];"+cs.NewLine); } if (v.DefaultValue!=null) { cs.Append(" int Reserved6;"+cs.NewLine); cs.Append(" int Reserved6L;"+cs.NewLine); cs.Append(" int Reserved7;"+cs.NewLine); cs.Append(" int Reserved7L;"+cs.NewLine); cs.Append(" char *DefaultValue;"+cs.NewLine); } cs.Append(" int Reserved8;"+cs.NewLine); cs.Append(" int Reserved8L;"+cs.NewLine); cs.Append("};"+cs.NewLine); } } } protected static void PopulateActionStructs(CodeProcessor cs, UPnPDevice d, Hashtable VarTable) { foreach(UPnPDevice ed in d.EmbeddedDevices) { PopulateActionStructs(cs,ed,VarTable); } foreach(UPnPService s in d.Services) { cs.Append("struct UPnP_ActionTable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+" UPnP_ActionTable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_Impl = "+cs.NewLine); cs.Append("{"+cs.NewLine); string stringX; int stringXLen; StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); foreach(UPnPAction a in s.Actions) { UPnPDebugObject dobj = new UPnPDebugObject(a); dobj.InvokeNonStaticMethod("GetXML",new object[1]{X}); } X.Flush(); InjectCompressedString(out stringX,out stringXLen,sb.ToString(),cs.NewLine); cs.Append(" "+stringX+","+cs.NewLine); cs.Append(" "+stringXLen.ToString()+","+cs.NewLine); cs.Append(" "+sb.Length.ToString()+cs.NewLine); cs.Append("};"+cs.NewLine); foreach(UPnPAction a in s.Actions) { Hashtable t = (Hashtable)VarTable[s]; cs.Append("struct UPnP_Action_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+a.Name+" UPnP_Action_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+a.Name+"_Impl = "+cs.NewLine); cs.Append("{"+cs.NewLine); cs.Append(" "+((object[])t[a])[0].ToString()+","+cs.NewLine); cs.Append(" "+((object[])t[a])[1].ToString()+cs.NewLine); cs.Append("};"+cs.NewLine); } } } protected static void BuildActionStructs(CodeProcessor cs, UPnPDevice d) { foreach(UPnPDevice ed in d.EmbeddedDevices) { BuildActionStructs(cs,ed); } foreach(UPnPService s in d.Services) { string stringX; int stringXLen; StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); foreach(UPnPAction a in s.Actions) { UPnPDebugObject dobj = new UPnPDebugObject(a); dobj.InvokeNonStaticMethod("GetXML",new object[1]{X}); } InjectCompressedString(out stringX,out stringXLen,sb.ToString(),cs.NewLine); cs.Append("struct UPnP_ActionTable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+cs.NewLine); cs.Append("{"+cs.NewLine); cs.Append(" char Reserved["+stringXLen.ToString()+"];"+cs.NewLine); cs.Append(" int ReservedXL;"+cs.NewLine); cs.Append(" int ReservedUXL;"+cs.NewLine); cs.Append("};"+cs.NewLine); foreach(UPnPAction a in s.Actions) { cs.Append("struct UPnP_Action_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+a.Name+cs.NewLine); cs.Append("{"+cs.NewLine); cs.Append(" int Reserved;"+cs.NewLine); cs.Append(" int Reserved2;"+cs.NewLine); cs.Append("};"+cs.NewLine); } } } protected static void PopulateServiceStructs(CodeProcessor cs, UPnPDevice d) { foreach(UPnPDevice ed in d.EmbeddedDevices) { PopulateServiceStructs(cs,ed); } foreach(UPnPService s in d.Services) { cs.Append("struct UPnP_Service_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+" UPnP_Service_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_Impl ="+cs.NewLine); cs.Append("{"+cs.NewLine); foreach(UPnPAction a in s.Actions) { cs.Append(" &UPnP_Action_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+a.Name+"_Impl,"+cs.NewLine); } foreach(UPnPStateVariable v in s.GetStateVariables()) { cs.Append(" &UPnP_StateVariable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+v.Name+"_Impl,"+cs.NewLine); } string stringX; int stringXLen; StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); s.GetServiceXML(X); InjectCompressedString(out stringX,out stringXLen,sb.ToString(),cs.NewLine); cs.Append(" "+stringX+","+cs.NewLine); cs.Append(" "+stringXLen.ToString()+","+cs.NewLine); cs.Append(" "+sb.Length.ToString()+","+cs.NewLine); cs.Append("};"+cs.NewLine); } } protected static void BuildServiceStructs(CodeProcessor cs, UPnPDevice d) { foreach(UPnPDevice ed in d.EmbeddedDevices) { BuildServiceStructs(cs,ed); } foreach(UPnPService s in d.Services) { cs.Append("struct UPnP_Service_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+cs.NewLine); cs.Append("{"+cs.NewLine); foreach(UPnPAction a in s.Actions) { cs.Append(" struct UPnP_Action_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+a.Name+" *"+a.Name+";"+cs.NewLine); } cs.Append(cs.NewLine); foreach(UPnPStateVariable v in s.GetStateVariables()) { cs.Append(" struct UPnP_StateVariable_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+v.Name+" *StateVar_"+v.Name+";"+cs.NewLine); } string stringX; int stringXLen; StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter X = new XmlTextWriter(SW); s.GetServiceXML(X); InjectCompressedString(out stringX,out stringXLen,sb.ToString(),cs.NewLine); cs.Append(cs.NewLine); cs.Append(" char Reserved["+stringXLen.ToString()+"];"+cs.NewLine); cs.Append(" int ReservedXL;"+cs.NewLine); cs.Append(" int ReservedUXL;"+cs.NewLine); cs.Append("};"+cs.NewLine); } } protected static void PopulateDeviceStructs(CodeProcessor cs, UPnPDevice d) { foreach(UPnPDevice ed in d.EmbeddedDevices) { PopulateDeviceStructs(cs,ed); } cs.Append("struct UPnP_Device_"+d.User2.ToString()+" UPnP_Device_"+d.User2.ToString()+"_Impl = "+cs.NewLine); cs.Append("{"+cs.NewLine); foreach(UPnPService s in d.Services) { cs.Append(" &UPnP_Service_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_Impl,"+cs.NewLine); } cs.Append(cs.NewLine); foreach(UPnPDevice ed in d.EmbeddedDevices) { cs.Append(" &UPnP_Device_"+ed.User2.ToString()+"_Impl,"+cs.NewLine); } cs.Append(" NULL,"+cs.NewLine); // Friendly if (d.ParentDevice==null) { cs.Append(" NULL,"+cs.NewLine+" NULL,"+cs.NewLine); //UDN, Serial } cs.Append(" NULL,"+cs.NewLine); //Manufacturer cs.Append(" NULL,"+cs.NewLine); //ManufacturerURL cs.Append(" NULL,"+cs.NewLine); //ModelDescription cs.Append(" NULL,"+cs.NewLine); //ModelName cs.Append(" NULL,"+cs.NewLine); //ModelNumber cs.Append(" NULL,"+cs.NewLine); //ModelURL cs.Append(" NULL,"+cs.NewLine); //Product Code UPnPDevice[] embeddedDevices = d.EmbeddedDevices; UPnPService[] services = d.Services; d.EmbeddedDevices = new UPnPDevice[0]; d.Services = new UPnPService[0]; string xmlString; if (d.ParentDevice==null) {byte[] xml; xml = d.GetRootDeviceXML(null); xmlString = (new UTF8Encoding()).GetString(xml); } else { StringBuilder sb = new StringBuilder(); StringWriter SW = new StringWriter(sb); XmlTextWriter XDoc = new XmlTextWriter(SW); (new UPnPDebugObject(d)).InvokeNonStaticMethod("GetNonRootDeviceXML",new object[2]{null,XDoc}); SW.Flush(); xmlString = sb.ToString(); } string stringX; int stringXLen; InjectCompressedString(out stringX,out stringXLen,xmlString,cs.NewLine); cs.Append(" "+stringX+","+cs.NewLine); cs.Append(" "+stringXLen.ToString()+","+cs.NewLine); cs.Append(" "+xmlString.Length.ToString()+","+cs.NewLine); if (d.ParentDevice==null) { cs.Append(" NULL,"+cs.NewLine); } cs.Append(" NULL"+cs.NewLine); cs.Append("};"+cs.NewLine); d.EmbeddedDevices = embeddedDevices; d.Services = services; } protected static void BuildDeviceStructs(CodeProcessor cs, UPnPDevice d) { foreach(UPnPDevice ed in d.EmbeddedDevices) { BuildDeviceStructs(cs,ed); } cs.Append("struct UPnP_Device_"+d.User2.ToString()+cs.NewLine); cs.Append("{"+cs.NewLine); foreach(UPnPService s in d.Services) { cs.Append(" struct UPnP_Service_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+" *"+((ServiceGenerator.ServiceConfiguration)s.User).Name+";"+cs.NewLine); } cs.Append(cs.NewLine); foreach(UPnPDevice ed in d.EmbeddedDevices) { cs.Append(" struct UPnP_Device_"+ed.User2.ToString()+" *UPnP_Device_"+ed.User2.ToString()+";"+cs.NewLine); } cs.Append(" const char *FriendlyName;"+cs.NewLine); if (d.ParentDevice==null) { cs.Append(" const char *UDN;"+cs.NewLine); cs.Append(" const char *Serial;"+cs.NewLine); } cs.Append(" const char *Manufacturer;"+cs.NewLine); cs.Append(" const char *ManufacturerURL;"+cs.NewLine); cs.Append(" const char *ModelDescription;"+cs.NewLine); cs.Append(" const char *ModelName;"+cs.NewLine); cs.Append(" const char *ModelNumber;"+cs.NewLine); cs.Append(" const char *ModelURL;"+cs.NewLine); cs.Append(" const char *ProductCode;"+cs.NewLine); UPnPDevice[] embeddedDevices = d.EmbeddedDevices; UPnPService[] services = d.Services; d.EmbeddedDevices = new UPnPDevice[0]; d.Services = new UPnPService[0]; byte[] xml; if (d.Root) { xml = d.GetRootDeviceXML(null); } else { xml = (byte[])(new UPnPDebugObject(d)).InvokeNonStaticMethod("GetRootDeviceXML",new object[1]{null}); } UTF8Encoding U = new UTF8Encoding(); string xmlString = U.GetString(xml); string stringX; int stringXLen; InjectCompressedString(out stringX,out stringXLen,xmlString,cs.NewLine); d.EmbeddedDevices = embeddedDevices; d.Services = services; cs.Append(" char Reserved["+stringXLen.ToString()+"];"+cs.NewLine); cs.Append(" int ReservedXL;"+cs.NewLine); cs.Append(" int ReservedUXL;"+cs.NewLine); cs.Append(" void *User;"+cs.NewLine); if (d.ParentDevice==null) { cs.Append(" void *MicrostackToken;"+cs.NewLine); } cs.Append("};"+cs.NewLine); } public static void PrepDevice(UPnPDevice[] devices) { foreach(UPnPDevice d in devices) { Hashtable t = new Hashtable(); LabelDevices(t,d); } } public static int CalculateMaxAllowedValues(UPnPDevice d, int maxVal) { foreach(UPnPDevice ed in d.EmbeddedDevices) { maxVal = CalculateMaxAllowedValues(ed,maxVal); } foreach(UPnPService s in d.Services) { foreach(UPnPStateVariable v in s.GetStateVariables()) { if (v.AllowedStringValues!=null) { if (v.AllowedStringValues.Length>maxVal) { maxVal = v.AllowedStringValues.Length; } } } } return(maxVal); } public static string GetDeviceObjectsString(UPnPDevice d) { CodeProcessor cs = new CodeProcessor(new StringBuilder(),false); cs.NewLine = "\r\n"; // // Calculate the size to initialize "UPnP_StateVariable_AllowedValues_MAX" // int max = CalculateMaxAllowedValues(d,0); if (max!=0) { ++max; cs.Append("#define UPnP_StateVariable_AllowedValues_MAX "+max+cs.NewLine); } BuildStateVariableStructs(cs,d); BuildActionStructs(cs,d); BuildServiceStructs(cs,d); BuildDeviceStructs(cs,d); return(cs.ToString()); } public static string GetPopulatedDeviceObjectsString(UPnPDevice d) { Hashtable VarTable = new Hashtable(); Hashtable ActionTable = new Hashtable(); CodeProcessor cs = new CodeProcessor(new StringBuilder(),false); cs.NewLine = "\r\n"; DeviceObjectGenerator.GenerateStateVariableLookupTable(d,VarTable); DeviceObjectGenerator.GenerateActionLookupTable(d,ActionTable); PopulateStateVariableStructs(cs,d,VarTable); PopulateActionStructs(cs,d,ActionTable); PopulateServiceStructs(cs,d); PopulateDeviceStructs(cs,d); return(cs.ToString()); } private static string BuildDeviceDescriptionStreamer_EmbeddedDevice(UPnPDevice d, string WS, string WS2) { string DeviceTemplate = WS2; string WS3; string deviceIdentifier = ""; string rootDeviceIdentifier = ""; UPnPDevice t = d; while(t.ParentDevice!=null) { t = t.ParentDevice; } deviceIdentifier = DeviceObjectGenerator.GetDeviceIdentifier(d); rootDeviceIdentifier = DeviceObjectGenerator.GetDeviceIdentifier(t)+"."; if (d.ParentDevice==null) { deviceIdentifier += "."; } else { deviceIdentifier += "->"; } WS2 = WS2.Replace("{{{DEVICE}}}",deviceIdentifier); WS2 = WS2.Replace("{{{DEVICE2}}}",rootDeviceIdentifier); if (d.ParentDevice==null) { // Root Device WS2 = WS2.Replace("{{{DEVICE_SUBTRACTION}}}","19"); } else { // Embedded Device WS2 = WS2.Replace("{{{DEVICE_SUBTRACTION}}}","9"); } foreach(UPnPService s in d.Services) { WS3 = SourceCodeRepository.GetTextBetweenTags(WS2,"//{{{SERVICE_BEGIN}}}","//{{{SERVICE_END}}}"); string serviceIdentifier = ""; UPnPDevice serviceDevice = s.ParentDevice; while(serviceDevice!=null) { if (serviceIdentifier=="") { serviceIdentifier = "UPnP_Device_"+serviceDevice.User2.ToString(); } else { if (serviceDevice.ParentDevice!=null) { serviceIdentifier = "UPnP_Device_"+serviceDevice.User2.ToString()+"->" + serviceIdentifier; } else { serviceIdentifier = "UPnP_Device_"+serviceDevice.User2.ToString()+"_Impl." + serviceIdentifier; } } serviceDevice = serviceDevice.ParentDevice; } if (s.ParentDevice.ParentDevice==null) { serviceIdentifier += "_Impl."+((ServiceGenerator.ServiceConfiguration)s.User).Name; } else { serviceIdentifier += "->"+((ServiceGenerator.ServiceConfiguration)s.User).Name; } WS3 = WS3.Replace("{{{SERVICE}}}",serviceIdentifier); WS2 = SourceCodeRepository.InsertTextBeforeTag(WS2,"//{{{SERVICE_BEGIN}}}",WS3); } if (d.EmbeddedDevices.Length>0) { WS3 = " if ("; string WS4 = ""; foreach(UPnPDevice ed in d.EmbeddedDevices) { WS3 = WS3 + WS4 + DeviceObjectGenerator.GetDeviceIdentifier(ed)+"!=NULL"; WS4 = " || "; } WS3 += ")\r\n"; WS3 += "{\r\n"; WS2 = SourceCodeRepository.InsertTextBeforeTag(WS2,"//{{{BEGIN_HASEMBEDDEDDEVICES}}}",WS3); foreach(UPnPDevice ed in d.EmbeddedDevices) { WS3 = BuildDeviceDescriptionStreamer_EmbeddedDevice(ed,"",DeviceTemplate); WS2 = SourceCodeRepository.InsertTextBeforeTag(WS2,"//{{{EMBEDDED_DEVICES}}}",WS3); } WS2 = WS2.Replace("//{{{EMBEDDED_DEVICES}}}",""); WS3 = "}\r\n"; WS2 = SourceCodeRepository.InsertTextBeforeTag(WS2,"//{{{END_HASEMBEDDEDDEVICES}}}",WS3); WS2 = SourceCodeRepository.RemoveTag("//{{{BEGIN_HASEMBEDDEDDEVICES}}}","//{{{END_HASEMBEDDEDDEVICES}}}",WS2); } else { WS2 = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_HASEMBEDDEDDEVICES}}}","//{{{END_HASEMBEDDEDDEVICES}}}",WS2); } WS2 = SourceCodeRepository.RemoveAndClearTag("//{{{SERVICE_BEGIN}}}","//{{{SERVICE_END}}}",WS2); if (d.ParentDevice==null) { WS = WS + "\r\n" + WS2; } else { // // This is an embedded device, so we need to check it first // WS = WS + "\r\n" + "if ("+DeviceObjectGenerator.GetDeviceIdentifier(d)+"!=NULL)\r\n"; WS += "{\r\n" + WS2 + "\r\n}\r\n"; } return(WS); } public static string BuildDeviceDescriptionStreamer(UPnPDevice d, string templateString) { string WS = BuildDeviceDescriptionStreamer_EmbeddedDevice(d,"",SourceCodeRepository.GetTextBetweenTags(templateString,"//{{{DEVICE_BEGIN}}}","//{{{DEVICE_END}}}")); templateString = SourceCodeRepository.InsertTextBeforeTag(templateString,"//{{{DEVICE_BEGIN}}}",WS); templateString = SourceCodeRepository.RemoveAndClearTag("//{{{DEVICE_BEGIN}}}","//{{{DEVICE_END}}}",templateString); return(templateString); } public static string GetStateVariableIdentifier(UPnPStateVariable var) { string servID = GetServiceIdentifier(var.OwningService); return(servID+"->StateVar_"+var.Name); } public static string GetServiceIdentifier(UPnPService service) { string devID = GetDeviceIdentifier(service.ParentDevice); if (service.ParentDevice.ParentDevice==null) { return(devID+"."+((ServiceGenerator.ServiceConfiguration)service.User).Name); } else { return(devID+"->"+((ServiceGenerator.ServiceConfiguration)service.User).Name); } } public static string GetDeviceIdentifier(UPnPDevice device) { string deviceIdent = ""; UPnPDevice pDevice = device; string prefix = ((ServiceGenerator.Configuration)device.User).Prefix; while(pDevice!=null) { if (deviceIdent=="") { if (pDevice.ParentDevice==null) { deviceIdent = "UPnP_Device_"+pDevice.User2.ToString()+"_Impl"; } else { deviceIdent = "UPnP_Device_"+pDevice.User2.ToString(); } } else { if (pDevice.ParentDevice==null) { deviceIdent = "UPnP_Device_"+pDevice.User2.ToString()+"_Impl."+deviceIdent; } else { deviceIdent = "UPnP_Device_"+pDevice.User2.ToString()+"->"+deviceIdent; } } deviceIdent = deviceIdent.Replace("UPnP",prefix); pDevice = pDevice.ParentDevice; } return(deviceIdent); } protected static string GetCPlusPlusAbstraction_H_Service(string WC, UPnPService s) { string WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Service_Begin}}}","//{{{Service_End}}}"); string WC3; foreach(UPnPStateVariable V in s.GetStateVariables()) { if (V.SendEvent) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{Service_Events_BEGIN}}}","//{{{Service_Events_END}}}"); WC3 = WC3.Replace("{{{VARNAME}}}",V.Name); WC3 = WC3.Replace("{{{PARAMDEF}}}",EmbeddedCGenerator.ToCTypeFromStateVar(V)); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{Service_Events_BEGIN}}}",WC3); } } WC2 = SourceCodeRepository.RemoveAndClearTag("//{{{Service_Events_BEGIN}}}","//{{{Service_Events_END}}}",WC2); WC2 = WC2.Replace("{{{SERVICE}}}","UPnP_Service_"+((ServiceGenerator.ServiceConfiguration)s.User).Name); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+s.ParentDevice.User2.ToString()); StringBuilder sb = new StringBuilder(); foreach(UPnPAction a in s.Actions) { sb.Append("virtual void "+a.Name+"(void *session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { sb.Append(", "+EmbeddedCGenerator.ToCTypeFromArg(arg)); } } sb.Append(");\r\n"); } WC2 = WC2.Replace("//{{{Service_VirtualMethods}}}",sb.ToString()); sb = new StringBuilder(); foreach(UPnPAction a in s.Actions) { sb.Append("void Response_"+a.Name+"(void *session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="out") { sb.Append(", "+EmbeddedCGenerator.ToCTypeFromArg(arg)); } } sb.Append(");\r\n"); if (((ServiceGenerator.ServiceConfiguration)s.User).Actions_Fragmented.Contains(a)) { sb.Append(" void Response_Async_"+a.Name+"(void *session, char* ArgName, char *ArgValue, int ArgValueLength, int ArgStart, int ArgDone, int ResponseDone);\r\n"); } } WC2 = WC2.Replace("//{{{Service_VirtualMethods_Response}}}",sb.ToString()); return(WC2); } protected static string GetCPlusPlusAbstraction_H_Device(string WC, UPnPDevice d) { string WC2; foreach(UPnPDevice ed in d.EmbeddedDevices) { WC = GetCPlusPlusAbstraction_H_Device(WC,ed); } foreach(UPnPService s in d.Services) { WC2 = GetCPlusPlusAbstraction_H_Service(WC,s); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Service_Begin}}}",WC2); } WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Device_Begin}}}","//{{{Device_End}}}"); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); StringBuilder sSinks = new StringBuilder(); StringBuilder sList = new StringBuilder(); foreach(UPnPService s in d.Services) { sList.Append("CUPnP_Service_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+" *m_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+";\r\n"); foreach(UPnPAction a in s.Actions) { sSinks.Append("static void "+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+a.Name+"_Sink("); sSinks.Append("void *session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { sSinks.Append(", "+EmbeddedCGenerator.ToCTypeFromArg(arg)); } } sSinks.Append(");\r\n"); } } WC2 = WC2.Replace("//{{{Device_ServiceList}}}",sList.ToString()); WC2 = WC2.Replace("//{{{Device_StaticSinks}}}",sSinks.ToString()); sList = new StringBuilder(); foreach(UPnPDevice ed in d.EmbeddedDevices) { sList.Append("CUPnP_Device_"+ed.User2.ToString()+" *m_Device_"+ed.User2.ToString()+";\r\n"); } WC2 = WC2.Replace("//{{{Device_DeviceList}}}",sList.ToString()); if (d.ParentDevice!=null) { WC2 = WC2.Replace("//{{{ParentFriends}}}","friend class CUPnP_Device_"+d.ParentDevice.User2.ToString()+";\r\n"); WC2 = WC2.Replace("{{{EMBEDDED}}}",", CUPnP_Device_"+d.ParentDevice.User2.ToString()+" *parentDevice"); } else { WC2 = WC2.Replace("//{{{ParentFriends}}}",""); WC2 = WC2.Replace("{{{EMBEDDED}}}",""); } WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Device_Begin}}}",WC2); return(WC); } protected static string GetCPlusPlusAbstraction_CPP_Device_FriendlyName(string WC, UPnPDevice d, int i) { WC += ",\""+d.FriendlyName; if (i!=1) { WC += i.ToString(); } WC += "\""; foreach(UPnPDevice ed in d.EmbeddedDevices) { WC = GetCPlusPlusAbstraction_CPP_Device_FriendlyName(WC,ed,++i); } return(WC); } protected static string GetCPlusPlusAbstraction_CPP_Device(string WC, UPnPDevice d) { string WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Device_Begin}}}","//{{{Device_End}}}"); string WC3,WC4; if (d.ParentDevice==null) { // // This is the root device // WC3 = "MicrostackToken = "+((ServiceGenerator.Configuration)d.User).Prefix+"CreateMicroStack(MicrostackChain"+GetCPlusPlusAbstraction_CPP_Device_FriendlyName("",d,1); WC3 += ",\""+Guid.NewGuid()+"\",\"000001\","+((ServiceGenerator.Configuration)d.User).SSDPCycleTime.ToString()+","+((ServiceGenerator.Configuration)d.User).WebPort+");\r\n"; WC2 = WC2.Replace("//{{{CreateMicroStack}}}",WC3); } else { WC2 = WC2.Replace("//{{{CreateMicroStack}}}",""); } foreach(UPnPService s in d.Services) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{Destructor_Begin}}}","//{{{Destructor_End}}}"); WC3 = WC3.Replace("{{{NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{Destructor_Begin}}}",WC3); WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{Service_Instantiation_Begin}}}","//{{{Service_Instantiation_End}}}"); WC3 = WC3.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{Service_Instantiation_Begin}}}",WC3); foreach(UPnPAction a in s.Actions) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{SinkList_Begin}}}","//{{{SinkList_End}}}"); WC3 = WC3.Replace("{{{Prefix}}}",((ServiceGenerator.Configuration)d.User).Prefix); WC3 = WC3.Replace("{{{SERVICE_SHORT_NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC3 = WC3.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC3 = WC3.Replace("{{{ACTION_NAME}}}",a.Name); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{SinkList_Begin}}}",WC3); // // Dispatch // WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{Dispatch_Begin}}}","//{{{Dispatch_End}}}"); WC3 = WC3.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC3 = WC3.Replace("{{{SERVICE_SHORT_NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC3 = WC3.Replace("{{{ACTION_NAME}}}",a.Name); UPnPDevice rDevice = s.ParentDevice; while(rDevice.ParentDevice!=null) { rDevice = rDevice.ParentDevice; } WC3 = WC3.Replace("{{{ROOTDEVICE}}}","UPnP_Device_"+rDevice.User2.ToString()); rDevice = s.ParentDevice; WC4 = ""; while(rDevice.ParentDevice!=null) { WC4 = "m_Device_"+rDevice.User2.ToString()+"->" + WC4; rDevice = rDevice.ParentDevice; } WC3 = WC3.Replace("{{{DEVICELIST}}}",WC4); StringBuilder paramList = new StringBuilder(); paramList.Append("void *session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { paramList.Append(","); paramList.Append(EmbeddedCGenerator.ToCTypeFromArg(arg)); } } WC3 = WC3.Replace("{{{PARAM_LIST}}}",paramList.ToString()); paramList = new StringBuilder(); paramList.Append("session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { paramList.Append(","+arg.Name); } } WC3 = WC3.Replace("{{{PARAM_LIST_DISPATCH}}}",paramList.ToString()); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{Dispatch_Begin}}}",WC3); } } foreach(UPnPDevice ed in d.EmbeddedDevices) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{Destructor_Begin}}}","//{{{Destructor_End}}}"); WC3 = WC3.Replace("{{{NAME}}}","Device_"+ed.User2.ToString()); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{Destructor_Begin}}}",WC3); WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{Device_Instantiation_Begin}}}","//{{{Device_Instantiation_End}}}"); WC3 = WC3.Replace("{{{DEVICE}}}","Device_"+ed.User2.ToString()); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{Device_Instantiation_Begin}}}",WC3); } WC2 = WC2.Replace("{{{Prefix}}}",((ServiceGenerator.Configuration)d.User).Prefix); //WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Device_Begin}}}",WC2); foreach(UPnPDevice ed in d.EmbeddedDevices) { WC3 = GetCPlusPlusAbstraction_CPP_Device(WC,ed); WC2 = WC3 + "\r\n" + WC2; //WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Device_Begin}}}",WC3); } foreach(UPnPService s in d.Services) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Service_Begin}}}","//{{{Service_End}}}"); WC3 = WC3.Replace("{{{SERVICE_NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC3 = WC3.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC3 = WC3.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); // // Evented State Variables // foreach(UPnPStateVariable V in s.GetStateVariables()) { if (V.SendEvent) { WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{SERVICE_EVENTS_BEGIN}}}","//{{{SERVICE_EVENTS_END}}}"); WC4 = WC4.Replace("{{{SERVICE_NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC4 = WC4.Replace("{{{VARNAME}}}",V.Name); WC4 = WC4.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); WC4 = WC4.Replace("{{{PARAMDEF}}}",EmbeddedCGenerator.ToCTypeFromStateVar(V)); WC4 = WC4.Replace("{{{PARAMLIST}}}","ParentDevice->GetToken(),"+EmbeddedCGenerator.ToCTypeFromStateVar_Dispatch(V)); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{SERVICE_EVENTS_BEGIN}}}",WC4); } } WC3 = SourceCodeRepository.RemoveAndClearTag("//{{{SERVICE_EVENTS_BEGIN}}}","//{{{SERVICE_EVENTS_END}}}",WC3); foreach(UPnPAction a in s.Actions) { WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{SERVICE_VIRTUAL_METHOD_BASE_IMPLEMENTATION_BEGIN}}}","//{{{SERVICE_VIRTUAL_METHOD_BASE_IMPLEMENTATION_END}}}"); WC4 = WC4.Replace("{{{SERVICE_NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC4 = WC4.Replace("{{{ACTION_NAME}}}",a.Name); WC4 = WC4.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)s.ParentDevice.User).Prefix); WC4 = WC4.Replace("{{{URN}}}",s.ServiceURN); if (((ServiceGenerator.ServiceConfiguration)s.User).Actions_Fragmented.Contains(a)) { WC4 = SourceCodeRepository.RemoveTag("//(((FragmentedResponse_Begin}}}","//(((FragmentedResponse_End}}}",WC4); } else { WC4 = SourceCodeRepository.RemoveAndClearTag("//(((FragmentedResponse_Begin}}}","//(((FragmentedResponse_End}}}",WC4); } StringBuilder paramList = new StringBuilder(); // // Input Arguments // paramList.Append("void *session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { paramList.Append(","+EmbeddedCGenerator.ToCTypeFromArg(arg)); } } WC4 = WC4.Replace("{{{PARAM_LIST}}}",paramList.ToString()); // // Output Arguments Declaration // paramList = new StringBuilder(); paramList.Append("void *session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="out") { paramList.Append(","+EmbeddedCGenerator.ToCTypeFromArg(arg)); } } WC4 = WC4.Replace("{{{OUTPUT_PARAM_LIST}}}",paramList.ToString()); // // Output Arguments Dispatch // paramList = new StringBuilder(); paramList.Append("session"); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="out") { paramList.Append(","+EmbeddedCGenerator.ToCTypeFromArg_Dispatch(arg)); } } WC4 = WC4.Replace("{{{OUTPUT_PARAM_LIST_DISPATCH}}}",paramList.ToString()); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{SERVICE_VIRTUAL_METHOD_BASE_IMPLEMENTATION_BEGIN}}}",WC4); } //WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Service_Begin}}}",WC3); WC2 = WC2 + "\r\n" + WC3; } WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); if (d.ParentDevice!=null) { WC2 = WC2.Replace("{{{EMBEDDED}}}",", CUPnP_Device_"+d.ParentDevice.User2.ToString()+" *parentDevice"); WC2 = SourceCodeRepository.RemoveTag("//{{{SetToken_Begin}}}","//{{{SetToken_End}}}",WC2); WC2 = SourceCodeRepository.RemoveAndClearTag("//{{{Device_Root_Begin}}}","//{{{Device_Root_End}}}",WC2); } else { WC2 = WC2.Replace("{{{EMBEDDED}}}",""); WC2 = SourceCodeRepository.RemoveAndClearTag("//{{{SetToken_Begin}}}","//{{{SetToken_End}}}",WC2); WC2 = SourceCodeRepository.RemoveTag("//{{{Device_Root_Begin}}}","//{{{Device_Root_End}}}",WC2); } return(WC2); } public static string GetCPlusPlus_DerivedSampleClasses_Implementation(UPnPDevice[] devices) { string RetVal = ""; foreach(UPnPDevice d in devices) { foreach(UPnPDevice ed in d.EmbeddedDevices) { RetVal += GetCPlusPlus_DerivedSampleClasses_Implementation(new UPnPDevice[1]{ed}); } foreach(UPnPService S in d.Services) { StringBuilder sb = new StringBuilder(); if (((ServiceGenerator.Configuration)S.ParentDevice.User).ConfigType==ServiceGenerator.ConfigurationType.DEVICE) { sb.Append("CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"::"+"CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"(CUPnP_Device_"+S.ParentDevice.User2.ToString()+" *parent):CUPnP_Service_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"(parent)\r\n"); sb.Append("{\r\n"); sb.Append("}\r\n"); sb.Append("CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"::~"+"CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"()\r\n"); sb.Append("{\r\n"); sb.Append("}\r\n"); foreach(UPnPAction A in S.Actions) { sb.Append("void CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"::"+A.Name+"(void *session"); foreach(UPnPArgument arg in A.Arguments) { if (arg.Direction=="in") { sb.Append(","+EmbeddedCGenerator.ToCTypeFromArg(arg)); } } sb.Append(")\r\n"); sb.Append("{\r\n"); sb.Append(" Error(session,501,\"Sample Implementation\");\r\n"); sb.Append("}\r\n"); } } RetVal += sb.ToString(); } } return(RetVal); } public static string GetCPlusPlus_DerivedSampleClasses_Insertion(UPnPDevice[] devices) { string RetVal = ""; foreach(UPnPDevice d in devices) { foreach(UPnPDevice ed in d.EmbeddedDevices) { RetVal += GetCPlusPlus_DerivedSampleClasses_Insertion(new UPnPDevice[1]{ed}); } foreach(UPnPService S in d.Services) { if (((ServiceGenerator.Configuration)S.ParentDevice.User).ConfigType==ServiceGenerator.ConfigurationType.DEVICE) { string val = ""; UPnPDevice pD = S.ParentDevice; while(pD.ParentDevice!=null) { if (val=="") { val = "m_Device_"+pD.User2.ToString(); } else { val = "m_Device_"+pD.User2.ToString()+"->"+val; } pD = pD.ParentDevice; } if (S.ParentDevice.ParentDevice==null) { val = "pUPnP->Get_UPnP_Device_"+pD.User2.ToString()+"()"; } else { val = "pUPnP->Get_UPnP_Device_"+pD.User2.ToString()+"()->"+val; } RetVal += " delete " + val + "->m_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+";\r\n"; RetVal += " "+val+"->m_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+" = new CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"("+val+");\r\n"; } } } return(RetVal); } public static string GetCPlusPlus_DerivedSampleClasses(UPnPDevice[] devices) { string RetVal = ""; foreach(UPnPDevice d in devices) { foreach(UPnPDevice ed in d.EmbeddedDevices) { RetVal += GetCPlusPlus_DerivedSampleClasses(new UPnPDevice[1]{ed}); } foreach(UPnPService S in d.Services) { StringBuilder sb = new StringBuilder(); if (((ServiceGenerator.Configuration)S.ParentDevice.User).ConfigType==ServiceGenerator.ConfigurationType.DEVICE) { sb.Append("class CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+" : public CUPnP_Service_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"\r\n"); sb.Append("{\r\n"); sb.Append(" public:\r\n"); sb.Append(" CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"(CUPnP_Device_"+S.ParentDevice.User2.ToString()+" *parent);\r\n"); sb.Append(" virtual ~CUPnP_SampleService_"+((ServiceGenerator.ServiceConfiguration)S.User).Name+"();\r\n"); sb.Append("\r\n"); foreach(UPnPAction A in S.Actions) { sb.Append(" virtual void "+A.Name+"(void *session"); foreach(UPnPArgument arg in A.Arguments) { if (arg.Direction=="in") { sb.Append(","+EmbeddedCGenerator.ToCTypeFromArg(arg)); } } sb.Append(");\r\n"); } sb.Append("};\r\n"); } RetVal += sb.ToString(); } } return(RetVal); } private static string AddCPlusPlusAbstraction_CPP_ControlPoint(string WC, UPnPDevice d) { string WC2; string WC3; string arglist,arglist2; string outarglist, outarglist2; foreach(UPnPDevice ed in d.EmbeddedDevices) { WC = AddCPlusPlusAbstraction_CPP_ControlPoint(WC,ed); } foreach(UPnPService s in d.Services) { WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_ServiceCheck}}}","//{{{END_ServiceCheck}}}"); WC3 = "if (strlen(s->ServiceType)>"+s.ServiceURN_Prefix.Length.ToString()+" && strncmp(s->ServiceType,\""+s.ServiceURN_Prefix+"\","+s.ServiceURN_Prefix.Length.ToString()+")==0)"; WC2 = WC2.Replace("{{{COMPARESTRING}}}",WC3); WC2 = WC2.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_ServiceCheck}}}",WC2); // Constructor WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_CP_Constructor}}}","//{{{END_CP_Constructor}}}"); WC2 = WC2.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); foreach(UPnPStateVariable sv in s.GetStateVariables()) { if (sv.SendEvent) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC2,"//{{{BEGIN_EVENT}}}","//{{{END_EVENT}}}"); WC3 = WC3.Replace("{{{STATEVAR}}}",sv.Name); WC2 = SourceCodeRepository.InsertTextBeforeTag(WC2,"//{{{BEGIN_EVENT}}}",WC3); } } WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_CP_Constructor}}}",WC2); // // Subscription Override // bool HasEventing = false; foreach(UPnPStateVariable sv in s.GetStateVariables()) { if (sv.SendEvent) { HasEventing=true; break; } } if (HasEventing) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_CPEVENT_SUBSCRIBE}}}","//{{{END_CPEVENT_SUBSCRIBE}}}"); WC3 = WC3.Replace("{{{SERVICE_NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); foreach(UPnPStateVariable sv in s.GetStateVariables()) { if (sv.SendEvent) { string reg = ((ServiceGenerator.Configuration)d.User).Prefix+"EventCallback_"+((ServiceGenerator.ServiceConfiguration)s.User).Name+"_"+sv.Name+" = &EventSink_"+sv.Name+";"; WC3 = WC3.Replace("//{{{REGISTER}}}",reg+"\n"+"//{{{REGISTER}}}"); } } WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_CPEVENT_SUBSCRIBE}}}",WC3); foreach(UPnPStateVariable sv in s.GetStateVariables()) { if (sv.SendEvent) { WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_CPEVENT_SINK}}}","//{{{END_CPEVENT_SINK}}}"); WC2 = WC2.Replace("{{{SERVICE_NAME}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC2 = WC2.Replace("{{{STATEVAR}}}",sv.Name); WC2 = WC2.Replace("{{{ARGTYPE}}}",EmbeddedCGenerator.ToCTypeFromStateVar(sv)); WC2 = WC2.Replace("{{{ARGLIST}}}",EmbeddedCGenerator.ToCTypeFromStateVar_Dispatch(sv)); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_CPEVENT_SINK}}}",WC2); } } } // Invoke and InvokeSink foreach(UPnPAction a in s.Actions) { WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_CP_Invoke}}}","//{{{END_CP_Invoke}}}"); WC2 = WC2.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC2 = WC2.Replace("{{{ACTION}}}",a.Name); WC2 = WC2.Replace("{{{ONACTION}}}","On"+a.Name); WC2 = WC2.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); arglist = ""; arglist2 = ""; outarglist = ""; outarglist2 = ""; foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { arglist += ","+EmbeddedCGenerator.ToCTypeFromArg(arg); arglist2 += ","+EmbeddedCGenerator.ToCTypeFromArg_Dispatch(arg); } if (arg.Direction=="out") { outarglist += ","+EmbeddedCGenerator.ToCTypeFromArg(arg); outarglist2 += ","+EmbeddedCGenerator.ToCTypeFromArg_Dispatch(arg); } } WC2 = WC2.Replace("{{{INARGS}}}",arglist); WC2 = WC2.Replace("{{{INARGS_Values}}}",arglist2); WC2 = WC2.Replace("{{{OUTARGS}}}",outarglist); WC2 = WC2.Replace("{{{OUTARGS_Values}}}",outarglist2); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_CP_Invoke}}}",WC2); } } return(WC); } public static string GetCPlusPlusAbstraction_CPP(UPnPDevice[] devices) { string WC = SourceCodeRepository.GetCPlusPlus_Template_CPP("UPnP"); string WC2; CodeProcessor sb = new CodeProcessor(new StringBuilder(),false); bool ok = false; bool cpok = false; foreach(UPnPDevice d in devices) { if (((ServiceGenerator.Configuration)d.User).ConfigType==ServiceGenerator.ConfigurationType.DEVICE) { WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{MicroStackInclude_Begin}}}","//{{{MicroStackInclude_End}}}"); WC2 = WC2.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{MicroStackInclude_Begin}}}",WC2); WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_Constructor_Begin}}}","//{{{Manager_Constructor_End}}}"); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_Constructor_Begin}}}",WC2); WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_GetDevice_Begin}}}","//{{{Manager_GetDevice_End}}}"); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_GetDevice_Begin}}}",WC2); WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_Destructor_Begin}}}","//{{{Manager_Destructor_End}}}"); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_Destructor_Begin}}}",WC2); WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{IPADDRESS_HANDLER_BEGIN}}}","//{{{IPADDRESS_HANDLER_END}}}"); WC2 = WC2.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{IPADDRESS_HANDLER_BEGIN}}}",WC2); WC2 = GetCPlusPlusAbstraction_CPP_Device(WC,d); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Device_Begin}}}",WC2); ok = true; } else { // Includes WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{CPMicroStackInclude_Begin}}}","//{{{CPMicroStackInclude_End}}}"); WC2 = WC2.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{CPMicroStackInclude_Begin}}}",WC2); // Constructor WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_CPConstructor_Begin}}}","//{{{Manager_CPConstructor_End}}}"); WC2 = WC2.Replace("{{{DEVICE}}}",d.User2.ToString()); WC2 = WC2.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); WC2 = WC2.Replace("{{{DEVICEID}}}",d.GetHashCode().ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_CPConstructor_Begin}}}",WC2); // Discover/Remove Sinks WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_CPDiscoverSink}}}","//{{{END_CPDiscoverSink}}}"); WC2 = WC2.Replace("{{{PREFIX}}}",((ServiceGenerator.Configuration)d.User).Prefix); WC2 = WC2.Replace("{{{DEVICE}}}",d.User2.ToString()); WC2 = WC2.Replace("{{{DEVICEID}}}",d.GetHashCode().ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_CPDiscoverSink}}}",WC2); // SetControlPoint WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_SetControlPoint}}}","//{{{END_SetControlPoint}}}"); WC2 = WC2.Replace("{{{DEVICE}}}",d.User2.ToString()); WC2 = WC2.Replace("{{{DEVICEID}}}",d.GetHashCode().ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_SetControlPoint}}}",WC2); // Device/Service Specific Stuff WC = AddCPlusPlusAbstraction_CPP_ControlPoint(WC,d); cpok = true; ok = true; } } if (!cpok) { WC = SourceCodeRepository.RemoveAndClearTag("//{{{CP_BEGIN}}}","//{{{CP_END}}}",WC); } else { WC = SourceCodeRepository.RemoveTag("//{{{CP_BEGIN}}}","//{{{CP_END}}}",WC); } if (ok) { WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_Destructor_Begin}}}","//{{{Manager_Destructor_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_Constructor_Begin}}}","//{{{Manager_Constructor_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_GetDevice_Begin}}}","//{{{Manager_GetDevice_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Device_Begin}}}","//{{{Device_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Service_Begin}}}","//{{{Service_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{SERVICE_VIRTUAL_METHOD_BASE_IMPLEMENTATION_BEGIN}}}","//{{{SERVICE_VIRTUAL_METHOD_BASE_IMPLEMENTATION_END}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Service_Instantiation_Begin}}}","//{{{Service_Instantiation_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Device_Instantiation_Begin}}}","//{{{Device_Instantiation_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{SinkList_Begin}}}","//{{{SinkList_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Destructor_Begin}}}","//{{{Destructor_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Dispatch_Begin}}}","//{{{Dispatch_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{MicroStackInclude_Begin}}}","//{{{MicroStackInclude_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{IPADDRESS_HANDLER_BEGIN}}}","//{{{IPADDRESS_HANDLER_END}}}",WC); // Control Point Specific WC = SourceCodeRepository.RemoveAndClearTag("//{{{CPMicroStackInclude_Begin}}}","//{{{CPMicroStackInclude_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_CPConstructor_Begin}}}","//{{{Manager_CPConstructor_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CPDiscoverSink}}}","//{{{END_CPDiscoverSink}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_ServiceCheck}}}","//{{{END_ServiceCheck}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_SetControlPoint}}}","//{{{END_SetControlPoint}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CP_Constructor}}}","//{{{END_CP_Constructor}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CP_Invoke}}}","//{{{END_CP_Invoke}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CPEVENT_SINK}}}","//{{{END_CPEVENT_SINK}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CPEVENT_SUBSCRIBE}}}","//{{{END_CPEVENT_SUBSCRIBE}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_EVENT}}}","//{{{END_EVENT}}}",WC); WC = WC.Replace("//{{{REGISTER}}}",""); sb.Append(WC); } return(sb.ToString()); } private static string GetCPlusPlusAbstraction_H_FriendDevice(string WC,UPnPDevice d) { string WC2; if (((ServiceGenerator.Configuration)d.User).ConfigType==ServiceGenerator.ConfigurationType.DEVICE) { WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_Friends_BEGIN}}}","//{{{Manager_Friends_END}}}"); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); foreach(UPnPDevice ed in d.EmbeddedDevices) { WC2 += GetCPlusPlusAbstraction_H_FriendDevice(WC,ed); } return(WC2); } else { return(""); } } private static string GetCPlusPlusAbstraction_H_Device_CP(string WC, UPnPDevice d) { string WC2 = ""; string WC3,WC4; string arglist; foreach(UPnPDevice ed in d.EmbeddedDevices) { WC2 += GetCPlusPlusAbstraction_H_Device_CP(WC,ed); } foreach(UPnPService s in d.Services) { WC3 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{BEGIN_CP_SERVICE}}}","//{{{END_CP_SERVICE}}}"); foreach(UPnPStateVariable v in s.GetStateVariables()) { if (v.SendEvent) { // Event Sink WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{BEGIN_CP_EVENTSINK}}}","//{{{END_CP_EVENTSINK}}}"); WC4 = WC4.Replace("{{{STATEVAR}}}",v.Name); WC4 = WC4.Replace("{{{ARGTYPE}}}",EmbeddedCGenerator.ToCTypeFromStateVar(v)); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{BEGIN_CP_EVENTSINK}}}",WC4); //Typedef WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{BEGIN_EVENT_TYPEDEF}}}","//{{{END_EVENT_TYPEDEF}}}"); WC4 = WC4.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC4 = WC4.Replace("{{{STATEVAR}}}",v.Name); WC4 = WC4.Replace("{{{ARGLIST}}}",EmbeddedCGenerator.ToCTypeFromStateVar(v)); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{BEGIN_EVENT_TYPEDEF}}}",WC4); //Event WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{BEGIN_EVENT}}}","//{{{END_EVENT}}}"); WC4 = WC4.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC4 = WC4.Replace("{{{STATEVAR}}}",v.Name); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{BEGIN_EVENT}}}",WC4); } } foreach(UPnPAction a in s.Actions) { // Typedef WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{BEGIN_INVOKE_TYPEDEF}}}","//{{{END_INVOKE_TYPEDEF}}}"); WC4 = WC4.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC4 = WC4.Replace("{{{ONACTION}}}","On"+a.Name); arglist = ""; foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="out") { arglist += ","+EmbeddedCGenerator.ToCTypeFromArg(arg); } } WC4 = WC4.Replace("{{{OUTARGLIST}}}",arglist); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{BEGIN_INVOKE_TYPEDEF}}}",WC4); // InvokeSink WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{BEGIN_CP_INVOKESINK}}}","//{{{END_CP_INVOKESINK}}}"); WC4 = WC4.Replace("{{{ACTION}}}",a.Name); arglist = ""; foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="out") { arglist += ","+EmbeddedCGenerator.ToCTypeFromArg(arg); } } WC4 = WC4.Replace("{{{OUTARGLIST}}}",arglist); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{BEGIN_CP_INVOKESINK}}}",WC4); // Invoke WC4 = SourceCodeRepository.GetTextBetweenTags(WC3,"//{{{BEGIN_CP_INVOKE}}}","//{{{END_CP_INVOKE}}}"); WC4 = WC4.Replace("{{{ACTION}}}",a.Name); WC4 = WC4.Replace("{{{ONACTION}}}","On"+a.Name); WC4 = WC4.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); arglist = ""; foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { arglist += ","+EmbeddedCGenerator.ToCTypeFromArg(arg); } } WC4 = WC4.Replace("{{{INARGLIST}}}",arglist); WC3 = SourceCodeRepository.InsertTextBeforeTag(WC3,"//{{{BEGIN_CP_INVOKE}}}",WC4); } WC3 = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_INVOKE_TYPEDEF}}}","//{{{END_INVOKE_TYPEDEF}}}",WC3); WC3 = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CP_INVOKESINK}}}","//{{{END_CP_INVOKESINK}}}",WC3); WC3 = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CP_INVOKE}}}","//{{{END_CP_INVOKE}}}",WC3); WC3 = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CP_EVENTSINK}}}","//{{{END_CP_EVENTSINK}}}",WC3); WC3 = WC3.Replace("{{{SERVICE}}}",((ServiceGenerator.ServiceConfiguration)s.User).Name); WC3 = WC3.Replace("{{{URN}}}",s.ServiceURN); WC2 += WC3; } return(WC2); } public static string GetCPlusPlusAbstraction_H(UPnPDevice[] devices) { string WC = SourceCodeRepository.GetCPlusPlus_Template_H("UPnP"); string WC2; CodeProcessor sb = new CodeProcessor(new StringBuilder(),false); bool ok = false; bool CPok = false; foreach(UPnPDevice d in devices) { if (((ServiceGenerator.Configuration)d.User).ConfigType==ServiceGenerator.ConfigurationType.DEVICE) { WC2 = GetCPlusPlusAbstraction_H_FriendDevice(WC,d); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_Friends_BEGIN}}}",WC2); WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_GetDevice_BEGIN}}}","//{{{Manager_GetDevice_END}}}"); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_GetDevice_BEGIN}}}",WC2); WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_Device_BEGIN}}}","//{{{Manager_Device_END}}}"); WC2 = WC2.Replace("{{{DEVICE}}}","UPnP_Device_"+d.User2.ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_Device_BEGIN}}}",WC2); WC = GetCPlusPlusAbstraction_H_Device(WC,d); ok = true; } else { WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_SetControlPoint_BEGIN}}}","//{{{Manager_SetControlPoint_END}}}"); WC2 = WC2.Replace("{{{DEVICE}}}",d.User2.ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_SetControlPoint_BEGIN}}}",WC2); WC2 = SourceCodeRepository.GetTextBetweenTags(WC,"//{{{Manager_ProtectedCP_Stuff_BEGIN}}}","//{{{Manager_ProtectedCP_Stuff_END}}}"); WC2 = WC2.Replace("{{{DEVICE}}}",d.User2.ToString()); WC2 = WC2.Replace("{{{DEVICE_ID}}}",d.GetHashCode().ToString()); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{Manager_ProtectedCP_Stuff_BEGIN}}}",WC2); WC2 = GetCPlusPlusAbstraction_H_Device_CP(WC,d); WC = SourceCodeRepository.InsertTextBeforeTag(WC,"//{{{BEGIN_CP_SERVICE}}}",WC2); CPok = true; ok = true; } } WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_SetControlPoint_BEGIN}}}","//{{{Manager_SetControlPoint_END}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_ProtectedCP_Stuff_BEGIN}}}","//{{{Manager_ProtectedCP_Stuff_END}}}",WC); if (!CPok) { WC = SourceCodeRepository.RemoveAndClearTag("//{{{ControlPoint_Begin}}}","//{{{ControlPoint_End}}}",WC); } else { WC = SourceCodeRepository.RemoveTag("//{{{ControlPoint_Begin}}}","//{{{ControlPoint_End}}}",WC); } if (ok) { WC = SourceCodeRepository.RemoveAndClearTag("//{{{Device_Begin}}}","//{{{Device_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Service_Begin}}}","//{{{Service_End}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_Friends_BEGIN}}}","//{{{Manager_Friends_END}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_GetDevice_BEGIN}}}","{{{Manager_GetDevice_END}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{Manager_Device_BEGIN}}}","//{{{Manager_Device_END}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_CP_SERVICE}}}","//{{{END_CP_SERVICE}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_EVENT_TYPEDEF}}}","//{{{END_EVENT_TYPEDEF}}}",WC); WC = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_EVENT}}}","//{{{END_EVENT}}}",WC); sb.Append(WC); } return(sb.ToString()); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// AddOnResultResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Api.V2010.Account.Recording { public class AddOnResultResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Canceled = new StatusEnum("canceled"); public static readonly StatusEnum Completed = new StatusEnum("completed"); public static readonly StatusEnum Deleted = new StatusEnum("deleted"); public static readonly StatusEnum Failed = new StatusEnum("failed"); public static readonly StatusEnum InProgress = new StatusEnum("in-progress"); public static readonly StatusEnum Init = new StatusEnum("init"); public static readonly StatusEnum Processing = new StatusEnum("processing"); public static readonly StatusEnum Queued = new StatusEnum("queued"); } private static Request BuildFetchRequest(FetchAddOnResultOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Recordings/" + options.PathReferenceSid + "/AddOnResults/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch an instance of an AddOnResult /// </summary> /// <param name="options"> Fetch AddOnResult parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AddOnResult </returns> public static AddOnResultResource Fetch(FetchAddOnResultOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch an instance of an AddOnResult /// </summary> /// <param name="options"> Fetch AddOnResult parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AddOnResult </returns> public static async System.Threading.Tasks.Task<AddOnResultResource> FetchAsync(FetchAddOnResultOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch an instance of an AddOnResult /// </summary> /// <param name="pathReferenceSid"> The SID of the recording to which the result to fetch belongs </param> /// <param name="pathSid"> The unique string that identifies the resource to fetch </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AddOnResult </returns> public static AddOnResultResource Fetch(string pathReferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchAddOnResultOptions(pathReferenceSid, pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch an instance of an AddOnResult /// </summary> /// <param name="pathReferenceSid"> The SID of the recording to which the result to fetch belongs </param> /// <param name="pathSid"> The unique string that identifies the resource to fetch </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AddOnResult </returns> public static async System.Threading.Tasks.Task<AddOnResultResource> FetchAsync(string pathReferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchAddOnResultOptions(pathReferenceSid, pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadAddOnResultOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Recordings/" + options.PathReferenceSid + "/AddOnResults.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of results belonging to the recording /// </summary> /// <param name="options"> Read AddOnResult parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AddOnResult </returns> public static ResourceSet<AddOnResultResource> Read(ReadAddOnResultOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<AddOnResultResource>.FromJson("add_on_results", response.Content); return new ResourceSet<AddOnResultResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of results belonging to the recording /// </summary> /// <param name="options"> Read AddOnResult parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AddOnResult </returns> public static async System.Threading.Tasks.Task<ResourceSet<AddOnResultResource>> ReadAsync(ReadAddOnResultOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<AddOnResultResource>.FromJson("add_on_results", response.Content); return new ResourceSet<AddOnResultResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of results belonging to the recording /// </summary> /// <param name="pathReferenceSid"> The SID of the recording to which the result to read belongs </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AddOnResult </returns> public static ResourceSet<AddOnResultResource> Read(string pathReferenceSid, string pathAccountSid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAddOnResultOptions(pathReferenceSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of results belonging to the recording /// </summary> /// <param name="pathReferenceSid"> The SID of the recording to which the result to read belongs </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AddOnResult </returns> public static async System.Threading.Tasks.Task<ResourceSet<AddOnResultResource>> ReadAsync(string pathReferenceSid, string pathAccountSid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAddOnResultOptions(pathReferenceSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<AddOnResultResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<AddOnResultResource>.FromJson("add_on_results", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<AddOnResultResource> NextPage(Page<AddOnResultResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<AddOnResultResource>.FromJson("add_on_results", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<AddOnResultResource> PreviousPage(Page<AddOnResultResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<AddOnResultResource>.FromJson("add_on_results", response.Content); } private static Request BuildDeleteRequest(DeleteAddOnResultOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Recordings/" + options.PathReferenceSid + "/AddOnResults/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a result and purge all associated Payloads /// </summary> /// <param name="options"> Delete AddOnResult parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AddOnResult </returns> public static bool Delete(DeleteAddOnResultOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a result and purge all associated Payloads /// </summary> /// <param name="options"> Delete AddOnResult parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AddOnResult </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteAddOnResultOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a result and purge all associated Payloads /// </summary> /// <param name="pathReferenceSid"> The SID of the recording to which the result to delete belongs </param> /// <param name="pathSid"> The unique string that identifies the resource to delete </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AddOnResult </returns> public static bool Delete(string pathReferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteAddOnResultOptions(pathReferenceSid, pathSid){PathAccountSid = pathAccountSid}; return Delete(options, client); } #if !NET35 /// <summary> /// Delete a result and purge all associated Payloads /// </summary> /// <param name="pathReferenceSid"> The SID of the recording to which the result to delete belongs </param> /// <param name="pathSid"> The unique string that identifies the resource to delete </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AddOnResult </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathReferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteAddOnResultOptions(pathReferenceSid, pathSid){PathAccountSid = pathAccountSid}; return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a AddOnResultResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> AddOnResultResource object represented by the provided JSON </returns> public static AddOnResultResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<AddOnResultResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The status of the result /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public AddOnResultResource.StatusEnum Status { get; private set; } /// <summary> /// The SID of the Add-on to which the result belongs /// </summary> [JsonProperty("add_on_sid")] public string AddOnSid { get; private set; } /// <summary> /// The SID of the Add-on configuration /// </summary> [JsonProperty("add_on_configuration_sid")] public string AddOnConfigurationSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The date and time in GMT that the result was completed /// </summary> [JsonProperty("date_completed")] public DateTime? DateCompleted { get; private set; } /// <summary> /// The SID of the recording to which the AddOnResult resource belongs /// </summary> [JsonProperty("reference_sid")] public string ReferenceSid { get; private set; } /// <summary> /// A list of related resources identified by their relative URIs /// </summary> [JsonProperty("subresource_uris")] public Dictionary<string, string> SubresourceUris { get; private set; } private AddOnResultResource() { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace DNG.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System; using System.Collections; using System.Collections.Generic; using System.Runtime; using System.Threading; using System.Xml; using System.Xml.XPath; /// <summary> /// A navigator is a cursor over the nodes in a DOM, where each node is assigned a unique position. /// A node is a (navigator, position) pair. /// </summary> internal struct QueryNode { SeekableXPathNavigator node; long nodePosition; /// <summary> /// Create a query node from the given navigator and its current position /// </summary> /// <param name="node"></param> internal QueryNode(SeekableXPathNavigator node) { this.node = node; this.nodePosition = node.CurrentPosition; } /// <summary> /// Initialize using the given (node, position) pair /// </summary> #if NO internal QueryNode(SeekableXPathNavigator node, long nodePosition) { this.node = node; this.nodePosition = nodePosition; } #endif internal string LocalName { get { return this.node.GetLocalName(this.nodePosition); } } /// <summary> /// Return the node's name /// </summary> internal string Name { get { return this.node.GetName(this.nodePosition); } } /// <summary> /// Return the node's namespace /// </summary> internal string Namespace { get { return this.node.GetNamespace(this.nodePosition); } } /// <summary> /// Return this query node's underlying Node /// </summary> internal SeekableXPathNavigator Node { get { return this.node; } } /// <summary> /// /// </summary> internal long Position { get { return this.nodePosition; } } #if NO /// <summary> /// This node's type /// </summary> internal QueryNodeType Type { get { return QueryDataModel.GetNodeType(this.node.GetNodeType(this.nodePosition)); } } #endif /// <summary> /// This node's string value /// </summary> internal string Value { get { return this.node.GetValue(this.nodePosition); } } #if NO /// <summary> /// Raw xpath node type /// </summary> internal XPathNodeType XPathNodeType { get { return this.node.GetNodeType(this.nodePosition); } } #endif /// <summary> /// Move this node's navigator to its position /// </summary> /// <returns></returns> internal SeekableXPathNavigator MoveTo() { this.node.CurrentPosition = this.nodePosition; return this.node; } } internal enum NodeSequenceItemFlags : byte { None = 0x00, NodesetLast = 0x01, } // PERF, [....], Remove when generic sort works // Used to sort in document order #if NO internal class NodeSequenceItemObjectComparer : IComparer { internal NodeSequenceItemObjectComparer() { } public int Compare(object obj1, object obj2) { NodeSequenceItem item1 = (NodeSequenceItem)obj1; NodeSequenceItem item2 = (NodeSequenceItem)obj2; XmlNodeOrder order = item1.Node.Node.ComparePosition(item1.Node.Position, item2.Node.Position); int ret; switch(order) { case XmlNodeOrder.Before: ret = -1; break; case XmlNodeOrder.Same: ret = 0; break; case XmlNodeOrder.After: ret = 1; break; case XmlNodeOrder.Unknown: default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XPathException(SR.GetString(SR.QueryNotSortable)), TraceEventType.Critical); } return ret; } } // Used to sort in document order internal class NodeSequenceItemComparer : IComparer<NodeSequenceItem> { internal NodeSequenceItemComparer() { } public int Compare(NodeSequenceItem item1, NodeSequenceItem item2) { XmlNodeOrder order = item1.Node.Node.ComparePosition(item1.Node.Position, item2.Node.Position); int ret; switch(order) { case XmlNodeOrder.Before: ret = -1; break; case XmlNodeOrder.Same: ret = 0; break; case XmlNodeOrder.After: ret = 1; break; case XmlNodeOrder.Unknown: default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XPathException(SR.GetString(SR.QueryNotSortable)), TraceEventType.Critical); } return ret; } public bool Equals(NodeSequenceItem item1, NodeSequenceItem item2) { return Compare(item1, item2) == 0; } public int GetHashCode(NodeSequenceItem item) { return item.GetHashCode(); } } #endif // Used to sort in document order internal class QueryNodeComparer : IComparer<QueryNode> { public QueryNodeComparer() { } public int Compare(QueryNode item1, QueryNode item2) { XmlNodeOrder order = item1.Node.ComparePosition(item1.Position, item2.Position); int ret; switch (order) { case XmlNodeOrder.Before: ret = -1; break; case XmlNodeOrder.Same: ret = 0; break; case XmlNodeOrder.After: ret = 1; break; case XmlNodeOrder.Unknown: default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new XPathException(SR.GetString(SR.QueryNotSortable))); } return ret; } public bool Equals(QueryNode item1, QueryNode item2) { return Compare(item1, item2) == 0; } public int GetHashCode(QueryNode item) { return item.GetHashCode(); } } internal struct NodeSequenceItem { NodeSequenceItemFlags flags; QueryNode node; int position; int size; internal NodeSequenceItemFlags Flags { get { return this.flags; } set { this.flags = value; } } internal bool Last { get { return (0 != (NodeSequenceItemFlags.NodesetLast & this.flags)); } set { if (value) { this.flags |= NodeSequenceItemFlags.NodesetLast; } else { this.flags &= ~(NodeSequenceItemFlags.NodesetLast); } } } internal string LocalName { get { return this.node.LocalName; } } internal string Name { get { return this.node.Name; } } internal string Namespace { get { return this.node.Namespace; } } internal QueryNode Node { get { return this.node; } #if NO set { this.node = value; } #endif } internal int Position { get { return this.position; } #if NO set { this.position = value; } #endif } internal int Size { get { return this.size; } set { this.size = value; } } internal bool Compare(double dblVal, RelationOperator op) { return QueryValueModel.Compare(this.NumberValue(), dblVal, op); } internal bool Compare(string strVal, RelationOperator op) { return QueryValueModel.Compare(this.StringValue(), strVal, op); } internal bool Compare(ref NodeSequenceItem item, RelationOperator op) { return QueryValueModel.Compare(this.StringValue(), item.StringValue(), op); } internal bool Equals(string literal) { return QueryValueModel.Equals(this.StringValue(), literal); } internal bool Equals(double literal) { return (this.NumberValue() == literal); } internal SeekableXPathNavigator GetNavigator() { return this.node.MoveTo(); } internal long GetNavigatorPosition() { return this.node.Position; } internal double NumberValue() { return QueryValueModel.Double(this.StringValue()); } internal void Set(SeekableXPathNavigator node, int position, int size) { Fx.Assert(position > 0, ""); Fx.Assert(null != node, ""); this.node = new QueryNode(node); this.position = position; this.size = size; this.flags = NodeSequenceItemFlags.None; } internal void Set(QueryNode node, int position, int size) { Fx.Assert(position > 0, ""); this.node = node; this.position = position; this.size = size; this.flags = NodeSequenceItemFlags.None; } internal void Set(ref NodeSequenceItem item, int position, int size) { Fx.Assert(position > 0, ""); this.node = item.node; this.position = position; this.size = size; this.flags = item.flags; } internal void SetPositionAndSize(int position, int size) { this.position = position; this.size = size; this.flags &= ~NodeSequenceItemFlags.NodesetLast; } internal void SetSizeAndLast() { this.size = 1; this.flags |= NodeSequenceItemFlags.NodesetLast; } // This is not optimized right now // We may want to CACHE string values once they are computed internal string StringValue() { return this.node.Value; } } internal class NodeSequence { #if DEBUG // debugging aid. Because C# references do not have displayble numeric values, hard to deduce the // graph structure to see what opcode is connected to what static long nextUniqueId = 0; internal long uniqueID; #endif int count; internal static NodeSequence Empty = new NodeSequence(0); NodeSequenceItem[] items; NodeSequence next; ProcessingContext ownerContext; int position; internal int refCount; int sizePosition; static readonly QueryNodeComparer staticQueryNodeComparerInstance = new QueryNodeComparer(); internal NodeSequence() : this(8, null) { } internal NodeSequence(int capacity) : this(capacity, null) { } internal NodeSequence(int capacity, ProcessingContext ownerContext) { this.items = new NodeSequenceItem[capacity]; this.ownerContext = ownerContext; #if DEBUG this.uniqueID = Interlocked.Increment(ref NodeSequence.nextUniqueId); #endif } #if NO internal NodeSequence(int capacity, ProcessingContext ownerContext, XPathNodeIterator iter) : this(capacity, ownerContext) { while(iter.MoveNext()) { SeekableXPathNavigator nav = iter.Current as SeekableXPathNavigator; if(nav != null) { Add(nav); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryMustBeSeekable)), TraceEventType.Critical); } } } #endif internal int Count { get { return this.count; } #if NO set { Fx.Assert(value >= 0 && value <= this.count, ""); this.count = value; } #endif } internal NodeSequenceItem this[int index] { get { return this.items[index]; } } internal NodeSequenceItem[] Items { get { return this.items; } } internal bool IsNotEmpty { get { return (this.count > 0); } } internal string LocalName { get { if (this.count > 0) { return this.items[0].LocalName; } return string.Empty; } } internal string Name { get { if (this.count > 0) { return this.items[0].Name; } return string.Empty; } } internal string Namespace { get { if (this.count > 0) { return this.items[0].Namespace; } return string.Empty; } } internal NodeSequence Next { get { return this.next; } set { this.next = value; } } internal ProcessingContext OwnerContext { get { return this.ownerContext; } set { this.ownerContext = value; } } #if NO internal int NodesetStartAt { get { return -this.sizePosition; } } #endif internal void Add(XPathNodeIterator iter) { while (iter.MoveNext()) { SeekableXPathNavigator nav = iter.Current as SeekableXPathNavigator; if (nav != null) { this.Add(nav); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryMustBeSeekable))); } } } internal void Add(SeekableXPathNavigator node) { Fx.Assert(this.items.Length > 0, ""); if (this.count == this.items.Length) { this.Grow(this.items.Length * 2); } this.position++; this.items[this.count++].Set(node, this.position, this.sizePosition); } internal void Add(QueryNode node) { Fx.Assert(this.items.Length > 0, ""); if (this.count == this.items.Length) { this.Grow(this.items.Length * 2); } this.position++; this.items[this.count++].Set(node, this.position, this.sizePosition); } internal void Add(ref NodeSequenceItem item) { Fx.Assert(this.items.Length > 0, ""); if (this.count == this.items.Length) { this.Grow(this.items.Length * 2); } this.position++; this.items[this.count++].Set(ref item, this.position, this.sizePosition); } internal void AddCopy(ref NodeSequenceItem item, int size) { Fx.Assert(this.items.Length > 0, ""); if (this.count == this.items.Length) { this.Grow(this.items.Length * 2); } this.items[this.count] = item; this.items[this.count++].Size = size; } internal void AddCopy(ref NodeSequenceItem item) { Fx.Assert(this.items.Length > 0, ""); if (this.count == this.items.Length) { this.Grow(this.items.Length * 2); } this.items[this.count++] = item; } #if NO internal void Add(NodeSequence seq) { int newCount = this.count + seq.count; if (newCount > this.items.Length) { // We are going to need room. Grow the array int growTo = this.items.Length * 2; this.Grow(newCount > growTo ? newCount : growTo); } Array.Copy(seq.items, 0, this.items, this.count, seq.count); this.count += seq.count; } #endif internal bool CanReuse(ProcessingContext context) { return (this.count == 1 && this.ownerContext == context && this.refCount == 1); } internal void Clear() { this.count = 0; } internal void Reset(NodeSequence nextSeq) { this.count = 0; this.refCount = 0; this.next = nextSeq; } internal bool Compare(double val, RelationOperator op) { for (int i = 0; i < this.count; ++i) { if (this.items[i].Compare(val, op)) { return true; } } return false; } internal bool Compare(string val, RelationOperator op) { Fx.Assert(null != val, ""); for (int i = 0; i < this.count; ++i) { if (this.items[i].Compare(val, op)) { return true; } } return false; } internal bool Compare(ref NodeSequenceItem item, RelationOperator op) { for (int i = 0; i < this.count; ++i) { if (this.items[i].Compare(ref item, op)) { return true; } } return false; } internal bool Compare(NodeSequence sequence, RelationOperator op) { Fx.Assert(null != sequence, ""); for (int i = 0; i < sequence.count; ++i) { if (this.Compare(ref sequence.items[i], op)) { return true; } } return false; } #if NO void EnsureCapacity() { if (this.count == this.items.Length) { this.Grow(this.items.Length * 2); } } void EnsureCapacity(int capacity) { if (capacity > this.items.Length) { int newSize = this.items.Length * 2; this.Grow(newSize > capacity ? newSize : capacity); } } #endif internal bool Equals(string val) { Fx.Assert(null != val, ""); for (int i = 0; i < this.count; ++i) { if (this.items[i].Equals(val)) { return true; } } return false; } internal bool Equals(double val) { for (int i = 0; i < this.count; ++i) { if (this.items[i].Equals(val)) { return true; } } return false; } internal static int GetContextSize(NodeSequence sequence, int itemIndex) { Fx.Assert(null != sequence, ""); int size = sequence.items[itemIndex].Size; if (size <= 0) { return sequence.items[-size].Size; } return size; } void Grow(int newSize) { NodeSequenceItem[] newItems = new NodeSequenceItem[newSize]; if (this.items != null) { Array.Copy(this.items, newItems, this.items.Length); } this.items = newItems; } /// <summary> /// Merge all nodesets in this sequence... turning it into a sequence with a single nodeset /// This is done by simply renumbering all positions.. and clearing the nodeset flag /// </summary> internal void Merge() { Merge(true); } internal void Merge(bool renumber) { if (this.count == 0) { return; } if (renumber) { RenumberItems(); } } #if NO // Assumes list is flat and sorted internal void RemoveDuplicates() { if(this.count < 2) { return; } int last = 0; for(int next = 1; next < this.count; ++next) { if(Comparer.Compare(this.items[last], this.items[next]) != 0) { ++last; if(last != next) { this.items[last] = this.items[next]; } } } this.count = last + 1; RenumberItems(); } #endif void RenumberItems() { if (this.count > 0) { for (int i = 0; i < this.count; ++i) { this.items[i].SetPositionAndSize(i + 1, this.count); } this.items[this.count - 1].Flags |= NodeSequenceItemFlags.NodesetLast; } } #if NO internal void SortNodes() { this.Merge(false); // PERF, [....], make this work //Array.Sort<NodeSequenceItem>(this.items, 0, this.count, NodeSequence.Comparer); Array.Sort(this.items, 0, this.count, NodeSequence.ObjectComparer); RenumberItems(); } #endif internal void StartNodeset() { this.position = 0; this.sizePosition = -this.count; } internal void StopNodeset() { switch (this.position) { default: int sizePos = -this.sizePosition; this.items[sizePos].Size = this.position; this.items[sizePos + this.position - 1].Last = true; break; case 0: break; case 1: this.items[-this.sizePosition].SetSizeAndLast(); break; } } internal string StringValue() { if (this.count > 0) { return this.items[0].StringValue(); } return string.Empty; } /// <summary> /// Union algorithm: /// 1. Add both sequences of items to a newly created sequence /// 2. Sort the items based on document position /// 3. Renumber positions in this new unionized sequence /// </summary> internal NodeSequence Union(ProcessingContext context, NodeSequence otherSeq) { NodeSequence seq = context.CreateSequence(); SortedBuffer<QueryNode, QueryNodeComparer> buff = new SortedBuffer<QueryNode, QueryNodeComparer>(staticQueryNodeComparerInstance); for (int i = 0; i < this.count; ++i) buff.Add(this.items[i].Node); for (int i = 0; i < otherSeq.count; ++i) buff.Add(otherSeq.items[i].Node); for (int i = 0; i < buff.Count; ++i) seq.Add(buff[i]); seq.RenumberItems(); return seq; /* // PERF, [....], I think we can do the merge ourselves and avoid the sort. // Need to verify that the sequences are always in document order. for(int i = 0; i < this.count; ++i) { seq.AddCopy(ref this.items[i]); } for(int i = 0; i < otherSeq.count; ++i) { seq.AddCopy(ref otherSeq.items[i]); } seq.SortNodes(); seq.RemoveDuplicates(); return seq; */ } #region IQueryBufferPool Members #if NO public void Reset() { this.count = 0; this.Trim(); } public void Trim() { if (this.count == 0) { this.items = null; } else if (this.count < this.items.Length) { NodeSequenceItem[] newItems = new NodeSequenceItem[this.count]; Array.Copy(this.items, newItems, this.count); this.items = newItems; } } #endif #endregion } internal class NodeSequenceIterator : XPathNodeIterator { // Shared NodeSequence seq; // Instance NodeSequenceIterator data; int index; SeekableXPathNavigator nav; // the navigator that will be used by this iterator internal NodeSequenceIterator(NodeSequence seq) : base() { this.data = this; this.seq = seq; } internal NodeSequenceIterator(NodeSequenceIterator iter) { this.data = iter.data; this.index = iter.index; } public override int Count { get { return this.data.seq.Count; } } public override XPathNavigator Current { get { if (this.index == 0) { #pragma warning suppress 56503 // [....], postponing the public change throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryContextNotSupportedInSequences))); } if (this.index > this.data.seq.Count) { #pragma warning suppress 56503 // [....], postponing the public change throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.QueryAfterNodes))); } // // From MSDN - the public contract of .Current // You can use the properties of the XPathNavigator to return information on the current node. // However, the XPathNavigator cannot be used to move away from the selected node set. // Doing so could invalidate the state of the navigator. Alternatively, you can clone the XPathNavigator. // The cloned XPathNavigator can then be moved away from the selected node set. This is an application level decision. // Providing this functionality may effect the performance of the XPath query. // // Return the navigator as is - where it is positioned. If the user moved the navigator, then the user is // hosed. We will make no guarantees - and are not required to. Doing so would force cloning, which is expensive. // // NOTE: .Current can get called repeatedly, so its activity should be relative CHEAP. // No cloning, copying etc. All that work should be done in MoveNext() return this.nav; } } public override int CurrentPosition { get { return this.index; } } internal void Clear() { this.data.seq = null; this.nav = null; } public override XPathNodeIterator Clone() { return new NodeSequenceIterator(this); } public override IEnumerator GetEnumerator() { return new NodeSequenceEnumerator(this); } public override bool MoveNext() { if (null == this.data.seq) { // User is trying to use an iterator that is out of scope. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.QueryIteratorOutOfScope))); } if (this.index < this.data.seq.Count) { if (null == this.nav) { // We haven't aquired the navigator we will use for this iterator yet. this.nav = (SeekableXPathNavigator)this.data.seq[this.index].GetNavigator().Clone(); } else { this.nav.CurrentPosition = this.data.seq[this.index].GetNavigatorPosition(); } this.index++; return true; } this.index++; this.nav = null; return false; } public void Reset() { this.nav = null; this.index = 0; } } internal class NodeSequenceEnumerator : IEnumerator { NodeSequenceIterator iter; internal NodeSequenceEnumerator(NodeSequenceIterator iter) { this.iter = new NodeSequenceIterator(iter); Reset(); } public object Current { get { if (this.iter.CurrentPosition == 0) { #pragma warning suppress 56503 // [....], postponing the public change throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.QueryBeforeNodes))); } if (this.iter.CurrentPosition > this.iter.Count) { #pragma warning suppress 56503 // [....], postponing the public change throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.QueryAfterNodes))); } return this.iter.Current; } } public bool MoveNext() { return iter.MoveNext(); } public void Reset() { this.iter.Reset(); } } internal class SafeNodeSequenceIterator : NodeSequenceIterator, IDisposable { ProcessingContext context; int disposed; NodeSequence seq; public SafeNodeSequenceIterator(NodeSequence seq, ProcessingContext context) : base(seq) { this.context = context; this.seq = seq; Interlocked.Increment(ref this.seq.refCount); this.context.Processor.AddRef(); } public override XPathNodeIterator Clone() { return new SafeNodeSequenceIterator(this.seq, this.context); } public void Dispose() { if (Interlocked.CompareExchange(ref this.disposed, 1, 0) == 0) { QueryProcessor processor = this.context.Processor; this.context.ReleaseSequence(this.seq); this.context.Processor.Matcher.ReleaseProcessor(processor); } } } internal struct NodesetIterator { int index; int indexStart; NodeSequence sequence; NodeSequenceItem[] items; internal NodesetIterator(NodeSequence sequence) { Fx.Assert(null != sequence, ""); this.sequence = sequence; this.items = sequence.Items; this.index = -1; this.indexStart = -1; } internal int Index { get { return this.index; } } internal bool NextItem() { if (-1 == this.index) { this.index = this.indexStart; return true; } if (this.items[this.index].Last) { return false; } this.index++; return true; } internal bool NextNodeset() { this.indexStart = this.index + 1; this.index = -1; return (this.indexStart < this.sequence.Count); } } internal struct NodeSequenceBuilder { ProcessingContext context; NodeSequence sequence; internal NodeSequenceBuilder(ProcessingContext context, NodeSequence sequence) { this.context = context; this.sequence = sequence; } internal NodeSequenceBuilder(ProcessingContext context) : this(context, null) { } #if NO internal NodeSequenceBuilder(NodeSequence sequence) : this(sequence.OwnerContext, sequence) { } #endif internal NodeSequence Sequence { get { return (null != this.sequence) ? this.sequence : NodeSequence.Empty; } set { this.sequence = value; } } internal void Add(ref NodeSequenceItem item) { if (null == this.sequence) { this.sequence = this.context.CreateSequence(); this.sequence.StartNodeset(); } this.sequence.Add(ref item); } internal void EndNodeset() { if (null != this.sequence) { this.sequence.StopNodeset(); } } internal void StartNodeset() { if (null != this.sequence) { this.sequence.StartNodeset(); } } } }
//--------------------------------------------------------------------------- // // File: HtmlLexicalAnalyzer.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Lexical analyzer for Html-to-Xaml converter // //--------------------------------------------------------------------------- using System; using System.IO; using System.Diagnostics; using System.Collections; using System.Text; namespace MailSecure.FormatConverter { /// <summary> /// lexical analyzer class /// recognizes tokens as groups of characters separated by arbitrary amounts of whitespace /// also classifies tokens according to type /// </summary> internal class HtmlLexicalAnalyzer { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// initializes the _inputStringReader member with the string to be read /// also sets initial values for _nextCharacterCode and _nextTokenType /// </summary> /// <param name="inputTextString"> /// text string to be parsed for xml content /// </param> internal HtmlLexicalAnalyzer(string inputTextString) { _inputStringReader = new StringReader(inputTextString); _nextCharacterCode = 0; _nextCharacter = ' '; _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; _previousCharacter = ' '; _ignoreNextWhitespace = true; _nextToken = new StringBuilder(100); _nextTokenType = HtmlTokenType.Text; // read the first character so we have some value for the NextCharacter property this.GetNextCharacter(); } #endregion Constructors // --------------------------------------------------------------------- // // Internal methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// retrieves next recognizable token from input string /// and identifies its type /// if no valid token is found, the output parameters are set to null /// if end of stream is reached without matching any token, token type /// paramter is set to EOF /// </summary> internal void GetNextContentToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } if (this.IsAtTagStart) { this.GetNextCharacter(); if (this.NextCharacter == '/') { _nextToken.Append("</"); _nextTokenType = HtmlTokenType.ClosingTagStart; // advance this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespaces after closing tags are significant } else { _nextTokenType = HtmlTokenType.OpeningTagStart; _nextToken.Append("<"); _ignoreNextWhitespace = true; // Whitespaces after opening tags are insignificant } } else if (this.IsAtDirectiveStart) { // either a comment or CDATA this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // cdata this.ReadDynamicContent(); } else if (_lookAheadCharacter == '-') { this.ReadComment(); } else { // neither a comment nor cdata, should be something like DOCTYPE // skip till the next tag ender this.ReadUnknownDirective(); } } else { // read text content, unless you encounter a tag _nextTokenType = HtmlTokenType.Text; while (!this.IsAtTagStart && !this.IsAtEndOfStream && !this.IsAtDirectiveStart) { if (this.NextCharacter == '<' && !this.IsNextCharacterEntity && _lookAheadCharacter == '?') { // ignore processing directive this.SkipProcessingDirective(); } else { if (this.NextCharacter <= ' ') { // Respect xml:preserve or its equivalents for whitespace processing if (_ignoreNextWhitespace) { // Ignore repeated whitespaces } else { // Treat any control character sequence as one whitespace _nextToken.Append(' '); } _ignoreNextWhitespace = true; // and keep ignoring the following whitespaces } else { _nextToken.Append(this.NextCharacter); _ignoreNextWhitespace = false; } this.GetNextCharacter(); } } } } /// <summary> /// Unconditionally returns a token which is one of: TagEnd, EmptyTagEnd, Name, Atom or EndOfStream /// Does not guarantee token reader advancing. /// </summary> internal void GetNextTagToken() { _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } this.SkipWhiteSpace(); if (this.NextCharacter == '>' && !this.IsNextCharacterEntity) { // &gt; should not end a tag, so make sure it's not an entity _nextTokenType = HtmlTokenType.TagEnd; _nextToken.Append('>'); this.GetNextCharacter(); // Note: _ignoreNextWhitespace must be set appropriately on tag start processing } else if (this.NextCharacter == '/' && _lookAheadCharacter == '>') { // could be start of closing of empty tag _nextTokenType = HtmlTokenType.EmptyTagEnd; _nextToken.Append("/>"); this.GetNextCharacter(); this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespace after no-scope tags are sifnificant } else if (IsGoodForNameStart(this.NextCharacter)) { _nextTokenType = HtmlTokenType.Name; // starts a name // we allow character entities here // we do not throw exceptions here if end of stream is encountered // just stop and return whatever is in the token // if the parser is not expecting end of file after this it will call // the get next token function and throw an exception while (IsGoodForName(this.NextCharacter) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } else { // Unexpected type of token for a tag. Reprot one character as Atom, expecting that HtmlParser will ignore it. _nextTokenType = HtmlTokenType.Atom; _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns equal sign token. Even if there is no /// real equal sign in the stream, it behaves as if it were there. /// Does not guarantee token reader advancing. /// </summary> internal void GetNextEqualSignToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; _nextToken.Append('='); _nextTokenType = HtmlTokenType.EqualSign; this.SkipWhiteSpace(); if (this.NextCharacter == '=') { // '=' is not in the list of entities, so no need to check for entities here this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns an atomic value for an attribute /// Even if there is no appropriate token it returns Atom value /// Does not guarantee token reader advancing. /// </summary> internal void GetNextAtomToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; this.SkipWhiteSpace(); _nextTokenType = HtmlTokenType.Atom; if ((this.NextCharacter == '\'' || this.NextCharacter == '"') && !this.IsNextCharacterEntity) { char startingQuote = this.NextCharacter; this.GetNextCharacter(); // Consume all characters between quotes while (!(this.NextCharacter == startingQuote && !this.IsNextCharacterEntity) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } if (this.NextCharacter == startingQuote) { this.GetNextCharacter(); } // complete the quoted value // NOTE: our recovery here is different from IE's // IE keeps reading until it finds a closing quote or end of file // if end of file, it treats current value as text // if it finds a closing quote at any point within the text, it eats everything between the quotes // TODO: Suggestion: // however, we could stop when we encounter end of file or an angle bracket of any kind // and assume there was a quote there // so the attribute value may be meaningless but it is never treated as text } else { while (!this.IsAtEndOfStream && !Char.IsWhiteSpace(this.NextCharacter) && this.NextCharacter != '>') { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties internal HtmlTokenType NextTokenType { get { return _nextTokenType; } } internal string NextToken { get { return _nextToken.ToString(); } } #endregion Internal Properties // --------------------------------------------------------------------- // // Private methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Advances a reading position by one character code /// and reads the next availbale character from a stream. /// This character becomes available as NextCharacter property. /// </summary> /// <remarks> /// Throws InvalidOperationException if attempted to be called on EndOfStream /// condition. /// </remarks> private void GetNextCharacter() { if (_nextCharacterCode == -1) { throw new InvalidOperationException("GetNextCharacter method called at the end of a stream"); } _previousCharacter = _nextCharacter; _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; // next character not an entity as of now _isNextCharacterEntity = false; this.ReadLookAheadCharacter(); if (_nextCharacter == '&') { if (_lookAheadCharacter == '#') { // numeric entity - parse digits - &#DDDDD; int entityCode; entityCode = 0; this.ReadLookAheadCharacter(); // largest numeric entity is 7 characters for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++) { entityCode = 10 * entityCode + (_lookAheadCharacterCode - (int)'0'); this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // correct format - advance this.ReadLookAheadCharacter(); _nextCharacterCode = entityCode; // if this is out of range it will set the character to '?' _nextCharacter = (char)_nextCharacterCode; // as far as we are concerned, this is an entity _isNextCharacterEntity = true; } else { // not an entity, set next character to the current lookahread character // we would have eaten up some digits _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } else if (Char.IsLetter(_lookAheadCharacter)) { // entity is written as a string string entity = ""; // maximum length of string entities is 10 characters for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++) { entity += _lookAheadCharacter; this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // advance this.ReadLookAheadCharacter(); if (HtmlSchema.IsEntity(entity)) { _nextCharacter = HtmlSchema.EntityCharacterValue(entity); _nextCharacterCode = (int)_nextCharacter; _isNextCharacterEntity = true; } else { // just skip the whole thing - invalid entity // move on to the next character _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); // not an entity _isNextCharacterEntity = false; } } else { // skip whatever we read after the ampersand // set next character and move on _nextCharacter = _lookAheadCharacter; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } } } private void ReadLookAheadCharacter() { if (_lookAheadCharacterCode != -1) { _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; } } /// <summary> /// skips whitespace in the input string /// leaves the first non-whitespace character available in the NextCharacter property /// this may be the end-of-file character, it performs no checking /// </summary> private void SkipWhiteSpace() { // TODO: handle character entities while processing comments, cdata, and directives // TODO: SUGGESTION: we could check if lookahead and previous characters are entities also while (true) { if (_nextCharacter == '<' && (_lookAheadCharacter == '?' || _lookAheadCharacter == '!')) { this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // Skip CDATA block and DTDs(?) while (!this.IsAtEndOfStream && !(_previousCharacter == ']' && _nextCharacter == ']' && _lookAheadCharacter == '>')) { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } else { // Skip processing instruction, comments while (!this.IsAtEndOfStream && _nextCharacter != '>') { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } } if (!Char.IsWhiteSpace(this.NextCharacter)) { break; } this.GetNextCharacter(); } } /// <summary> /// checks if a character can be used to start a name /// if this check is true then the rest of the name can be read /// </summary> /// <param name="character"> /// character value to be checked /// </param> /// <returns> /// true if the character can be the first character in a name /// false otherwise /// </returns> private bool IsGoodForNameStart(char character) { return character == '_' || Char.IsLetter(character); } /// <summary> /// checks if a character can be used as a non-starting character in a name /// uses the IsExtender and IsCombiningCharacter predicates to see /// if a character is an extender or a combining character /// </summary> /// <param name="character"> /// character to be checked for validity in a name /// </param> /// <returns> /// true if the character can be a valid part of a name /// </returns> private bool IsGoodForName(char character) { // we are not concerned with escaped characters in names // we assume that character entities are allowed as part of a name return this.IsGoodForNameStart(character) || character == '.' || character == '-' || character == ':' || Char.IsDigit(character) || IsCombiningCharacter(character) || IsExtender(character); } /// <summary> /// identifies a character as being a combining character, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of combining characters in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is a combining character, false otherwise /// </returns> private bool IsCombiningCharacter(char character) { // TODO: put actual code with checks against all combining characters here return false; } /// <summary> /// identifies a character as being an extender, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of extenders in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is an extender, false otherwise /// </returns> private bool IsExtender(char character) { // TODO: put actual code with checks against all extenders here return false; } /// <summary> /// skips dynamic content starting with '<![' and ending with ']>' /// </summary> private void ReadDynamicContent() { // verify that we are at dynamic content, which may include CDATA Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '['); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance twice, once to get the lookahead character and then to reach the start of the cdata this.GetNextCharacter(); this.GetNextCharacter(); // NOTE: 10/12/2004: modified this function to check when called if's reading CDATA or something else // some directives may start with a <![ and then have some data and they will just end with a ]> // this function is modified to stop at the sequence ]> and not ]]> // this means that CDATA and anything else expressed in their own set of [] within the <! [...]> // directive cannot contain a ]> sequence. However it is doubtful that cdata could contain such // sequence anyway, it probably stops at the first ] while (!(_nextCharacter == ']' && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } /// <summary> /// skips comments starting with '<!-' and ending with '-->' /// NOTE: 10/06/2004: processing changed, will now skip anything starting with /// the "<!-" sequence and ending in "!>" or "->", because in practice many html pages do not /// use the full comment specifying conventions /// </summary> private void ReadComment() { // verify that we are at a comment Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '-'); // Initialize a token _nextTokenType = HtmlTokenType.Comment; _nextToken.Length = 0; // advance to the next character, so that to be at the start of comment value this.GetNextCharacter(); // get first '-' this.GetNextCharacter(); // get second '-' this.GetNextCharacter(); // get first character of comment content while (true) { // Read text until end of comment // Note that in many actual html pages comments end with "!>" (while xml standard is "-->") while (!this.IsAtEndOfStream && !(_nextCharacter == '-' && _lookAheadCharacter == '-' || _nextCharacter == '!' && _lookAheadCharacter == '>')) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } // Finish comment reading this.GetNextCharacter(); if (_previousCharacter == '-' && _nextCharacter == '-' && _lookAheadCharacter == '>') { // Standard comment end. Eat it and exit the loop this.GetNextCharacter(); // get '>' break; } else if (_previousCharacter == '!' && _nextCharacter == '>') { // Nonstandard but possible comment end - '!>'. Exit the loop break; } else { // Not an end. Save character and continue continue reading _nextToken.Append(_previousCharacter); continue; } } // Read end of comment combination if (_nextCharacter == '>') { this.GetNextCharacter(); } } /// <summary> /// skips past unknown directives that start with "<!" but are not comments or Cdata /// ignores content of such directives until the next ">" character /// applies to directives such as DOCTYPE, etc that we do not presently support /// </summary> private void ReadUnknownDirective() { // verify that we are at an unknown directive Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && !(_lookAheadCharacter == '-' || _lookAheadCharacter == '[')); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance to the next character this.GetNextCharacter(); // skip to the first tag end we find while (!(_nextCharacter == '>' && !IsNextCharacterEntity) && !this.IsAtEndOfStream) { this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance past the tag end this.GetNextCharacter(); } } /// <summary> /// skips processing directives starting with the characters '<?' and ending with '?>' /// NOTE: 10/14/2004: IE also ends processing directives with a />, so this function is /// being modified to recognize that condition as well /// </summary> private void SkipProcessingDirective() { // verify that we are at a processing directive Debug.Assert(_nextCharacter == '<' && _lookAheadCharacter == '?'); // advance twice, once to get the lookahead character and then to reach the start of the drective this.GetNextCharacter(); this.GetNextCharacter(); while (!((_nextCharacter == '?' || _nextCharacter == '/') && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance // we don't need to check for entities here because '?' is not an entity // and even though > is an entity there is no entity processing when reading lookahead character this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } #endregion Private Methods // --------------------------------------------------------------------- // // Private Properties // // --------------------------------------------------------------------- #region Private Properties private char NextCharacter { get { return _nextCharacter; } } private bool IsAtEndOfStream { get { return _nextCharacterCode == -1; } } private bool IsAtTagStart { get { return _nextCharacter == '<' && (_lookAheadCharacter == '/' || IsGoodForNameStart(_lookAheadCharacter)) && !_isNextCharacterEntity; } } private bool IsAtTagEnd { // check if at end of empty tag or regular tag get { return (_nextCharacter == '>' || (_nextCharacter == '/' && _lookAheadCharacter == '>')) && !_isNextCharacterEntity; } } private bool IsAtDirectiveStart { get { return (_nextCharacter == '<' && _lookAheadCharacter == '!' && !this.IsNextCharacterEntity); } } private bool IsNextCharacterEntity { // check if next character is an entity get { return _isNextCharacterEntity; } } #endregion Private Properties // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // string reader which will move over input text private StringReader _inputStringReader; // next character code read from input that is not yet part of any token // and the character it represents private int _nextCharacterCode; private char _nextCharacter; private int _lookAheadCharacterCode; private char _lookAheadCharacter; private char _previousCharacter; private bool _ignoreNextWhitespace; private bool _isNextCharacterEntity; // store token and type in local variables before copying them to output parameters StringBuilder _nextToken; HtmlTokenType _nextTokenType; #endregion Private Fields } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractVector128Int161() { var test = new ExtractVector128Test__ExtractVector128Int161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ExtractVector128Test__ExtractVector128Int161 { private struct TestStruct { public Vector256<Int16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ExtractVector128Test__ExtractVector128Int161 testClass) { var result = Avx2.ExtractVector128(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar; private Vector256<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static ExtractVector128Test__ExtractVector128Int161() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ExtractVector128Test__ExtractVector128Int161() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ExtractVector128( Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ExtractVector128( Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ExtractVector128( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ExtractVector128( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr); var result = Avx2.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractVector128Test__ExtractVector128Int161(); var result = Avx2.ExtractVector128(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ExtractVector128(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ExtractVector128(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != firstOp[8]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((result[i] != firstOp[i + 8])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ExtractVector128)}<Int16>(Vector256<Int16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using System.Security.Policy; using System.Text; using System.Threading; using System.Xml; using OpenMetaverse; using log4net; using Nini.Config; using Amib.Threading; using OpenSim.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.Api.Runtime; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Region.ScriptEngine.Interfaces; namespace OpenSim.Region.ScriptEngine.Shared.Instance { public class ScriptInstance : MarshalByRefObject, IScriptInstance { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool StatePersistedHere { get { return m_AttachedAvatar == UUID.Zero; } } /// <summary> /// The current work item if an event for this script is running or waiting to run, /// </summary> /// <remarks> /// Null if there is no running or waiting to run event. Must be changed only under an EventQueue lock. /// </remarks> private IScriptWorkItem m_CurrentWorkItem; private IScript m_Script; private DetectParams[] m_DetectParams; private bool m_TimerQueued; private DateTime m_EventStart; private bool m_InEvent; private string m_assemblyPath; private string m_dataPath; private string m_CurrentEvent = String.Empty; private bool m_InSelfDelete; private int m_MaxScriptQueue; private bool m_SaveState; private int m_ControlEventsInQueue; private int m_LastControlLevel; private bool m_CollisionInQueue; // The following is for setting a minimum delay between events private double m_minEventDelay; private long m_eventDelayTicks; private long m_nextEventTimeTicks; private bool m_startOnInit = true; private UUID m_AttachedAvatar; private StateSource m_stateSource; private bool m_postOnRez; private bool m_startedFromSavedState; private UUID m_CurrentStateHash; private UUID m_RegionID; public int DebugLevel { get; set; } public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get; set; } private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>(); public Object[] PluginData = new Object[0]; /// <summary> /// Used by llMinEventDelay to suppress events happening any faster than this speed. /// This currently restricts all events in one go. Not sure if each event type has /// its own check so take the simple route first. /// </summary> public double MinEventDelay { get { return m_minEventDelay; } set { if (value > 0.001) m_minEventDelay = value; else m_minEventDelay = 0.0; m_eventDelayTicks = (long)(m_minEventDelay * 10000000L); m_nextEventTimeTicks = DateTime.Now.Ticks; } } public bool Running { get; set; } public bool Suspended { get { return m_Suspended; } set { // Need to do this inside a lock in order to avoid races with EventProcessor() lock (m_Script) { bool wasSuspended = m_Suspended; m_Suspended = value; if (wasSuspended && !m_Suspended) { lock (EventQueue) { // Need to place ourselves back in a work item if there are events to process if (EventQueue.Count > 0 && Running && !ShuttingDown) m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } } } private bool m_Suspended; public bool ShuttingDown { get; set; } public string State { get; set; } public IScriptEngine Engine { get; private set; } public UUID AppDomain { get; set; } public SceneObjectPart Part { get; private set; } public string PrimName { get; private set; } public string ScriptName { get; private set; } public UUID ItemID { get; private set; } public UUID ObjectID { get { return Part.UUID; } } public uint LocalID { get { return Part.LocalId; } } public UUID RootObjectID { get { return Part.ParentGroup.UUID; } } public uint RootLocalID { get { return Part.ParentGroup.LocalId; } } public UUID AssetID { get; private set; } public Queue EventQueue { get; private set; } public long EventsQueued { get { lock (EventQueue) return EventQueue.Count; } } public long EventsProcessed { get; private set; } public int StartParam { get; set; } public TaskInventoryItem ScriptTask { get; private set; } public DateTime TimeStarted { get; private set; } public long MeasurementPeriodTickStart { get; private set; } public long MeasurementPeriodExecutionTime { get; private set; } public static readonly long MaxMeasurementPeriod = 30 * TimeSpan.TicksPerMinute; private bool m_coopTermination; private EventWaitHandle m_coopSleepHandle; public void ClearQueue() { m_TimerQueued = false; EventQueue.Clear(); } public ScriptInstance( IScriptEngine engine, SceneObjectPart part, TaskInventoryItem item, int startParam, bool postOnRez, int maxScriptQueue) { State = "default"; EventQueue = new Queue(32); Engine = engine; Part = part; ScriptTask = item; // This is currently only here to allow regression tests to get away without specifying any inventory // item when they are testing script logic that doesn't require an item. if (ScriptTask != null) { ScriptName = ScriptTask.Name; ItemID = ScriptTask.ItemID; AssetID = ScriptTask.AssetID; } PrimName = part.ParentGroup.Name; StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_postOnRez = postOnRez; m_AttachedAvatar = Part.ParentGroup.AttachedAvatar; m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID; m_SaveState = StatePersistedHere; // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Instantiated script instance {0} (id {1}) in part {2} (id {3}) in object {4} attached avatar {5} in {6}", // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, m_AttachedAvatar, Engine.World.Name); } /// <summary> /// Load the script from an assembly into an AppDomain. /// </summary> /// <param name='dom'></param> /// <param name='assembly'></param> /// <param name='dataPath'> /// Path for all script associated data (state, etc.). In a multi-region set up /// with all scripts loading into the same AppDomain this may not be the same place as the DLL itself. /// </param> /// <param name='stateSource'></param> /// <returns>false if load failed, true if suceeded</returns> public bool Load( IScript script, EventWaitHandle coopSleepHandle, string assemblyPath, string dataPath, StateSource stateSource, bool coopTermination) { m_Script = script; m_coopSleepHandle = coopSleepHandle; m_assemblyPath = assemblyPath; m_dataPath = dataPath; m_stateSource = stateSource; m_coopTermination = coopTermination; ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle); } try { foreach (KeyValuePair<string,IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error initializing script instance. Exception {6}{7}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace); return false; } // For attachments, XEngine saves the state into a .state file when XEngine.SetXMLState() is called. string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state"); if (File.Exists(savedState)) { // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Found state for script {0} for {1} ({2}) at {3} in {4}", // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name); string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = Encoding.UTF8.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(Engine, LocalID, ItemID, ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (!Running) m_startOnInit = false; Running = false; // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } // If this script is in an attachment then we no longer need the state file. if (!StatePersistedHere) RemoveState(); } // else // { // m_log.WarnFormat( // "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. Memory limit exceeded.", // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState); // } } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. XML is {7}. Exception {8}{9}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace); } } // else // { // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Did not find state for script {0} for {1} ({2}) at {3} in {4}", // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name); // } return true; } public void Init() { if (ShuttingDown) return; if (m_startedFromSavedState) { if (m_startOnInit) Start(); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } else if (m_stateSource == StateSource.RegionStart) { //m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script"); PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0])); } else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting) { // CHANGED_REGION PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0])); // CHANGED_TELEPORT if (m_stateSource == StateSource.Teleporting) PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0])); } } else { if (m_startOnInit) Start(); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } } } private void ReleaseControls() { int permsMask; UUID permsGranter; lock (Part.TaskInventory) { if (!Part.TaskInventory.ContainsKey(ItemID)) return; permsGranter = Part.TaskInventory[ItemID].PermsGranter; permsMask = Part.TaskInventory[ItemID].PermsMask; } if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0) { ScenePresence presence = Engine.World.GetScenePresence(permsGranter); if (presence != null) presence.UnRegisterControlEventsToScript(LocalID, ItemID); } } public void DestroyScriptInstance() { ReleaseControls(); AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); } public void RemoveState() { string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state"); // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Deleting state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}.", // savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name); try { File.Delete(savedState); } catch (Exception e) { m_log.Warn( string.Format( "[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ", savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name), e); } } public void VarDump(Dictionary<string, object> vars) { // m_log.Info("Variable dump for script "+ ItemID.ToString()); // foreach (KeyValuePair<string, object> v in vars) // { // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString()); // } } public void Start() { lock (EventQueue) { if (Running) return; Running = true; TimeStarted = DateTime.Now; MeasurementPeriodTickStart = Util.EnvironmentTickCount(); MeasurementPeriodExecutionTime = 0; if (EventQueue.Count > 0) { if (m_CurrentWorkItem == null) m_CurrentWorkItem = Engine.QueueEventHandler(this); // else // m_log.Error("[Script] Tried to start a script that was already queued"); } } } public bool Stop(int timeout, bool clearEventQueue = false) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Stopping script {0} {1} in {2} {3} with timeout {4} {5} {6}", ScriptName, ItemID, PrimName, ObjectID, timeout, m_InSelfDelete, DateTime.Now.Ticks); IScriptWorkItem workItem; lock (EventQueue) { if (clearEventQueue) ClearQueue(); if (!Running) return true; // If we're not running or waiting to run an event then we can safely stop. if (m_CurrentWorkItem == null) { Running = false; return true; } // If we are waiting to run an event then we can try to cancel it. if (m_CurrentWorkItem.Cancel()) { m_CurrentWorkItem = null; Running = false; return true; } workItem = m_CurrentWorkItem; Running = false; } // Wait for the current event to complete. if (!m_InSelfDelete) { if (!m_coopTermination) { // If we're not co-operative terminating then try and wait for the event to complete before stopping if (workItem.Wait(timeout)) return true; } else { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); // This will terminate the event on next handle check by the script. m_coopSleepHandle.Set(); // For now, we will wait forever since the event should always cleanly terminate once LSL loop // checking is implemented. May want to allow a shorter timeout option later. if (workItem.Wait(Timeout.Infinite)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); return true; } } } lock (EventQueue) { workItem = m_CurrentWorkItem; } if (workItem == null) return true; // If the event still hasn't stopped and we the stop isn't the result of script or object removal, then // forcibly abort the work item (this aborts the underlying thread). // Co-operative termination should never reach this point. if (!m_InSelfDelete) { m_log.DebugFormat( "[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms", ScriptName, ItemID, PrimName, LocalID, timeout); workItem.Abort(); } lock (EventQueue) { m_CurrentWorkItem = null; } return true; } public void SetState(string state) { if (state == State) return; PostEvent(new EventParams("state_exit", new Object[0], new DetectParams[0])); PostEvent(new EventParams("state", new Object[] { state }, new DetectParams[0])); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } /// <summary> /// Post an event to this script instance. /// </summary> /// <remarks> /// The request to run the event is sent /// </remarks> /// <param name="data"></param> public void PostEvent(EventParams data) { // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); if (!Running) return; // If min event delay is set then ignore any events untill the time has expired // This currently only allows 1 event of any type in the given time period. // This may need extending to allow for a time for each individual event type. if (m_eventDelayTicks != 0) { if (DateTime.Now.Ticks < m_nextEventTimeTicks) return; m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks; } lock (EventQueue) { if (EventQueue.Count >= m_MaxScriptQueue) return; if (data.EventName == "timer") { if (m_TimerQueued) return; m_TimerQueued = true; } if (data.EventName == "control") { int held = ((LSL_Types.LSLInteger)data.Params[1]).value; // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value; // If the last message was a 0 (nothing held) // and this one is also nothing held, drop it // if (m_LastControlLevel == held && held == 0) return; // If there is one or more queued, then queue // only changed ones, else queue unconditionally // if (m_ControlEventsInQueue > 0) { if (m_LastControlLevel == held) return; } m_LastControlLevel = held; m_ControlEventsInQueue++; } if (data.EventName == "collision") { if (m_CollisionInQueue) return; if (data.DetectParams == null) return; m_CollisionInQueue = true; } EventQueue.Enqueue(data); if (m_CurrentWorkItem == null) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } /// <summary> /// Process the next event queued for this script /// </summary> /// <returns></returns> public object EventProcessor() { // We check here as the thread stopping this instance from running may itself hold the m_Script lock. if (!Running) return 0; lock (m_Script) { // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName); if (Suspended) return 0; EventParams data = null; lock (EventQueue) { data = (EventParams)EventQueue.Dequeue(); if (data == null) // Shouldn't happen { if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } return 0; } if (data.EventName == "timer") m_TimerQueued = false; if (data.EventName == "control") { if (m_ControlEventsInQueue > 0) m_ControlEventsInQueue--; } if (data.EventName == "collision") m_CollisionInQueue = false; } if (DebugLevel >= 2) m_log.DebugFormat( "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", data.EventName, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); m_DetectParams = data.DetectParams; if (data.EventName == "state") // Hardcoded state change { State = data.Params[0].ToString(); if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", State, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); AsyncCommandManager.StateChange(Engine, LocalID, ItemID); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } else { if (Engine.World.PipeEventsForScript(LocalID) || data.EventName == "control") // Don't freeze avies! { // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); try { m_CurrentEvent = data.EventName; m_EventStart = DateTime.Now; m_InEvent = true; int start = Util.EnvironmentTickCount(); // Reset the measurement period when we reach the end of the current one. if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod) MeasurementPeriodTickStart = start; m_Script.ExecuteEvent(State, data.EventName, data.Params); MeasurementPeriodExecutionTime += Util.EnvironmentTickCount() - start; m_InEvent = false; m_CurrentEvent = String.Empty; if (m_SaveState) { // This will be the very first event we deliver // (state_entry) in default state // SaveState(); m_SaveState = false; } } catch (Exception e) { // m_log.DebugFormat( // "[SCRIPT] Exception in script {0} {1}: {2}{3}", // ScriptName, ItemID, e.Message, e.StackTrace); m_InEvent = false; m_CurrentEvent = String.Empty; if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException) && !(e.InnerException is ScriptCoopStopException))) && !(e is ThreadAbortException)) { try { // DISPLAY ERROR INWORLD string text = FormatException(e); if (text.Length > 1000) text = text.Substring(0, 1000); Engine.World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, Part.AbsolutePosition, Part.Name, Part.UUID, false); m_log.Debug(string.Format( "[SCRIPT INSTANCE]: Runtime error in script {0} (event {1}), part {2} {3} at {4} in {5} ", ScriptName, data.EventName, PrimName, Part.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name), e); } catch (Exception) { } // catch (Exception e2) // LEGIT: User Scripting // { // m_log.Error("[SCRIPT]: "+ // "Error displaying error in-world: " + // e2.ToString()); // m_log.Error("[SCRIPT]: " + // "Errormessage: Error compiling script:\r\n" + // e.ToString()); // } } else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException)) { m_InSelfDelete = true; Engine.World.DeleteSceneObject(Part.ParentGroup, false); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException)) { m_InSelfDelete = true; Part.Inventory.RemoveInventoryItem(ItemID); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.", PrimName, ScriptName, data.EventName, State); } } } } // If there are more events and we are currently running and not shutting down, then ask the // script engine to run the next event. lock (EventQueue) { EventsProcessed++; if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } } m_DetectParams = null; return 0; } } public int EventTime() { if (!m_InEvent) return 0; return (DateTime.Now - m_EventStart).Seconds; } public void ResetScript(int timeout) { if (m_Script == null) return; bool running = Running; RemoveState(); ReleaseControls(); Stop(timeout); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (running) Start(); m_SaveState = StatePersistedHere; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); } public void ApiResetScript() { // bool running = Running; RemoveState(); ReleaseControls(); m_Script.ResetVars(); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_CurrentEvent != "state_entry") { m_SaveState = StatePersistedHere; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } } public Dictionary<string, object> GetVars() { if (m_Script != null) return m_Script.GetVars(); else return new Dictionary<string, object>(); } public void SetVars(Dictionary<string, object> vars) { // foreach (KeyValuePair<string, object> kvp in vars) // m_log.DebugFormat("[SCRIPT INSTANCE]: Setting var {0}={1}", kvp.Key, kvp.Value); m_Script.SetVars(vars); } public DetectParams GetDetectParams(int idx) { if (m_DetectParams == null) return null; if (idx < 0 || idx >= m_DetectParams.Length) return null; return m_DetectParams[idx]; } public UUID GetDetectID(int idx) { if (m_DetectParams == null) return UUID.Zero; if (idx < 0 || idx >= m_DetectParams.Length) return UUID.Zero; return m_DetectParams[idx].Key; } public void SaveState() { if (!Running) return; // We cannot call this inside the EventQueue lock since it will currently take AsyncCommandManager.staticLock. // This may already be held by AsyncCommandManager.DoOneCmdHandlerPass() which in turn can take EventQueue // lock via ScriptInstance.PostEvent(). PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); // We need to lock here to avoid any race with a thread that is removing this script. lock (EventQueue) { // Check again to avoid a race with a thread in Stop() if (!Running) return; // If we're currently in an event, just tell it to save upon return // if (m_InEvent) { m_SaveState = true; return; } // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Saving state for script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}", // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name); string xml = ScriptSerializer.Serialize(this); // Compare hash of the state we just just created with the state last written to disk // If the state is different, update the disk file. UUID hash = UUID.Parse(Utils.MD5String(xml)); if (hash != m_CurrentStateHash) { try { using (FileStream fs = File.Create(Path.Combine(m_dataPath, ItemID.ToString() + ".state"))) { Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml); fs.Write(buf, 0, buf.Length); } } catch(Exception) { // m_log.Error("Unable to save xml\n"+e.ToString()); } //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"))) //{ // throw new Exception("Completed persistence save, but no file was created"); //} m_CurrentStateHash = hash; } } } public IScriptApi GetApi(string name) { if (m_Apis.ContainsKey(name)) { // m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName); return m_Apis[name]; } // m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName); return null; } public override string ToString() { return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName); } string FormatException(Exception e) { if (e.InnerException == null) // Not a normal runtime error return e.ToString(); string message = "Runtime error:\n" + e.InnerException.StackTrace; string[] lines = message.Split(new char[] {'\n'}); foreach (string line in lines) { if (line.Contains("SecondLife.Script")) { int idx = line.IndexOf(':'); if (idx != -1) { string val = line.Substring(idx+1); int lineNum = 0; if (int.TryParse(val, out lineNum)) { KeyValuePair<int, int> pos = Compiler.FindErrorPosition( lineNum, 0, LineMap); int scriptLine = pos.Key; int col = pos.Value; if (scriptLine == 0) scriptLine++; if (col == 0) col++; message = string.Format("Runtime error:\n" + "({0}): {1}", scriptLine - 1, e.InnerException.Message); return message; } } } } // m_log.ErrorFormat("Scripting exception:"); // m_log.ErrorFormat(e.ToString()); return e.ToString(); } public string GetAssemblyName() { return m_assemblyPath; } public string GetXMLState() { bool run = Running; Stop(100); Running = run; // We should not be doing this, but since we are about to // dispose this, it really doesn't make a difference // This is meant to work around a Windows only race // m_InEvent = false; // Force an update of the in-memory plugin data // PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); return ScriptSerializer.Serialize(this); } public UUID RegionID { get { return m_RegionID; } } public void Suspend() { Suspended = true; } public void Resume() { Suspended = false; } } /// <summary> /// Xengine event wait handle. /// </summary> /// <remarks> /// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that /// when scripts are running in different AppDomains the lease does not expire. /// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this, /// proper remoting sponsorship needs to be implemented across the board. /// </remarks> public class XEngineEventWaitHandle : EventWaitHandle { public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) {} public override Object InitializeLifetimeService() { return null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Web; using System.Windows.Forms; using Microsoft.NodejsTools.Debugger; using Microsoft.NodejsTools.Debugger.DebugEngine; using Microsoft.NodejsTools.Options; using Microsoft.NodejsTools.Telemetry; using Microsoft.NodejsTools.TypeScript; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Setup.Configuration; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project; using Newtonsoft.Json.Linq; namespace Microsoft.NodejsTools.Project { internal class NodejsProjectLauncher : IProjectLauncher { private readonly NodejsProjectNode _project; private int? _testServerPort; private static readonly Guid WebkitDebuggerGuid = Guid.Parse("4cc6df14-0ab5-4a91-8bb4-eb0bf233d0fe"); private static readonly Guid WebkitPortSupplierGuid = Guid.Parse("4103f338-2255-40c0-acf5-7380e2bea13d"); internal static readonly Guid WebKitDebuggerV2Guid = Guid.Parse("30d423cc-6d0b-4713-b92d-6b2a374c3d89"); public NodejsProjectLauncher(NodejsProjectNode project) { this._project = project; var portNumber = this._project.GetProjectProperty(NodeProjectProperty.NodejsPort); int portNum; if (Int32.TryParse(portNumber, out portNum)) { this._testServerPort = portNum; } } #region IProjectLauncher Members public int LaunchProject(bool debug) { return LaunchFile(ResolveStartupFile(), debug); } public int LaunchFile(string file, bool debug) { var nodePath = GetNodePath(); if (nodePath == null) { Nodejs.ShowNodejsNotInstalled(); return VSConstants.S_OK; } var nodeVersion = Nodejs.GetNodeVersion(nodePath); var chromeProtocolRequired = nodeVersion >= new Version(8, 0) || CheckDebugProtocolOption(); var startBrowser = ShouldStartBrowser(); // The call to Version.ToString() is safe, since changes to the ToString method are very unlikely, as the current output is widely documented. if (debug && !chromeProtocolRequired) { StartWithDebugger(file); TelemetryHelper.LogDebuggingStarted("Node6", nodeVersion.ToString()); } else if (debug && chromeProtocolRequired) { if (CheckUseNewChromeDebugProtocolOption()) { StartWithChromeV2Debugger(file, nodePath, startBrowser); TelemetryHelper.LogDebuggingStarted("ChromeV2", nodeVersion.ToString()); } else { StartAndAttachDebugger(file, nodePath, startBrowser); TelemetryHelper.LogDebuggingStarted("Chrome", nodeVersion.ToString()); } } else { StartNodeProcess(file, nodePath, startBrowser); TelemetryHelper.LogDebuggingStarted("None", nodeVersion.ToString()); } return VSConstants.S_OK; } internal static bool CheckUseNewChromeDebugProtocolOption() { var optionString = NodejsDialogPage.LoadString(name: "WebKitVersion", cat: "Debugging"); return !StringComparer.OrdinalIgnoreCase.Equals(optionString, "V1"); } internal static bool CheckDebugProtocolOption() { var optionString = NodejsDialogPage.LoadString(name: "DebugProtocol", cat: "Debugging"); return StringComparer.OrdinalIgnoreCase.Equals(optionString, "chrome"); } internal static bool CheckEnableDiagnosticLoggingOption() { var optionString = NodejsDialogPage.LoadString(name: "DiagnosticLogging", cat: "Debugging"); return StringComparer.OrdinalIgnoreCase.Equals(optionString, "true"); } internal static string CheckForRegistrySpecifiedNodeParams() { var paramString = NodejsDialogPage.LoadString(name: "NodeCmdParams", cat: "Debugging"); return paramString; } private void StartAndAttachDebugger(string file, string nodePath, bool startBrowser) { // start the node process var workingDir = _project.GetWorkingDirectory(); var url = GetFullUrl(); var env = GetEnvironmentVariablesString(url); var interpreterOptions = _project.GetProjectProperty(NodeProjectProperty.NodeExeArguments); var debugOptions = this.GetDebugOptions(); var script = GetFullArguments(file, includeNodeArgs: false); var process = NodeDebugger.StartNodeProcessWithInspect(exe: nodePath, script: script, dir: workingDir, env: env, interpreterOptions: interpreterOptions, debugOptions: debugOptions); process.Start(); // setup debug info and attach var debugUri = $"http://127.0.0.1:{process.DebuggerPort}"; var dbgInfo = new VsDebugTargetInfo4(); dbgInfo.dlo = (uint)DEBUG_LAUNCH_OPERATION.DLO_AlreadyRunning; dbgInfo.LaunchFlags = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd; dbgInfo.guidLaunchDebugEngine = WebkitDebuggerGuid; dbgInfo.dwDebugEngineCount = 1; var enginesPtr = MarshalDebugEngines(new[] { WebkitDebuggerGuid }); dbgInfo.pDebugEngines = enginesPtr; dbgInfo.guidPortSupplier = WebkitPortSupplierGuid; dbgInfo.bstrPortName = debugUri; dbgInfo.fSendToOutputWindow = 0; // we connect through a URI, so no need to set the process, // we need to set the process id to '1' so the debugger is able to attach dbgInfo.bstrExe = $"\01"; AttachDebugger(dbgInfo); if (startBrowser) { Uri uri = null; if (!String.IsNullOrWhiteSpace(url)) { uri = new Uri(url); } if (uri != null) { OnPortOpenedHandler.CreateHandler( uri.Port, shortCircuitPredicate: () => process.HasExited, action: () => { VsShellUtilities.OpenBrowser(url, (uint)__VSOSPFLAGS.OSP_LaunchNewBrowser); } ); } } } private NodeDebugOptions GetDebugOptions() { var debugOptions = NodeDebugOptions.None; if (NodejsPackage.Instance.GeneralOptionsPage.WaitOnAbnormalExit) { debugOptions |= NodeDebugOptions.WaitOnAbnormalExit; } if (NodejsPackage.Instance.GeneralOptionsPage.WaitOnNormalExit) { debugOptions |= NodeDebugOptions.WaitOnNormalExit; } return debugOptions; } private void AttachDebugger(VsDebugTargetInfo4 dbgInfo) { var serviceProvider = _project.Site; var debugger = serviceProvider.GetService(typeof(SVsShellDebugger)) as IVsDebugger4; if (debugger == null) { throw new InvalidOperationException("Failed to get the debugger service."); } var launchResults = new VsDebugTargetProcessInfo[1]; debugger.LaunchDebugTargets4(1, new[] { dbgInfo }, launchResults); } private static IntPtr MarshalDebugEngines(Guid[] debugEngines) { if (debugEngines.Length == 0) { return IntPtr.Zero; } var guidSize = Marshal.SizeOf(typeof(Guid)); var size = debugEngines.Length * guidSize; var bytes = new byte[size]; for (var i = 0; i < debugEngines.Length; ++i) { debugEngines[i].ToByteArray().CopyTo(bytes, i * guidSize); } var pDebugEngines = Marshal.AllocCoTaskMem(size); Marshal.Copy(bytes, 0, pDebugEngines, size); return pDebugEngines; } private void StartNodeProcess(string file, string nodePath, bool startBrowser) { //TODO: looks like this duplicates a bunch of code in NodeDebugger var psi = new ProcessStartInfo() { UseShellExecute = false, FileName = nodePath, Arguments = GetFullArguments(file, includeNodeArgs: true), WorkingDirectory = _project.GetWorkingDirectory() }; var webBrowserUrl = GetFullUrl(); Uri uri = null; if (!String.IsNullOrWhiteSpace(webBrowserUrl)) { uri = new Uri(webBrowserUrl); psi.EnvironmentVariables["PORT"] = uri.Port.ToString(); } foreach (var nameValue in GetEnvironmentVariables()) { psi.EnvironmentVariables[nameValue.Key] = nameValue.Value; } var process = NodeProcess.Start( psi, waitOnAbnormal: NodejsPackage.Instance.GeneralOptionsPage.WaitOnAbnormalExit, waitOnNormal: NodejsPackage.Instance.GeneralOptionsPage.WaitOnNormalExit); this._project.OnDispose += process.ResponseToTerminateEvent; if (startBrowser && uri != null) { OnPortOpenedHandler.CreateHandler( uri.Port, shortCircuitPredicate: () => process.HasExited, action: () => { VsShellUtilities.OpenBrowser(webBrowserUrl, (uint)__VSOSPFLAGS.OSP_LaunchNewBrowser); } ); } } private string GetFullArguments(string file, bool includeNodeArgs) { var res = string.Empty; if (includeNodeArgs) { var nodeArgs = this._project.GetProjectProperty(NodeProjectProperty.NodeExeArguments); if (!string.IsNullOrWhiteSpace(nodeArgs)) { res = nodeArgs + " "; } } res += "\"" + file + "\""; var scriptArgs = this._project.GetProjectProperty(NodeProjectProperty.ScriptArguments); if (!string.IsNullOrWhiteSpace(scriptArgs)) { res += " " + scriptArgs; } return res; } private string GetNodePath() { var overridePath = this._project.GetProjectProperty(NodeProjectProperty.NodeExePath); return Nodejs.GetAbsoluteNodeExePath(this._project.ProjectHome, overridePath); } #endregion private string GetFullUrl() { var host = this._project.GetProjectProperty(NodeProjectProperty.LaunchUrl); try { return GetFullUrl(host, this.TestServerPort); } catch (UriFormatException) { var output = OutputWindowRedirector.GetGeneral(NodejsPackage.Instance); output.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, Resources.ErrorInvalidLaunchUrl, host)); output.ShowAndActivate(); return string.Empty; } } internal static string GetFullUrl(string host, int port) { UriBuilder builder; Uri uri; if (Uri.TryCreate(host, UriKind.Absolute, out uri)) { builder = new UriBuilder(uri); } else { builder = new UriBuilder(); builder.Scheme = Uri.UriSchemeHttp; builder.Host = "localhost"; builder.Path = host; } builder.Port = port; return builder.ToString(); } private int TestServerPort { get { if (!this._testServerPort.HasValue) { this._testServerPort = GetFreePort(); } return this._testServerPort.Value; } } /// <summary> /// Default implementation of the "Start Debugging" command. /// </summary> private void StartWithDebugger(string startupFile) { var dbgInfo = new VsDebugTargetInfo(); dbgInfo.cbSize = (uint)Marshal.SizeOf(dbgInfo); if (SetupDebugInfo(ref dbgInfo, startupFile)) { LaunchDebugger(this._project.Site, dbgInfo); } } private void StartWithChromeV2Debugger(string file, string nodePath, bool startBrowser) { var serviceProvider = _project.Site; var setupConfiguration = new SetupConfiguration(); var setupInstance = setupConfiguration.GetInstanceForCurrentProcess(); var visualStudioInstallationInstanceID = setupInstance.GetInstanceId(); // The Node2Adapter depends on features only in Node v6+, so the old v5.4 version of node will not suffice for this scenario // This node.exe will be the one used by the node2 debug adapter, not the one used to host the user code. var pathToNodeExe = Path.Combine(setupInstance.GetInstallationPath(), "JavaScript\\Node.JS\\v6.4.0_x86\\Node.exe"); // We check the registry to see if any parameters for the node.exe invocation have been specified (like "--inspect"), and append them if we find them. string nodeParams = CheckForRegistrySpecifiedNodeParams(); if (!string.IsNullOrEmpty(nodeParams)) { pathToNodeExe = pathToNodeExe + " " + nodeParams; } var pathToNode2DebugAdapterRuntime = Environment.ExpandEnvironmentVariables(@"""%ALLUSERSPROFILE%\" + $@"Microsoft\VisualStudio\NodeAdapter\{visualStudioInstallationInstanceID}\extension\out\src\nodeDebug.js"""); string trimmedPathToNode2DebugAdapter = pathToNode2DebugAdapterRuntime.Replace("\"", ""); if (!File.Exists(trimmedPathToNode2DebugAdapter)) { pathToNode2DebugAdapterRuntime = Environment.ExpandEnvironmentVariables(@"""%ALLUSERSPROFILE%\" + $@"Microsoft\VisualStudio\NodeAdapter\{visualStudioInstallationInstanceID}\out\src\nodeDebug.js"""); } // Here we need to massage the env variables into the format expected by node and vs code var webBrowserUrl = GetFullUrl(); var envVars = GetEnvironmentVariables(webBrowserUrl); var cwd = _project.GetWorkingDirectory(); // Current working directory var configuration = new JObject( new JProperty("name", "Debug Node.js program from Visual Studio"), new JProperty("type", "node2"), new JProperty("request", "launch"), new JProperty("program", file), new JProperty("runtimeExecutable", nodePath), new JProperty("cwd", cwd), new JProperty("console", "externalTerminal"), new JProperty("env", JObject.FromObject(envVars)), new JProperty("trace", CheckEnableDiagnosticLoggingOption()), new JProperty("sourceMaps", true), new JProperty("stopOnEntry", true), new JProperty("$adapter", pathToNodeExe), new JProperty("$adapterArgs", pathToNode2DebugAdapterRuntime)); var jsonContent = configuration.ToString(); var debugTargets = new[] { new VsDebugTargetInfo4() { dlo = (uint)DEBUG_LAUNCH_OPERATION.DLO_CreateProcess, guidLaunchDebugEngine = WebKitDebuggerV2Guid, bstrExe = file, bstrOptions = jsonContent } }; var processInfo = new VsDebugTargetProcessInfo[debugTargets.Length]; var debugger = serviceProvider.GetService(typeof(SVsShellDebugger)) as IVsDebugger4; debugger.LaunchDebugTargets4(1, debugTargets, processInfo); // Launch browser if (startBrowser) { Uri uri = null; if (!String.IsNullOrWhiteSpace(webBrowserUrl)) { uri = new Uri(webBrowserUrl); } if (uri != null) { OnPortOpenedHandler.CreateHandler( uri.Port, shortCircuitPredicate: () => false, action: () => { VsShellUtilities.OpenBrowser(webBrowserUrl, (uint)__VSOSPFLAGS.OSP_LaunchNewBrowser); } ); } } } private void LaunchDebugger(IServiceProvider provider, VsDebugTargetInfo dbgInfo) { if (!Directory.Exists(dbgInfo.bstrCurDir)) { MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.DebugWorkingDirectoryDoesNotExistErrorMessage, dbgInfo.bstrCurDir), SR.ProductName); } else if (!File.Exists(dbgInfo.bstrExe)) { MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.DebugInterpreterDoesNotExistErrorMessage, dbgInfo.bstrExe), SR.ProductName); } else if (DoesProjectSupportDebugging()) { VsShellUtilities.LaunchDebugger(provider, dbgInfo); } } private bool DoesProjectSupportDebugging() { var typeScriptOutFile = this._project.GetProjectProperty("TypeScriptOutFile"); if (!string.IsNullOrEmpty(typeScriptOutFile)) { return MessageBox.Show( Resources.DebugTypeScriptCombineNotSupportedWarningMessage, SR.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning ) == DialogResult.Yes; } return true; } private void AppendOption(ref VsDebugTargetInfo dbgInfo, string option, string value) { if (!string.IsNullOrWhiteSpace(dbgInfo.bstrOptions)) { dbgInfo.bstrOptions += ";"; } dbgInfo.bstrOptions += option + "=" + HttpUtility.UrlEncode(value); } /// <summary> /// Sets up debugger information. /// </summary> private bool SetupDebugInfo(ref VsDebugTargetInfo dbgInfo, string startupFile) { dbgInfo.dlo = DEBUG_LAUNCH_OPERATION.DLO_CreateProcess; dbgInfo.bstrExe = GetNodePath(); dbgInfo.bstrCurDir = this._project.GetWorkingDirectory(); dbgInfo.bstrArg = GetFullArguments(startupFile, includeNodeArgs: false); // we need to supply node args via options dbgInfo.bstrRemoteMachine = null; var nodeArgs = this._project.GetProjectProperty(NodeProjectProperty.NodeExeArguments); if (!string.IsNullOrWhiteSpace(nodeArgs)) { AppendOption(ref dbgInfo, AD7Engine.InterpreterOptions, nodeArgs); } var url = GetFullUrl(); if (ShouldStartBrowser() && !string.IsNullOrWhiteSpace(url)) { AppendOption(ref dbgInfo, AD7Engine.WebBrowserUrl, url); } var debuggerPort = this._project.GetProjectProperty(NodeProjectProperty.DebuggerPort); if (!string.IsNullOrWhiteSpace(debuggerPort)) { AppendOption(ref dbgInfo, AD7Engine.DebuggerPort, debuggerPort); } if (NodejsPackage.Instance.GeneralOptionsPage.WaitOnAbnormalExit) { AppendOption(ref dbgInfo, AD7Engine.WaitOnAbnormalExitSetting, "true"); } if (NodejsPackage.Instance.GeneralOptionsPage.WaitOnNormalExit) { AppendOption(ref dbgInfo, AD7Engine.WaitOnNormalExitSetting, "true"); } dbgInfo.fSendStdoutToOutputWindow = 0; dbgInfo.bstrEnv = GetEnvironmentVariablesString(url); // Set the Node debugger dbgInfo.clsidCustom = AD7Engine.DebugEngineGuid; dbgInfo.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd; return true; } private string GetEnvironmentVariablesString(string url) { var env = GetEnvironmentVariables(url); if (env.Count > 0) { //Environment variables should be passed as a //null-terminated block of null-terminated strings. //Each string is in the following form:name=value\0 var buf = new StringBuilder(); foreach (var entry in env) { buf.AppendFormat("{0}={1}\0", entry.Key, entry.Value); } buf.Append("\0"); return buf.ToString(); } return null; } private Dictionary<string, string> GetEnvironmentVariables(string url) { var env = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrWhiteSpace(url)) { var webUrl = new Uri(url); env["PORT"] = webUrl.Port.ToString(); } foreach (var nameValue in GetEnvironmentVariables()) { env[nameValue.Key] = nameValue.Value; } if (env.Count > 0) { // add any inherited env vars var variables = Environment.GetEnvironmentVariables(); foreach (var key in variables.Keys) { var strKey = (string)key; if (!env.ContainsKey(strKey)) { env.Add(strKey, (string)variables[key]); } } } return env; } private bool ShouldStartBrowser() { var startBrowser = this._project.GetProjectProperty(NodeProjectProperty.StartWebBrowser); bool fStartBrowser; if (!string.IsNullOrEmpty(startBrowser) && Boolean.TryParse(startBrowser, out fStartBrowser)) { return fStartBrowser; } return true; } private IEnumerable<KeyValuePair<string, string>> GetEnvironmentVariables() { var envVars = this._project.GetProjectProperty(NodeProjectProperty.Environment); if (envVars != null) { foreach (var envVar in envVars.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { var nameValue = envVar.Split(new[] { '=' }, 2); if (nameValue.Length == 2) { yield return new KeyValuePair<string, string>(nameValue[0], nameValue[1]); } } } } private static int GetFreePort() { return Enumerable.Range(new Random().Next(1200, 2000), 60000).Except( from connection in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections() select connection.LocalEndPoint.Port ).First(); } private string ResolveStartupFile() { var startupFile = this._project.GetStartupFile(); if (string.IsNullOrEmpty(startupFile)) { throw new ApplicationException(Resources.DebugCouldNotResolveStartupFileErrorMessage); } if (TypeScriptHelpers.IsTypeScriptFile(startupFile)) { startupFile = TypeScriptHelpers.GetTypeScriptBackedJavaScriptFile(this._project, startupFile); } return startupFile; } } internal class OnPortOpenedHandler { private class OnPortOpenedInfo { public readonly int Port; public readonly TimeSpan? Timeout; public readonly int Sleep; public readonly Func<bool> ShortCircuitPredicate; public readonly Action Action; public readonly DateTime StartTime; public OnPortOpenedInfo( int port, int? timeout = null, int? sleep = null, Func<bool> shortCircuitPredicate = null, Action action = null ) { this.Port = port; if (timeout.HasValue) { this.Timeout = TimeSpan.FromMilliseconds(Convert.ToDouble(timeout)); } this.Sleep = sleep ?? 500; // 1/2 second sleep this.ShortCircuitPredicate = shortCircuitPredicate ?? (() => false); this.Action = action ?? (() => { }); this.StartTime = System.DateTime.Now; } } internal static void CreateHandler( int port, int? timeout = null, int? sleep = null, Func<bool> shortCircuitPredicate = null, Action action = null ) { ThreadPool.QueueUserWorkItem( OnPortOpened, new OnPortOpenedInfo( port, timeout, sleep, shortCircuitPredicate, action ) ); } private static void OnPortOpened(object infoObj) { var info = (OnPortOpenedInfo)infoObj; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Blocking = true; try { while (true) { // Short circuit if (info.ShortCircuitPredicate()) { return; } // Try connect try { socket.Connect(IPAddress.Loopback, info.Port); break; } catch { // Connect failure // Fall through } // Timeout if (info.Timeout.HasValue && (System.DateTime.Now - info.StartTime) >= info.Timeout) { break; } // Sleep System.Threading.Thread.Sleep(info.Sleep); } } finally { socket.Close(); } } // Launch browser (if not short-circuited) if (!info.ShortCircuitPredicate()) { info.Action(); } } } }
using System; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using NHibernate; using NHibernate.Criterion; using System.Collections.Generic; namespace EBE.Data { /// <summary> /// Simple database interface. /// </summary> public class EBEContext : IDisposable { private static bool _created = false; private static object _lock = new object(); private static ISessionFactory _sessionFactory; private static Configuration _configuration; /// <summary> /// Gets the session factory thinger. /// </summary> private static ISessionFactory SessionFactory { get { lock (_lock) { return _sessionFactory; } } } /// <summary> /// Releases all resource used by the <see cref="EBE.Data.EBEContext"/> object. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="EBE.Data.EBEContext"/>. The /// <see cref="Dispose"/> method leaves the <see cref="EBE.Data.EBEContext"/> in an unusable state. After /// calling <see cref="Dispose"/>, you must release all references to the <see cref="EBE.Data.EBEContext"/> so /// the garbage collector can reclaim the memory that the <see cref="EBE.Data.EBEContext"/> was occupying.</remarks> public void Dispose() { } /// <summary> /// Opens the database session. /// </summary> public static ISession OpenSession() { return SessionFactory.OpenSession(); } /// <summary> /// Gets the encyclopedia repository. /// </summary> public IRepository<Encyclopedia> Encyclopedia { get; private set; } /// <summary> /// Gets the gen repository. /// </summary> public IRepository<Gen> Gen { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="EBE.Data.EBEContext"/> class. /// </summary> public EBEContext() { Setup(); if (Encyclopedia == null) { Encyclopedia = new Repository<Encyclopedia>(); } if (Gen == null) { Gen = new Repository<Gen>(); } } /// <summary> /// Save item to database. /// </summary> internal void TransactSave(object obj) { using(ISession session = OpenSession()) using(ITransaction transaction = session.BeginTransaction()) { session.Save(obj); transaction.Commit(); } } /// <summary> /// Update item in database. /// </summary> internal void TransactUpdate(object obj) { using(ISession session = OpenSession()) using(ITransaction transaction = session.BeginTransaction()) { session.Update(obj); transaction.Commit(); } } /// <summary> /// Delete item from database. /// </summary> internal void TransactDelete(object obj) { using(ISession session = OpenSession()) using(ITransaction transaction = session.BeginTransaction()) { session.Delete(obj); transaction.Commit(); } } /// <summary> /// Get item from database. /// </summary> /// <returns>Item to find.</returns> /// <param name="key">Key to find item.</param> /// <typeparam name="T">Type of object.</typeparam> internal T TransactGet<T>(object key) { using(ISession session = _sessionFactory.OpenSession()) { return session.Get<T>(key); } } /// <summary> /// Find objects that have property with the given value. /// </summary> /// <returns>Finds items that match the given property with the given value.</returns> /// <param name="propertyName">Property name to look at.</param> /// <param name="value">Value for the property.</param> /// <typeparam name="T">Type of object.</typeparam> internal List<T> TransactFind<T>(string propertyName, object value) where T : class { using(ISession session = _sessionFactory.OpenSession()) { var results = session.CreateCriteria<T>() .Add(Restrictions.Eq(propertyName, value)) .List<T>(); List<T> list = new List<T>(); foreach (var r in results) { list.Add(r); } return list; } } /// <summary> /// Finds items that matches the given properties with the given values. /// </summary> /// <returns>List of items that match.</returns> /// <param name="propertyName">Property name to look at.</param> /// <param name="value">Value for the property.</param> /// <param name="propertyName2">Second property name to look at.</param> /// <param name="value2">Value for the second property.</param> /// <typeparam name="T">Type of object.</typeparam> internal List<T> TransactFind2<T>(string propertyName, object value, string propertyName2, object value2) where T : class { using(ISession session = _sessionFactory.OpenSession()) { var results = session.CreateCriteria<T>() .Add(Restrictions.Eq(propertyName, value)) .Add(Restrictions.Eq(propertyName2, value2)) .List<T>(); List<T> list = new List<T>(); foreach (var r in results) { list.Add(r); } return list; } } private void Setup() { if (_created == false) { lock (_lock) { _configuration = new Configuration(); _configuration.Configure(); _configuration.AddAssembly(typeof(Encyclopedia).Assembly); _sessionFactory = _configuration.BuildSessionFactory(); _created = true; } } } private void Generate() { // should (somehow) drop and create table // http://nhforge.org/wikis/howtonh/your-first-nhibernate-based-application.aspx var cfg = new Configuration(); cfg.Configure(); cfg.AddAssembly(typeof(Encyclopedia).Assembly); new SchemaExport(cfg); //new SchemaExport(cfg).Execute(false, true, false, false); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using bv.common; using bv.common.Core; using bv.common.db.Core; using bv.model.BLToolkit; using eidss.model.AVR.Db; using eidss.model.Avr.Pivot; using eidss.model.Core; using eidss.model.Enums; using eidss.model.Resources; using eidss.model.Schema; namespace eidss.avr.db.Common { public static class QueryProcessor { private const string CopySuffix = QueryHelper.CopySuffix; private const string AliasColumnName = QueryHelper.ColumnAlias; private const string CaptionColumnName = "FieldCaption"; private const string EnCaptionColumnName = "FieldENCaption"; private const string QueryIdColumnName = "idflQuery"; private const string PersonalDataGroupIdColumnName = "idfPersonalDataGroup"; public static void TranslateTableFields(DataTable dataTable, long queryId) { Utils.CheckNotNull(dataTable, "dataTable"); Dictionary<string, string> translations = GetTranslations(queryId); Dictionary<string, string> copy = translations.ToDictionary(pair => pair.Key + CopySuffix, pair => pair.Value); foreach (KeyValuePair<string, string> pair in copy) { translations.Add(pair.Key, pair.Value); } dataTable.BeginLoadData(); foreach (DataColumn column in dataTable.Columns) { if (translations.ContainsKey(column.ColumnName)) { column.Caption = translations[column.ColumnName]; } else { Trace.WriteLine(Trace.Kind.Error, "Translation of field {0} not found", column.ColumnName); } } dataTable.EndLoadData(); dataTable.AcceptChanges(); } public static DataTable RemoveNotExistingColumns(DataTable dataTable, long queryId) { Utils.CheckNotNull(dataTable, "dataTable"); string rowFilter = String.Format("idflQuery = {0} and blnShow = 1 ", queryId); var dataView = new DataView( QueryLookupHelper.GetQueryLookupTable(), rowFilter, QueryHelper.ColumnAlias, DataViewRowState.CurrentRows); var aliases = new List<string>(); foreach (DataRowView row in dataView) { string alias = Utils.Str(row[QueryHelper.ColumnAlias]); aliases.Add(alias); aliases.Add(alias + CopySuffix); } var columnsToRemove = new List<DataColumn>(); foreach (DataColumn column in dataTable.Columns) { if (!aliases.Contains(column.ColumnName)) { columnsToRemove.Add(column); } } dataTable.Constraints.Clear(); foreach (DataColumn column in columnsToRemove) { dataTable.Columns.Remove(column); } return dataTable; } public static void SetNullForForbiddenTableFields(DataTable dataTable, long queryId) { Utils.CheckNotNull(dataTable, "dataTable"); Dictionary<PersonalDataGroup, List<string>> groups = GetPersonalDataGroups(queryId); var forbiddenColumn = new List<string>(); foreach (KeyValuePair<PersonalDataGroup, List<string>> group in groups) { if (EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(@group.Key)) { foreach (string columnName in @group.Value) { if (dataTable.Columns.Contains(columnName) && !forbiddenColumn.Contains(columnName)) { forbiddenColumn.Add(columnName); } string copyColumnName = columnName + CopySuffix; if (dataTable.Columns.Contains(copyColumnName) && !forbiddenColumn.Contains(copyColumnName)) { forbiddenColumn.Add(copyColumnName); } } } } if (forbiddenColumn.Count > 0) { dataTable.Constraints.Clear(); foreach (string columnName in forbiddenColumn) { dataTable.Columns[columnName].ReadOnly = false; } dataTable.BeginLoadData(); foreach (DataRow row in dataTable.Rows) { foreach (string columnName in forbiddenColumn) { row[columnName] = DBNull.Value; } } dataTable.EndLoadData(); dataTable.AcceptChanges(); } } public static void SetCopyPropertyForColumnsIfNeeded(DataTable dataTable) { Utils.CheckNotNull(dataTable, "dataTable"); foreach (DataColumn column in dataTable.Columns) { if (AvrPivotGridFieldHelper.GetIsCopyForFilter(column.ColumnName) && !column.ExtendedProperties.ContainsKey(CopySuffix)) { column.ExtendedProperties[CopySuffix] = true; } } } public static KeyValuePair<string, string> GetTranslations(long queryId, string alias) { DataTable dataTable = QueryLookupHelper.GetQueryLookupTable(); CheckColumnExists(dataTable, AliasColumnName); CheckColumnExists(dataTable, CaptionColumnName); // for copied fields we should get original field alias if (alias.Length > CopySuffix.Length && alias.Substring(alias.Length - CopySuffix.Length) == CopySuffix) { alias = alias.Substring(0, alias.Length - CopySuffix.Length); } string rowFilter = String.Format("{0} = {1} and {2} = '{3}' and blnShow = 1 ", QueryIdColumnName, queryId, AliasColumnName, alias); var dataView = new DataView(dataTable,rowFilter,CaptionColumnName,DataViewRowState.CurrentRows); if (dataView.Count == 0) { // hope it will fix 9224. if query search field didn't found - maybe cache didn't refreshes LookupCache.NotifyChange("QuerySearchField"); dataView = new DataView(dataTable, rowFilter, CaptionColumnName, DataViewRowState.CurrentRows); if (dataView.Count == 0) { // if field still not fouynd - return with no translation. It bad practice, I know, but it's better than failed GAT return new KeyValuePair<string, string>(alias, alias); } } string key = dataView[0][EnCaptionColumnName].ToString(); string value = dataView[0][CaptionColumnName].ToString(); return new KeyValuePair<string, string>(key, value); } public static Dictionary<string, string> GetTranslations(long queryId) { var translations = new Dictionary<string, string>(); DataTable dataTable = QueryLookupHelper.GetQueryLookupTable(); CheckColumnExists(dataTable, AliasColumnName); CheckColumnExists(dataTable, QueryIdColumnName); CheckColumnExists(dataTable, CaptionColumnName); string rowFilter = String.Format("{0} = {1} and blnShow = 1 ", QueryIdColumnName, queryId); var dataView = new DataView( dataTable, rowFilter, EnCaptionColumnName, DataViewRowState.CurrentRows); foreach (DataRowView row in dataView) { string msg = EidssMessages.Get("msgEmptyRow", "One of rows has empty translation {0}"); if (Utils.IsEmpty(row[AliasColumnName])) { throw new AvrDbException(String.Format(msg, AliasColumnName)); } if (Utils.IsEmpty(row[CaptionColumnName])) { throw new AvrDbException(String.Format(msg, CaptionColumnName)); } string key = row[AliasColumnName].ToString(); string value = row[CaptionColumnName].ToString(); if (translations.ContainsKey(key)) { throw new AvrDbException(String.Format("Dublicate row with {0} = '{1}' in table of translations", AliasColumnName, key)); } translations.Add(key, value); } return translations; } public static Dictionary<PersonalDataGroup, List<string>> GetPersonalDataGroups(long queryId) { var groups = new Dictionary<PersonalDataGroup, List<string>>(); DataTable dataTable = QueryLookupHelper.GetQueryPersonalDataGroupTable(); if (dataTable == null) { throw new AvrDbException("Cannot get Personal Data Group from Database"); } CheckColumnExists(dataTable, AliasColumnName); CheckColumnExists(dataTable, QueryIdColumnName); CheckColumnExists(dataTable, PersonalDataGroupIdColumnName); string rowFilter = String.Format("{0} = {1} and blnShow = 1 ", QueryIdColumnName, queryId); var dataView = new DataView( dataTable, rowFilter, PersonalDataGroupIdColumnName, DataViewRowState.CurrentRows); foreach (DataRowView row in dataView) { var key = (PersonalDataGroup) (long) row[PersonalDataGroupIdColumnName]; List<string> values; if (!groups.TryGetValue(key, out values)) { values = new List<string>(); groups.Add(key, values); } values.Add(row[AliasColumnName].ToString()); } return groups; } public static string GetQueryName(long queryId) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create()) { AvrQueryLookup.Accessor accessor = AvrQueryLookup.Accessor.Instance(null); List<AvrQueryLookup> lookup = accessor.SelectLookupList(manager, queryId); AvrQueryLookup query = lookup.SingleOrDefault(); return query == null ? "NO_QUERY_FOUND_WITH_ID_" + queryId : query.QueryName; } } private static void CheckColumnExists(DataTable dataTable, string alias) { Utils.CheckNotNull(dataTable, "dataTable"); Utils.CheckNotNullOrEmpty(alias, "alias"); if (!dataTable.Columns.Contains(alias)) { throw new AvrDbException(String.Format("Column {0} not found in table of translations", alias)); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Scenes.Serialization { /// <summary> /// Serialize and deserialize scene objects. /// </summary> /// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems /// right now - hopefully this isn't forever. public class SceneObjectSerializer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="serialization"></param> /// <returns></returns> public static SceneObjectGroup FromOriginalXmlFormat(string serialization) { return FromOriginalXmlFormat(UUID.Zero, serialization); } /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="serialization"></param> /// <returns></returns> public static SceneObjectGroup FromOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; try { StringReader sr; XmlTextReader reader; XmlNodeList parts; XmlDocument doc; int linkNum; doc = new XmlDocument(); doc.LoadXml(xmlData); parts = doc.GetElementsByTagName("RootPart"); if (parts.Count == 0) throw new Exception("Invalid Xml format - no root part"); sr = new StringReader(parts[0].InnerXml); reader = new XmlTextReader(sr); SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(fromUserInventoryItemID, reader)); reader.Close(); sr.Close(); parts = doc.GetElementsByTagName("Part"); for (int i = 0; i < parts.Count; i++) { sr = new StringReader(parts[i].InnerXml); reader = new XmlTextReader(sr); SceneObjectPart part = SceneObjectPart.FromXml(reader); linkNum = part.LinkNum; sceneObject.AddPart(part); part.LinkNum = linkNum; part.TrimPermissions(); part.StoreUndoState(); reader.Close(); sr.Close(); } // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(doc); return sceneObject; } catch (Exception e) { m_log.ErrorFormat( "[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { ToOriginalXmlFormat(sceneObject, writer); } return sw.ToString(); } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer) { //m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", Name); //int time = System.Environment.TickCount; writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); writer.WriteStartElement(String.Empty, "RootPart", String.Empty); ToXmlFormat(sceneObject.RootPart, writer); writer.WriteEndElement(); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); SceneObjectPart[] parts = sceneObject.Parts; for (int i = 0; i < parts.Length; i++) { SceneObjectPart part = parts[i]; if (part.UUID != sceneObject.RootPart.UUID) { writer.WriteStartElement(String.Empty, "Part", String.Empty); ToXmlFormat(part, writer); writer.WriteEndElement(); } } writer.WriteEndElement(); // OtherParts sceneObject.SaveScriptedState(writer); writer.WriteEndElement(); // SceneObjectGroup //m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time); } protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer) { SOPToXml2(writer, part, new Dictionary<string, object>()); } public static SceneObjectGroup FromXml2Format(string xmlData) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; try { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlData); XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart"); if (parts.Count == 0) { m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes. xml was " + xmlData); return null; } StringReader sr = new StringReader(parts[0].OuterXml); XmlTextReader reader = new XmlTextReader(sr); SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader)); reader.Close(); sr.Close(); // Then deal with the rest for (int i = 1; i < parts.Count; i++) { sr = new StringReader(parts[i].OuterXml); reader = new XmlTextReader(sr); SceneObjectPart part = SceneObjectPart.FromXml(reader); int originalLinkNum = part.LinkNum; sceneObject.AddPart(part); // SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum. // We override that here if (originalLinkNum != 0) part.LinkNum = originalLinkNum; part.StoreUndoState(); reader.Close(); sr.Close(); } // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(doc); return sceneObject; } catch (Exception e) { m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } } /// <summary> /// Serialize a scene object to the 'xml2' format. /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToXml2Format(SceneObjectGroup sceneObject) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { SOGToXml2(writer, sceneObject, new Dictionary<string,object>()); } return sw.ToString(); } } #region manual serialization private delegate void SOPXmlProcessor(SceneObjectPart sop, XmlTextReader reader); private static Dictionary<string, SOPXmlProcessor> m_SOPXmlProcessors = new Dictionary<string, SOPXmlProcessor>(); private delegate void TaskInventoryXmlProcessor(TaskInventoryItem item, XmlTextReader reader); private static Dictionary<string, TaskInventoryXmlProcessor> m_TaskInventoryXmlProcessors = new Dictionary<string, TaskInventoryXmlProcessor>(); private delegate void ShapeXmlProcessor(PrimitiveBaseShape shape, XmlTextReader reader); private static Dictionary<string, ShapeXmlProcessor> m_ShapeXmlProcessors = new Dictionary<string, ShapeXmlProcessor>(); static SceneObjectSerializer() { #region SOPXmlProcessors initialization m_SOPXmlProcessors.Add("AllowedDrop", ProcessAllowedDrop); m_SOPXmlProcessors.Add("CreatorID", ProcessCreatorID); m_SOPXmlProcessors.Add("FolderID", ProcessFolderID); m_SOPXmlProcessors.Add("InventorySerial", ProcessInventorySerial); m_SOPXmlProcessors.Add("TaskInventory", ProcessTaskInventory); m_SOPXmlProcessors.Add("UUID", ProcessUUID); m_SOPXmlProcessors.Add("LocalId", ProcessLocalId); m_SOPXmlProcessors.Add("Name", ProcessName); m_SOPXmlProcessors.Add("Material", ProcessMaterial); m_SOPXmlProcessors.Add("PassTouches", ProcessPassTouches); m_SOPXmlProcessors.Add("RegionHandle", ProcessRegionHandle); m_SOPXmlProcessors.Add("ScriptAccessPin", ProcessScriptAccessPin); m_SOPXmlProcessors.Add("GroupPosition", ProcessGroupPosition); m_SOPXmlProcessors.Add("OffsetPosition", ProcessOffsetPosition); m_SOPXmlProcessors.Add("RotationOffset", ProcessRotationOffset); m_SOPXmlProcessors.Add("Velocity", ProcessVelocity); m_SOPXmlProcessors.Add("AngularVelocity", ProcessAngularVelocity); m_SOPXmlProcessors.Add("Acceleration", ProcessAcceleration); m_SOPXmlProcessors.Add("Description", ProcessDescription); m_SOPXmlProcessors.Add("Color", ProcessColor); m_SOPXmlProcessors.Add("Text", ProcessText); m_SOPXmlProcessors.Add("SitName", ProcessSitName); m_SOPXmlProcessors.Add("TouchName", ProcessTouchName); m_SOPXmlProcessors.Add("LinkNum", ProcessLinkNum); m_SOPXmlProcessors.Add("ClickAction", ProcessClickAction); m_SOPXmlProcessors.Add("Shape", ProcessShape); m_SOPXmlProcessors.Add("Scale", ProcessScale); m_SOPXmlProcessors.Add("UpdateFlag", ProcessUpdateFlag); m_SOPXmlProcessors.Add("SitTargetOrientation", ProcessSitTargetOrientation); m_SOPXmlProcessors.Add("SitTargetPosition", ProcessSitTargetPosition); m_SOPXmlProcessors.Add("SitTargetPositionLL", ProcessSitTargetPositionLL); m_SOPXmlProcessors.Add("SitTargetOrientationLL", ProcessSitTargetOrientationLL); m_SOPXmlProcessors.Add("ParentID", ProcessParentID); m_SOPXmlProcessors.Add("CreationDate", ProcessCreationDate); m_SOPXmlProcessors.Add("Category", ProcessCategory); m_SOPXmlProcessors.Add("SalePrice", ProcessSalePrice); m_SOPXmlProcessors.Add("ObjectSaleType", ProcessObjectSaleType); m_SOPXmlProcessors.Add("OwnershipCost", ProcessOwnershipCost); m_SOPXmlProcessors.Add("GroupID", ProcessGroupID); m_SOPXmlProcessors.Add("OwnerID", ProcessOwnerID); m_SOPXmlProcessors.Add("LastOwnerID", ProcessLastOwnerID); m_SOPXmlProcessors.Add("BaseMask", ProcessBaseMask); m_SOPXmlProcessors.Add("OwnerMask", ProcessOwnerMask); m_SOPXmlProcessors.Add("GroupMask", ProcessGroupMask); m_SOPXmlProcessors.Add("EveryoneMask", ProcessEveryoneMask); m_SOPXmlProcessors.Add("NextOwnerMask", ProcessNextOwnerMask); m_SOPXmlProcessors.Add("Flags", ProcessFlags); m_SOPXmlProcessors.Add("CollisionSound", ProcessCollisionSound); m_SOPXmlProcessors.Add("CollisionSoundVolume", ProcessCollisionSoundVolume); m_SOPXmlProcessors.Add("MediaUrl", ProcessMediaUrl); m_SOPXmlProcessors.Add("TextureAnimation", ProcessTextureAnimation); m_SOPXmlProcessors.Add("ParticleSystem", ProcessParticleSystem); #endregion #region TaskInventoryXmlProcessors initialization m_TaskInventoryXmlProcessors.Add("AssetID", ProcessTIAssetID); m_TaskInventoryXmlProcessors.Add("BasePermissions", ProcessTIBasePermissions); m_TaskInventoryXmlProcessors.Add("CreationDate", ProcessTICreationDate); m_TaskInventoryXmlProcessors.Add("CreatorID", ProcessTICreatorID); m_TaskInventoryXmlProcessors.Add("Description", ProcessTIDescription); m_TaskInventoryXmlProcessors.Add("EveryonePermissions", ProcessTIEveryonePermissions); m_TaskInventoryXmlProcessors.Add("Flags", ProcessTIFlags); m_TaskInventoryXmlProcessors.Add("GroupID", ProcessTIGroupID); m_TaskInventoryXmlProcessors.Add("GroupPermissions", ProcessTIGroupPermissions); m_TaskInventoryXmlProcessors.Add("InvType", ProcessTIInvType); m_TaskInventoryXmlProcessors.Add("ItemID", ProcessTIItemID); m_TaskInventoryXmlProcessors.Add("OldItemID", ProcessTIOldItemID); m_TaskInventoryXmlProcessors.Add("LastOwnerID", ProcessTILastOwnerID); m_TaskInventoryXmlProcessors.Add("Name", ProcessTIName); m_TaskInventoryXmlProcessors.Add("NextPermissions", ProcessTINextPermissions); m_TaskInventoryXmlProcessors.Add("OwnerID", ProcessTIOwnerID); m_TaskInventoryXmlProcessors.Add("CurrentPermissions", ProcessTICurrentPermissions); m_TaskInventoryXmlProcessors.Add("ParentID", ProcessTIParentID); m_TaskInventoryXmlProcessors.Add("ParentPartID", ProcessTIParentPartID); m_TaskInventoryXmlProcessors.Add("PermsGranter", ProcessTIPermsGranter); m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask); m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType); m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged); #endregion #region ShapeXmlProcessors initialization m_ShapeXmlProcessors.Add("ProfileCurve", ProcessShpProfileCurve); m_ShapeXmlProcessors.Add("TextureEntry", ProcessShpTextureEntry); m_ShapeXmlProcessors.Add("ExtraParams", ProcessShpExtraParams); m_ShapeXmlProcessors.Add("PathBegin", ProcessShpPathBegin); m_ShapeXmlProcessors.Add("PathCurve", ProcessShpPathCurve); m_ShapeXmlProcessors.Add("PathEnd", ProcessShpPathEnd); m_ShapeXmlProcessors.Add("PathRadiusOffset", ProcessShpPathRadiusOffset); m_ShapeXmlProcessors.Add("PathRevolutions", ProcessShpPathRevolutions); m_ShapeXmlProcessors.Add("PathScaleX", ProcessShpPathScaleX); m_ShapeXmlProcessors.Add("PathScaleY", ProcessShpPathScaleY); m_ShapeXmlProcessors.Add("PathShearX", ProcessShpPathShearX); m_ShapeXmlProcessors.Add("PathShearY", ProcessShpPathShearY); m_ShapeXmlProcessors.Add("PathSkew", ProcessShpPathSkew); m_ShapeXmlProcessors.Add("PathTaperX", ProcessShpPathTaperX); m_ShapeXmlProcessors.Add("PathTaperY", ProcessShpPathTaperY); m_ShapeXmlProcessors.Add("PathTwist", ProcessShpPathTwist); m_ShapeXmlProcessors.Add("PathTwistBegin", ProcessShpPathTwistBegin); m_ShapeXmlProcessors.Add("PCode", ProcessShpPCode); m_ShapeXmlProcessors.Add("ProfileBegin", ProcessShpProfileBegin); m_ShapeXmlProcessors.Add("ProfileEnd", ProcessShpProfileEnd); m_ShapeXmlProcessors.Add("ProfileHollow", ProcessShpProfileHollow); m_ShapeXmlProcessors.Add("Scale", ProcessShpScale); m_ShapeXmlProcessors.Add("State", ProcessShpState); m_ShapeXmlProcessors.Add("ProfileShape", ProcessShpProfileShape); m_ShapeXmlProcessors.Add("HollowShape", ProcessShpHollowShape); m_ShapeXmlProcessors.Add("SculptTexture", ProcessShpSculptTexture); m_ShapeXmlProcessors.Add("SculptType", ProcessShpSculptType); m_ShapeXmlProcessors.Add("SculptData", ProcessShpSculptData); m_ShapeXmlProcessors.Add("FlexiSoftness", ProcessShpFlexiSoftness); m_ShapeXmlProcessors.Add("FlexiTension", ProcessShpFlexiTension); m_ShapeXmlProcessors.Add("FlexiDrag", ProcessShpFlexiDrag); m_ShapeXmlProcessors.Add("FlexiGravity", ProcessShpFlexiGravity); m_ShapeXmlProcessors.Add("FlexiWind", ProcessShpFlexiWind); m_ShapeXmlProcessors.Add("FlexiForceX", ProcessShpFlexiForceX); m_ShapeXmlProcessors.Add("FlexiForceY", ProcessShpFlexiForceY); m_ShapeXmlProcessors.Add("FlexiForceZ", ProcessShpFlexiForceZ); m_ShapeXmlProcessors.Add("LightColorR", ProcessShpLightColorR); m_ShapeXmlProcessors.Add("LightColorG", ProcessShpLightColorG); m_ShapeXmlProcessors.Add("LightColorB", ProcessShpLightColorB); m_ShapeXmlProcessors.Add("LightColorA", ProcessShpLightColorA); m_ShapeXmlProcessors.Add("LightRadius", ProcessShpLightRadius); m_ShapeXmlProcessors.Add("LightCutoff", ProcessShpLightCutoff); m_ShapeXmlProcessors.Add("LightFalloff", ProcessShpLightFalloff); m_ShapeXmlProcessors.Add("LightIntensity", ProcessShpLightIntensity); m_ShapeXmlProcessors.Add("FlexiEntry", ProcessShpFlexiEntry); m_ShapeXmlProcessors.Add("LightEntry", ProcessShpLightEntry); m_ShapeXmlProcessors.Add("SculptEntry", ProcessShpSculptEntry); m_ShapeXmlProcessors.Add("Media", ProcessShpMedia); #endregion } #region SOPXmlProcessors private static void ProcessAllowedDrop(SceneObjectPart obj, XmlTextReader reader) { obj.AllowedDrop = reader.ReadElementContentAsBoolean("AllowedDrop", String.Empty); } private static void ProcessCreatorID(SceneObjectPart obj, XmlTextReader reader) { obj.CreatorID = ReadUUID(reader, "CreatorID"); } private static void ProcessFolderID(SceneObjectPart obj, XmlTextReader reader) { obj.FolderID = ReadUUID(reader, "FolderID"); } private static void ProcessInventorySerial(SceneObjectPart obj, XmlTextReader reader) { obj.InventorySerial = (uint)reader.ReadElementContentAsInt("InventorySerial", String.Empty); } private static void ProcessTaskInventory(SceneObjectPart obj, XmlTextReader reader) { obj.TaskInventory = ReadTaskInventory(reader, "TaskInventory"); } private static void ProcessUUID(SceneObjectPart obj, XmlTextReader reader) { obj.UUID = ReadUUID(reader, "UUID"); } private static void ProcessLocalId(SceneObjectPart obj, XmlTextReader reader) { obj.LocalId = (uint)reader.ReadElementContentAsLong("LocalId", String.Empty); } private static void ProcessName(SceneObjectPart obj, XmlTextReader reader) { obj.Name = reader.ReadElementString("Name"); } private static void ProcessMaterial(SceneObjectPart obj, XmlTextReader reader) { obj.Material = (byte)reader.ReadElementContentAsInt("Material", String.Empty); } private static void ProcessPassTouches(SceneObjectPart obj, XmlTextReader reader) { obj.PassTouches = reader.ReadElementContentAsBoolean("PassTouches", String.Empty); } private static void ProcessRegionHandle(SceneObjectPart obj, XmlTextReader reader) { obj.RegionHandle = (ulong)reader.ReadElementContentAsLong("RegionHandle", String.Empty); } private static void ProcessScriptAccessPin(SceneObjectPart obj, XmlTextReader reader) { obj.ScriptAccessPin = reader.ReadElementContentAsInt("ScriptAccessPin", String.Empty); } private static void ProcessGroupPosition(SceneObjectPart obj, XmlTextReader reader) { obj.GroupPosition = ReadVector(reader, "GroupPosition"); } private static void ProcessOffsetPosition(SceneObjectPart obj, XmlTextReader reader) { obj.OffsetPosition = ReadVector(reader, "OffsetPosition"); ; } private static void ProcessRotationOffset(SceneObjectPart obj, XmlTextReader reader) { obj.RotationOffset = ReadQuaternion(reader, "RotationOffset"); } private static void ProcessVelocity(SceneObjectPart obj, XmlTextReader reader) { obj.Velocity = ReadVector(reader, "Velocity"); } private static void ProcessAngularVelocity(SceneObjectPart obj, XmlTextReader reader) { obj.AngularVelocity = ReadVector(reader, "AngularVelocity"); } private static void ProcessAcceleration(SceneObjectPart obj, XmlTextReader reader) { obj.Acceleration = ReadVector(reader, "Acceleration"); } private static void ProcessDescription(SceneObjectPart obj, XmlTextReader reader) { obj.Description = reader.ReadElementString("Description"); } private static void ProcessColor(SceneObjectPart obj, XmlTextReader reader) { reader.ReadStartElement("Color"); if (reader.Name == "R") { float r = reader.ReadElementContentAsFloat("R", String.Empty); float g = reader.ReadElementContentAsFloat("G", String.Empty); float b = reader.ReadElementContentAsFloat("B", String.Empty); float a = reader.ReadElementContentAsFloat("A", String.Empty); obj.Color = Color.FromArgb((int)a, (int)r, (int)g, (int)b); reader.ReadEndElement(); } } private static void ProcessText(SceneObjectPart obj, XmlTextReader reader) { obj.Text = reader.ReadElementString("Text", String.Empty); } private static void ProcessSitName(SceneObjectPart obj, XmlTextReader reader) { obj.SitName = reader.ReadElementString("SitName", String.Empty); } private static void ProcessTouchName(SceneObjectPart obj, XmlTextReader reader) { obj.TouchName = reader.ReadElementString("TouchName", String.Empty); } private static void ProcessLinkNum(SceneObjectPart obj, XmlTextReader reader) { obj.LinkNum = reader.ReadElementContentAsInt("LinkNum", String.Empty); } private static void ProcessClickAction(SceneObjectPart obj, XmlTextReader reader) { obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty); } private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader) { obj.Shape = ReadShape(reader, "Shape"); } private static void ProcessScale(SceneObjectPart obj, XmlTextReader reader) { obj.Scale = ReadVector(reader, "Scale"); } private static void ProcessUpdateFlag(SceneObjectPart obj, XmlTextReader reader) { obj.UpdateFlag = (byte)reader.ReadElementContentAsInt("UpdateFlag", String.Empty); } private static void ProcessSitTargetOrientation(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetOrientation = ReadQuaternion(reader, "SitTargetOrientation"); } private static void ProcessSitTargetPosition(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetPosition = ReadVector(reader, "SitTargetPosition"); } private static void ProcessSitTargetPositionLL(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetPositionLL = ReadVector(reader, "SitTargetPositionLL"); } private static void ProcessSitTargetOrientationLL(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetOrientationLL = ReadQuaternion(reader, "SitTargetOrientationLL"); } private static void ProcessParentID(SceneObjectPart obj, XmlTextReader reader) { string str = reader.ReadElementContentAsString("ParentID", String.Empty); obj.ParentID = Convert.ToUInt32(str); } private static void ProcessCreationDate(SceneObjectPart obj, XmlTextReader reader) { obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessCategory(SceneObjectPart obj, XmlTextReader reader) { obj.Category = (uint)reader.ReadElementContentAsInt("Category", String.Empty); } private static void ProcessSalePrice(SceneObjectPart obj, XmlTextReader reader) { obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty); } private static void ProcessObjectSaleType(SceneObjectPart obj, XmlTextReader reader) { obj.ObjectSaleType = (byte)reader.ReadElementContentAsInt("ObjectSaleType", String.Empty); } private static void ProcessOwnershipCost(SceneObjectPart obj, XmlTextReader reader) { obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty); } private static void ProcessGroupID(SceneObjectPart obj, XmlTextReader reader) { obj.GroupID = ReadUUID(reader, "GroupID"); } private static void ProcessOwnerID(SceneObjectPart obj, XmlTextReader reader) { obj.OwnerID = ReadUUID(reader, "OwnerID"); } private static void ProcessLastOwnerID(SceneObjectPart obj, XmlTextReader reader) { obj.LastOwnerID = ReadUUID(reader, "LastOwnerID"); } private static void ProcessBaseMask(SceneObjectPart obj, XmlTextReader reader) { obj.BaseMask = (uint)reader.ReadElementContentAsInt("BaseMask", String.Empty); } private static void ProcessOwnerMask(SceneObjectPart obj, XmlTextReader reader) { obj.OwnerMask = (uint)reader.ReadElementContentAsInt("OwnerMask", String.Empty); } private static void ProcessGroupMask(SceneObjectPart obj, XmlTextReader reader) { obj.GroupMask = (uint)reader.ReadElementContentAsInt("GroupMask", String.Empty); } private static void ProcessEveryoneMask(SceneObjectPart obj, XmlTextReader reader) { obj.EveryoneMask = (uint)reader.ReadElementContentAsInt("EveryoneMask", String.Empty); } private static void ProcessNextOwnerMask(SceneObjectPart obj, XmlTextReader reader) { obj.NextOwnerMask = (uint)reader.ReadElementContentAsInt("NextOwnerMask", String.Empty); } private static void ProcessFlags(SceneObjectPart obj, XmlTextReader reader) { string value = reader.ReadElementContentAsString("Flags", String.Empty); // !!!!! to deal with flags without commas if (value.Contains(" ") && !value.Contains(",")) value = value.Replace(" ", ", "); obj.Flags = (PrimFlags)Enum.Parse(typeof(PrimFlags), value); } private static void ProcessCollisionSound(SceneObjectPart obj, XmlTextReader reader) { obj.CollisionSound = ReadUUID(reader, "CollisionSound"); } private static void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlTextReader reader) { obj.CollisionSoundVolume = reader.ReadElementContentAsFloat("CollisionSoundVolume", String.Empty); } private static void ProcessMediaUrl(SceneObjectPart obj, XmlTextReader reader) { obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty); } private static void ProcessTextureAnimation(SceneObjectPart obj, XmlTextReader reader) { obj.TextureAnimation = Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty)); } private static void ProcessParticleSystem(SceneObjectPart obj, XmlTextReader reader) { obj.ParticleSystem = Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty)); } #endregion #region TaskInventoryXmlProcessors private static void ProcessTIAssetID(TaskInventoryItem item, XmlTextReader reader) { item.AssetID = ReadUUID(reader, "AssetID"); } private static void ProcessTIBasePermissions(TaskInventoryItem item, XmlTextReader reader) { item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty); } private static void ProcessTICreationDate(TaskInventoryItem item, XmlTextReader reader) { item.CreationDate = (uint)reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessTICreatorID(TaskInventoryItem item, XmlTextReader reader) { item.CreatorID = ReadUUID(reader, "CreatorID"); } private static void ProcessTIDescription(TaskInventoryItem item, XmlTextReader reader) { item.Description = reader.ReadElementContentAsString("Description", String.Empty); } private static void ProcessTIEveryonePermissions(TaskInventoryItem item, XmlTextReader reader) { item.EveryonePermissions = (uint)reader.ReadElementContentAsInt("EveryonePermissions", String.Empty); } private static void ProcessTIFlags(TaskInventoryItem item, XmlTextReader reader) { item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty); } private static void ProcessTIGroupID(TaskInventoryItem item, XmlTextReader reader) { item.GroupID = ReadUUID(reader, "GroupID"); } private static void ProcessTIGroupPermissions(TaskInventoryItem item, XmlTextReader reader) { item.GroupPermissions = (uint)reader.ReadElementContentAsInt("GroupPermissions", String.Empty); } private static void ProcessTIInvType(TaskInventoryItem item, XmlTextReader reader) { item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty); } private static void ProcessTIItemID(TaskInventoryItem item, XmlTextReader reader) { item.ItemID = ReadUUID(reader, "ItemID"); } private static void ProcessTIOldItemID(TaskInventoryItem item, XmlTextReader reader) { item.OldItemID = ReadUUID(reader, "OldItemID"); } private static void ProcessTILastOwnerID(TaskInventoryItem item, XmlTextReader reader) { item.LastOwnerID = ReadUUID(reader, "LastOwnerID"); } private static void ProcessTIName(TaskInventoryItem item, XmlTextReader reader) { item.Name = reader.ReadElementContentAsString("Name", String.Empty); } private static void ProcessTINextPermissions(TaskInventoryItem item, XmlTextReader reader) { item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty); } private static void ProcessTIOwnerID(TaskInventoryItem item, XmlTextReader reader) { item.OwnerID = ReadUUID(reader, "OwnerID"); } private static void ProcessTICurrentPermissions(TaskInventoryItem item, XmlTextReader reader) { item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty); } private static void ProcessTIParentID(TaskInventoryItem item, XmlTextReader reader) { item.ParentID = ReadUUID(reader, "ParentID"); } private static void ProcessTIParentPartID(TaskInventoryItem item, XmlTextReader reader) { item.ParentPartID = ReadUUID(reader, "ParentPartID"); } private static void ProcessTIPermsGranter(TaskInventoryItem item, XmlTextReader reader) { item.PermsGranter = ReadUUID(reader, "PermsGranter"); } private static void ProcessTIPermsMask(TaskInventoryItem item, XmlTextReader reader) { item.PermsMask = reader.ReadElementContentAsInt("PermsMask", String.Empty); } private static void ProcessTIType(TaskInventoryItem item, XmlTextReader reader) { item.Type = reader.ReadElementContentAsInt("Type", String.Empty); } private static void ProcessTIOwnerChanged(TaskInventoryItem item, XmlTextReader reader) { item.OwnerChanged = reader.ReadElementContentAsBoolean("OwnerChanged", String.Empty); } #endregion #region ShapeXmlProcessors private static void ProcessShpProfileCurve(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileCurve = (byte)reader.ReadElementContentAsInt("ProfileCurve", String.Empty); } private static void ProcessShpTextureEntry(PrimitiveBaseShape shp, XmlTextReader reader) { byte[] teData = Convert.FromBase64String(reader.ReadElementString("TextureEntry")); shp.Textures = new Primitive.TextureEntry(teData, 0, teData.Length); } private static void ProcessShpExtraParams(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ExtraParams = Convert.FromBase64String(reader.ReadElementString("ExtraParams")); } private static void ProcessShpPathBegin(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathBegin = (ushort)reader.ReadElementContentAsInt("PathBegin", String.Empty); } private static void ProcessShpPathCurve(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathCurve = (byte)reader.ReadElementContentAsInt("PathCurve", String.Empty); } private static void ProcessShpPathEnd(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathEnd = (ushort)reader.ReadElementContentAsInt("PathEnd", String.Empty); } private static void ProcessShpPathRadiusOffset(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathRadiusOffset = (sbyte)reader.ReadElementContentAsInt("PathRadiusOffset", String.Empty); } private static void ProcessShpPathRevolutions(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathRevolutions = (byte)reader.ReadElementContentAsInt("PathRevolutions", String.Empty); } private static void ProcessShpPathScaleX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathScaleX = (byte)reader.ReadElementContentAsInt("PathScaleX", String.Empty); } private static void ProcessShpPathScaleY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathScaleY = (byte)reader.ReadElementContentAsInt("PathScaleY", String.Empty); } private static void ProcessShpPathShearX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathShearX = (byte)reader.ReadElementContentAsInt("PathShearX", String.Empty); } private static void ProcessShpPathShearY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathShearY = (byte)reader.ReadElementContentAsInt("PathShearY", String.Empty); } private static void ProcessShpPathSkew(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathSkew = (sbyte)reader.ReadElementContentAsInt("PathSkew", String.Empty); } private static void ProcessShpPathTaperX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTaperX = (sbyte)reader.ReadElementContentAsInt("PathTaperX", String.Empty); } private static void ProcessShpPathTaperY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTaperY = (sbyte)reader.ReadElementContentAsInt("PathTaperY", String.Empty); } private static void ProcessShpPathTwist(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTwist = (sbyte)reader.ReadElementContentAsInt("PathTwist", String.Empty); } private static void ProcessShpPathTwistBegin(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTwistBegin = (sbyte)reader.ReadElementContentAsInt("PathTwistBegin", String.Empty); } private static void ProcessShpPCode(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PCode = (byte)reader.ReadElementContentAsInt("PCode", String.Empty); } private static void ProcessShpProfileBegin(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileBegin = (ushort)reader.ReadElementContentAsInt("ProfileBegin", String.Empty); } private static void ProcessShpProfileEnd(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileEnd = (ushort)reader.ReadElementContentAsInt("ProfileEnd", String.Empty); } private static void ProcessShpProfileHollow(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileHollow = (ushort)reader.ReadElementContentAsInt("ProfileHollow", String.Empty); } private static void ProcessShpScale(PrimitiveBaseShape shp, XmlTextReader reader) { shp.Scale = ReadVector(reader, "Scale"); } private static void ProcessShpState(PrimitiveBaseShape shp, XmlTextReader reader) { shp.State = (byte)reader.ReadElementContentAsInt("State", String.Empty); } private static void ProcessShpProfileShape(PrimitiveBaseShape shp, XmlTextReader reader) { string value = reader.ReadElementContentAsString("ProfileShape", String.Empty); // !!!!! to deal with flags without commas if (value.Contains(" ") && !value.Contains(",")) value = value.Replace(" ", ", "); shp.ProfileShape = (ProfileShape)Enum.Parse(typeof(ProfileShape), value); } private static void ProcessShpHollowShape(PrimitiveBaseShape shp, XmlTextReader reader) { string value = reader.ReadElementContentAsString("HollowShape", String.Empty); // !!!!! to deal with flags without commas if (value.Contains(" ") && !value.Contains(",")) value = value.Replace(" ", ", "); shp.HollowShape = (HollowShape)Enum.Parse(typeof(HollowShape), value); } private static void ProcessShpSculptTexture(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptTexture = ReadUUID(reader, "SculptTexture"); } private static void ProcessShpSculptType(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptType = (byte)reader.ReadElementContentAsInt("SculptType", String.Empty); } private static void ProcessShpSculptData(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptData = Convert.FromBase64String(reader.ReadElementString("SculptData")); } private static void ProcessShpFlexiSoftness(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiSoftness = reader.ReadElementContentAsInt("FlexiSoftness", String.Empty); } private static void ProcessShpFlexiTension(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiTension = reader.ReadElementContentAsFloat("FlexiTension", String.Empty); } private static void ProcessShpFlexiDrag(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiDrag = reader.ReadElementContentAsFloat("FlexiDrag", String.Empty); } private static void ProcessShpFlexiGravity(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiGravity = reader.ReadElementContentAsFloat("FlexiGravity", String.Empty); } private static void ProcessShpFlexiWind(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiWind = reader.ReadElementContentAsFloat("FlexiWind", String.Empty); } private static void ProcessShpFlexiForceX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiForceX = reader.ReadElementContentAsFloat("FlexiForceX", String.Empty); } private static void ProcessShpFlexiForceY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiForceY = reader.ReadElementContentAsFloat("FlexiForceY", String.Empty); } private static void ProcessShpFlexiForceZ(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiForceZ = reader.ReadElementContentAsFloat("FlexiForceZ", String.Empty); } private static void ProcessShpLightColorR(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorR = reader.ReadElementContentAsFloat("LightColorR", String.Empty); } private static void ProcessShpLightColorG(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorG = reader.ReadElementContentAsFloat("LightColorG", String.Empty); } private static void ProcessShpLightColorB(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorB = reader.ReadElementContentAsFloat("LightColorB", String.Empty); } private static void ProcessShpLightColorA(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorA = reader.ReadElementContentAsFloat("LightColorA", String.Empty); } private static void ProcessShpLightRadius(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightRadius = reader.ReadElementContentAsFloat("LightRadius", String.Empty); } private static void ProcessShpLightCutoff(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightCutoff = reader.ReadElementContentAsFloat("LightCutoff", String.Empty); } private static void ProcessShpLightFalloff(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightFalloff = reader.ReadElementContentAsFloat("LightFalloff", String.Empty); } private static void ProcessShpLightIntensity(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightIntensity = reader.ReadElementContentAsFloat("LightIntensity", String.Empty); } private static void ProcessShpFlexiEntry(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiEntry = reader.ReadElementContentAsBoolean("FlexiEntry", String.Empty); } private static void ProcessShpLightEntry(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightEntry = reader.ReadElementContentAsBoolean("LightEntry", String.Empty); } private static void ProcessShpSculptEntry(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptEntry = reader.ReadElementContentAsBoolean("SculptEntry", String.Empty); } private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlTextReader reader) { string value = reader.ReadElementContentAsString("Media", String.Empty); shp.Media = PrimitiveBaseShape.MediaList.FromXml(value); } #endregion ////////// Write ///////// public static void SOGToXml2(XmlTextWriter writer, SceneObjectGroup sog, Dictionary<string, object>options) { writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); SOPToXml2(writer, sog.RootPart, options); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); sog.ForEachPart(delegate(SceneObjectPart sop) { if (sop.UUID != sog.RootPart.UUID) SOPToXml2(writer, sop, options); }); writer.WriteEndElement(); writer.WriteEndElement(); } public static void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options) { writer.WriteStartElement("SceneObjectPart"); writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower()); WriteUUID(writer, "CreatorID", sop.CreatorID, options); WriteUUID(writer, "FolderID", sop.FolderID, options); writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString()); WriteTaskInventory(writer, sop.TaskInventory, options); WriteUUID(writer, "UUID", sop.UUID, options); writer.WriteElementString("LocalId", sop.LocalId.ToString()); writer.WriteElementString("Name", sop.Name); writer.WriteElementString("Material", sop.Material.ToString()); writer.WriteElementString("PassTouches", sop.PassTouches.ToString().ToLower()); writer.WriteElementString("RegionHandle", sop.RegionHandle.ToString()); writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString()); WriteVector(writer, "GroupPosition", sop.GroupPosition); WriteVector(writer, "OffsetPosition", sop.OffsetPosition); WriteQuaternion(writer, "RotationOffset", sop.RotationOffset); WriteVector(writer, "Velocity", sop.Velocity); WriteVector(writer, "AngularVelocity", sop.AngularVelocity); WriteVector(writer, "Acceleration", sop.Acceleration); writer.WriteElementString("Description", sop.Description); if (sop.Color != null) { writer.WriteStartElement("Color"); writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture)); writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture)); writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture)); writer.WriteElementString("A", sop.Color.G.ToString(Utils.EnUsCulture)); writer.WriteEndElement(); } writer.WriteElementString("Text", sop.Text); writer.WriteElementString("SitName", sop.SitName); writer.WriteElementString("TouchName", sop.TouchName); writer.WriteElementString("LinkNum", sop.LinkNum.ToString()); writer.WriteElementString("ClickAction", sop.ClickAction.ToString()); WriteShape(writer, sop.Shape, options); WriteVector(writer, "Scale", sop.Scale); writer.WriteElementString("UpdateFlag", sop.UpdateFlag.ToString()); WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation); WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition); WriteVector(writer, "SitTargetPositionLL", sop.SitTargetPositionLL); WriteQuaternion(writer, "SitTargetOrientationLL", sop.SitTargetOrientationLL); writer.WriteElementString("ParentID", sop.ParentID.ToString()); writer.WriteElementString("CreationDate", sop.CreationDate.ToString()); writer.WriteElementString("Category", sop.Category.ToString()); writer.WriteElementString("SalePrice", sop.SalePrice.ToString()); writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString()); writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString()); WriteUUID(writer, "GroupID", sop.GroupID, options); WriteUUID(writer, "OwnerID", sop.OwnerID, options); WriteUUID(writer, "LastOwnerID", sop.LastOwnerID, options); writer.WriteElementString("BaseMask", sop.BaseMask.ToString()); writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString()); writer.WriteElementString("GroupMask", sop.GroupMask.ToString()); writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString()); writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString()); WriteFlags(writer, "Flags", sop.Flags.ToString(), options); WriteUUID(writer, "CollisionSound", sop.CollisionSound, options); writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString()); if (sop.MediaUrl != null) writer.WriteElementString("MediaUrl", sop.MediaUrl.ToString()); WriteBytes(writer, "TextureAnimation", sop.TextureAnimation); WriteBytes(writer, "ParticleSystem", sop.ParticleSystem); writer.WriteEndElement(); } static void WriteUUID(XmlTextWriter writer, string name, UUID id, Dictionary<string, object> options) { writer.WriteStartElement(name); if (options.ContainsKey("old-guids")) writer.WriteElementString("Guid", id.ToString()); else writer.WriteElementString("UUID", id.ToString()); writer.WriteEndElement(); } static void WriteVector(XmlTextWriter writer, string name, Vector3 vec) { writer.WriteStartElement(name); writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture)); writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture)); writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture)); writer.WriteEndElement(); } static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat) { writer.WriteStartElement(name); writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture)); writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture)); writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture)); writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture)); writer.WriteEndElement(); } static void WriteBytes(XmlTextWriter writer, string name, byte[] data) { writer.WriteStartElement(name); byte[] d; if (data != null) d = data; else d = Utils.EmptyBytes; writer.WriteBase64(d, 0, d.Length); writer.WriteEndElement(); // name } static void WriteFlags(XmlTextWriter writer, string name, string flagsStr, Dictionary<string, object> options) { // Older versions of serialization can't cope with commas if (options.ContainsKey("version")) { float version = 0.5F; float.TryParse(options["version"].ToString(), out version); if (version < 0.5) flagsStr = flagsStr.Replace(",", ""); } writer.WriteElementString(name, flagsStr); } static void WriteTaskInventory(XmlTextWriter writer, TaskInventoryDictionary tinv, Dictionary<string, object> options) { if (tinv.Count > 0) // otherwise skip this { writer.WriteStartElement("TaskInventory"); foreach (TaskInventoryItem item in tinv.Values) { writer.WriteStartElement("TaskInventoryItem"); WriteUUID(writer, "AssetID", item.AssetID, options); writer.WriteElementString("BasePermissions", item.BasePermissions.ToString()); writer.WriteElementString("CreationDate", item.CreationDate.ToString()); WriteUUID(writer, "CreatorID", item.CreatorID, options); writer.WriteElementString("Description", item.Description); writer.WriteElementString("EveryonePermissions", item.EveryonePermissions.ToString()); writer.WriteElementString("Flags", item.Flags.ToString()); WriteUUID(writer, "GroupID", item.GroupID, options); writer.WriteElementString("GroupPermissions", item.GroupPermissions.ToString()); writer.WriteElementString("InvType", item.InvType.ToString()); WriteUUID(writer, "ItemID", item.ItemID, options); WriteUUID(writer, "OldItemID", item.OldItemID, options); WriteUUID(writer, "LastOwnerID", item.LastOwnerID, options); writer.WriteElementString("Name", item.Name); writer.WriteElementString("NextPermissions", item.NextPermissions.ToString()); WriteUUID(writer, "OwnerID", item.OwnerID, options); writer.WriteElementString("CurrentPermissions", item.CurrentPermissions.ToString()); WriteUUID(writer, "ParentID", item.ParentID, options); WriteUUID(writer, "ParentPartID", item.ParentPartID, options); WriteUUID(writer, "PermsGranter", item.PermsGranter, options); writer.WriteElementString("PermsMask", item.PermsMask.ToString()); writer.WriteElementString("Type", item.Type.ToString()); writer.WriteElementString("OwnerChanged", item.OwnerChanged.ToString().ToLower()); writer.WriteEndElement(); // TaskInventoryItem } writer.WriteEndElement(); // TaskInventory } } static void WriteShape(XmlTextWriter writer, PrimitiveBaseShape shp, Dictionary<string, object> options) { if (shp != null) { writer.WriteStartElement("Shape"); writer.WriteElementString("ProfileCurve", shp.ProfileCurve.ToString()); writer.WriteStartElement("TextureEntry"); byte[] te; if (shp.TextureEntry != null) te = shp.TextureEntry; else te = Utils.EmptyBytes; writer.WriteBase64(te, 0, te.Length); writer.WriteEndElement(); // TextureEntry writer.WriteStartElement("ExtraParams"); byte[] ep; if (shp.ExtraParams != null) ep = shp.ExtraParams; else ep = Utils.EmptyBytes; writer.WriteBase64(ep, 0, ep.Length); writer.WriteEndElement(); // ExtraParams writer.WriteElementString("PathBegin", shp.PathBegin.ToString()); writer.WriteElementString("PathCurve", shp.PathCurve.ToString()); writer.WriteElementString("PathEnd", shp.PathEnd.ToString()); writer.WriteElementString("PathRadiusOffset", shp.PathRadiusOffset.ToString()); writer.WriteElementString("PathRevolutions", shp.PathRevolutions.ToString()); writer.WriteElementString("PathScaleX", shp.PathScaleX.ToString()); writer.WriteElementString("PathScaleY", shp.PathScaleY.ToString()); writer.WriteElementString("PathShearX", shp.PathShearX.ToString()); writer.WriteElementString("PathShearY", shp.PathShearY.ToString()); writer.WriteElementString("PathSkew", shp.PathSkew.ToString()); writer.WriteElementString("PathTaperX", shp.PathTaperX.ToString()); writer.WriteElementString("PathTaperY", shp.PathTaperY.ToString()); writer.WriteElementString("PathTwist", shp.PathTwist.ToString()); writer.WriteElementString("PathTwistBegin", shp.PathTwistBegin.ToString()); writer.WriteElementString("PCode", shp.PCode.ToString()); writer.WriteElementString("ProfileBegin", shp.ProfileBegin.ToString()); writer.WriteElementString("ProfileEnd", shp.ProfileEnd.ToString()); writer.WriteElementString("ProfileHollow", shp.ProfileHollow.ToString()); writer.WriteElementString("State", shp.State.ToString()); WriteFlags(writer, "ProfileShape", shp.ProfileShape.ToString(), options); WriteFlags(writer, "HollowShape", shp.HollowShape.ToString(), options); WriteUUID(writer, "SculptTexture", shp.SculptTexture, options); writer.WriteElementString("SculptType", shp.SculptType.ToString()); writer.WriteStartElement("SculptData"); byte[] sd; if (shp.SculptData != null) sd = shp.ExtraParams; else sd = Utils.EmptyBytes; writer.WriteBase64(sd, 0, sd.Length); writer.WriteEndElement(); // SculptData writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString()); writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString()); writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString()); writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString()); writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString()); writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString()); writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString()); writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString()); writer.WriteElementString("LightColorR", shp.LightColorR.ToString()); writer.WriteElementString("LightColorG", shp.LightColorG.ToString()); writer.WriteElementString("LightColorB", shp.LightColorB.ToString()); writer.WriteElementString("LightColorA", shp.LightColorA.ToString()); writer.WriteElementString("LightRadius", shp.LightRadius.ToString()); writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString()); writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString()); writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString()); writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower()); writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower()); writer.WriteElementString("SculptEntry", shp.SculptEntry.ToString().ToLower()); if (shp.Media != null) writer.WriteElementString("Media", shp.Media.ToXml()); writer.WriteEndElement(); // Shape } } //////// Read ///////// public static bool Xml2ToSOG(XmlTextReader reader, SceneObjectGroup sog) { reader.Read(); reader.ReadStartElement("SceneObjectGroup"); SceneObjectPart root = Xml2ToSOP(reader); if (root != null) sog.SetRootPart(root); else { return false; } if (sog.UUID == UUID.Zero) sog.UUID = sog.RootPart.UUID; reader.Read(); // OtherParts while (!reader.EOF) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "SceneObjectPart") { SceneObjectPart child = Xml2ToSOP(reader); if (child != null) sog.AddPart(child); } else { //Logger.Log("Found unexpected prim XML element " + reader.Name, Helpers.LogLevel.Debug); reader.Read(); } break; case XmlNodeType.EndElement: default: reader.Read(); break; } } return true; } public static SceneObjectPart Xml2ToSOP(XmlTextReader reader) { SceneObjectPart obj = new SceneObjectPart(); reader.ReadStartElement("SceneObjectPart"); string nodeName = string.Empty; while (reader.NodeType != XmlNodeType.EndElement) { nodeName = reader.Name; SOPXmlProcessor p = null; if (m_SOPXmlProcessors.TryGetValue(reader.Name, out p)) { //m_log.DebugFormat("[XXX] Processing: {0}", reader.Name); try { p(obj, reader); } catch (Exception e) { m_log.DebugFormat("[SceneObjectSerializer]: exception while parsing {0}: {1}", nodeName, e); if (reader.NodeType == XmlNodeType.EndElement) reader.Read(); } } else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element {0}", nodeName); reader.ReadOuterXml(); // ignore } } reader.ReadEndElement(); // SceneObjectPart //m_log.DebugFormat("[XXX]: parsed SOP {0} - {1}", obj.Name, obj.UUID); return obj; } static UUID ReadUUID(XmlTextReader reader, string name) { UUID id; string idStr; reader.ReadStartElement(name); if (reader.Name == "Guid") idStr = reader.ReadElementString("Guid"); else // UUID idStr = reader.ReadElementString("UUID"); UUID.TryParse(idStr, out id); reader.ReadEndElement(); return id; } static Vector3 ReadVector(XmlTextReader reader, string name) { Vector3 vec; reader.ReadStartElement(name); vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z reader.ReadEndElement(); return vec; } static Quaternion ReadQuaternion(XmlTextReader reader, string name) { Quaternion quat = new Quaternion(); reader.ReadStartElement(name); while (reader.NodeType != XmlNodeType.EndElement) { switch (reader.Name.ToLower()) { case "x": quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); break; case "y": quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); break; case "z": quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); break; case "w": quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty); break; } } reader.ReadEndElement(); return quat; } static TaskInventoryDictionary ReadTaskInventory(XmlTextReader reader, string name) { TaskInventoryDictionary tinv = new TaskInventoryDictionary(); reader.ReadStartElement(name, String.Empty); while (reader.Name == "TaskInventoryItem") { reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory TaskInventoryItem item = new TaskInventoryItem(); while (reader.NodeType != XmlNodeType.EndElement) { TaskInventoryXmlProcessor p = null; if (m_TaskInventoryXmlProcessors.TryGetValue(reader.Name, out p)) p(item, reader); else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element in TaskInventory {0}, {1}", reader.Name, reader.Value); reader.ReadOuterXml(); } } reader.ReadEndElement(); // TaskInventoryItem tinv.Add(item.ItemID, item); } if (reader.NodeType == XmlNodeType.EndElement) reader.ReadEndElement(); // TaskInventory return tinv; } static PrimitiveBaseShape ReadShape(XmlTextReader reader, string name) { PrimitiveBaseShape shape = new PrimitiveBaseShape(); reader.ReadStartElement(name, String.Empty); // Shape string nodeName = string.Empty; while (reader.NodeType != XmlNodeType.EndElement) { nodeName = reader.Name; //m_log.DebugFormat("[XXX] Processing: {0}", reader.Name); ShapeXmlProcessor p = null; if (m_ShapeXmlProcessors.TryGetValue(reader.Name, out p)) { try { p(shape, reader); } catch (Exception e) { m_log.DebugFormat("[SceneObjectSerializer]: exception while parsing Shape {0}: {1}", nodeName, e); if (reader.NodeType == XmlNodeType.EndElement) reader.Read(); } } else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element in Shape {0}", reader.Name); reader.ReadOuterXml(); } } reader.ReadEndElement(); // Shape return shape; } #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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.ReferenceHighlighting { internal abstract class AbstractDocumentHighlightsService : IDocumentHighlightsService { public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { // use speculative semantic model to see whether we are on a symbol we can do HR var span = new TextSpan(position, 0); var solution = document.Project.Solution; var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } // Get unique tags for referenced symbols return await GetTagsForReferencedSymbolAsync( new SymbolAndProjectId(symbol, document.Project.Id), documentsToSearch, solution, cancellationToken).ConfigureAwait(false); } private async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken) { // see whether we can use the symbol as it is var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (currentSemanticModel == semanticModel) { return symbol; } // get symbols from current document again return await SymbolFinder.FindSymbolAtPositionAsync(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<DocumentHighlights>> GetTagsForReferencedSymbolAsync( SymbolAndProjectId symbolAndProjectId, IImmutableSet<Document> documentsToSearch, Solution solution, CancellationToken cancellationToken) { var symbol = symbolAndProjectId.Symbol; Contract.ThrowIfNull(symbol); if (ShouldConsiderSymbol(symbol)) { var progress = new StreamingProgressCollector( StreamingFindReferencesProgress.Instance); await SymbolFinder.FindReferencesAsync( symbolAndProjectId, solution, progress, documentsToSearch, cancellationToken).ConfigureAwait(false); return await FilterAndCreateSpansAsync( progress.GetReferencedSymbols(), solution, documentsToSearch, symbol, cancellationToken).ConfigureAwait(false); } return ImmutableArray<DocumentHighlights>.Empty; } private bool ShouldConsiderSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: switch (((IMethodSymbol)symbol).MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: return false; default: return true; } default: return true; } } private async Task<ImmutableArray<DocumentHighlights>> FilterAndCreateSpansAsync( IEnumerable<ReferencedSymbol> references, Solution solution, IImmutableSet<Document> documentsToSearch, ISymbol symbol, CancellationToken cancellationToken) { references = references.FilterToItemsToShow(); references = references.FilterNonMatchingMethodNames(solution, symbol); references = references.FilterToAliasMatches(symbol as IAliasSymbol); if (symbol.IsConstructor()) { references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition)); } var additionalReferences = new List<Location>(); foreach (var document in documentsToSearch) { additionalReferences.AddRange(await GetAdditionalReferencesAsync(document, symbol, cancellationToken).ConfigureAwait(false)); } return await CreateSpansAsync( solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false); } private Task<IEnumerable<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { var additionalReferenceProvider = document.Project.LanguageServices.GetService<IReferenceHighlightingAdditionalReferenceProvider>(); if (additionalReferenceProvider != null) { return additionalReferenceProvider.GetAdditionalReferencesAsync(document, symbol, cancellationToken); } return Task.FromResult(SpecializedCollections.EmptyEnumerable<Location>()); } private async Task<ImmutableArray<DocumentHighlights>> CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable<ReferencedSymbol> references, IEnumerable<Location> additionalReferences, IImmutableSet<Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet<DocumentSpan>(); var tagMap = new MultiDictionary<Document, HighlightSpan>(); bool addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind == "Interactive"); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } var list = ArrayBuilder<DocumentHighlights>.GetInstance(tagMap.Count); foreach (var kvp in tagMap) { var spans = ArrayBuilder<HighlightSpan>.GetInstance(kvp.Value.Count); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans.ToImmutableAndFree())); } return list.ToImmutableAndFree(); } private static bool ShouldIncludeDefinition(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Namespace: return false; case SymbolKind.NamedType: return !((INamedTypeSymbol)symbol).IsScriptClass; case SymbolKind.Parameter: // If it's an indexer parameter, we will have also cascaded to the accessor // one that actually receives the references var containingProperty = symbol.ContainingSymbol as IPropertySymbol; if (containingProperty != null && containingProperty.IsIndexer) { return false; } break; } return true; } private async Task AddLocationSpan(Location location, Solution solution, HashSet<DocumentSpan> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken) { var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false); if (span != null && !spanSet.Contains(span.Value)) { spanSet.Add(span.Value); tagList.Add(span.Value.Document, new HighlightSpan(span.Value.SourceSpan, kind)); } } private async Task<DocumentSpan?> GetLocationSpanAsync( Solution solution, Location location, CancellationToken cancellationToken) { try { if (location != null && location.IsInSource) { var tree = location.SourceTree; var document = solution.GetDocument(tree); var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); if (syntaxFacts != null) { // Specify findInsideTrivia: true to ensure that we search within XML doc comments. var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true); return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent) ? new DocumentSpan(document, token.Span) : new DocumentSpan(document, location.SourceSpan); } } } catch (NullReferenceException e) when (FatalError.ReportWithoutCrash(e)) { // We currently are seeing a strange null references crash in this code. We have // a strong belief that this is recoverable, but we'd like to know why it is // happening. This exception filter allows us to report the issue and continue // without damaging the user experience. Once we get more crash reports, we // can figure out the root cause and address appropriately. This is preferable // to just using conditionl access operators to be resilient (as we won't actually // know why this is happening). } return null; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: TextWriter ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: Abstract base class for Text-only Writers. ** Subclasses will include StreamWriter & StringWriter. ** ** ===========================================================*/ using System; using System.Text; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection; using System.Security.Permissions; using System.Globalization; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; #if FEATURE_ASYNC_IO using System.Threading.Tasks; #endif namespace System.IO { // This abstract base class represents a writer that can write a sequential // stream of characters. A subclass must minimally implement the // Write(char) method. // // This class is intended for character output, not bytes. // There are methods on the Stream class for writing bytes. [Serializable] [ComVisible(true)] #if FEATURE_REMOTING public abstract class TextWriter : MarshalByRefObject, IDisposable { #else // FEATURE_REMOTING public abstract class TextWriter : IDisposable { #endif // FEATURE_REMOTING public static readonly TextWriter Null = new NullTextWriter(); #if FEATURE_ASYNC_IO [NonSerialized] private static Action<object> _WriteCharDelegate = state => { Tuple<TextWriter, char> tuple = (Tuple<TextWriter, char>)state; tuple.Item1.Write(tuple.Item2); }; [NonSerialized] private static Action<object> _WriteStringDelegate = state => { Tuple<TextWriter, string> tuple = (Tuple<TextWriter, string>)state; tuple.Item1.Write(tuple.Item2); }; [NonSerialized] private static Action<object> _WriteCharArrayRangeDelegate = state => { Tuple<TextWriter, char[], int, int> tuple = (Tuple<TextWriter, char[],int, int>)state; tuple.Item1.Write(tuple.Item2, tuple.Item3, tuple.Item4); }; [NonSerialized] private static Action<object> _WriteLineCharDelegate = state => { Tuple<TextWriter, char> tuple = (Tuple<TextWriter, char>)state; tuple.Item1.WriteLine(tuple.Item2); }; [NonSerialized] private static Action<object> _WriteLineStringDelegate = state => { Tuple<TextWriter, string> tuple = (Tuple<TextWriter, string>)state; tuple.Item1.WriteLine(tuple.Item2); }; [NonSerialized] private static Action<object> _WriteLineCharArrayRangeDelegate = state => { Tuple<TextWriter, char[], int, int> tuple = (Tuple<TextWriter, char[],int, int>)state; tuple.Item1.WriteLine(tuple.Item2, tuple.Item3, tuple.Item4); }; [NonSerialized] private static Action<object> _FlushDelegate = state => ((TextWriter)state).Flush(); #endif // This should be initialized to Environment.NewLine, but // to avoid loading Environment unnecessarily so I've duplicated // the value here. #if MONO static string InitialNewLine { get { return Environment.NewLine; } } protected char[] CoreNewLine = InitialNewLine.ToCharArray (); #else #if !PLATFORM_UNIX private const String InitialNewLine = "\r\n"; protected char[] CoreNewLine = new char[] { '\r', '\n' }; #else private const String InitialNewLine = "\n"; protected char[] CoreNewLine = new char[] {'\n'}; #endif // !PLATFORM_UNIX #endif // Can be null - if so, ask for the Thread's CurrentCulture every time. private IFormatProvider InternalFormatProvider; protected TextWriter() { InternalFormatProvider = null; // Ask for CurrentCulture all the time. } protected TextWriter(IFormatProvider formatProvider) { InternalFormatProvider = formatProvider; } public virtual IFormatProvider FormatProvider { get { if (InternalFormatProvider == null) return Thread.CurrentThread.CurrentCulture; else return InternalFormatProvider; } } // Closes this TextWriter and releases any system resources associated with the // TextWriter. Following a call to Close, any operations on the TextWriter // may raise exceptions. This default method is empty, but descendant // classes can override the method to provide the appropriate // functionality. public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Clears all buffers for this TextWriter and causes any buffered data to be // written to the underlying device. This default method is empty, but // descendant classes can override the method to provide the appropriate // functionality. public virtual void Flush() { } public abstract Encoding Encoding { get; } // Returns the line terminator string used by this TextWriter. The default line // terminator string is a carriage return followed by a line feed ("\r\n"). // // Sets the line terminator string for this TextWriter. The line terminator // string is written to the text stream whenever one of the // WriteLine methods are called. In order for text written by // the TextWriter to be readable by a TextReader, only one of the following line // terminator strings should be used: "\r", "\n", or "\r\n". // public virtual String NewLine { get { return new String(CoreNewLine); } set { if (value == null) value = InitialNewLine; CoreNewLine = value.ToCharArray(); } } [HostProtection(Synchronization=true)] public static TextWriter Synchronized(TextWriter writer) { if (writer==null) throw new ArgumentNullException("writer"); Contract.Ensures(Contract.Result<TextWriter>() != null); Contract.EndContractBlock(); if (writer is SyncTextWriter) return writer; return new SyncTextWriter(writer); } // Writes a character to the text stream. This default method is empty, // but descendant classes can override the method to provide the // appropriate functionality. // public virtual void Write(char value) { } // Writes a character array to the text stream. This default method calls // Write(char) for each of the characters in the character array. // If the character array is null, nothing is written. // public virtual void Write(char[] buffer) { if (buffer != null) Write(buffer, 0, buffer.Length); } // Writes a range of a character array to the text stream. This method will // write count characters of data into this TextWriter from the // buffer character array starting at position index. // public virtual void Write(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); for (int i = 0; i < count; i++) Write(buffer[index + i]); } // Writes the text representation of a boolean to the text stream. This // method outputs either Boolean.TrueString or Boolean.FalseString. // public virtual void Write(bool value) { Write(value ? Boolean.TrueLiteral : Boolean.FalseLiteral); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // Int32.ToString() method. // public virtual void Write(int value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // UInt32.ToString() method. // [CLSCompliant(false)] public virtual void Write(uint value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the // Int64.ToString() method. // public virtual void Write(long value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an unsigned long to the text // stream. The text representation of the given value is produced // by calling the UInt64.ToString() method. // [CLSCompliant(false)] public virtual void Write(ulong value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the // Float.toString(float) method. // public virtual void Write(float value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the // Double.toString(double) method. // public virtual void Write(double value) { Write(value.ToString(FormatProvider)); } public virtual void Write(Decimal value) { Write(value.ToString(FormatProvider)); } // Writes a string to the text stream. If the given string is null, nothing // is written to the text stream. // public virtual void Write(String value) { if (value != null) Write(value.ToCharArray()); } // Writes the text representation of an object to the text stream. If the // given object is null, nothing is written to the text stream. // Otherwise, the object's ToString method is called to produce the // string representation, and the resulting string is then written to the // output stream. // public virtual void Write(Object value) { if (value != null) { IFormattable f = value as IFormattable; if (f != null) Write(f.ToString(null, FormatProvider)); else Write(value.ToString()); } } #if false // // Converts the wchar * to a string and writes this to the stream. // // // __attribute NonCLSCompliantAttribute() // public void Write(wchar *value) { // Write(new String(value)); // } // // Treats the byte* as a LPCSTR, converts it to a string, and writes it to the stream. // // // __attribute NonCLSCompliantAttribute() // public void Write(byte *value) { // Write(new String(value)); // } #endif // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, Object arg0) { Write(String.Format(FormatProvider, format, arg0)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, Object arg0, Object arg1) { Write(String.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, Object arg0, Object arg1, Object arg2) { Write(String.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, params Object[] arg) { Write(String.Format(FormatProvider, format, arg)); } // Writes a line terminator to the text stream. The default line terminator // is a carriage return followed by a line feed ("\r\n"), but this value // can be changed by setting the NewLine property. // public virtual void WriteLine() { Write(CoreNewLine); } // Writes a character followed by a line terminator to the text stream. // public virtual void WriteLine(char value) { Write(value); WriteLine(); } // Writes an array of characters followed by a line terminator to the text // stream. // public virtual void WriteLine(char[] buffer) { Write(buffer); WriteLine(); } // Writes a range of a character array followed by a line terminator to the // text stream. // public virtual void WriteLine(char[] buffer, int index, int count) { Write(buffer, index, count); WriteLine(); } // Writes the text representation of a boolean followed by a line // terminator to the text stream. // public virtual void WriteLine(bool value) { Write(value); WriteLine(); } // Writes the text representation of an integer followed by a line // terminator to the text stream. // public virtual void WriteLine(int value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned integer followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(uint value) { Write(value); WriteLine(); } // Writes the text representation of a long followed by a line terminator // to the text stream. // public virtual void WriteLine(long value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned long followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(ulong value) { Write(value); WriteLine(); } // Writes the text representation of a float followed by a line terminator // to the text stream. // public virtual void WriteLine(float value) { Write(value); WriteLine(); } // Writes the text representation of a double followed by a line terminator // to the text stream. // public virtual void WriteLine(double value) { Write(value); WriteLine(); } public virtual void WriteLine(decimal value) { Write(value); WriteLine(); } // Writes a string followed by a line terminator to the text stream. // public virtual void WriteLine(String value) { if (value==null) { WriteLine(); } else { // We'd ideally like WriteLine to be atomic, in that one call // to WriteLine equals one call to the OS (ie, so writing to // console while simultaneously calling printf will guarantee we // write out a string and new line chars, without any interference). // Additionally, we need to call ToCharArray on Strings anyways, // so allocating a char[] here isn't any worse than what we were // doing anyways. We do reduce the number of calls to the // backing store this way, potentially. int vLen = value.Length; int nlLen = CoreNewLine.Length; char[] chars = new char[vLen+nlLen]; value.CopyTo(0, chars, 0, vLen); // CoreNewLine will almost always be 2 chars, and possibly 1. if (nlLen == 2) { chars[vLen] = CoreNewLine[0]; chars[vLen+1] = CoreNewLine[1]; } else if (nlLen == 1) chars[vLen] = CoreNewLine[0]; else Buffer.InternalBlockCopy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2); Write(chars, 0, vLen + nlLen); } /* Write(value); // We could call Write(String) on StreamWriter... WriteLine(); */ } // Writes the text representation of an object followed by a line // terminator to the text stream. // public virtual void WriteLine(Object value) { if (value==null) { WriteLine(); } else { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. IFormattable f = value as IFormattable; if (f != null) WriteLine(f.ToString(null, FormatProvider)); else WriteLine(value.ToString()); } } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(String format, Object arg0) { WriteLine(String.Format(FormatProvider, format, arg0)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine (String format, Object arg0, Object arg1) { WriteLine(String.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine (String format, Object arg0, Object arg1, Object arg2) { WriteLine(String.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine (String format, params Object[] arg) { WriteLine(String.Format(FormatProvider, format, arg)); } #if FEATURE_ASYNC_IO #region Task based Async APIs [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(char value) { Tuple<TextWriter, char> tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(_WriteCharDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(String value) { Tuple<TextWriter, string> tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(_WriteStringDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task WriteAsync(char[] buffer) { if (buffer == null) return Task.CompletedTask; return WriteAsync(buffer, 0, buffer.Length); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(char[] buffer, int index, int count) { Tuple<TextWriter, char[], int, int> tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(_WriteCharArrayRangeDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync(char value) { Tuple<TextWriter, char> tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(_WriteLineCharDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync(String value) { Tuple<TextWriter, string> tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(_WriteLineStringDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task WriteLineAsync(char[] buffer) { if (buffer == null) return Task.CompletedTask; return WriteLineAsync(buffer, 0, buffer.Length); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync(char[] buffer, int index, int count) { Tuple<TextWriter, char[], int, int> tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(_WriteLineCharArrayRangeDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync() { return WriteAsync(CoreNewLine); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task FlushAsync() { return Task.Factory.StartNew(_FlushDelegate, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } #endregion #endif //FEATURE_ASYNC_IO [Serializable] private sealed class NullTextWriter : TextWriter { internal NullTextWriter(): base(CultureInfo.InvariantCulture) { } public override Encoding Encoding { get { return Encoding.Default; } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void Write(char[] buffer, int index, int count) { } public override void Write(String value) { } // Not strictly necessary, but for perf reasons public override void WriteLine() { } // Not strictly necessary, but for perf reasons public override void WriteLine(String value) { } public override void WriteLine(Object value) { } } [Serializable] internal sealed class SyncTextWriter : TextWriter, IDisposable { private TextWriter _out; internal SyncTextWriter(TextWriter t): base(t.FormatProvider) { _out = t; } public override Encoding Encoding { get { return _out.Encoding; } } public override IFormatProvider FormatProvider { get { return _out.FormatProvider; } } public override String NewLine { [MethodImplAttribute(MethodImplOptions.Synchronized)] get { return _out.NewLine; } [MethodImplAttribute(MethodImplOptions.Synchronized)] set { _out.NewLine = value; } } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Close() { // So that any overriden Close() gets run _out.Close(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_out).Dispose(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Flush() { _out.Flush(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(char value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(char[] buffer) { _out.Write(buffer); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(char[] buffer, int index, int count) { _out.Write(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(bool value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(int value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(uint value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(long value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(ulong value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(float value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(double value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(Decimal value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(Object value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object arg0) { _out.Write(format, arg0); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object arg0, Object arg1) { _out.Write(format, arg0, arg1); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object arg0, Object arg1, Object arg2) { _out.Write(format, arg0, arg1, arg2); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object[] arg) { _out.Write(format, arg); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine() { _out.WriteLine(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(char value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(decimal value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer) { _out.WriteLine(buffer); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer, int index, int count) { _out.WriteLine(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(bool value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(int value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(uint value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(long value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(ulong value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(float value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(double value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(Object value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object arg0) { _out.WriteLine(format, arg0); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object arg0, Object arg1) { _out.WriteLine(format, arg0, arg1); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object arg0, Object arg1, Object arg2) { _out.WriteLine(format, arg0, arg1, arg2); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object[] arg) { _out.WriteLine(format, arg); } #if FEATURE_ASYNC_IO // // On SyncTextWriter all APIs should run synchronously, even the async ones. // [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteAsync(char value) { Write(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteAsync(String value) { Write(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteAsync(char[] buffer, int index, int count) { Write(buffer, index, count); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteLineAsync(char value) { WriteLine(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteLineAsync(String value) { WriteLine(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteLineAsync(char[] buffer, int index, int count) { WriteLine(buffer, index, count); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task FlushAsync() { Flush(); return Task.CompletedTask; } #endif //FEATURE_ASYNC_IO } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Microsoft.RestrictedUsage.CSharp; using Microsoft.RestrictedUsage.CSharp.Compiler; using Microsoft.RestrictedUsage.CSharp.Extensions; using Microsoft.RestrictedUsage.CSharp.Semantics; using Microsoft.RestrictedUsage.CSharp.Syntax; using Microsoft.Cci.Contracts; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Outlining; using Adornments; using Microsoft.Cci; using System.Threading.Tasks; using System.Threading; using System.Runtime.InteropServices; using UtilitiesNamespace; using System.Collections.ObjectModel; namespace ContractAdornments { internal sealed class InheritanceTracker { public const string InheritanceTrackerKey = "InheritanceTracker"; public const double DelayOnVSModelFailedBeforeTryingAgain = 500d; public const double DelayAfterMembersRevalutation = 500d; readonly TextViewTracker _textViewTracker; readonly AdornmentManager _adornmentManager; readonly Queue<KeyValuePair<object, MethodDeclarationNode>> _methodsNeedingContractLookup; readonly Queue<KeyValuePair<Tuple<object, object>, PropertyDeclarationNode>> _propertiesNeedingContractLookup; readonly ISet<object> _methodKeys; readonly ISet<object> _propertyKeys; int semanticModelsFetchedCounter = 0; bool trackingNumberOfFetchedSemanticModels = false; [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(_textViewTracker != null); Contract.Invariant(_adornmentManager != null); Contract.Invariant(_methodsNeedingContractLookup != null); Contract.Invariant(_propertiesNeedingContractLookup != null); Contract.Invariant(_methodKeys != null); Contract.Invariant(_propertyKeys != null); } #region Static getters [ContractVerification(false)] public static InheritanceTracker GetOrCreateAdornmentTracker(TextViewTracker textViewTracker) { Contract.Requires(textViewTracker != null); Contract.Ensures(Contract.Result<InheritanceTracker>() != null); return textViewTracker.TextView.Properties.GetOrCreateSingletonProperty<InheritanceTracker>(InheritanceTrackerKey, delegate { return new InheritanceTracker(textViewTracker); }); } #endregion private InheritanceTracker(TextViewTracker textViewTracker) { Contract.Requires(textViewTracker != null); Contract.Requires(textViewTracker.TextView != null); if (!AdornmentManager.TryGetAdornmentManager(textViewTracker.TextView, "InheritanceAdornments", out _adornmentManager)) { ContractsPackageAccessor.Current.Logger.WriteToLog("Inheritance adornment layer not instantiated."); throw new InvalidOperationException("Inheritance adornment layer not instantiated."); } _methodsNeedingContractLookup = new Queue<KeyValuePair<object, MethodDeclarationNode>>(); _propertiesNeedingContractLookup = new Queue<KeyValuePair<Tuple<object, object>, PropertyDeclarationNode>>(); _methodKeys = new HashSet<object>(); _propertyKeys = new HashSet<object>(); _textViewTracker = textViewTracker; _textViewTracker.LatestCompilationChanged += OnLatestCompilationChanged; _textViewTracker.LatestSourceFileChanged += OnLatestSourceFileChanged; _textViewTracker.ProjectTracker.BuildDone += OnBuildDone; _textViewTracker.TextView.Closed += OnClosed; } void OnClosed(object sender, EventArgs e) { _textViewTracker.ProjectTracker.BuildDone -= OnBuildDone; _textViewTracker.LatestSourceFileChanged -= OnLatestSourceFileChanged; _textViewTracker.LatestCompilationChanged -= OnLatestCompilationChanged; } void OnBuildDone() { ContractsPackageAccessor.Current.Logger.WriteToLog("Removing all old adornments because of a new build for text file: " + _textViewTracker.FileName); _adornmentManager.Adornments.Clear(); _methodsNeedingContractLookup.Clear(); _propertiesNeedingContractLookup.Clear(); _methodKeys.Clear(); _propertyKeys.Clear(); } void OnLatestSourceFileChanged(object sender, LatestSourceFileChangedEventArgs e) { //Is the source file change significant? if (e.WasLatestSourceFileStale == true) { //Revaluate the inheritance adornments on the text view when we next have focus if (ContractsPackageAccessor.Current.VSOptionsPage.InheritanceOnMethods) ContractsPackageAccessor.Current.QueueWorkItem(() => RevaluateMethodInheritanceAdornments(this), () => _textViewTracker.TextView.HasAggregateFocus); if (ContractsPackageAccessor.Current.VSOptionsPage.InheritanceOnProperties) ContractsPackageAccessor.Current.QueueWorkItem(() => RevaluatePropertyInheritanceAdornments(this), () => _textViewTracker.TextView.HasAggregateFocus); } } void OnLatestCompilationChanged(object sender, LatestCompilationChangedEventArgs e) { Contract.Requires(e.LatestCompilation != null); //Do any methods need their contract information looked up? if (ContractsPackageAccessor.Current.VSOptionsPage.InheritanceOnMethods && _methodsNeedingContractLookup.Count > 0) { //Recursively look up the needed contract information ContractsPackageAccessor.Current.Logger.WriteToLog("Attempting to lookup contracts for " + _methodsNeedingContractLookup.Count + " methods."); ContractsPackageAccessor.Current.QueueWorkItem(() => RecursivelyLookupContractsForMethods(this), () => _textViewTracker.TextView.HasAggregateFocus); } //Do any properties need their contract information looked up? if (ContractsPackageAccessor.Current.VSOptionsPage.InheritanceOnProperties && _propertiesNeedingContractLookup.Count > 0) { //Recursively look up the needed contract information ContractsPackageAccessor.Current.Logger.WriteToLog("Attempting to lookup contracts for " + _propertiesNeedingContractLookup.Count + " properties."); ContractsPackageAccessor.Current.QueueWorkItem(() => RecursivelyLookupContractsForProperties(this), () => _textViewTracker.TextView.HasAggregateFocus); } } static void RevaluateMethodInheritanceAdornments(InheritanceTracker @this) { Contract.Requires(@this != null); var workingSnapshot = @this._textViewTracker.TextView.TextSnapshot; //Save the current snapshot so it doesn't change while you work, we assume that the snapshot is the same as the source file. //Check if model is ready var parseTree = @this._textViewTracker.LatestSourceFile == null ? null : @this._textViewTracker.LatestSourceFile.GetParseTree(); if (parseTree == null || !parseTree.IsModelReady()) { @this._textViewTracker.IsLatestSourceFileStale = true; Utilities.Delay(() => ContractsPackageAccessor.Current.AskForNewVSModel(), DelayOnVSModelFailedBeforeTryingAgain); return; } //Collect all the methods in this text view var methodCollector = new MethodCollector(workingSnapshot); methodCollector.Visit(parseTree.RootNode); var methods = methodCollector.GetMethods(); //Calculate which methods are new var newKeys = new List<object>(methods.Keys.Where((k) => !@this._methodKeys.Contains(k))); ContractsPackageAccessor.Current.Logger.WriteToLog(String.Format("Found {0} new methods.", newKeys.Count)); //Update our method keys @this._methodKeys.Clear(); @this._methodKeys.AddAll(methods.Keys); ContractsPackageAccessor.Current.QueueWorkItem(() => { if (@this._textViewTracker.TextView.IsClosed) return; var adornmentKeys = new List<object>(@this._adornmentManager.Adornments.Keys); foreach (var key in adornmentKeys) { var keyAsString = key as string; if (keyAsString == null) { ContractsPackageAccessor.Current.Logger.WriteToLog("Unexpected: A key in the AdornmentManager wasn't a string! key: " + key.ToString()); continue; } if (!@this._methodKeys.Contains(key) && keyAsString.EndsWith(MethodCollector.MethodTagSuffix)) { @this._adornmentManager.RemoveAdornment(key); ContractsPackageAccessor.Current.Logger.WriteToLog("Removing obsolete method adornment with tag: " + keyAsString); } } }, () => @this._textViewTracker.TextView.IsClosed || @this._textViewTracker.TextView.HasAggregateFocus); //Create placeholder adornments for our new methods and queue them for contract lookup ContractsPackageAccessor.Current.QueueWorkItem(() => { foreach (var key in newKeys) { MethodDeclarationNode method; if (methods.TryGetValue(key, out method)) { ContractsPackageAccessor.Current.Logger.WriteToLog("Creating placeholder adornment and enqueueing for future contract lookup for: " + key.ToString()); #region Create placeholder adornment //We add the placeholder adornment here because our workingSnapshot corresponds most closely to the syntactic model's text var snapshotSpan = new SnapshotSpan(method.GetSpan().Convert(workingSnapshot).Start, 1); var trackingSpan = workingSnapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeExclusive); var ops = AdornmentOptionsHelper.GetAdornmentOptions(ContractsPackageAccessor.Current.VSOptionsPage); @this._adornmentManager.AddAdornment(new InheritanceContractAdornment(trackingSpan, @this._textViewTracker.VSTextProperties, ContractsPackageAccessor.Current.Logger, @this._adornmentManager.QueueRefreshLineTransformer, ops), key); #endregion @this._methodsNeedingContractLookup.Enqueue(new KeyValuePair<object, MethodDeclarationNode>(key, method)); } } }); //Most likely we've changed something (and this is a pretty cheap call), so let's ask for a refresh Utilities.Delay(() => ContractsPackageAccessor.Current.QueueWorkItem(@this._adornmentManager.QueueRefreshLineTransformer), DelayAfterMembersRevalutation); //Ask for the new VS model so we can look up contracts Utilities.Delay(() => ContractsPackageAccessor.Current.QueueWorkItem(ContractsPackageAccessor.Current.AskForNewVSModel), DelayAfterMembersRevalutation); } static void RevaluatePropertyInheritanceAdornments(InheritanceTracker @this) { Contract.Requires(@this != null); var workingSnapshot = @this._textViewTracker.TextView.TextSnapshot; //Save the current snapshot so it doesn't change while you work, we assume that the snapshot is the same as the source file. //Check if model is ready var parseTree = @this._textViewTracker.LatestSourceFile == null ? null : @this._textViewTracker.LatestSourceFile.GetParseTree(); if (parseTree == null || !parseTree.IsModelReady()) { @this._textViewTracker.IsLatestSourceFileStale = true; Utilities.Delay(() => ContractsPackageAccessor.Current.AskForNewVSModel(), DelayOnVSModelFailedBeforeTryingAgain); return; } //Collect all the properties in this text view var propertyCollector = new PropertyCollector(workingSnapshot); propertyCollector.Visit(parseTree.RootNode); var properties = propertyCollector.GetProperties(); //Get our property keys var keys = new List<object>(); var newTuples = new List<Tuple<object, object>>(); foreach (var tuple in properties.Keys) { if (tuple.Item1 != null) keys.Add(tuple.Item1); if (tuple.Item2 != null) keys.Add(tuple.Item2); if (!(@this._propertyKeys.Contains(tuple.Item1) && @this._propertyKeys.Contains(tuple.Item1))) newTuples.Add(tuple); } ContractsPackageAccessor.Current.Logger.WriteToLog(String.Format("Found {0} new properties.", newTuples.Count)); //Update our property keys @this._propertyKeys.Clear(); @this._propertyKeys.AddAll(keys); ContractsPackageAccessor.Current.QueueWorkItem(() => { if (@this._textViewTracker.TextView.IsClosed) return; var adornmentKeys = new List<object>(@this._adornmentManager.Adornments.Keys); foreach (var key in adornmentKeys) { var keyAsString = key as string; if (keyAsString == null) { ContractsPackageAccessor.Current.Logger.WriteToLog("Unexpected: A key in the AdornmentManager wasn't a string! key: " + key.ToString()); continue; } if (!@this._propertyKeys.Contains(key) && keyAsString.EndsWith(PropertyCollector.PropertyTagSuffix)) { @this._adornmentManager.RemoveAdornment(key); ContractsPackageAccessor.Current.Logger.WriteToLog("Removing obsolete property adornment with tag: " + keyAsString); } } }, () => @this._textViewTracker.TextView.IsClosed || @this._textViewTracker.TextView.HasAggregateFocus); //Create placeholder adornments for our new properties and queue them for contract lookup ContractsPackageAccessor.Current.QueueWorkItem(() => { foreach (var tuple in newTuples) { PropertyDeclarationNode property; if (properties.TryGetValue(tuple, out property)) { if (tuple.Item1 != null && tuple.Item2 != null && property.GetAccessorDeclaration.GetSpan().Start.Line == property.SetAccessorDeclaration.GetSpan().Start.Line) { // set and get on same line, don't add adornment ContractsPackageAccessor.Current.Logger.WriteToLog("Skipping adornments for " + property.GetName(workingSnapshot) + " because get and set are on same line"); } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Creating placeholder adornment and enqueueing for future contract lookup for: " + property.GetName(workingSnapshot)); if (tuple.Item1 != null) { #region Create getter placeholder adornment ContractsPackageAccessor.Current.Logger.WriteToLog(String.Format("\t(Creating getter placeholder with tag {0})", tuple.Item1)); //We add the placeholder adornment here because our workingSnapshot corresponds most closely to the syntactic model's text var snapshotSpan = new SnapshotSpan(property.GetAccessorDeclaration.GetSpan().Convert(workingSnapshot).Start, 1); var trackingSpan = workingSnapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeExclusive); var ops = AdornmentOptionsHelper.GetAdornmentOptions(ContractsPackageAccessor.Current.VSOptionsPage); @this._adornmentManager.AddAdornment(new InheritanceContractAdornment(trackingSpan, @this._textViewTracker.VSTextProperties, ContractsPackageAccessor.Current.Logger, @this._adornmentManager.QueueRefreshLineTransformer, ops), tuple.Item1); #endregion } if (tuple.Item2 != null) { #region Create setter placeholder adornment ContractsPackageAccessor.Current.Logger.WriteToLog(String.Format("\t(Creating setter placeholder with tag {0})", tuple.Item2)); //We add the placeholder adornment here because our workingSnapshot corresponds most closely to the syntactic model's text var snapshotSpan = new SnapshotSpan(property.SetAccessorDeclaration.GetSpan().Convert(workingSnapshot).Start, 1); var trackingSpan = workingSnapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeExclusive); var ops = AdornmentOptionsHelper.GetAdornmentOptions(ContractsPackageAccessor.Current.VSOptionsPage); @this._adornmentManager.AddAdornment(new InheritanceContractAdornment(trackingSpan, @this._textViewTracker.VSTextProperties, ContractsPackageAccessor.Current.Logger, @this._adornmentManager.QueueRefreshLineTransformer, ops), tuple.Item2); #endregion } @this._propertiesNeedingContractLookup.Enqueue(new KeyValuePair<Tuple<object, object>, PropertyDeclarationNode>(tuple, property)); } } } }); //Most likely we've changed something (and this is a pretty cheap call), so let's ask for a refresh Utilities.Delay(() => ContractsPackageAccessor.Current.QueueWorkItem(@this._adornmentManager.QueueRefreshLineTransformer, () => @this._textViewTracker.TextView.HasAggregateFocus), DelayAfterMembersRevalutation); //Ask for the new VS model so we can look up contracts Utilities.Delay(() => ContractsPackageAccessor.Current.QueueWorkItem(ContractsPackageAccessor.Current.AskForNewVSModel, () => @this._textViewTracker.TextView.HasAggregateFocus), DelayAfterMembersRevalutation); } static void RecursivelyLookupContractsForMethods(InheritanceTracker @this) { Contract.Requires(@this != null); #region Dequeue if (@this._methodsNeedingContractLookup.Count < 1) return; var methodPair = @this._methodsNeedingContractLookup.Dequeue(); var method = methodPair.Value; var tag = methodPair.Key; #endregion try { ContractsPackageAccessor.Current.Logger.WriteToLog(String.Format("Attempting to lookup contracts for '{0}'", tag.ToString())); var comp = @this._textViewTracker.LatestCompilation; if (comp == null) { ContractsPackageAccessor.Current.Logger.WriteToLog("No LatestCompilation, waiting for a new semantic model."); @this._textViewTracker.IsLatestCompilationStale = true; Utilities.Delay(() => ContractsPackageAccessor.Current.AskForNewVSModel(), DelayOnVSModelFailedBeforeTryingAgain); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } #region Get semantic method from syntactic method CSharpMember semanticMethod = null; semanticMethod = comp.GetMemberForMethodDeclaration(method); if (semanticMethod == null) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 3) { ContractsPackageAccessor.Current.Logger.WriteToLog("Failed to get semantic method from syntactic method, waiting for a new semantic model."); @this._textViewTracker.IsLatestCompilationStale = true; Utilities.Delay(() => ContractsPackageAccessor.Current.AskForNewVSModel(), DelayOnVSModelFailedBeforeTryingAgain); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Failed to get semantic method from syntactic method. Too many semantic models have already been fetched, skipping this method..."); goto Continue; } } #endregion #region Try get the method that this method is inherited from CSharpMember inheritedFromMethod; if (!TryGetIheritedFromMember(semanticMethod, method.Parent as TypeDeclarationNode, out inheritedFromMethod)) { goto Continue; } #endregion #region Uninstantiated method semanticMethod = semanticMethod.Uninstantiate(); #endregion #region Get our tool tip var toolTip = ""; if (!semanticMethod.IsAbstract && !semanticMethod.ContainingType.IsInterface) toolTip = String.Format("Contracts inherited from {0}.", inheritedFromMethod.ContainingType.Name.Text); #endregion #region Try get method contracts and update adornment IMethodContract contracts = null; if (((ContractsProvider)@this._textViewTracker.ProjectTracker.ContractsProvider).TryGetMethodContract(inheritedFromMethod, out contracts)) { var possibleAdornment = @this._adornmentManager.GetAdornment(tag); if (possibleAdornment != null) { var adornment = possibleAdornment as ContractAdornment; if (adornment != null) { adornment.SetContracts(contracts, toolTip); } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Placeholder adornment isn't a ContractAdornment (not good!), skipping method..."); } } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Placeholder adornment not found, skipping method..."); } } #endregion } #region Exception handeling catch (IllFormedSemanticModelException e) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 2) { ContractsPackageAccessor.Current.Logger.WriteToLog("Error: An 'IllFormedSemanticModelException' occured: '" + e.Message + "' Asking for a new semantic model..."); @this._textViewTracker.IsLatestCompilationStale = true; ContractsPackageAccessor.Current.AskForNewVSModel(); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("An 'IllFormedSemanticModelException' occured: '" + e.Message + "' Too many semantic models have been fetched, skipping this method..."); goto Continue; } } catch (InvalidOperationException e) { if (e.Message.Contains(ContractsPackageAccessor.InvalidOperationExceptionMessage_TheSnapshotIsOutOfDate)) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 5) { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts, getting new compilation..."); @this._textViewTracker.IsLatestCompilationStale = true; ContractsPackageAccessor.Current.AskForNewVSModel(); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts. Too many compilations have already been fetched, skipping this method..."); goto Continue; } } else throw e; } catch (COMException e) { if (e.Message.Contains(ContractsPackageAccessor.COMExceptionMessage_BindingFailed)) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 5) { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts, getting new compilation..."); @this._textViewTracker.IsLatestCompilationStale = true; ContractsPackageAccessor.Current.AskForNewVSModel(); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts. Too many compilations have already been fetched, skipping this method..."); goto Continue; } } else throw e; } #endregion Continue: ContractsPackageAccessor.Current.QueueWorkItem(() => RecursivelyLookupContractsForMethods(@this)); return; RequeueAndAbort: @this._methodsNeedingContractLookup.Enqueue(methodPair); return; } static void RecursivelyLookupContractsForProperties(InheritanceTracker @this) { Contract.Requires(@this != null); #region Dequeue if (@this._propertiesNeedingContractLookup.Count < 1) return; var propertyPair = @this._propertiesNeedingContractLookup.Dequeue(); var property = propertyPair.Value; var tagTuple = propertyPair.Key; #endregion try { var comp = @this._textViewTracker.LatestCompilation; if (comp == null) { ContractsPackageAccessor.Current.Logger.WriteToLog("No LatestCompilation, waiting for a new semantic model."); @this._textViewTracker.IsLatestCompilationStale = true; Utilities.Delay(() => ContractsPackageAccessor.Current.AskForNewVSModel(), DelayOnVSModelFailedBeforeTryingAgain); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } #region Get semantic property from syntactic property CSharpMember semanticProperty = null; semanticProperty = comp.GetMemberForPropertyDeclaration(property); if (semanticProperty == null) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 3) { ContractsPackageAccessor.Current.Logger.WriteToLog("Failed to get semantic property from syntactic property, waiting for a new semantic model."); @this._textViewTracker.IsLatestCompilationStale = true; Utilities.Delay(() => ContractsPackageAccessor.Current.AskForNewVSModel(), DelayOnVSModelFailedBeforeTryingAgain); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Failed to get semantic property from syntactic property. Too many semantic models have already been fetched, skipping this property..."); goto Continue; } } #endregion #region Try get the property that this property is inherited from CSharpMember inheritedFromProperty; if (!TryGetIheritedFromMember(semanticProperty, property.Parent as TypeDeclarationNode, out inheritedFromProperty)) { goto Continue; } #endregion #region Uninstantiated property semanticProperty = semanticProperty.Uninstantiate(); #endregion #region Get our tool tip var toolTip = ""; if (!semanticProperty.IsAbstract && !semanticProperty.ContainingType.IsInterface) toolTip = String.Format("Contracts inherited from {0}.", inheritedFromProperty.ContainingType.Name.Text); #endregion #region Try get accessor contracts and update adornment IMethodReference getterReference = null; IMethodReference setterReference = null; if (((ContractsProvider)@this._textViewTracker.ProjectTracker.ContractsProvider).TryGetPropertyAccessorReferences(inheritedFromProperty, out getterReference, out setterReference)) { if (tagTuple.Item1 != null && getterReference != null) { IMethodContract getterContracts; if (((ContractsProvider)@this._textViewTracker.ProjectTracker.ContractsProvider).TryGetMethodContract(getterReference, out getterContracts)) { var possibleAdornment = @this._adornmentManager.GetAdornment(tagTuple.Item1); if (possibleAdornment != null) { var adornment = possibleAdornment as ContractAdornment; if (adornment != null) { adornment.SetContracts(getterContracts, toolTip); } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Placeholder adornment isn't a ContractAdornment (not good!), skipping getter..."); } } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Placeholder adornment not found, skipping getter..."); } } } if (tagTuple.Item2 != null && setterReference != null) { IMethodContract setterContracts; if (((ContractsProvider)@this._textViewTracker.ProjectTracker.ContractsProvider).TryGetMethodContract(setterReference, out setterContracts)) { var possibleAdornment = @this._adornmentManager.GetAdornment(tagTuple.Item2); if (possibleAdornment != null) { var adornment = possibleAdornment as ContractAdornment; if (adornment != null) { adornment.SetContracts(setterContracts, toolTip); } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Placeholder adornment isn't a ContractAdornment (not good!), skipping setter..."); } } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Placeholder adornment not found, skipping setter..."); } } } } else { ContractsPackageAccessor.Current.Logger.WriteToLog("Failed to get CCI reference for: " + inheritedFromProperty.Name.Text); } #endregion } #region Exception handeling catch (IllFormedSemanticModelException e) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 2) { ContractsPackageAccessor.Current.Logger.WriteToLog("Error: An 'IllFormedSemanticModelException' occured: '" + e.Message + "' Asking for a new semantic model..."); @this._textViewTracker.IsLatestCompilationStale = true; ContractsPackageAccessor.Current.AskForNewVSModel(); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("An 'IllFormedSemanticModelException' occured: '" + e.Message + "' Too many semantic models have been fetched, skipping this property..."); goto Continue; } } catch (InvalidOperationException e) { if (e.Message.Contains(ContractsPackageAccessor.InvalidOperationExceptionMessage_TheSnapshotIsOutOfDate)) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 5) { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts, getting new compilation..."); @this._textViewTracker.IsLatestCompilationStale = true; ContractsPackageAccessor.Current.AskForNewVSModel(); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts. Too many compilations have already been fetched, skipping this property..."); goto Continue; } } else throw e; } catch (COMException e) { if (e.Message.Contains(ContractsPackageAccessor.COMExceptionMessage_BindingFailed)) { if (@this.trackingNumberOfFetchedSemanticModels && @this.semanticModelsFetchedCounter <= 5) { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts, getting new compilation..."); @this._textViewTracker.IsLatestCompilationStale = true; ContractsPackageAccessor.Current.AskForNewVSModel(); @this.semanticModelsFetchedCounter++; goto RequeueAndAbort; } else { ContractsPackageAccessor.Current.Logger.WriteToLog("The Visual Studio Semantic/Syntactic model threw an exception (it's snapshot is out of date) while looking up contracts. Too many compilations have already been fetched, skipping this property..."); goto Continue; } } else throw e; } #endregion Continue: ContractsPackageAccessor.Current.QueueWorkItem(() => RecursivelyLookupContractsForProperties(@this)); return; RequeueAndAbort: @this._propertiesNeedingContractLookup.Enqueue(propertyPair); return; } static bool TryGetIheritedFromMember(CSharpMember semanticMember, TypeDeclarationNode syntacticParentType, out CSharpMember inheritedFromMember) { Contract.Requires(semanticMember != null); Contract.Requires(semanticMember.IsMethod); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out inheritedFromMember) != null && Contract.ValueAtReturn(out inheritedFromMember).IsMethod); inheritedFromMember = null; #region If member is from struct, ignore it if (semanticMember.ContainingType.IsValueType || semanticMember.ContainingType.IsStruct) { ContractsPackageAccessor.Current.Logger.WriteToLog("Member is struct or value type, skipping member..."); return false; } #endregion #region If member is from a contract class, ignore it //TODO: Get proper attributes from semantic model! Bug in semantic model, custom attributes don't seem to work right. bool ignoreIt = false; var containingType = semanticMember.ContainingType; if (containingType.IsClass) { if (syntacticParentType != null) { foreach (var attributeSection in syntacticParentType.Attributes) { foreach (var attribute in attributeSection.AttributeList) { var attributeName = attribute.AttributeName as IdentifierNode; if (attributeName != null) { if (attributeName.Name.Text.Contains("ContractClassFor")) ignoreIt = true; } } } } } if (ignoreIt) { ContractsPackageAccessor.Current.Logger.WriteToLog("Member has 'ContractClassForAttribute', skipping member..."); return false; } #endregion // If member is override, get base member if (semanticMember.IsOverride) { if (!CSharpToCCIHelper.TryGetBaseMember(semanticMember, out inheritedFromMember)) { ContractsPackageAccessor.Current.Logger.WriteToLog("Member is an override but we can't get its base member, skipping member..."); return false; //If we can't get the base member, we don't want to keep going with this member. } } else if (semanticMember.ContainingType.IsInterface || semanticMember.IsAbstract) { inheritedFromMember = semanticMember; } #region Else member implements an interface or it doesn't have inherited contracts, get interface member else { if (!CSharpToCCIHelper.TryGetInterfaceMember(semanticMember, out inheritedFromMember)) { ContractsPackageAccessor.Current.Logger.WriteToLog("Member isn't override, abstract, in an interface or an interface member, skipping member..."); return false; //If we can't get the interface member, we don't want to keep going with this member. } } #endregion return inheritedFromMember != null; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Samples.Controls.VLVControl.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap; using Novell.Directory.Ldap.Controls; /// <summary> The following sample demonstrates how to use the VLV /// control with Synchronous search requests. As required a /// Server Side Sort Control is also included in the request. /// /// The program is hard coded to sort based on the common name /// attribute, and it searches for all objects at the specified /// searchBase. /// /// Usage: Usage: VLVControl <host name> <login dn> <password> /// <searchBase> /// /// </summary> public class VLVControl { public static void Main(System.String[] args) { /* Check if we have the correct number of command line arguments */ if (args.Length != 4) { System.Console.Error.WriteLine("Usage: mono VLVControl <host name> <login dn>" + " <password> <container>"); System.Console.Error.WriteLine("Example: mono VLVControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\""); System.Environment.Exit(1); } /* Parse the command line arguments */ System.String LdapHost = args[0]; System.String loginDN = args[1]; System.String password = args[2]; System.String searchBase = args[3]; int LdapPort = LdapConnection.DEFAULT_PORT; int LdapVersion = LdapConnection.Ldap_V3; LdapConnection conn = new LdapConnection(); try { // connect to the server conn.Connect(LdapHost, LdapPort); // bind to the server conn.Bind(LdapVersion, loginDN, password); System.Console.Out.WriteLine("Succesfully logged in to server: " + LdapHost); /* Set default filter - Change this line if you need a different set * of search restrictions. Read the "NDS and Ldap Integration Guide" * for information on support by Novell eDirectory of this * functionaliry. */ System.String MY_FILTER = "cn=*"; /* We are requesting that the givenname and cn fields for each * object be returned */ System.String[] attrs = new System.String[2]; attrs[0] = "givenname"; attrs[1] = "cn"; // We will be sending two controls to the server LdapControl[] requestControls = new LdapControl[2]; /* Create the sort key to be used by the sort control * Results should be sorted based on the cn attribute. * See the "NDS and Ldap Integration Guide" for information on * Novell eDirectory support of this functionaliry. */ LdapSortKey[] keys = new LdapSortKey[1]; keys[0] = new LdapSortKey("cn"); // Create the sort control requestControls[0] = new LdapSortControl(keys, true); /* Create the VLV Control. * These two fields in the VLV Control identify the before and * after count of entries to be returned */ int beforeCount = 0; int afterCount = 2; /* The VLV control request can specify the index * using one of the two methods described below: * * TYPED INDEX: Here we request all objects that have cn greater * than or equal to the letter "a" */ requestControls[1] = new LdapVirtualListControl("a", beforeCount, afterCount); /* The following code needs to be enabled to specify the index * directly * int offset = 0; - offset of the index * int contentCount = 3; - our estimate of the search result size * requestControls[1] = new LdapVirtualListControl(offset, * beforeCount, afterCount, contentCount); */ // Set the controls to be sent as part of search request LdapSearchConstraints cons = conn.SearchConstraints; cons.setControls(requestControls); conn.Constraints = cons; // Send the search request - Synchronous Search is being used here System.Console.Out.WriteLine("Calling Asynchronous Search..."); LdapSearchResults res = conn.Search(searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchConstraints) null); // Loop through the results and print them out while (res.hasMore()) { /* Get next returned entry. Note that we should expect a Ldap- *Exception object as well just in case something goes wrong */ LdapEntry nextEntry=null; try { nextEntry = res.next(); } catch (LdapException e) { if (e is LdapReferralException) continue; else { System.Console.Out.WriteLine("Search stopped with exception " + e.ToString()); break; } } /* Print out the returned Entries distinguished name. */ System.Console.Out.WriteLine(); System.Console.Out.WriteLine(nextEntry.DN); /* Get the list of attributes for the current entry */ LdapAttributeSet findAttrs = nextEntry.getAttributeSet(); /* Convert attribute list to Enumeration */ System.Collections.IEnumerator enumAttrs = findAttrs.GetEnumerator(); System.Console.Out.WriteLine("Attributes: "); /* Loop through all attributes in the enumeration */ while (enumAttrs.MoveNext()) { LdapAttribute anAttr = (LdapAttribute) enumAttrs.Current; /* Print out the attribute name */ System.String attrName = anAttr.Name; System.Console.Out.WriteLine("" + attrName); // Loop through all values for this attribute and print them System.Collections.IEnumerator enumVals = anAttr.StringValues; while (enumVals.MoveNext()) { System.String aVal = (System.String) enumVals.Current; System.Console.Out.WriteLine("" + aVal); } } } // Server should send back a control irrespective of the // status of the search request LdapControl[] controls = res.ResponseControls; if (controls == null) { System.Console.Out.WriteLine("No controls returned"); } else { // We are likely to have multiple controls returned for (int i = 0; i < controls.Length; i++) { /* Is this the Sort Response Control. */ if (controls[i] is LdapSortResponse) { System.Console.Out.WriteLine("Received Ldap Sort Control from " + "Server"); /* We could have an error code and maybe a string * identifying erring attribute in the response control. */ System.String bad = ((LdapSortResponse) controls[i]).FailedAttribute; int result = ((LdapSortResponse) controls[i]).ResultCode; // Print out error code (0 if no error) and any // returned attribute System.Console.Out.WriteLine("Error code: " + result); if ((System.Object) bad != null) System.Console.Out.WriteLine("Offending " + "attribute: " + bad); else System.Console.Out.WriteLine("No offending " + "attribute " + "returned"); } /* Is this a VLV Response Control */ if (controls[i] is LdapVirtualListResponse) { System.Console.Out.WriteLine("Received VLV Response Control from " + "Server..."); /* Get all returned fields */ int firstPosition = ((LdapVirtualListResponse) controls[i]).FirstPosition; int ContentCount = ((LdapVirtualListResponse) controls[i]).ContentCount; int resultCode = ((LdapVirtualListResponse) controls[i]).ResultCode; System.String context = ((LdapVirtualListResponse) controls[i]).Context; /* Print out the returned fields. Typically you would * have used these fields to reissue another VLV request * or to display the list on a GUI */ System.Console.Out.WriteLine("Result Code => " + resultCode); System.Console.Out.WriteLine("First Position => " + firstPosition); System.Console.Out.WriteLine("Content Count => " + ContentCount); if ((System.Object) context != null) System.Console.Out.WriteLine("Context String => " + context); else System.Console.Out.WriteLine("No Context String in returned" + " control"); } } } /* We are done - disconnect */ if (conn.Connected) conn.Disconnect(); } catch (LdapException e) { System.Console.Out.WriteLine(e.ToString()); } catch (System.IO.IOException e) { System.Console.Out.WriteLine("Error: " + e.ToString()); } catch(Exception e) { System.Console.WriteLine("Error: " + e.Message); } } }
using System; using System.Globalization; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Shouldly; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests { /// <summary> /// Unit tests for the ResolveAssemblyReference task. /// </summary> [Trait("Category", "non-mono-tests")] public sealed class WinMDTests : ResolveAssemblyReferenceTestFixture { public WinMDTests(ITestOutputHelper output) : base(output) { } #region AssemblyInformationIsWinMDFile Tests /// <summary> /// Verify a null file path passed in return the fact the file is not a winmd file. /// </summary> [Fact] public void IsWinMDFileNullFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(null, getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// Verify if a empty file path is passed in that the file is not a winmd file. /// </summary> [Fact] public void IsWinMDFileEmptyFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(String.Empty, getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// If the file does not exist then we should report this is not a winmd file. /// </summary> [Fact] public void IsWinMDFileFileDoesNotExistFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleDoesNotExist.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// The file exists and has the correct windowsruntime metadata, we should report this is a winmd file. /// </summary> [Fact] public void IsWinMDFileGoodFile() { string imageRuntime; bool isManagedWinMD; Assert.True(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleWindowsRuntimeOnly.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// This file is a mixed file with CLR and windowsruntime metadata we should report this is a winmd file. /// </summary> [Fact] public void IsWinMDFileMixedFile() { string imageRuntime; bool isManagedWinMD; Assert.True(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleWindowsRuntimeAndCLR.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.True(isManagedWinMD); } /// <summary> /// The file has only CLR metadata we should report this is not a winmd file /// </summary> [Fact] public void IsWinMDFileCLROnlyFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleClrOnly.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// The windows runtime string is not correctly formatted, report this is not a winmd file. /// </summary> [Fact] public void IsWinMDFileBadWindowsRuntimeFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleBadWindowsRuntime.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// We should report that a regular net assembly is not a winmd file. /// </summary> [Fact] public void IsWinMDFileRegularNetAssemblyFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\Framework\Whidbey\System.dll", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// When a project to project reference is passed in we want to verify that /// the winmd references get the correct metadata applied to them /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void VerifyP2PHaveCorrectMetadataWinMD(bool setImplementationMetadata) { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem taskItem = new TaskItem(@"C:\WinMD\SampleWindowsRuntimeOnly.Winmd"); if (setImplementationMetadata) { taskItem.SetMetadata(ItemMetadataNames.winmdImplmentationFile, "SampleWindowsRuntimeOnly.dll"); } ITaskItem[] assemblyFiles = new TaskItem[] { taskItem }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Equal(2, t.RelatedFiles.Length); bool dllFound = false; bool priFound = false; foreach (ITaskItem item in t.RelatedFiles) { if (item.ItemSpec.EndsWith(@"C:\WinMD\SampleWindowsRuntimeOnly.dll")) { dllFound = true; Assert.Empty(item.GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winMDFile)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winmdImplmentationFile)); } if (item.ItemSpec.EndsWith(@"C:\WinMD\SampleWindowsRuntimeOnly.pri")) { priFound = true; Assert.Empty(item.GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winMDFile)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winmdImplmentationFile)); } } Assert.True(dllFound && priFound); // "Expected to find .dll and .pri related files." Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal("Native", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType)); Assert.Equal("SampleWindowsRuntimeOnly.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal("WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); } [Fact] public void VerifyP2PHaveCorrectMetadataWinMDStaticLib() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem taskItem = new TaskItem(@"C:\WinMDLib\LibWithWinmdAndNoDll.Winmd"); taskItem.SetMetadata(ItemMetadataNames.winmdImplmentationFile, "LibWithWinmdAndNoDll.lib"); ITaskItem[] assemblyFiles = new TaskItem[] { taskItem }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; Execute(t).ShouldBeTrue(); engine.Errors.ShouldBe(0); engine.Warnings.ShouldBe(0); t.ResolvedFiles.ShouldHaveSingleItem(); t.RelatedFiles.ShouldHaveSingleItem(); t.RelatedFiles[0].ItemSpec.ShouldBe(@"C:\WinMDLib\LibWithWinmdAndNoDll.pri", "Expected to find .pri related files but NOT the lib."); t.RelatedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime).ShouldBeEmpty(); t.RelatedFiles[0].GetMetadata(ItemMetadataNames.winMDFile).ShouldBeEmpty(); t.RelatedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile).ShouldBeEmpty(); t.ResolvedDependencyFiles.ShouldBeEmpty(); bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)).ShouldBeTrue(); t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType).ShouldBe("Native"); t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile).ShouldBe("LibWithWinmdAndNoDll.lib"); } /// <summary> /// When a project to project reference is passed in we want to verify that /// the winmd references get the correct metadata applied to them /// </summary> [Fact] public void VerifyP2PHaveCorrectMetadataWinMDManaged() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem taskItem = new TaskItem(@"C:\WinMD\SampleWindowsRuntimeAndCLR.Winmd"); ITaskItem[] assemblyFiles = new TaskItem[] { taskItem }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Empty(t.RelatedFiles); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal("Managed", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType)); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal("WindowsRuntime 1.0, CLR V2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); } /// <summary> /// When a project to project reference is passed in we want to verify that /// the winmd references get the correct metadata applied to them /// </summary> [Fact] public void VerifyP2PHaveCorrectMetadataNonWinMD() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"C:\AssemblyFolder\SomeAssembly.dll") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)); Assert.Equal("v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); } /// <summary> /// Verify when we reference a winmd file as a reference item make sure we ignore the mscorlib. /// </summary> [Fact] public void IgnoreReferenceToMscorlib() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeOnly"), new TaskItem(@"SampleWindowsRuntimeAndClr") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Equal(2, t.ResolvedFiles.Length); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); engine.AssertLogDoesntContain("conflict"); } /// <summary> /// Verify when we reference a mixed winmd file that we do resolve the reference to the mscorlib /// </summary> [Fact] public void MixedWinMDGoodReferenceToMscorlib() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeAndClr") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); engine.AssertLogContainsMessageFromResource(resourceDelegate, "ResolveAssemblyReference.Resolved", @"C:\WinMD\v4\mscorlib.dll"); } /// <summary> /// Verify when a winmd file depends on another winmd file that we do resolve the dependency /// </summary> [Fact] public void WinMdFileDependsOnAnotherWinMDFile() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeOnly2") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly2.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly.winmd", t.ResolvedDependencyFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); } /// <summary> /// We have two dlls which depend on a winmd, the first dll does not have the winmd beside it, the second one does /// we want to make sure that the winmd file is resolved beside the second dll. /// </summary> [Fact] public void ResolveWinmdBesideDll() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"C:\DirectoryContainsOnlyDll\A.dll"), new TaskItem(@"C:\DirectoryContainsdllAndWinmd\B.dll"), }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { "{RAWFILENAME}" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Equal(2, t.ResolvedFiles.Length); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\DirectoryContainsdllAndWinmd\C.winmd", t.ResolvedDependencyFiles[0].ItemSpec); } /// <summary> /// We have a winmd file and a dll depend on a winmd, there are copies of the winmd beside each of the files. /// we want to make sure that the winmd file is resolved beside the winmd since that is the first file resolved. /// </summary> [Fact] public void ResolveWinmdBesideDll2() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"C:\DirectoryContainstwoWinmd\A.winmd"), new TaskItem(@"C:\DirectoryContainsdllAndWinmd\B.dll"), }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"{RAWFILENAME}" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Equal(2, t.ResolvedFiles.Length); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\DirectoryContainstwoWinmd\C.winmd", t.ResolvedDependencyFiles[0].ItemSpec); } /// <summary> /// Verify when a winmd file depends on another winmd file that itself has framework dependencies that we do not resolve any of the /// dependencies due to the winmd to winmd reference /// </summary> [Fact] public void WinMdFileDependsOnAnotherWinMDFileWithFrameworkDependencies() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeOnly3") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"{TargetFrameworkDirectory}", @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; t.TargetFrameworkDirectories = new string[] { @"c:\WINNT\Microsoft.NET\Framework\v4.0.MyVersion" }; t.TargetProcessorArchitecture = "x86"; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Equal(4, t.ResolvedDependencyFiles.Length); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly3.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); } /// <summary> /// Make sure when a dot net assembly depends on a WinMDFile that /// we get the winmd file resolved. Also make sure that if there is Implementation, ImageRuntime, or IsWinMD set on the dll that /// it does not get propagated to the winmd file dependency. /// </summary> [Fact] public void DotNetAssemblyDependsOnAWinMDFile() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem(@"DotNetAssemblyDependsOnWinMD"); // This should not be used for anything, it is recalculated in rar, this is to make sure it is not forwarded to child items. item.SetMetadata(ItemMetadataNames.imageRuntime, "FOO"); // This should not be used for anything, it is recalculated in rar, this is to make sure it is not forwarded to child items. item.SetMetadata(ItemMetadataNames.winMDFile, "NOPE"); item.SetMetadata(ItemMetadataNames.winmdImplmentationFile, "IMPL"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.TargetProcessorArchitecture = "X86"; t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\DotNetAssemblyDependsOnWinMD.dll", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Equal("NOPE", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)); Assert.Equal("IMPL", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly.winmd", t.ResolvedDependencyFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal("SampleWindowsRuntimeOnly.dll", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); } /// <summary> /// Resolve a winmd file which depends on a native implementation dll that has an invalid pe header. /// This will always result in an error since the dll is malformed /// </summary> [Fact] public void ResolveWinmdWithInvalidPENativeDependency() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem(@"DependsOnInvalidPeHeader"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; bool succeeded = Execute(t); // Should fail since PE Header is not valid and this is always an error. Assert.False(succeeded); Assert.Equal(1, engine.Errors); Assert.Equal(0, engine.Warnings); // The original winmd will resolve but its implementation dll must not be there Assert.Single(t.ResolvedFiles); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); string invalidPEMessage = ResourceUtilities.GetResourceString("ResolveAssemblyReference.ImplementationDllHasInvalidPEHeader"); string fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.ProblemReadingImplementationDll", @"C:\WinMDArchVerification\DependsOnInvalidPeHeader.dll", invalidPEMessage); engine.AssertLogContains(fullMessage); } /// <summary> /// Resolve a winmd file which depends a native dll that matches the targeted architecture /// </summary> [Fact] public void ResolveWinmdWithArchitectureDependencyMatchingArchitecturesX86() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem("DependsOnX86"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; t.TargetProcessorArchitecture = "X86"; t.WarnOrErrorOnTargetArchitectureMismatch = "Error"; bool succeeded = Execute(t); Assert.Single(t.ResolvedFiles); Assert.Equal(@"C:\WinMDArchVerification\DependsOnX86.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.True(succeeded); Assert.Equal("DependsOnX86.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); } /// <summary> /// Resolve a winmd file which depends a native dll that matches the targeted architecture /// </summary> [Fact] public void ResolveWinmdWithArchitectureDependencyAnyCPUNative() { // Create the engine. MockEngine engine = new MockEngine(_output); // IMAGE_FILE_MACHINE unknown is supposed to work on all machine types TaskItem item = new TaskItem("DependsOnAnyCPUUnknown"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; t.TargetProcessorArchitecture = "X86"; t.WarnOrErrorOnTargetArchitectureMismatch = "Error"; bool succeeded = Execute(t); Assert.Single(t.ResolvedFiles); Assert.Equal(@"C:\WinMDArchVerification\DependsOnAnyCPUUnknown.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.True(succeeded); Assert.Equal("DependsOnAnyCPUUnknown.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); } /// <summary> /// Resolve a winmd file which depends on a native implementation dll that has an invalid pe header. /// A warning or error is expected in the log depending on the WarnOrErrorOnTargetArchitecture property value. /// </summary> [Fact] public void ResolveWinmdWithArchitectureDependency() { VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "Error"); VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "Warning"); VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "None"); VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "Error"); VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "Warning"); VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "None"); VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "Error"); VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "Warning"); VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "None"); VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "Error"); VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "Warning"); VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "None"); VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "Error"); VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "Warning"); VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "None"); VerifyImplementationArchitecture("DependsOnARMV7", "MSIL", "ARM", "Error"); VerifyImplementationArchitecture("DependsOnARMV7", "MSIL", "ARM", "Warning"); VerifyImplementationArchitecture("DependsOnARMv7", "MSIL", "ARM", "None"); VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "Error"); VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "Warning"); VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "None"); VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "Error"); VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "Warning"); VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "None"); } private void VerifyImplementationArchitecture(string winmdName, string targetProcessorArchitecture, string implementationFileArch, string warnOrErrorOnTargetArchitectureMismatch) { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem(winmdName); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; t.TargetProcessorArchitecture = targetProcessorArchitecture; t.WarnOrErrorOnTargetArchitectureMismatch = warnOrErrorOnTargetArchitectureMismatch; bool succeeded = Execute(t); Assert.Single(t.ResolvedFiles); Assert.Equal(@"C:\WinMDArchVerification\" + winmdName + ".winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); string fullMessage; if (implementationFileArch.Equals("Unknown")) { fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.UnknownProcessorArchitecture", @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd", NativeMethods.IMAGE_FILE_MACHINE_R4000.ToString("X", CultureInfo.InvariantCulture)); } else { fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.MismatchBetweenTargetedAndReferencedArchOfImplementation", targetProcessorArchitecture, implementationFileArch, @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd"); } if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase)) { engine.AssertLogDoesntContain(fullMessage); } else { engine.AssertLogContains(fullMessage); } if (warnOrErrorOnTargetArchitectureMismatch.Equals("Warning", StringComparison.OrdinalIgnoreCase)) { // Should fail since PE Header is not valid and this is always an error. Assert.True(succeeded); Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(1, engine.Warnings); } else if (warnOrErrorOnTargetArchitectureMismatch.Equals("Error", StringComparison.OrdinalIgnoreCase)) { // Should fail since PE Header is not valid and this is always an error. Assert.False(succeeded); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(1, engine.Errors); Assert.Equal(0, engine.Warnings); } else if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase)) { Assert.True(succeeded); Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); } } /// <summary> /// Verify when a winmd file depends on another winmd file that we resolve both and that the metadata is correct. /// </summary> [Fact] public void DotNetAssemblyDependsOnAWinMDFileWithVersion255() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"DotNetAssemblyDependsOn255WinMD") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\DotNetAssemblyDependsOn255WinMD.dll", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)); Assert.Equal(@"C:\WinMD\WinMDWithVersion255.winmd", t.ResolvedDependencyFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); } #endregion } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.txt file at the root of this distribution. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.Project { #region structures [StructLayoutAttribute(LayoutKind.Sequential)] internal struct _DROPFILES { public Int32 pFiles; public Int32 X; public Int32 Y; public Int32 fNC; public Int32 fWide; } #endregion #region enums /// <summary> /// The type of build performed. /// </summary> public enum BuildKind { Sync, Async } /// <summary> /// Defines possible types of output that can produced by a language project /// </summary> [PropertyPageTypeConverterAttribute(typeof(OutputTypeConverter))] public enum OutputType { /// <summary> /// The output type is a class library. /// </summary> Library, /// <summary> /// The output type is a windows executable. /// </summary> WinExe, /// <summary> /// The output type is an executable. /// </summary> Exe, /// <summary> /// The output type is an application Container. /// </summary> AppContainerExe, /// <summary> /// The output type is an WinMD Assembly /// </summary> WinMDObj, } /// <summary> /// Debug values used by DebugModeConverter. /// </summary> [PropertyPageTypeConverterAttribute(typeof(DebugModeConverter))] public enum DebugMode { Project, Program, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URL")] URL } [PropertyPageTypeConverterAttribute(typeof(CopyToOutputDirectoryConverter))] public enum CopyToOutputDirectory { DoNotCopy, Always, PreserveNewest, } /// <summary> /// An enumeration that describes the type of action to be taken by the build. /// </summary> //[PropertyPageTypeConverterAttribute(typeof(BuildActionConverter))] //public enum BuildAction //{ // None, // Compile, // Content, // EmbeddedResource //} /// <summary> /// Defines the currect state of a property page. /// </summary> [Flags] public enum PropPageStatus { Dirty = 0x1, Validate = 0x2, Clean = 0x4 } [Flags] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum ModuleKindFlags { ConsoleApplication, WindowsApplication, DynamicallyLinkedLibrary, ManifestResourceFile, UnmanagedDynamicallyLinkedLibrary } /// <summary> /// Defines the status of the command being queried /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum QueryStatusResult { /// <summary> /// The command is not supported. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NOTSUPPORTED")] NOTSUPPORTED = 0, /// <summary> /// The command is supported /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SUPPORTED")] SUPPORTED = 1, /// <summary> /// The command is enabled /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ENABLED")] ENABLED = 2, /// <summary> /// The command is toggled on /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "LATCHED")] LATCHED = 4, /// <summary> /// The command is toggled off (the opposite of LATCHED). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NINCHED")] NINCHED = 8, /// <summary> /// The command is invisible. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "INVISIBLE")] INVISIBLE = 16 } /// <summary> /// Defines the type of item to be added to the hierarchy. /// </summary> public enum HierarchyAddType { AddNewItem, AddExistingItem } /// <summary> /// Defines the component from which a command was issued. /// </summary> public enum CommandOrigin { [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ui")] UiHierarchy, OleCommandTarget } /// <summary> /// Defines the current status of the build process. /// </summary> public enum MSBuildResult { /// <summary> /// The build is currently suspended. /// </summary> Suspended, /// <summary> /// The build has been restarted. /// </summary> Resumed, /// <summary> /// The build failed. /// </summary> Failed, /// <summary> /// The build was successful. /// </summary> Successful, } /// <summary> /// Defines the type of action to be taken in showing the window frame. /// </summary> public enum WindowFrameShowAction { DoNotShow, Show, ShowNoActivate, Hide, } /// <summary> /// Defines drop types /// </summary> internal enum DropDataType { None, Shell, VsStg, VsRef } /// <summary> /// Used by the hierarchy node to decide which element to redraw. /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] public enum UIHierarchyElement { None = 0, /// <summary> /// This will be translated to VSHPROPID_IconIndex /// </summary> Icon = 1, /// <summary> /// This will be translated to VSHPROPID_StateIconIndex /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] SccState = 2, /// <summary> /// This will be translated to VSHPROPID_Caption /// </summary> Caption = 4, /// <summary> /// This will be translated to VSHPROPID_OverlayIconIndex /// </summary> OverlayIcon = 8 } /// <summary> /// Defines the global propeties used by the msbuild project. /// </summary> public enum GlobalProperty { /// <summary> /// Property specifying that we are building inside VS. /// </summary> BuildingInsideVisualStudio, /// <summary> /// The VS installation directory. This is the same as the $(DevEnvDir) macro. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Env")] DevEnvDir, /// <summary> /// The name of the solution the project is created. This is the same as the $(SolutionName) macro. /// </summary> SolutionName, /// <summary> /// The file name of the solution. This is the same as $(SolutionFileName) macro. /// </summary> SolutionFileName, /// <summary> /// The full path of the solution. This is the same as the $(SolutionPath) macro. /// </summary> SolutionPath, /// <summary> /// The directory of the solution. This is the same as the $(SolutionDir) macro. /// </summary> SolutionDir, /// <summary> /// The extension of teh directory. This is the same as the $(SolutionExt) macro. /// </summary> SolutionExt, /// <summary> /// The fxcop installation directory. /// </summary> FxCopDir, /// <summary> /// The ResolvedNonMSBuildProjectOutputs msbuild property /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VSIDE")] VSIDEResolvedNonMSBuildProjectOutputs, /// <summary> /// The Configuartion property. /// </summary> Configuration, /// <summary> /// The platform property. /// </summary> Platform, /// <summary> /// The RunCodeAnalysisOnce property /// </summary> RunCodeAnalysisOnce, /// <summary> /// The VisualStudioStyleErrors property /// </summary> VisualStudioStyleErrors, } #endregion public class AfterProjectFileOpenedEventArgs : EventArgs { #region fields private bool added; #endregion #region properties /// <summary> /// True if the project is added to the solution after the solution is opened. false if the project is added to the solution while the solution is being opened. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool Added { get { return this.added; } } #endregion #region ctor internal AfterProjectFileOpenedEventArgs(bool added) { this.added = added; } #endregion } public class BeforeProjectFileClosedEventArgs : EventArgs { #region fields private bool _removed; private IVsHierarchy _hierarchy; #endregion #region properties /// <summary> /// true if the project was removed from the solution before the solution was closed. false if the project was removed from the solution while the solution was being closed. /// </summary> internal bool Removed { get { return _removed; } } internal IVsHierarchy Hierarchy { get { return _hierarchy; } } #endregion #region ctor internal BeforeProjectFileClosedEventArgs(IVsHierarchy hierarchy, bool removed) { this._removed = removed; _hierarchy = hierarchy; } #endregion } /// <summary> /// Argument of the event raised when a project property is changed. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class ProjectPropertyChangedArgs : EventArgs { private string propertyName; private string oldValue; private string newValue; internal ProjectPropertyChangedArgs(string propertyName, string oldValue, string newValue) { this.propertyName = propertyName; this.oldValue = oldValue; this.newValue = newValue; } public string NewValue { get { return newValue; } } public string OldValue { get { return oldValue; } } public string PropertyName { get { return propertyName; } } } /// <summary> /// This class is used for the events raised by a HierarchyNode object. /// </summary> public class HierarchyNodeEventArgs : EventArgs { private HierarchyNode child; internal HierarchyNodeEventArgs(HierarchyNode child) { this.child = child; } public HierarchyNode Child { get { return this.child; } } } /// <summary> /// Event args class for triggering file change event arguments. /// </summary> internal class FileChangedOnDiskEventArgs : EventArgs { #region Private fields /// <summary> /// File name that was changed on disk. /// </summary> private string fileName; /// <summary> /// The item ide of the file that has changed. /// </summary> private uint itemID; /// <summary> /// The reason the file has changed on disk. /// </summary> private _VSFILECHANGEFLAGS fileChangeFlag; #endregion /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">File name that was changed on disk.</param> /// <param name="id">The item id of the file that was changed on disk.</param> internal FileChangedOnDiskEventArgs(string fileName, uint id, _VSFILECHANGEFLAGS flag) { this.fileName = fileName; this.itemID = id; this.fileChangeFlag = flag; } /// <summary> /// Gets the file name that was changed on disk. /// </summary> /// <value>The file that was changed on disk.</value> internal string FileName { get { return this.fileName; } } /// <summary> /// Gets item id of the file that has changed /// </summary> /// <value>The file that was changed on disk.</value> internal uint ItemID { get { return this.itemID; } } /// <summary> /// The reason while the file has chnaged on disk. /// </summary> /// <value>The reason while the file has chnaged on disk.</value> internal _VSFILECHANGEFLAGS FileChangeFlag { get { return this.fileChangeFlag; } } } /// <summary> /// Defines the event args for the active configuration chnage event. /// </summary> public class ActiveConfigurationChangedEventArgs : EventArgs { #region Private fields /// <summary> /// The hierarchy whose configuration has changed /// </summary> private IVsHierarchy hierarchy; #endregion /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">The hierarchy that has changed its configuration.</param> internal ActiveConfigurationChangedEventArgs(IVsHierarchy hierarchy) { this.hierarchy = hierarchy; } /// <summary> /// The hierarchy whose configuration has changed /// </summary> internal IVsHierarchy Hierarchy { get { return this.hierarchy; } } } }
/* * Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details. */using UnityEngine; using System.Collections.Generic; public class TeacherFeaturesWindow : ILearnRWUIElement, IActionNotifier { Vector2 scrollPos; Vector2 tmpVect; //bool canChangeLanguageArea = false; //bool canChangeDifficulty = false; int langArea; int diff; int questGiverID; // IGBActivityReference acRefMat; List<ApplicationID> applicableActivities; int currAcListIndex; ApplicationID currAcID = ApplicationID.APP_ID_NOT_SET_UP; string defaultParamStrForConfig; Dictionary<string,string> optionParamStore; List<string> paramKeyOrder; AvailableOptions loadedOptions; Dictionary<ApplicationID,AvailableOptions> optionsCache = null; int[] selectorArr = null; void OnGUI() { if( ! hasInitGUIStyles) { this.prepGUIStyles(); hasInitGUIStyles = true; } else { GUI.color = Color.black; GUI.Label(uiBounds["Title"],textContent["Title"],availableGUIStyles["FieldTitle"]); GUI.Label(uiBounds["LangAreaTitle"],textContent["LangAreaTitle"],availableGUIStyles["FieldContent"]); GUI.Label(uiBounds["DifficultyTitle"],textContent["DifficultyTitle"],availableGUIStyles["FieldContent"]); GUI.Label(uiBounds["LangAreaContent"],textContent["LangAreaContent"],availableGUIStyles["FieldContent"]); GUI.Label(uiBounds["DifficultyContent"],textContent["DifficultyContent"],availableGUIStyles["FieldContent"]); GUI.Label(uiBounds["ApplicableActivitiesTitle"],textContent["ApplicableActivitiesTitle"],availableGUIStyles["FieldContentTiny"]); GUI.Label(uiBounds["ActivityOptionsTitle"],textContent["ActivityOptionsTitle"],availableGUIStyles["FieldContent"]); GUI.color = Color.clear; if(GUI.Button(uiBounds["PrevActivityButton"],textContent["PrevActivityButton"])) { // See previous activity options. if(currAcListIndex > 0) { triggerSoundAtCamera("Blop",1f,false); currAcListIndex--; updateActivitySymbol(); } } if(GUI.Button(uiBounds["NextActivityButton"],textContent["NextActivityButton"])) { // See next activity options. if(currAcListIndex < (applicableActivities.Count)-1) { triggerSoundAtCamera("Blip",1f,false); currAcListIndex++; updateActivitySymbol(); } } if(currAcID != ApplicationID.APP_ID_NOT_SET_UP){ GUI.color = Color.black; GUI.Label(uiBounds["OkButton"],textContent["OkButton"],availableGUIStyles["FieldContent"]); GUI.color = Color.clear; if(GUI.Button(uiBounds["OkButton"],"")) { // Create level parameter string based on the options. string finalParamStr = buildParamString(); ExternalParams eParams = new ExternalParams(currAcID,questGiverID,langArea,diff,finalParamStr,true); notifyAllListeners("TeacherFeaturesWindow","Ok",eParams); //Destroy(transform.gameObject); } } GUI.color = Color.white; if((Application.platform == RuntimePlatform.Android) ||(Application.platform == RuntimePlatform.IPhonePlayer)) { if(Input.touchCount == 1) { tmpVect.x = Input.touches[0].position.x; tmpVect.y = Screen.height - Input.touches[0].position.y; if(uiBounds["ActivityOpScrollArea"].Contains(tmpVect)) { scrollPos.y += (Input.touches[0].deltaPosition.y * 1f); } } } GUILayout.BeginArea(uiBounds["ActivityOpScrollArea"]); scrollPos = GUILayout.BeginScrollView(scrollPos); // Write code about activity specific options here. GUIStyle selGridStyle = availableGUIStyles["SelectionGrid"]; List<string> opKeys = loadedOptions.validKeys; Dictionary<string,OptionInfo> opLookup = loadedOptions.validOptions; for(int i=0; i<opKeys.Count; i++) { string currOpKey = opKeys[i]; OptionInfo currOpInfo = opLookup[currOpKey]; GUILayout.BeginVertical(); GUI.color = Color.black; GUILayout.BeginHorizontal(); GUILayout.Label(currOpInfo.opReadableTitle,availableGUIStyles["FieldContentML"]); GUI.color = Color.white; //GUILayout.BeginHorizontal(); selectorArr[i] = GUILayout.SelectionGrid(selectorArr[i],currOpInfo.opReadableSelections,currOpInfo.opReadableSelections.Length,selGridStyle); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } GUILayout.EndScrollView(); GUILayout.EndArea(); } } private new void prepGUIStyles() { availableGUIStyles = new Dictionary<string, GUIStyle>(); float targetWidth = 1280f; float targetHeight = 800f; Vector3 scaleForCurrRes = new Vector3((Screen.width * 1.0f)/targetWidth,(Screen.height * 1.0f)/targetHeight,1f); GUIStyle fieldTitleStyle = new GUIStyle(GUI.skin.label); fieldTitleStyle.alignment = TextAnchor.MiddleCenter; fieldTitleStyle.fontSize = (int) (50 * scaleForCurrRes.x); GUIStyle fieldContentStyle = new GUIStyle(GUI.skin.label); fieldContentStyle.alignment = TextAnchor.MiddleCenter; fieldContentStyle.fontSize = (int) (30 * scaleForCurrRes.x); GUIStyle fieldContentMLStyle = new GUIStyle(GUI.skin.label); fieldContentMLStyle.alignment = TextAnchor.MiddleLeft; fieldContentMLStyle.fontSize = (int) (30 * scaleForCurrRes.x); GUIStyle fieldContentTinyStyle = new GUIStyle(GUI.skin.label); fieldContentTinyStyle.alignment = TextAnchor.MiddleCenter; fieldContentTinyStyle.fontSize = (int) (25 * scaleForCurrRes.x); Texture2D clearTex = new Texture2D(1,1); clearTex.SetPixel(0,0,ColorUtils.convertColor(0,0,0,20)); clearTex.Apply(); GUIStyle selectionGridStyle = new GUIStyle(GUI.skin.button); selectionGridStyle.normal.background = clearTex; selectionGridStyle.normal.textColor = Color.black; selectionGridStyle.fixedHeight = (int) (60 * scaleForCurrRes.x); GUIStyle btnStyle = new GUIStyle(GUI.skin.button); btnStyle.wordWrap = true; availableGUIStyles.Add("FieldTitle",fieldTitleStyle); availableGUIStyles.Add("FieldContent",fieldContentStyle); availableGUIStyles.Add("FieldContentML",fieldContentMLStyle); availableGUIStyles.Add("FieldContentTiny",fieldContentTinyStyle); availableGUIStyles.Add("SelectionGrid",selectionGridStyle); availableGUIStyles.Add("Button",btnStyle); hasInitGUIStyles = true; } // Use this if language area and difficulty are fixed and cannot be altered by the user. // Eg. If a user has selected a langArea and Diff by selecting to play a ghostbook photo page. public void init(int para_langArea, int para_difficulty, int para_questGiverID) { //canChangeLanguageArea = false; //canChangeDifficulty = false; GhostbookManagerLight gbMang = GhostbookManagerLight.getInstance(); //IGBLangAreaReference langAreaRef = gbMang.getLangAreaReferenceMaterial(); //IGBDifficultyReference diffRefMat = gbMang.getDifficultyReferenceMaterial(); // acRefMat = gbMang.getActivityReferenceMaterial(); string langAreaName = gbMang.getNameForLangArea(para_langArea); string diffName = gbMang.createDifficultyShortDescription(para_langArea,para_difficulty); langArea = para_langArea; diff = para_difficulty; questGiverID = para_questGiverID; // Switch on dimer object. GameObject dimScreen = transform.FindChild("DimScreen").gameObject; dimScreen.renderer.enabled = true; dimScreen.renderer.material.color = Color.black; // Init text items. string[] elementNames = {"Title","LangAreaTitle","DifficultyTitle","LangAreaContent","DifficultyContent","ActivityOpScrollArea","PrevActivityButton","NextActivityButton","OkButton","ApplicableActivitiesTitle","ActivityOptionsTitle"}; string[] elementContent = {LocalisationMang.translate("Teacher options"),LocalisationMang.translate("Language area"),LocalisationMang.translate("Difficulty"),langAreaName,diffName,"AcOpScrollArea","<",">",LocalisationMang.translate("Ok"),LocalisationMang.translate("Applicable activities"),LocalisationMang.translate("Activity options")}; bool[] destroyGuideArr = {true,true,true,false,false,false,true,true,true,true,true}; int[] textElementTypeArr = {0,0,0,0,0,0,0,0,0,0,0}; prepTextElements(elementNames,elementContent,destroyGuideArr,textElementTypeArr,null); scrollPos = new Vector2(); tmpVect = new Vector2(); applicableActivities = LocalisationMang.getAllApplicableActivitiesForLangArea(langArea); currAcListIndex = 0;//applicableActivities.Count-1; currAcID = applicableActivities[currAcListIndex];//acRefMat.getAcIDEnum_byAcPKey(); updateActivitySymbol(); } private void updateActivitySymbol() { currAcID = applicableActivities[currAcListIndex]; Debug.Log(currAcID); if(currAcID == ApplicationID.APP_ID_NOT_SET_UP){ Debug.LogWarning("needs something here?"); if(optionsCache == null) { optionsCache = new Dictionary<ApplicationID, AvailableOptions>(); } updateAvailableOptions(); return; } Transform reqActivitySymbolPrefab = Resources.Load<Transform>("Prefabs/Ghostbook/ActivitySymbols/SmallSymbols_"+currAcID); if(reqActivitySymbolPrefab != null) { Sprite reqSymbolSprite = reqActivitySymbolPrefab.GetComponent<SpriteRenderer>().sprite; transform.FindChild("ActivitySymbol").GetComponent<SpriteRenderer>().sprite = reqSymbolSprite; } if(optionParamStore == null) { optionParamStore = new Dictionary<string, string>(); paramKeyOrder = new List<string>(); } else { optionParamStore.Clear(); paramKeyOrder.Clear(); } defaultParamStrForConfig = LocalisationMang.getFirstLevelConfiguration(currAcID,langArea,diff); string[] splitParams = defaultParamStrForConfig.Split('-'); for(int i=0; i<splitParams.Length; i++) { string tmpItem = splitParams[i]; if((tmpItem != null)&&(tmpItem != "")) { string firstChar = ""+tmpItem[0]; paramKeyOrder.Add(firstChar); optionParamStore.Add(firstChar,tmpItem); } } updateAvailableOptions(); } private void updateAvailableOptions() { ApplicationID reqAppIDToSearch = currAcID; // Warning. Cache usage should be invalidated if the language area and difficulty combo changes. if(optionsCache == null) { optionsCache = new Dictionary<ApplicationID, AvailableOptions>(); } if(optionsCache.ContainsKey(reqAppIDToSearch)) { loadedOptions = optionsCache[reqAppIDToSearch]; } else { loadedOptions = LocalisationMang.workOutOptionsForActivityAndLangArea(reqAppIDToSearch,langArea); optionsCache.Add(reqAppIDToSearch,loadedOptions); } selectorArr = new int[loadedOptions.validKeys.Count]; for(int i=0; i<loadedOptions.validKeys.Count; i++) { selectorArr[i] = 0; } } private void invalidateOptionCache() { if(optionsCache == null) { optionsCache = new Dictionary<ApplicationID, AvailableOptions>(); } optionsCache.Clear(); } private void extractUserChoices() { if(optionParamStore == null) { optionParamStore = new Dictionary<string, string>(); } List<string> opKeys = loadedOptions.validKeys; Dictionary<string,OptionInfo> opLookup = loadedOptions.validOptions; for(int i=0; i<opKeys.Count; i++) { string currOpKey = opKeys[i]; OptionInfo currOpInfo = opLookup[currOpKey]; string codeSelection = currOpKey + (""+ currOpInfo.opCodes[selectorArr[i]]); if(optionParamStore.ContainsKey(currOpKey)) { optionParamStore[currOpKey] = codeSelection; } else { optionParamStore.Add(currOpKey,codeSelection); } } } private string buildParamString() { string retStr = ""; extractUserChoices(); if(optionParamStore == null) { retStr = defaultParamStrForConfig; } else { if(paramKeyOrder == null) { retStr = defaultParamStrForConfig; } else { int paramID = 0; for(int i=0; i<paramKeyOrder.Count; i++) { if(optionParamStore.ContainsKey(paramKeyOrder[i])) { if(paramID != 0) { retStr += "-"; } retStr += optionParamStore[paramKeyOrder[i]]; optionParamStore.Remove(paramKeyOrder[i]); paramID++; } } List<string> remainingKeys = new List<string>(optionParamStore.Keys); for(int i=0; i<remainingKeys.Count; i++) { if(paramID != 0) { retStr += "-"; } retStr += optionParamStore[remainingKeys[i]]; optionParamStore.Remove(remainingKeys[i]); paramID++; } } } return retStr; } /*public void forceCloseWindow() { notifyAllListeners("TeacherFeaturesWindow","Close",null); Destroy(transform.gameObject); }*/ // Action Notifier Methods. IActionNotifier acNotifier = new ConcActionNotifier(); public void registerListener(string para_name, CustomActionListener para_listener) { acNotifier.registerListener(para_name,para_listener); } public void unregisterListener(string para_name) { acNotifier.unregisterListener(para_name); } public void notifyAllListeners(string para_sourceID, string para_eventID, System.Object para_eventData) { acNotifier.notifyAllListeners(para_sourceID,para_eventID,para_eventData); } Transform sfxPrefab = null; private void triggerSoundAtCamera(string para_soundFileName, float para_volume, bool para_loop) { GameObject camGObj = Camera.main.gameObject; GameObject potentialOldSfx = GameObject.Find(para_soundFileName); if(potentialOldSfx != null) { Destroy(potentialOldSfx); } if(sfxPrefab == null) { sfxPrefab = Resources.Load<Transform>("Prefabs/SFxBox"); } GameObject nwSFX = ((Transform) Instantiate(sfxPrefab,camGObj.transform.position,Quaternion.identity)).gameObject; nwSFX.name = para_soundFileName; AudioSource audS = (AudioSource) nwSFX.GetComponent(typeof(AudioSource)); audS.clip = (AudioClip) Resources.Load("Sounds/"+para_soundFileName,typeof(AudioClip)); audS.volume = para_volume; audS.loop = para_loop; if(para_loop) { Destroy(nwSFX.GetComponent<DestroyAfterTime>()); } audS.Play(); } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using M2M; using NearestNeighbor; using PositionSetViewer; using PositionSetEditer; using PositionSetDrawer; using Configuration; using Position_Interface; using Position_Implement; namespace AlgorithmDemo { public class AlgorithmDemo_M2M_NN { M2M_NN m2m_NN; Layers layers; FlowControlerForm flowControlerForm; dUpdate Update; public AlgorithmDemo_M2M_NN(M2M_NN m2m_NN, Layers layers, FlowControlerForm flowControlerForm, dUpdate update) { this.m2m_NN = m2m_NN; this.layers = layers; this.flowControlerForm = flowControlerForm; this.Update = update; m2m_NN.GetQueryPosition += delegate { SearchPartSetLayer = null; ComparedPointLayer = null; shrinkBoundPointSetLayer = null; searchBoundLayer = null; }; m2m_NN.GetPositionSetOfComparedPoint += OnGetPositionSetOfComparedPoint; m2m_NN.GetM2MStructure += OnGetM2MStructure; m2m_NN.GetQueryPosition += OnGetQueryPosition; m2m_NN.GetQueryPart += OnGetQueryPart; m2m_NN.GetSearchPart += OnGetSearchPart; m2m_NN.GetComparedPoint += OnGetComparedPoint; m2m_NN.SearchBoundChanged += OnSearchBoundChanged; m2m_NN.CurrentNearestPointChanged += OnCurrentNearestPointChanged; flowControlerForm.SelectConfiguratoinObject(this); } public void EndDemo() { IsGetPositionSetOfComparedPoint = false; IsGetM2MStructure = false; IsGetComparedPoint = false; m2m_NN.GetQueryPosition -= OnGetQueryPosition; m2m_NN.GetQueryPart -= OnGetQueryPart; m2m_NN.GetSearchPart -= OnGetSearchPart; m2m_NN.SearchBoundChanged -= OnSearchBoundChanged; m2m_NN.CurrentNearestPointChanged -= OnCurrentNearestPointChanged; flowControlerForm.SelectConfiguratoinObject(null); flowControlerForm.Reset(); } bool isGetPositionSetOfComparedPoint = true; public bool IsGetPositionSetOfComparedPoint { get { return isGetPositionSetOfComparedPoint; } set { if (isGetPositionSetOfComparedPoint != value) { isGetPositionSetOfComparedPoint = value; if (value) { m2m_NN.GetPositionSetOfComparedPoint += OnGetPositionSetOfComparedPoint; } else { m2m_NN.GetPositionSetOfComparedPoint -= OnGetPositionSetOfComparedPoint; } } } } bool isGetM2MStructure = true; public bool IsGetM2MStructure { get { return isGetM2MStructure; } set { if (isGetM2MStructure != value) { isGetM2MStructure = value; if (value) { m2m_NN.GetM2MStructure += OnGetM2MStructure; } else { m2m_NN.GetM2MStructure -= OnGetM2MStructure; } } } } bool isGetComparedPoint = true; public bool IsGetComparedPoint { get { return isGetComparedPoint; } set { if (isGetComparedPoint != value) { isGetComparedPoint = value; if (value) { m2m_NN.GetComparedPoint += OnGetComparedPoint; } else { m2m_NN.GetComparedPoint -= OnGetComparedPoint; } } } } private void OnGetPositionSetOfComparedPoint(IPositionSet positionSet) { lock (layers) { Layer_PositionSet_Point layer = new Layer_PositionSet_Point(new PositionSet_Cloned(positionSet)); layer.Point.PointRadius = 2; layer.Point.IsDrawPointBorder = true; layer.MainColor = Color.FromArgb(0, 255, 0); layer.Name = "PositionSetOfComparedPoint"; layers.Add(layer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } private void OnGetM2MStructure(IM2MStructure m2mStructure) { lock (layers) { Layer_M2MStructure layer = new Layer_M2MStructure(m2mStructure); layer.Name = "M2MStructure"; layers.Add(layer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } private void OnGetQueryPosition(IPosition position) { lock (layers) { IPositionSetEdit temp = new PositionSetEdit_ImplementByICollectionTemplate(); temp.AddPosition(position); Layer_PositionSet_Point queryPositionLayer = new Layer_PositionSet_Point(temp); queryPositionLayer.Point.PointRadius = 3; queryPositionLayer.Point.PointColor = Color.IndianRed; queryPositionLayer.Point.IsDrawPointBorder = true; queryPositionLayer.Active = true; layers.Add(queryPositionLayer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } private void OnGetQueryPart(ILevel level, int levelSequence, IPart part) { lock (layers) { PositionSetEdit_ImplementByICollectionTemplate partSet = new PositionSetEdit_ImplementByICollectionTemplate(); partSet.AddPosition(part); Layer_M2MPartSetInSpecificLevel layer = new Layer_M2MPartSetInSpecificLevel(level, partSet); layer.MainColor = Color.FromArgb(255, 0, 0); layer.Active = true; layers.Add(layer); } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } Layer_M2MPartSetInSpecificLevel SearchPartSetLayer = null; IPositionSetEdit SearchPartSet = null; private void OnGetSearchPart(ILevel level, int levelSequence, IPart part) { lock (layers) { if (SearchPartSetLayer == null) { SearchPartSet = new PositionSetEdit_ImplementByICollectionTemplate(); SearchPartSetLayer = new Layer_M2MPartSetInSpecificLevel(level, SearchPartSet); SearchPartSetLayer.MainColor = Color.Blue; SearchPartSetLayer.Active = true; layers.Add(SearchPartSetLayer); } SearchPartSet.AddPosition(part); SearchPartSetLayer.PositionSet = SearchPartSet; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } Layer_PositionSet_Point ComparedPointLayer = null; IPositionSetEdit ComparedPointSet = null; private void OnGetComparedPoint(IPosition point) { lock (layers) { if (ComparedPointLayer == null) { ComparedPointSet = new PositionSetEdit_ImplementByICollectionTemplate(); ComparedPointLayer = new Layer_PositionSet_Point(ComparedPointSet); ComparedPointLayer.Active = true; ComparedPointLayer.Point.PointRadius = 2; ComparedPointLayer.Point.IsDrawPointBorder = true; ComparedPointLayer.Point.PointColor = Color.Goldenrod; layers.Add(ComparedPointLayer); } ComparedPointSet.AddPosition(point); ComparedPointLayer.PositionSet = ComparedPointSet; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } Layer_PositionSet_Point shrinkBoundPointSetLayer = null; IPositionSetEdit shrinkBoundPointSet = null; private void OnCurrentNearestPointChanged(IPosition point) { lock (layers) { if (shrinkBoundPointSetLayer == null) { shrinkBoundPointSet = new PositionSetEdit_ImplementByICollectionTemplate(); shrinkBoundPointSetLayer = new Layer_PositionSet_Point(shrinkBoundPointSet); shrinkBoundPointSetLayer.Active = true; shrinkBoundPointSetLayer.Point.PointRadius = 3; shrinkBoundPointSetLayer.Point.IsDrawPointBorder = true; shrinkBoundPointSetLayer.Point.PointColor = Color.Red; layers.Add(shrinkBoundPointSetLayer); } shrinkBoundPointSet.AddPosition(point); shrinkBoundPointSetLayer.PositionSet = shrinkBoundPointSet; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } Layer_Rectangle searchBoundLayer = null; private void OnSearchBoundChanged(float upperBound, float lowerBound, float leftBound, float rightBound) { lock (layers) { if (searchBoundLayer == null) { searchBoundLayer = new Layer_Rectangle(upperBound, lowerBound, leftBound, rightBound); searchBoundLayer.Active = true; searchBoundLayer.PenWidth = 2; searchBoundLayer.PenStyle = System.Drawing.Drawing2D.DashStyle.DashDot; searchBoundLayer.MainColor = Color.Orange; layers.Add(searchBoundLayer); } searchBoundLayer.UpperBound = upperBound; searchBoundLayer.LowerBound = lowerBound; searchBoundLayer.LeftBound = leftBound; searchBoundLayer.RightBound = rightBound; } flowControlerForm.BeginInvoke(Update); flowControlerForm.SuspendAndRecordWorkerThread(); } } }
using System; using NUnit.Framework; using Python.Runtime; namespace Python.EmbeddingTest { public class PyScopeTest { private PyScope ps; [SetUp] public void SetUp() { using (Py.GIL()) { ps = Py.CreateScope("test"); } } [TearDown] public void Dispose() { using (Py.GIL()) { ps.Dispose(); ps = null; } } /// <summary> /// Eval a Python expression and obtain its return value. /// </summary> [Test] public void TestEval() { using (Py.GIL()) { ps.Set("a", 1); var result = ps.Eval<int>("a + 2"); Assert.AreEqual(3, result); } } /// <summary> /// Exec Python statements and obtain the variables created. /// </summary> [Test] public void TestExec() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable ps.Exec("aa = bb + cc + 3"); var result = ps.Get<int>("aa"); Assert.AreEqual(113, result); } } /// <summary> /// Compile an expression into an ast object; /// Execute the ast and obtain its return value. /// </summary> [Test] public void TestCompileExpression() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable PyObject script = PythonEngine.Compile("bb + cc + 3", "", RunFlagType.Eval); var result = ps.Execute<int>(script); Assert.AreEqual(113, result); } } /// <summary> /// Compile Python statements into an ast object; /// Execute the ast; /// Obtain the local variables created. /// </summary> [Test] public void TestCompileStatements() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable PyObject script = PythonEngine.Compile("aa = bb + cc + 3", "", RunFlagType.File); ps.Execute(script); var result = ps.Get<int>("aa"); Assert.AreEqual(113, result); } } /// <summary> /// Create a function in the scope, then the function can read variables in the scope. /// It cannot write the variables unless it uses the 'global' keyword. /// </summary> [Test] public void TestScopeFunction() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); ps.Exec( "def func1():\n" + " bb = cc + 10\n"); dynamic func1 = ps.Get("func1"); func1(); //call the function, it can be called any times var result = ps.Get<int>("bb"); Assert.AreEqual(100, result); ps.Set("bb", 100); ps.Set("cc", 10); ps.Exec( "def func2():\n" + " global bb\n" + " bb = cc + 10\n"); dynamic func2 = ps.Get("func2"); func2(); result = ps.Get<int>("bb"); Assert.AreEqual(20, result); } } /// <summary> /// Create a class in the scope, the class can read variables in the scope. /// Its methods can write the variables with the help of 'global' keyword. /// </summary> [Test] public void TestScopeClass() { using (Py.GIL()) { dynamic _ps = ps; _ps.bb = 100; ps.Exec( "class Class1():\n" + " def __init__(self, value):\n" + " self.value = value\n" + " def call(self, arg):\n" + " return self.value + bb + arg\n" + //use scope variables " def update(self, arg):\n" + " global bb\n" + " bb = self.value + arg\n" //update scope variable ); dynamic obj1 = _ps.Class1(20); var result = obj1.call(10).As<int>(); Assert.AreEqual(130, result); obj1.update(10); result = ps.Get<int>("bb"); Assert.AreEqual(30, result); } } /// <summary> /// Import a python module into the session. /// Equivalent to the Python "import" statement. /// </summary> [Test] public void TestImportModule() { using (Py.GIL()) { dynamic sys = ps.Import("sys"); Assert.IsTrue(ps.Contains("sys")); ps.Exec("sys.attr1 = 2"); var value1 = ps.Eval<int>("sys.attr1"); var value2 = sys.attr1.As<int>(); Assert.AreEqual(2, value1); Assert.AreEqual(2, value2); //import as ps.Import("sys", "sys1"); Assert.IsTrue(ps.Contains("sys1")); } } /// <summary> /// Create a scope and import variables from a scope, /// exec Python statements in the scope then discard it. /// </summary> [Test] public void TestImportScope() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); using (var scope = Py.CreateScope()) { scope.Import(ps, "ps"); scope.Exec("aa = ps.bb + ps.cc + 3"); var result = scope.Get<int>("aa"); Assert.AreEqual(113, result); } Assert.IsFalse(ps.Contains("aa")); } } /// <summary> /// Create a scope and import variables from a scope, /// exec Python statements in the scope then discard it. /// </summary> [Test] public void TestImportAllFromScope() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); using (var scope = ps.NewScope()) { scope.Exec("aa = bb + cc + 3"); var result = scope.Get<int>("aa"); Assert.AreEqual(113, result); } Assert.IsFalse(ps.Contains("aa")); } } /// <summary> /// Create a scope and import variables from a scope, /// call the function imported. /// </summary> [Test] public void TestImportScopeFunction() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); ps.Exec( "def func1():\n" + " return cc + bb\n"); using (PyScope scope = ps.NewScope()) { //'func1' is imported from the origion scope scope.Exec( "def func2():\n" + " return func1() - cc - bb\n"); dynamic func2 = scope.Get("func2"); var result1 = func2().As<int>(); Assert.AreEqual(0, result1); scope.Set("cc", 20);//it has no effect on the globals of 'func1' var result2 = func2().As<int>(); Assert.AreEqual(-10, result2); scope.Set("cc", 10); //rollback ps.Set("cc", 20); var result3 = func2().As<int>(); Assert.AreEqual(10, result3); ps.Set("cc", 10); //rollback } } } /// <summary> /// Import a python module into the session with a new name. /// Equivalent to the Python "import .. as .." statement. /// </summary> [Test] public void TestImportScopeByName() { using (Py.GIL()) { ps.Set("bb", 100); using (var scope = Py.CreateScope()) { scope.ImportAll("test"); //scope.ImportModule("test"); Assert.IsTrue(scope.Contains("bb")); } } } /// <summary> /// Use the locals() and globals() method just like in python module /// </summary> [Test] public void TestVariables() { using (Py.GIL()) { (ps.Variables() as dynamic)["ee"] = new PyInt(200); var a0 = ps.Get<int>("ee"); Assert.AreEqual(200, a0); ps.Exec("locals()['ee'] = 210"); var a1 = ps.Get<int>("ee"); Assert.AreEqual(210, a1); ps.Exec("globals()['ee'] = 220"); var a2 = ps.Get<int>("ee"); Assert.AreEqual(220, a2); using (var item = ps.Variables()) { item["ee"] = new PyInt(230); } var a3 = ps.Get<int>("ee"); Assert.AreEqual(230, a3); } } /// <summary> /// Share a pyscope by multiple threads. /// </summary> [Test] public void TestThread() { //After the proposal here https://github.com/pythonnet/pythonnet/pull/419 complished, //the BeginAllowThreads statement blow and the last EndAllowThreads statement //should be removed. dynamic _ps = ps; var ts = PythonEngine.BeginAllowThreads(); try { using (Py.GIL()) { _ps.res = 0; _ps.bb = 100; _ps.th_cnt = 0; //add function to the scope //can be call many times, more efficient than ast ps.Exec( "def update():\n" + " global res, th_cnt\n" + " res += bb + 1\n" + " th_cnt += 1\n" ); } int th_cnt = 3; for (int i = 0; i < th_cnt; i++) { System.Threading.Thread th = new System.Threading.Thread(() => { using (Py.GIL()) { //ps.GetVariable<dynamic>("update")(); //call the scope function dynamicly _ps.update(); } }); th.Start(); } //equivalent to Thread.Join, make the main thread join the GIL competition int cnt = 0; while (cnt != th_cnt) { using (Py.GIL()) { cnt = ps.Get<int>("th_cnt"); } System.Threading.Thread.Sleep(10); } using (Py.GIL()) { var result = ps.Get<int>("res"); Assert.AreEqual(101 * th_cnt, result); } } finally { PythonEngine.EndAllowThreads(ts); } } } }
using System; using swf = System.Windows.Forms; using Eto.Forms; using System.Linq; using System.Collections.Generic; using sd = System.Drawing; using Eto.Drawing; using Eto.WinForms.Drawing; using System.Diagnostics; namespace Eto.WinForms.Forms.Controls { public interface IGridHandler { void Paint(GridColumnHandler column, sd.Graphics graphics, sd.Rectangle clipBounds, sd.Rectangle cellBounds, int rowIndex, swf.DataGridViewElementStates cellState, object value, object formattedValue, string errorText, swf.DataGridViewCellStyle cellStyle, swf.DataGridViewAdvancedBorderStyle advancedBorderStyle, ref swf.DataGridViewPaintParts paintParts); int GetRowOffset(GridColumnHandler column, int rowIndex); bool CellMouseClick(GridColumnHandler column, swf.MouseEventArgs e, int rowIndex); } public abstract class GridHandler<TWidget, TCallback> : WindowsControl<swf.DataGridView, TWidget, TCallback>, Grid.IHandler, IGridHandler where TWidget: Grid where TCallback: Grid.ICallback { ColumnCollection columns; bool isFirstSelection = true; protected int SupressSelectionChanged { get; set; } protected bool clearColumns; protected void ResetSelection() { if (!SelectedRows.Any()) isFirstSelection = true; } protected abstract object GetItemAtRow(int row); class EtoDataGridView : swf.DataGridView { public GridHandler<TWidget, TCallback> Handler { get; set; } public override sd.Size GetPreferredSize(sd.Size proposedSize) { var size = base.GetPreferredSize(proposedSize); var def = Handler.UserDesiredSize; if (def.Width >= 0) size.Width = def.Width; if (def.Height >= 0) size.Height = def.Height; else size.Height = Math.Min(size.Height, 100); return size; } } protected GridHandler() { Control = new EtoDataGridView { Handler = this, VirtualMode = true, MultiSelect = false, SelectionMode = swf.DataGridViewSelectionMode.FullRowSelect, CellBorderStyle = swf.DataGridViewCellBorderStyle.None, RowHeadersVisible = false, AllowUserToAddRows = false, AllowUserToResizeRows = false, AutoSize = true, AutoSizeColumnsMode = swf.DataGridViewAutoSizeColumnsMode.DisplayedCells, ColumnHeadersHeightSizeMode = swf.DataGridViewColumnHeadersHeightSizeMode.DisableResizing }; Control.CellValueNeeded += (sender, e) => { var item = GetItemAtRow(e.RowIndex); if (Widget.Columns.Count > e.ColumnIndex) { var col = Widget.Columns[e.ColumnIndex].Handler as GridColumnHandler; if (item != null && col != null) e.Value = col.GetCellValue(item); } }; Control.CellValuePushed += (sender, e) => { var item = GetItemAtRow(e.RowIndex); if (Widget.Columns.Count > e.ColumnIndex) { var col = Widget.Columns[e.ColumnIndex].Handler as GridColumnHandler; if (item != null && col != null) col.SetCellValue(item, e.Value); } }; Control.RowPostPaint += HandleRowPostPaint; Control.SelectionChanged += HandleFirstSelection; Control.DataError += HandleDataError; } void HandleDataError(object sender, swf.DataGridViewDataErrorEventArgs e) { // ignore errors to prevent ugly popup when clearing data Debug.WriteLine("Data Error: {0}", e.Exception); } void HandleFirstSelection(object sender, EventArgs e) { // don't select the first row on selection if (Widget.Loaded && isFirstSelection) { Control.ClearSelection(); isFirstSelection = false; } else if (SupressSelectionChanged == 0) Callback.OnSelectionChanged(Widget, EventArgs.Empty); } /// <summary> /// Unlike other controls, DataGridView's background color is implemented /// via the BackgroundColor property, not the BackColor property. /// </summary> public override Color BackgroundColor { get { return Control.BackgroundColor.ToEto(); } set { Control.BackgroundColor = value.ToSD(); } } public override void OnUnLoad(EventArgs e) { base.OnUnLoad(e); LeakHelper.UnhookObject(Control); } bool handledAutoSize; void HandleRowPostPaint(object sender, swf.DataGridViewRowPostPaintEventArgs e) { if (handledAutoSize) return; handledAutoSize = true; int colNum = 0; foreach (var col in Widget.Columns) { var colHandler = col.Handler as GridColumnHandler; if (col.AutoSize) { Control.AutoResizeColumn(colNum, colHandler.Control.InheritedAutoSizeMode); var width = col.Width; colHandler.Control.AutoSizeMode = swf.DataGridViewAutoSizeColumnMode.None; col.Width = width; } colNum++; } } class FormattingArgs : GridCellFormatEventArgs { public swf.DataGridViewCellFormattingEventArgs Args { get; private set; } public FormattingArgs(swf.DataGridViewCellFormattingEventArgs args, GridColumn column, object item, int row) : base(column, item, row) { this.Args = args; } Font font; public override Font Font { get { return font ?? (font = new Font(new FontHandler(Args.CellStyle.Font))); } set { font = value; Args.CellStyle.Font = font.ToSD(); } } public override Color BackgroundColor { get { return Args.CellStyle.BackColor.ToEto(); } set { Args.CellStyle.BackColor = value.ToSD(); } } public override Color ForegroundColor { get { return Args.CellStyle.ForeColor.ToEto(); } set { Args.CellStyle.ForeColor = value.ToSD(); } } } public override void AttachEvent(string id) { switch (id) { case Grid.ColumnHeaderClickEvent: Control.ColumnHeaderMouseClick += (sender, e) => Callback.OnColumnHeaderClick(Widget, new GridColumnEventArgs(Widget.Columns[e.ColumnIndex])); break; case Grid.CellEditingEvent: Control.CellBeginEdit += (sender, e) => { var item = GetItemAtRow(e.RowIndex); var column = Widget.Columns[e.ColumnIndex]; Callback.OnCellEditing(Widget, new GridViewCellEventArgs(column, e.RowIndex, e.ColumnIndex, item)); }; break; case Grid.CellEditedEvent: Control.CellEndEdit += (sender, e) => { var item = GetItemAtRow(e.RowIndex); var column = Widget.Columns[e.ColumnIndex]; Callback.OnCellEdited(Widget, new GridViewCellEventArgs(column, e.RowIndex, e.ColumnIndex, item)); }; break; case Grid.CellClickEvent: Control.CellClick += (sender, e) => { var item = GetItemAtRow(e.RowIndex); var column = Widget.Columns[e.ColumnIndex]; Callback.OnCellClick(Widget, new GridViewCellEventArgs(column, e.RowIndex, e.ColumnIndex, item)); }; break; case Grid.CellDoubleClickEvent: Control.CellDoubleClick += (sender, e) => { if (e.RowIndex > -1) { var item = GetItemAtRow(e.RowIndex); var column = Widget.Columns[e.ColumnIndex]; Callback.OnCellDoubleClick(Widget, new GridViewCellEventArgs(column, e.RowIndex, e.ColumnIndex, item)); } }; break; case Grid.SelectionChangedEvent: // handled automatically break; case Grid.CellFormattingEvent: Control.CellFormatting += (sender, e) => { var column = Widget.Columns[e.ColumnIndex]; var item = GetItemAtRow(e.RowIndex); Callback.OnCellFormatting(Widget, new FormattingArgs(e, column, item, e.RowIndex)); }; break; default: base.AttachEvent(id); break; } } protected override void Initialize() { base.Initialize(); columns = new ColumnCollection { Handler = this }; columns.Register(Widget.Columns); } class ColumnCollection : EnumerableChangedHandler<GridColumn, GridColumnCollection> { public GridHandler<TWidget, TCallback> Handler { get; set; } public override void AddItem(GridColumn item) { var colhandler = (GridColumnHandler)item.Handler; colhandler.Setup(Handler); Handler.Control.Columns.Add(colhandler.Control); if (Handler.clearColumns) { Handler.Control.Columns.RemoveAt(0); Handler.clearColumns = false; } } public override void InsertItem(int index, GridColumn item) { var colhandler = (GridColumnHandler)item.Handler; colhandler.Setup(Handler); Handler.Control.Columns.Insert(index, colhandler.Control); if (Handler.clearColumns && Handler.Control.Columns.Count == 2 && index == 0) { Handler.Control.Columns.RemoveAt(Handler.Control.Columns.Count - 1); Handler.clearColumns = false; } } public override void RemoveItem(int index) { Handler.Control.Columns.RemoveAt(index); } public override void RemoveAllItems() { Handler.Control.Columns.Clear(); } } public bool ShowHeader { get { return Control.ColumnHeadersVisible; } set { Control.ColumnHeadersVisible = value; } } public bool AllowColumnReordering { get { return Control.AllowUserToOrderColumns; } set { Control.AllowUserToOrderColumns = value; } } public bool AllowMultipleSelection { get { return Control.MultiSelect; } set { Control.MultiSelect = value; } } public IEnumerable<int> SelectedRows { get { return Control.SelectedRows.OfType<swf.DataGridViewRow>().Where(r => r.Index >= 0).Select(r => r.Index); } set { SupressSelectionChanged++; UnselectAll(); foreach (var row in value) { SelectRow(row); } SupressSelectionChanged--; if (SupressSelectionChanged == 0) Callback.OnSelectionChanged(Widget, EventArgs.Empty); } } public int RowHeight { get { return Control.RowTemplate.Height; } set { Control.RowTemplate.Height = value; foreach (swf.DataGridViewRow row in Control.Rows) { row.Height = value; } } } public void SelectAll() { Control.SelectAll(); } public void SelectRow(int row) { Control.Rows[row].Selected = true; } public void UnselectRow(int row) { Control.Rows[row].Selected = false; } public void UnselectAll() { Control.ClearSelection(); } public void BeginEdit(int row, int column) { Control.CurrentCell = Control.Rows[row].Cells[column]; Control.BeginEdit(true); } public virtual void Paint(GridColumnHandler column, System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, swf.DataGridViewElementStates cellState, object value, object formattedValue, string errorText, swf.DataGridViewCellStyle cellStyle, swf.DataGridViewAdvancedBorderStyle advancedBorderStyle, ref swf.DataGridViewPaintParts paintParts) { } public virtual int GetRowOffset(GridColumnHandler column, int rowIndex) { return 0; } public virtual bool CellMouseClick(GridColumnHandler column, swf.MouseEventArgs e, int rowIndex) { return false; } static readonly Win32.WM[] intrinsicEvents = { Win32.WM.LBUTTONDOWN, Win32.WM.LBUTTONUP, Win32.WM.LBUTTONDBLCLK, Win32.WM.RBUTTONDOWN, Win32.WM.RBUTTONUP, Win32.WM.RBUTTONDBLCLK }; public override bool ShouldBubbleEvent(swf.Message msg) { return !intrinsicEvents.Contains((Win32.WM)msg.Msg) && base.ShouldBubbleEvent(msg); } public void ScrollToRow(int row) { var displayedCount = Control.DisplayedRowCount(false); var idx = Control.FirstDisplayedScrollingRowIndex; if (row < idx) { Control.FirstDisplayedScrollingRowIndex = row; } else if (row >= idx + displayedCount) { Control.FirstDisplayedScrollingRowIndex = Math.Max(0, row - displayedCount + 1); } } public GridLines GridLines { get { switch (Control.CellBorderStyle) { case System.Windows.Forms.DataGridViewCellBorderStyle.Single: return GridLines.Both; case System.Windows.Forms.DataGridViewCellBorderStyle.SingleHorizontal: return GridLines.Horizontal; case System.Windows.Forms.DataGridViewCellBorderStyle.SingleVertical: return GridLines.Vertical; default: return GridLines.None; } } set { switch (value) { case GridLines.None: Control.CellBorderStyle = swf.DataGridViewCellBorderStyle.None; break; case GridLines.Horizontal: Control.CellBorderStyle = swf.DataGridViewCellBorderStyle.SingleHorizontal; break; case GridLines.Vertical: Control.CellBorderStyle = swf.DataGridViewCellBorderStyle.SingleVertical; break; case GridLines.Both: Control.CellBorderStyle = swf.DataGridViewCellBorderStyle.Single; break; default: throw new NotSupportedException(); } } } } }
// <copyright file="Keys.cs" company="WebDriver Committers"> // Copyright 2007-2011 WebDriver committers // Copyright 2007-2011 Google Inc. // Portions copyright 2007 ThoughtWorks, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace OpenQA.Selenium { /// <summary> /// Representations of pressable keys that are not text keys for sending to the browser. /// </summary> public static class Keys { /// <summary> /// Represents the NUL keystroke. /// </summary> public static readonly string Null = Convert.ToString(Convert.ToChar(0xE000, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Cancel keystroke. /// </summary> public static readonly string Cancel = Convert.ToString(Convert.ToChar(0xE001, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Help keystroke. /// </summary> public static readonly string Help = Convert.ToString(Convert.ToChar(0xE002, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Backspace key. /// </summary> public static readonly string Backspace = Convert.ToString(Convert.ToChar(0xE003, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Tab key. /// </summary> public static readonly string Tab = Convert.ToString(Convert.ToChar(0xE004, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Clear keystroke. /// </summary> public static readonly string Clear = Convert.ToString(Convert.ToChar(0xE005, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Return key. /// </summary> public static readonly string Return = Convert.ToString(Convert.ToChar(0xE006, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Enter key. /// </summary> public static readonly string Enter = Convert.ToString(Convert.ToChar(0xE007, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Shift key. /// </summary> public static readonly string Shift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Shift key. /// </summary> public static readonly string LeftShift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias /// <summary> /// Represents the Control key. /// </summary> public static readonly string Control = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Control key. /// </summary> public static readonly string LeftControl = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias /// <summary> /// Represents the Alt key. /// </summary> public static readonly string Alt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Alt key. /// </summary> public static readonly string LeftAlt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias /// <summary> /// Represents the Pause key. /// </summary> public static readonly string Pause = Convert.ToString(Convert.ToChar(0xE00B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Escape key. /// </summary> public static readonly string Escape = Convert.ToString(Convert.ToChar(0xE00C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Spacebar key. /// </summary> public static readonly string Space = Convert.ToString(Convert.ToChar(0xE00D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Page Up key. /// </summary> public static readonly string PageUp = Convert.ToString(Convert.ToChar(0xE00E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Page Down key. /// </summary> public static readonly string PageDown = Convert.ToString(Convert.ToChar(0xE00F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the End key. /// </summary> public static readonly string End = Convert.ToString(Convert.ToChar(0xE010, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Home key. /// </summary> public static readonly string Home = Convert.ToString(Convert.ToChar(0xE011, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the left arrow key. /// </summary> public static readonly string Left = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the left arrow key. /// </summary> public static readonly string ArrowLeft = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias /// <summary> /// Represents the up arrow key. /// </summary> public static readonly string Up = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the up arrow key. /// </summary> public static readonly string ArrowUp = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias /// <summary> /// Represents the right arrow key. /// </summary> public static readonly string Right = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the right arrow key. /// </summary> public static readonly string ArrowRight = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias /// <summary> /// Represents the Left arrow key. /// </summary> public static readonly string Down = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Left arrow key. /// </summary> public static readonly string ArrowDown = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias /// <summary> /// Represents the Insert key. /// </summary> public static readonly string Insert = Convert.ToString(Convert.ToChar(0xE016, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the Delete key. /// </summary> public static readonly string Delete = Convert.ToString(Convert.ToChar(0xE017, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the semi-colon key. /// </summary> public static readonly string Semicolon = Convert.ToString(Convert.ToChar(0xE018, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the equal sign key. /// </summary> public static readonly string Equal = Convert.ToString(Convert.ToChar(0xE019, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // Number pad keys /// <summary> /// Represents the number pad 0 key. /// </summary> public static readonly string NumberPad0 = Convert.ToString(Convert.ToChar(0xE01A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 1 key. /// </summary> public static readonly string NumberPad1 = Convert.ToString(Convert.ToChar(0xE01B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 2 key. /// </summary> public static readonly string NumberPad2 = Convert.ToString(Convert.ToChar(0xE01C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 3 key. /// </summary> public static readonly string NumberPad3 = Convert.ToString(Convert.ToChar(0xE01D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 4 key. /// </summary> public static readonly string NumberPad4 = Convert.ToString(Convert.ToChar(0xE01E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 5 key. /// </summary> public static readonly string NumberPad5 = Convert.ToString(Convert.ToChar(0xE01F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 6 key. /// </summary> public static readonly string NumberPad6 = Convert.ToString(Convert.ToChar(0xE020, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 7 key. /// </summary> public static readonly string NumberPad7 = Convert.ToString(Convert.ToChar(0xE021, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 8 key. /// </summary> public static readonly string NumberPad8 = Convert.ToString(Convert.ToChar(0xE022, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad 9 key. /// </summary> public static readonly string NumberPad9 = Convert.ToString(Convert.ToChar(0xE023, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad multiplication key. /// </summary> public static readonly string Multiply = Convert.ToString(Convert.ToChar(0xE024, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad addition key. /// </summary> public static readonly string Add = Convert.ToString(Convert.ToChar(0xE025, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad thousands separator key. /// </summary> public static readonly string Separator = Convert.ToString(Convert.ToChar(0xE026, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad subtraction key. /// </summary> public static readonly string Subtract = Convert.ToString(Convert.ToChar(0xE027, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad decimal separator key. /// </summary> public static readonly string Decimal = Convert.ToString(Convert.ToChar(0xE028, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the number pad division key. /// </summary> public static readonly string Divide = Convert.ToString(Convert.ToChar(0xE029, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // Function keys /// <summary> /// Represents the function key F1. /// </summary> public static readonly string F1 = Convert.ToString(Convert.ToChar(0xE031, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F2. /// </summary> public static readonly string F2 = Convert.ToString(Convert.ToChar(0xE032, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F3. /// </summary> public static readonly string F3 = Convert.ToString(Convert.ToChar(0xE033, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F4. /// </summary> public static readonly string F4 = Convert.ToString(Convert.ToChar(0xE034, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F5. /// </summary> public static readonly string F5 = Convert.ToString(Convert.ToChar(0xE035, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F6. /// </summary> public static readonly string F6 = Convert.ToString(Convert.ToChar(0xE036, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F7. /// </summary> public static readonly string F7 = Convert.ToString(Convert.ToChar(0xE037, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F8. /// </summary> public static readonly string F8 = Convert.ToString(Convert.ToChar(0xE038, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F9. /// </summary> public static readonly string F9 = Convert.ToString(Convert.ToChar(0xE039, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F10. /// </summary> public static readonly string F10 = Convert.ToString(Convert.ToChar(0xE03A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F12. /// </summary> public static readonly string F11 = Convert.ToString(Convert.ToChar(0xE03B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key F12. /// </summary> public static readonly string F12 = Convert.ToString(Convert.ToChar(0xE03C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key META. /// </summary> public static readonly string Meta = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); /// <summary> /// Represents the function key COMMAND. /// </summary> public static readonly string Command = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Type handler for empty or unsupported types. /// </summary> internal sealed class NullTypeInfo : TraceLoggingTypeInfo { public NullTypeInfo() : base(typeof(EmptyStruct)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddGroup(name); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { return; } public override object GetData(object value) { return null; } } /// <summary> /// Type handler for simple scalar types. /// </summary> sealed class ScalarTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; private ScalarTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value); } public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(Boolean), Statics.Format8, TraceLoggingDataType.Boolean8); } public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(Byte), Statics.Format8, TraceLoggingDataType.UInt8); } public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(SByte), Statics.Format8, TraceLoggingDataType.Int8); } public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(Char), Statics.Format16, TraceLoggingDataType.Char16); } public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(Int16), Statics.Format16, TraceLoggingDataType.Int16); } public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(UInt16), Statics.Format16, TraceLoggingDataType.UInt16); } public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(Int32), Statics.Format32, TraceLoggingDataType.Int32); } public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(UInt32), Statics.Format32, TraceLoggingDataType.UInt32); } public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(Int64), Statics.Format64, TraceLoggingDataType.Int64); } public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(UInt64), Statics.Format64, TraceLoggingDataType.UInt64); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); } public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(Single), Statics.Format32, TraceLoggingDataType.Float); } public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(Double), Statics.Format64, TraceLoggingDataType.Double); } public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); } } /// <summary> /// Type handler for arrays of scalars /// </summary> internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; int elementSize; private ScalarArrayTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat, int elementSize) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; this.elementSize = elementSize; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddArray(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddArray(value, elementSize); } public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(Boolean[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(Boolean)); } public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(Byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(Byte)); } public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(SByte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(SByte)); } public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(Char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(Char)); } public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(Int16[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(Int16)); } public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(UInt16[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(UInt16)); } public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(Int32[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(Int32)); } public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(UInt32[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(UInt32)); } public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(Int64[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(Int64)); } public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(UInt64[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(UInt64)); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(Single[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(Single)); } public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(Double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(Double)); } public static unsafe TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } } /// <summary> /// TraceLogging: Type handler for String. /// </summary> internal sealed class StringTypeInfo : TraceLoggingTypeInfo { public StringTypeInfo() : base(typeof(string)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddNullTerminatedString(name, Statics.MakeDataType(TraceLoggingDataType.Utf16String, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddNullTerminatedString((string)value.ReferenceValue); } public override object GetData(object value) { if(value == null) { return ""; } return value; } } /// <summary> /// TraceLogging: Type handler for DateTime. /// </summary> internal sealed class DateTimeTypeInfo : TraceLoggingTypeInfo { public DateTimeTypeInfo() : base(typeof(DateTime)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { DateTime dateTime = value.ScalarValue.AsDateTime; const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (dateTime.Ticks > UTCMinTicks) dateTimeTicks = dateTime.ToFileTimeUtc(); collector.AddScalar(dateTimeTicks); } } /// <summary> /// TraceLogging: Type handler for DateTimeOffset. /// </summary> internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo { public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); group.AddScalar("Offset", TraceLoggingDataType.Int64); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var dateTimeOffset = value.ScalarValue.AsDateTimeOffset; var ticks = dateTimeOffset.Ticks; collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000); collector.AddScalar(dateTimeOffset.Offset.Ticks); } } /// <summary> /// TraceLogging: Type handler for TimeSpan. /// </summary> internal sealed class TimeSpanTypeInfo : TraceLoggingTypeInfo { public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Int64, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value.ScalarValue.AsTimeSpan.Ticks); } } /// <summary> /// TraceLogging: Type handler for Decimal. (Note: not full-fidelity, exposed as Double.) /// </summary> internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo { public DecimalTypeInfo() : base(typeof(Decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar((double)value.ScalarValue.AsDecimal); } } /// <summary> /// TraceLogging: Type handler for Nullable. /// </summary> internal sealed class NullableTypeInfo : TraceLoggingTypeInfo { private readonly TraceLoggingTypeInfo valueInfo; private readonly Func<PropertyValue, PropertyValue> hasValueGetter; private readonly Func<PropertyValue, PropertyValue> valueGetter; public NullableTypeInfo(Type type, List<Type> recursionCheck) : base(type) { var typeArgs = type.GenericTypeArguments; Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue")); this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("HasValue", TraceLoggingDataType.Boolean8); this.valueInfo.WriteMetadata(group, "Value", format); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var hasValue = hasValueGetter(value); collector.AddScalar(hasValue); var val = hasValue.ScalarValue.AsBoolean ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType)); this.valueInfo.WriteData(collector, val); } } }
#region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // // 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.Reflection; using System.Collections.Generic; using System.Linq; using FluentMigrator.Exceptions; using FluentMigrator.Infrastructure; using FluentMigrator.Runner; using FluentMigrator.Runner.Exceptions; using FluentMigrator.Runner.Infrastructure; using FluentMigrator.Runner.Initialization; using FluentMigrator.Tests.Integration.Migrations; using FluentMigrator.Tests.Unit.TaggingTestFakes; using Microsoft.Extensions.DependencyInjection; using Moq; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit { [TestFixture] public class DefaultMigrationInformationLoaderTests { [Test] public void CanFindMigrationsInAssembly() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass1") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); var migrationList = loader.LoadMigrations(); var count = migrationList.Count; count.ShouldBeGreaterThan(0); } [Test] public void CanFindMigrationsInNamespace() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass1") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); var migrationList = loader.LoadMigrations(); migrationList.Select(x => x.Value.Migration.GetType()).ShouldNotContain(typeof(VersionedMigration)); migrationList.Count().ShouldBeGreaterThan(0); } [Test] public void DefaultBehaviorIsToNotLoadNestedNamespaces() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass1") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); Assert.IsInstanceOf<DefaultMigrationInformationLoader>(loader); var defaultLoader = (DefaultMigrationInformationLoader)loader; defaultLoader.LoadNestedNamespaces.ShouldBe(false); } [Test] public void FindsMigrationsInNestedNamespaceWhenLoadNestedNamespacesEnabled() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations.Nested", true) .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); List<Type> expected = new List<Type> { typeof(Integration.Migrations.Nested.NotGrouped), typeof(Integration.Migrations.Nested.Group1.FromGroup1), typeof(Integration.Migrations.Nested.Group1.AnotherFromGroup1), typeof(Integration.Migrations.Nested.Group2.FromGroup2), }; var migrationList = loader.LoadMigrations(); List<Type> actual = migrationList.Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] public void DoesNotFindsMigrationsInNestedNamespaceWhenLoadNestedNamespacesDisabled() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations.Nested") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); List<Type> expected = new List<Type> { typeof(Integration.Migrations.Nested.NotGrouped), }; var migrationList = loader.LoadMigrations(); List<Type> actual = migrationList.Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] public void DoesFindMigrationsThatHaveMatchingTags() { var migrationType = typeof(TaggedMigration); var tagsToMatch = new[] { "UK", "Production" }; var conventionsMock = new Mock<IMigrationRunnerConventions>(); conventionsMock.SetupGet(m => m.GetMigrationInfoForMigration).Returns(DefaultMigrationRunnerConventions.Instance.GetMigrationInfoForMigration); conventionsMock.SetupGet(m => m.TypeIsMigration).Returns(t => true); conventionsMock.SetupGet(m => m.TypeHasTags).Returns(t => migrationType == t); conventionsMock.SetupGet(m => m.TypeHasMatchingTags).Returns((type, tags) => (migrationType == type && tagsToMatch == tags)); var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn(migrationType.Namespace) .Configure<RunnerOptions>(opt => opt.Tags = tagsToMatch) .ConfigureRunner(builder => builder.WithRunnerConventions(conventionsMock.Object)) .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); var expected = new List<Type> { typeof(UntaggedMigration), migrationType }; var actual = loader.LoadMigrations().Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] public void DoesNotFindMigrationsThatDoNotHaveMatchingTags() { var migrationType = typeof(TaggedMigration); var tagsToMatch = new[] { "UK", "Production" }; var conventionsMock = new Mock<IMigrationRunnerConventions>(); conventionsMock.SetupGet(m => m.GetMigrationInfoForMigration).Returns(DefaultMigrationRunnerConventions.Instance.GetMigrationInfoForMigration); conventionsMock.SetupGet(m => m.TypeIsMigration).Returns(t => true); conventionsMock.SetupGet(m => m.TypeHasTags).Returns(t => migrationType == t); conventionsMock.SetupGet(m => m.TypeHasMatchingTags).Returns((type, tags) => false); var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn(migrationType.Namespace) .Configure<RunnerOptions>(opt => opt.Tags = tagsToMatch) .ConfigureRunner(builder => builder.WithRunnerConventions(conventionsMock.Object)) .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); var expected = new List<Type> { typeof(UntaggedMigration) }; var actual = loader.LoadMigrations().Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] public void HandlesNotFindingMigrations() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Unit.EmptyNamespace") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); Assert.Throws<MissingMigrationsException>(() => loader.LoadMigrations()); } [Test] public void ShouldThrowExceptionIfDuplicateVersionNumbersAreLoaded() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Unit.DuplicateVersionNumbers") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); Assert.Throws<DuplicateMigrationException>(() => loader.LoadMigrations()); } [Test] public void HandlesMigrationThatDoesNotInheritFromMigrationBaseClass() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Unit.DoesNotInheritFromBaseClass") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); Assert.That(loader.LoadMigrations().Count(), Is.EqualTo(1)); } [Test] public void ShouldHandleTransactionlessMigrations() { var loader = ServiceCollectionExtensions.CreateServices() .WithMigrationsIn("FluentMigrator.Tests.Unit.DoesHandleTransactionLessMigrations") .BuildServiceProvider() .GetRequiredService<IMigrationInformationLoader>(); var list = loader.LoadMigrations().ToList(); list.Count().ShouldBe(2); list[0].Value.Migration.GetType().ShouldBe(typeof(DoesHandleTransactionLessMigrations.MigrationThatIsTransactionLess)); list[0].Value.TransactionBehavior.ShouldBe(TransactionBehavior.None); list[0].Value.Version.ShouldBe(1); list[1].Value.Migration.GetType().ShouldBe(typeof(DoesHandleTransactionLessMigrations.MigrationThatIsNotTransactionLess)); list[1].Value.TransactionBehavior.ShouldBe(TransactionBehavior.Default); list[1].Value.Version.ShouldBe(2); } [Test] [Obsolete] public void ObsoleteCanFindMigrationsInAssembly() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass1", null); SortedList<long, IMigrationInfo> migrationList = loader.LoadMigrations(); //if this works, there will be at least one migration class because i've included on in this code file int count = migrationList.Count(); count.ShouldBeGreaterThan(0); } [Test] [Obsolete] public void ObsoleteCanFindMigrationsInNamespace() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass1", null); var migrationList = loader.LoadMigrations(); migrationList.Select(x => x.Value.Migration.GetType()).ShouldNotContain(typeof(VersionedMigration)); migrationList.Count().ShouldBeGreaterThan(0); } [Test] [Obsolete] public void ObsoleteDefaultBehaviorIsToNotLoadNestedNamespaces() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Nested", null); loader.LoadNestedNamespaces.ShouldBe(false); } [Test] [Obsolete] public void ObsoleteFindsMigrationsInNestedNamespaceWhenLoadNestedNamespacesEnabled() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Nested", true, null); List<Type> expected = new List<Type> { typeof(Integration.Migrations.Nested.NotGrouped), typeof(Integration.Migrations.Nested.Group1.FromGroup1), typeof(Integration.Migrations.Nested.Group1.AnotherFromGroup1), typeof(Integration.Migrations.Nested.Group2.FromGroup2), }; var migrationList = loader.LoadMigrations(); List<Type> actual = migrationList.Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] [Obsolete] public void ObsoleteDoesNotFindsMigrationsInNestedNamespaceWhenLoadNestedNamespacesDisabled() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Nested", false, null); List<Type> expected = new List<Type> { typeof(Integration.Migrations.Nested.NotGrouped), }; var migrationList = loader.LoadMigrations(); List<Type> actual = migrationList.Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] [Obsolete] public void ObsoleteDoesFindMigrationsThatHaveMatchingTags() { var asm = Assembly.GetExecutingAssembly(); var migrationType = typeof(TaggedMigration); var tagsToMatch = new[] { "UK", "Production" }; var conventionsMock = new Mock<IMigrationRunnerConventions>(); conventionsMock.SetupGet(m => m.GetMigrationInfoForMigration).Returns(DefaultMigrationRunnerConventions.Instance.GetMigrationInfoForMigration); conventionsMock.SetupGet(m => m.TypeIsMigration).Returns(t => true); conventionsMock.SetupGet(m => m.TypeHasTags).Returns(t => migrationType == t); conventionsMock.SetupGet(m => m.TypeHasMatchingTags).Returns((type, tags) => (migrationType == type && tagsToMatch == tags)); var loader = new DefaultMigrationInformationLoader(conventionsMock.Object, asm, migrationType.Namespace, tagsToMatch); var expected = new List<Type> { typeof(UntaggedMigration), migrationType }; var actual = loader.LoadMigrations().Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] [Obsolete] public void ObsoleteDoesNotFindMigrationsThatDoNotHaveMatchingTags() { var asm = Assembly.GetExecutingAssembly(); var migrationType = typeof(TaggedMigration); var tagsToMatch = new[] { "UK", "Production" }; var conventionsMock = new Mock<IMigrationRunnerConventions>(); conventionsMock.SetupGet(m => m.GetMigrationInfoForMigration).Returns(DefaultMigrationRunnerConventions.Instance.GetMigrationInfoForMigration); conventionsMock.SetupGet(m => m.TypeIsMigration).Returns(t => true); conventionsMock.SetupGet(m => m.TypeHasTags).Returns(t => migrationType == t); conventionsMock.SetupGet(m => m.TypeHasMatchingTags).Returns((type, tags) => false); var loader = new DefaultMigrationInformationLoader(conventionsMock.Object, asm, migrationType.Namespace, tagsToMatch); var expected = new List<Type> { typeof(UntaggedMigration) }; var actual = loader.LoadMigrations().Select(m => m.Value.Migration.GetType()).ToList(); CollectionAssert.AreEquivalent(expected, actual); } [Test] [Obsolete] public void ObsoleteHandlesNotFindingMigrations() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.EmptyNamespace", null); Assert.Throws<MissingMigrationsException>(() => loader.LoadMigrations()); } [Test] [Obsolete] public void ObsoleteShouldThrowExceptionIfDuplicateVersionNumbersAreLoaded() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var migrationLoader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.DuplicateVersionNumbers", null); Assert.Throws<DuplicateMigrationException>(() => migrationLoader.LoadMigrations()); } [Test] [Obsolete] public void ObsoleteHandlesMigrationThatDoesNotInheritFromMigrationBaseClass() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.DoesNotInheritFromBaseClass", null); Assert.That(loader.LoadMigrations().Count(), Is.EqualTo(1)); } [Test] [Obsolete] public void ObsoleteShouldHandleTransactionlessMigrations() { var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.DoesHandleTransactionLessMigrations", null); var list = loader.LoadMigrations().ToList(); list.Count().ShouldBe(2); list[0].Value.Migration.GetType().ShouldBe(typeof(DoesHandleTransactionLessMigrations.MigrationThatIsTransactionLess)); list[0].Value.TransactionBehavior.ShouldBe(TransactionBehavior.None); list[0].Value.Version.ShouldBe(1); list[1].Value.Migration.GetType().ShouldBe(typeof(DoesHandleTransactionLessMigrations.MigrationThatIsNotTransactionLess)); list[1].Value.TransactionBehavior.ShouldBe(TransactionBehavior.Default); list[1].Value.Version.ShouldBe(2); } } // ReSharper disable once EmptyNamespace namespace EmptyNamespace { } namespace DoesHandleTransactionLessMigrations { [Migration(1, TransactionBehavior.None)] public class MigrationThatIsTransactionLess : Migration { public override void Up() { throw new NotImplementedException(); } public override void Down() { throw new NotImplementedException(); } } [Migration(2)] public class MigrationThatIsNotTransactionLess : Migration { public override void Up() { throw new NotImplementedException(); } public override void Down() { throw new NotImplementedException(); } } } namespace DoesNotInheritFromBaseClass { [Migration(1)] public class MigrationThatDoesNotInheritFromMigrationBaseClass : IMigration { /// <summary>The arbitrary application context passed to the task runner.</summary> public object ApplicationContext { get { throw new NotImplementedException(); } } public string ConnectionString { get; } = null; public void GetUpExpressions(IMigrationContext context) { throw new NotImplementedException(); } public void GetDownExpressions(IMigrationContext context) { throw new NotImplementedException(); } } } namespace DuplicateVersionNumbers { [Migration(1)] public class Duplicate1 : Migration { public override void Up() { } public override void Down() { } } [Migration(1)] public class Duplicate2 : Migration { public override void Up() { } public override void Down() { } } } namespace TaggingTestFakes { [Tags("UK", "IE", "QA", "Production")] [Migration(123)] public class TaggedMigration : Migration { public override void Up() { } public override void Down() { } } [Migration(567)] public class UntaggedMigration : Migration { public override void Up() { } public override void Down() { } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// DF Transfer /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class DF_TFR : EduHubEntity { #region Navigation Property Cache private SKGS Cache_ORIG_SCHOOL_SKGS; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Transaction ID /// </summary> public int TID { get; internal set; } /// <summary> /// Orignating School /// [Uppercase Alphanumeric (8)] /// </summary> public string ORIG_SCHOOL { get; internal set; } /// <summary> /// Unique DF Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string DF_TRANS_ID { get; internal set; } /// <summary> /// Family ID /// [Uppercase Alphanumeric (10)] /// </summary> public string DFKEY { get; internal set; } /// <summary> /// New Family Key /// [Uppercase Alphanumeric (10)] /// </summary> public string DFKEY_NEW { get; internal set; } /// <summary> /// (Was MNAME) Parent/guardian A first given name /// [Alphanumeric (30)] /// </summary> public string NAME_A { get; internal set; } /// <summary> /// (Was MSURNAME) Parent/guardian A surname (default SURNAME) /// [Uppercase Alphanumeric (30)] /// </summary> public string SURNAME_A { get; internal set; } /// <summary> /// (Was MTITLE) Parent/guardian A title /// [Titlecase (4)] /// </summary> public string TITLE_A { get; internal set; } /// <summary> /// (Was MWORK_CONT) Can parent/guardian A be contacted at work? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string WORK_CONT_A { get; internal set; } /// <summary> /// (Was MOCCUPATION) Parent/guardian A occupation /// [Alphanumeric (35)] /// </summary> public string OCCUPATION_A { get; internal set; } /// <summary> /// (Was MEMPLOYER) Parent/guardian A employer /// [Alphanumeric (30)] /// </summary> public string EMPLOYER_A { get; internal set; } /// <summary> /// (Was MNATIVE_LANG) Parent/guardian A native language /// [Uppercase Alphanumeric (7)] /// </summary> public string NATIVE_LANG_A { get; internal set; } /// <summary> /// (Was M_OTHER_LANG) Parent/guardian A other language /// [Uppercase Alphanumeric (7)] /// </summary> public string OTHER_LANG_A { get; internal set; } /// <summary> /// (Was M_INTERPRETER) Parent/guardian A requires interpreter? Y=Yes, N=No, S=Sometimes /// [Uppercase Alphanumeric (1)] /// </summary> public string INTERPRETER_A { get; internal set; } /// <summary> /// (Was MBIRTH_COUNTRY) Parent/guardian A country of birth /// [Uppercase Alphanumeric (6)] /// </summary> public string BIRTH_COUNTRY_A { get; internal set; } /// <summary> /// Parent/guardian A at home during business hours? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string BH_AT_HOME_A { get; internal set; } /// <summary> /// Parent/guardian A telephone contact if not at home during business hours /// [Alphanumeric (20)] /// </summary> public string BH_CONTACT_A { get; internal set; } /// <summary> /// Parent/guardian A telephone contact if not at home during business hours /// [Memo] /// </summary> public string BH_CONTACT_A_MEMO { get; internal set; } /// <summary> /// Parent/guardian A at home after hours? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string AH_AT_HOME_A { get; internal set; } /// <summary> /// Parent/guardian A telephone contact if not at home after hours /// [Alphanumeric (20)] /// </summary> public string AH_CONTACT_A { get; internal set; } /// <summary> /// Parent/guardian A telephone contact if not at home after hours /// [Memo] /// </summary> public string AH_CONTACT_A_MEMO { get; internal set; } /// <summary> /// (Was M_E_MAIL) Parent/guardian A e-mail address /// [Alphanumeric (60)] /// </summary> public string E_MAIL_A { get; internal set; } /// <summary> /// (Was PREF_COM_A) Parent/guardian A preferred mail mechanism: M=Mail, E=E-mail, F=Fax, P=Phone /// [Uppercase Alphanumeric (1)] /// </summary> public string PREF_MAIL_MECH_A { get; internal set; } /// <summary> /// Parent/guardian A fax number /// [Uppercase Alphanumeric (20)] /// </summary> public string FAX_A { get; internal set; } /// <summary> /// Parent/guardian A gender: M=Male, F=Female /// [Uppercase Alphanumeric (1)] /// </summary> public string GENDER_A { get; internal set; } /// <summary> /// Parent/guardian A School Education /// [Uppercase Alphanumeric (1)] /// </summary> public string SCH_ED_A { get; internal set; } /// <summary> /// Parent/guardian A Non School Education (0,5-8) /// [Uppercase Alphanumeric (1)] /// </summary> public string NON_SCH_ED_A { get; internal set; } /// <summary> /// Parent/guardian A Occupation Status (A,B,C,D,N,U) /// [Uppercase Alphanumeric (1)] /// </summary> public string OCCUP_STATUS_A { get; internal set; } /// <summary> /// The Language other than English spoken at home by parent/guardian A /// [Uppercase Alphanumeric (7)] /// </summary> public string LOTE_HOME_CODE_A { get; internal set; } /// <summary> /// Parent/guardian A mobile number /// [Uppercase Alphanumeric (20)] /// </summary> public string MOBILE_A { get; internal set; } /// <summary> /// SMS can be used to notify this parent /// [Uppercase Alphanumeric (1)] /// </summary> public string SMS_NOTIFY_A { get; internal set; } /// <summary> /// Email can be used to notify this parent /// [Uppercase Alphanumeric (1)] /// </summary> public string E_MAIL_NOTIFY_A { get; internal set; } /// <summary> /// (Was FNAME) Parent/guardian B first given name /// [Alphanumeric (30)] /// </summary> public string NAME_B { get; internal set; } /// <summary> /// (Was FSURNAME) Parent/guardian B surname (default SURNAME) /// [Uppercase Alphanumeric (30)] /// </summary> public string SURNAME_B { get; internal set; } /// <summary> /// (Was FTITLE) Parent/guardian B title /// [Titlecase (4)] /// </summary> public string TITLE_B { get; internal set; } /// <summary> /// (Was FWORK_CONT) Can parent/guardian B be contacted at work? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string WORK_CONT_B { get; internal set; } /// <summary> /// (Was FOCCUPATION) Parent/guardian B occupation /// [Alphanumeric (35)] /// </summary> public string OCCUPATION_B { get; internal set; } /// <summary> /// (Was FEMPLOYER) Parent/guardian B employer /// [Alphanumeric (30)] /// </summary> public string EMPLOYER_B { get; internal set; } /// <summary> /// (Was FNATIVE_LANG) Parent/guardian B native language /// [Uppercase Alphanumeric (7)] /// </summary> public string NATIVE_LANG_B { get; internal set; } /// <summary> /// (Was F_OTHER_LANG) Parent/guardian B other language /// [Uppercase Alphanumeric (7)] /// </summary> public string OTHER_LANG_B { get; internal set; } /// <summary> /// (Was F_INTERPRETER) Parent/guardian B requires interpreter? Y=Yes, N=No, S=Sometimes /// [Uppercase Alphanumeric (1)] /// </summary> public string INTERPRETER_B { get; internal set; } /// <summary> /// (Was FBIRTH_COUNTRY) Parent/guardian B country of birth /// [Uppercase Alphanumeric (6)] /// </summary> public string BIRTH_COUNTRY_B { get; internal set; } /// <summary> /// Parent/guardian B at home during business hours? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string BH_AT_HOME_B { get; internal set; } /// <summary> /// Parent/guardian B telephone contact if not at home during business hours /// [Alphanumeric (20)] /// </summary> public string BH_CONTACT_B { get; internal set; } /// <summary> /// Parent/guardian B telephone contact if not at home during business hours /// [Memo] /// </summary> public string BH_CONTACT_B_MEMO { get; internal set; } /// <summary> /// Parent/guardian B at home after hours? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string AH_AT_HOME_B { get; internal set; } /// <summary> /// Parent/guardian B telephone contact if not at home after hours /// [Alphanumeric (20)] /// </summary> public string AH_CONTACT_B { get; internal set; } /// <summary> /// Parent/guardian B telephone contact if not at home after hours /// [Memo] /// </summary> public string AH_CONTACT_B_MEMO { get; internal set; } /// <summary> /// (Was F_E_MAIL) Parent/guardian B e-mail address /// [Alphanumeric (60)] /// </summary> public string E_MAIL_B { get; internal set; } /// <summary> /// (Was PREF_COM_B) Parent/guardian B preferred mail mechanism: M=Mail, E=E-mail, F=Fax, P=Phone /// [Uppercase Alphanumeric (1)] /// </summary> public string PREF_MAIL_MECH_B { get; internal set; } /// <summary> /// Parent/guardian B fax number /// [Uppercase Alphanumeric (20)] /// </summary> public string FAX_B { get; internal set; } /// <summary> /// Parent/guardian B gender: M=Male, F=Female /// [Uppercase Alphanumeric (1)] /// </summary> public string GENDER_B { get; internal set; } /// <summary> /// Parent/guardian B School Education (0-4) /// [Uppercase Alphanumeric (1)] /// </summary> public string SCH_ED_B { get; internal set; } /// <summary> /// Parent/guardian B Non School Education (0,5-8) /// [Uppercase Alphanumeric (1)] /// </summary> public string NON_SCH_ED_B { get; internal set; } /// <summary> /// Parent/guardian B Occupation Status (A,B,C,D,N,U) /// [Uppercase Alphanumeric (1)] /// </summary> public string OCCUP_STATUS_B { get; internal set; } /// <summary> /// The Language other than English spoken at home by parent/guardian B /// [Uppercase Alphanumeric (7)] /// </summary> public string LOTE_HOME_CODE_B { get; internal set; } /// <summary> /// Parent/guardian B mobile number /// [Uppercase Alphanumeric (20)] /// </summary> public string MOBILE_B { get; internal set; } /// <summary> /// SMS can be used to notify this parent /// [Uppercase Alphanumeric (1)] /// </summary> public string SMS_NOTIFY_B { get; internal set; } /// <summary> /// Email can be used to notify this parent /// [Uppercase Alphanumeric (1)] /// </summary> public string E_MAIL_NOTIFY_B { get; internal set; } /// <summary> /// Preferred language for notices /// [Uppercase Alphanumeric (7)] /// </summary> public string PREF_NOTICE_LANG { get; internal set; } /// <summary> /// (Was SG_PARTICIPATION) Special group participation: 1=Adult A, 2=Adult B, B=Both /// [Uppercase Alphanumeric (1)] /// </summary> public string GROUP_AVAILABILITY { get; internal set; } /// <summary> /// (Was FAM_OCCUP) Family occupation status group (1-5) /// [Uppercase Alphanumeric (1)] /// </summary> public string OCCUP_STATUS_GRP { get; internal set; } /// <summary> /// Home addressee /// [Titlecase (30)] /// </summary> public string HOMETITLE { get; internal set; } /// <summary> /// Home address ID /// </summary> public int? HOMEKEY { get; internal set; } /// <summary> /// New Home address ID /// </summary> public int? HOMEKEY_NEW { get; internal set; } /// <summary> /// Mail addressee /// [Titlecase (30)] /// </summary> public string MAILTITLE { get; internal set; } /// <summary> /// Mail address ID /// </summary> public int? MAILKEY { get; internal set; } /// <summary> /// New Home address ID /// </summary> public int? MAILKEY_NEW { get; internal set; } /// <summary> /// Billing name /// [Titlecase (40)] /// </summary> public string BILLINGTITLE { get; internal set; } /// <summary> /// Billing address ID /// </summary> public int? BILLINGKEY { get; internal set; } /// <summary> /// New Home address ID /// </summary> public int? BILLINGKEY_NEW { get; internal set; } /// <summary> /// Billing memo /// [Memo] /// </summary> public string BILLING_MEMO { get; internal set; } /// <summary> /// Account type: 0=Brought forward, 1=Open item /// </summary> public short? ACCTYPE { get; internal set; } /// <summary> /// Auto access inventory price level: related to sale of stock items to families: to be retained at present /// </summary> public short? PRICELEVEL { get; internal set; } /// <summary> /// Seed number for BPAY reference /// </summary> public int? BPAY_SEQUENCE { get; internal set; } /// <summary> /// Reference number with check digit /// </summary> public int? BPAY_REFERENCE { get; internal set; } /// <summary> /// Reference to local doctor (default for each student) /// [Uppercase Alphanumeric (10)] /// </summary> public string DOCTOR { get; internal set; } /// <summary> /// Name(s) of person(s) to contact in an emergency /// [Titlecase (30)] /// </summary> public string EMERG_NAME01 { get; internal set; } /// <summary> /// Name(s) of person(s) to contact in an emergency /// [Titlecase (30)] /// </summary> public string EMERG_NAME02 { get; internal set; } /// <summary> /// Name(s) of person(s) to contact in an emergency /// [Titlecase (30)] /// </summary> public string EMERG_NAME03 { get; internal set; } /// <summary> /// Name(s) of person(s) to contact in an emergency /// [Titlecase (30)] /// </summary> public string EMERG_NAME04 { get; internal set; } /// <summary> /// Relationship to a student in this family of each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_RELATION01 { get; internal set; } /// <summary> /// Relationship to a student in this family of each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_RELATION02 { get; internal set; } /// <summary> /// Relationship to a student in this family of each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_RELATION03 { get; internal set; } /// <summary> /// Relationship to a student in this family of each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_RELATION04 { get; internal set; } /// <summary> /// Language spoken by person(s) to contact in an emergency /// [Uppercase Alphanumeric (7)] /// </summary> public string EMERG_LANG01 { get; internal set; } /// <summary> /// Language spoken by person(s) to contact in an emergency /// [Uppercase Alphanumeric (7)] /// </summary> public string EMERG_LANG02 { get; internal set; } /// <summary> /// Language spoken by person(s) to contact in an emergency /// [Uppercase Alphanumeric (7)] /// </summary> public string EMERG_LANG03 { get; internal set; } /// <summary> /// Language spoken by person(s) to contact in an emergency /// [Uppercase Alphanumeric (7)] /// </summary> public string EMERG_LANG04 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_CONTACT01 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_CONTACT02 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_CONTACT03 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Alphanumeric (20)] /// </summary> public string EMERG_CONTACT04 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Memo] /// </summary> public string EMERG_CONTACT_MEMO01 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Memo] /// </summary> public string EMERG_CONTACT_MEMO02 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Memo] /// </summary> public string EMERG_CONTACT_MEMO03 { get; internal set; } /// <summary> /// Contact details for each person to contact in an emergency /// [Memo] /// </summary> public string EMERG_CONTACT_MEMO04 { get; internal set; } /// <summary> /// School has received authority to react to accident? (Y/N) (default for each student) /// [Uppercase Alphanumeric (1)] /// </summary> public string ACC_DECLARATION { get; internal set; } /// <summary> /// (Was CALL_AMBULANCE) Family has ambulance subscription? (Y/N) (default for each student) /// [Uppercase Alphanumeric (1)] /// </summary> public string AMBULANCE_SUBSCRIBER { get; internal set; } /// <summary> /// Medicare No (default for each student) /// [Uppercase Alphanumeric (12)] /// </summary> public string MEDICARE_NO { get; internal set; } /// <summary> /// The language spoken at home /// [Uppercase Alphanumeric (7)] /// </summary> public string HOME_LANG { get; internal set; } /// <summary> /// Cheque Account Name /// [Alphanumeric (30)] /// </summary> public string DRAWER { get; internal set; } /// <summary> /// Cheque BSB Number /// [Alphanumeric (6)] /// </summary> public string BSB { get; internal set; } /// <summary> /// The ABN number for this debtor /// [Uppercase Alphanumeric (15)] /// </summary> public string ABN { get; internal set; } /// <summary> /// General Email address for emailing financial statements direct to families /// [Alphanumeric (60)] /// </summary> public string BILLING_EMAIL { get; internal set; } /// <summary> /// Preferred Email: A=Adult A e-mail, B=Adult B e-mail, C=Billing e-mail /// [Uppercase Alphanumeric (1)] /// </summary> public string PREF_EMAIL { get; internal set; } /// <summary> /// Date last udpated /// </summary> public DateTime? SCH_ED_A_LU { get; internal set; } /// <summary> /// Date last udpated /// </summary> public DateTime? NON_SCH_ED_A_LU { get; internal set; } /// <summary> /// Date last udpated /// </summary> public DateTime? OCCUP_STATUS_A_LU { get; internal set; } /// <summary> /// Date last udpated /// </summary> public DateTime? SCH_ED_B_LU { get; internal set; } /// <summary> /// Date last udpated /// </summary> public DateTime? NON_SCH_ED_B_LU { get; internal set; } /// <summary> /// Date last udpated /// </summary> public DateTime? OCCUP_STATUS_B_LU { get; internal set; } /// <summary> /// Calculated Non School Education /// [Uppercase Alphanumeric (1)] /// </summary> public string CNSE { get; internal set; } /// <summary> /// Calculated School Education /// [Uppercase Alphanumeric (1)] /// </summary> public string CSE { get; internal set; } /// <summary> /// Final Education Value /// [Uppercase Alphanumeric (1)] /// </summary> public string FSE { get; internal set; } /// <summary> /// Parent/guardian A Self-described Gender /// [Alphanumeric (100)] /// </summary> public string GENDER_DESC_A { get; internal set; } /// <summary> /// Parent/guardian B Self-described Gender /// [Alphanumeric (100)] /// </summary> public string GENDER_DESC_B { get; internal set; } /// <summary> /// Unique Home UM Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string UMH_TRANS_ID { get; internal set; } /// <summary> /// Unique Mail UM Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string UMM_TRANS_ID { get; internal set; } /// <summary> /// Unique Billing UM Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string UMB_TRANS_ID { get; internal set; } /// <summary> /// Unique KCD Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string KCD_TRANS_ID { get; internal set; } /// <summary> /// Current Status of Import /// [Uppercase Alphanumeric (15)] /// </summary> public string IMP_STATUS { get; internal set; } /// <summary> /// Actual Date data transfered into live table /// </summary> public DateTime? IMP_DATE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last write operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// SKGS (Schools) related entity by [DF_TFR.ORIG_SCHOOL]-&gt;[SKGS.SCHOOL] /// Orignating School /// </summary> public SKGS ORIG_SCHOOL_SKGS { get { if (Cache_ORIG_SCHOOL_SKGS == null) { Cache_ORIG_SCHOOL_SKGS = Context.SKGS.FindBySCHOOL(ORIG_SCHOOL); } return Cache_ORIG_SCHOOL_SKGS; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ASP.NETSinglePageApplication.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // 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 { using System; using NLog.Internal; /// <summary> /// Defines available log levels. /// </summary> public sealed class LogLevel : IComparable { /// <summary> /// Trace log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Trace = new LogLevel("Trace", 0); /// <summary> /// Debug log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Debug = new LogLevel("Debug", 1); /// <summary> /// Info log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Info = new LogLevel("Info", 2); /// <summary> /// Warn log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Warn = new LogLevel("Warn", 3); /// <summary> /// Error log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Error = new LogLevel("Error", 4); /// <summary> /// Fatal log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Fatal = new LogLevel("Fatal", 5); /// <summary> /// Off log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Off = new LogLevel("Off", 6); private readonly int ordinal; private readonly string name; // to be changed into public in the future. private LogLevel(string name, int ordinal) { this.name = name; this.ordinal = ordinal; } /// <summary> /// Gets the name of the log level. /// </summary> public string Name { get { return this.name; } } internal static LogLevel MaxLevel { get { return Fatal; } } internal static LogLevel MinLevel { get { return Trace; } } /// <summary> /// Gets the ordinal of the log level. /// </summary> internal int Ordinal { get { return this.ordinal; } } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal == level2.Ordinal</c>.</returns> public static bool operator ==(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, null)) { return ReferenceEquals(level2, null); } if (ReferenceEquals(level2, null)) { return false; } return level1.Ordinal == level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is not equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal != level2.Ordinal</c>.</returns> public static bool operator !=(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, null)) { return !ReferenceEquals(level2, null); } if (ReferenceEquals(level2, null)) { return true; } return level1.Ordinal != level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is greater than the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &gt; level2.Ordinal</c>.</returns> public static bool operator >(LogLevel level1, LogLevel level2) { ParameterUtils.AssertNotNull(level1, "level1"); ParameterUtils.AssertNotNull(level2, "level2"); return level1.Ordinal > level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is greater than or equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &gt;= level2.Ordinal</c>.</returns> public static bool operator >=(LogLevel level1, LogLevel level2) { ParameterUtils.AssertNotNull(level1, "level1"); ParameterUtils.AssertNotNull(level2, "level2"); return level1.Ordinal >= level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is less than the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &lt; level2.Ordinal</c>.</returns> public static bool operator <(LogLevel level1, LogLevel level2) { ParameterUtils.AssertNotNull(level1, "level1"); ParameterUtils.AssertNotNull(level2, "level2"); return level1.Ordinal < level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is less than or equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &lt;= level2.Ordinal</c>.</returns> public static bool operator <=(LogLevel level1, LogLevel level2) { ParameterUtils.AssertNotNull(level1, "level1"); ParameterUtils.AssertNotNull(level2, "level2"); return level1.Ordinal <= level2.Ordinal; } /// <summary> /// Gets the <see cref="LogLevel"/> that corresponds to the specified ordinal. /// </summary> /// <param name="ordinal">The ordinal.</param> /// <returns>The <see cref="LogLevel"/> instance. For 0 it returns <see cref="LogLevel.Trace"/>, 1 gives <see cref="LogLevel.Debug"/> and so on.</returns> public static LogLevel FromOrdinal(int ordinal) { switch (ordinal) { case 0: return Trace; case 1: return Debug; case 2: return Info; case 3: return Warn; case 4: return Error; case 5: return Fatal; case 6: return Off; default: throw new ArgumentException("Invalid ordinal."); } } /// <summary> /// Returns the <see cref="T:NLog.LogLevel"/> that corresponds to the supplied <see langword="string" />. /// </summary> /// <param name="levelName">The texual representation of the log level.</param> /// <returns>The enumeration value.</returns> public static LogLevel FromString(string levelName) { if (levelName == null) { throw new ArgumentNullException("levelName"); } if (levelName.Equals("Trace", StringComparison.OrdinalIgnoreCase)) { return Trace; } if (levelName.Equals("Debug", StringComparison.OrdinalIgnoreCase)) { return Debug; } if (levelName.Equals("Info", StringComparison.OrdinalIgnoreCase)) { return Info; } if (levelName.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { return Warn; } if (levelName.Equals("Error", StringComparison.OrdinalIgnoreCase)) { return Error; } if (levelName.Equals("Fatal", StringComparison.OrdinalIgnoreCase)) { return Fatal; } if (levelName.Equals("Off", StringComparison.OrdinalIgnoreCase)) { return Off; } throw new ArgumentException("Unknown log level: " + levelName); } /// <summary> /// Returns a string representation of the log level. /// </summary> /// <returns>Log level name.</returns> public override string ToString() { return this.Name; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return this.Ordinal; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// Value of <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { LogLevel other = obj as LogLevel; if ((object)other == null) { return false; } return this.Ordinal == other.Ordinal; } /// <summary> /// Compares the level to the other <see cref="LogLevel"/> object. /// </summary> /// <param name="obj"> /// The object object. /// </param> /// <returns> /// A value less than zero when this logger's <see cref="Ordinal"/> is /// less than the other logger's ordinal, 0 when they are equal and /// greater than zero when this ordinal is greater than the /// other ordinal. /// </returns> public int CompareTo(object obj) { var level = (LogLevel)obj; return this.Ordinal - level.Ordinal; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Timers; using d60.Cirqus.Caching; using d60.Cirqus.Extensions; using d60.Cirqus.Logging; namespace d60.Cirqus.Events { /// <summary> /// Simple caching event store decorator that caches all event that it comes by /// </summary> public class CachingEventStoreDecorator : IEventStore, IDisposable { static Logger _log; static CachingEventStoreDecorator() { CirqusLoggerFactory.Changed += f => _log = f.GetCurrentClassLogger(); } readonly ConcurrentDictionary<string, ConcurrentDictionary<long, CacheEntry<EventData>>> _eventsPerAggregateRoot = new ConcurrentDictionary<string, ConcurrentDictionary<long, CacheEntry<EventData>>>(); readonly ConcurrentDictionary<long, CacheEntry<EventData>> _eventsPerGlobalSequenceNumber = new ConcurrentDictionary<long, CacheEntry<EventData>>(); readonly Timer _trimTimer = new Timer(30000); readonly IEventStore _innerEventStore; int _maxCacheEntries; readonly object _trimLock = new object(); volatile bool _currentlyTrimmingCache; public CachingEventStoreDecorator(IEventStore innerEventStore) { _innerEventStore = innerEventStore; _trimTimer.Elapsed += delegate { try { PossiblyTrimCache(); _log.Debug("Status after cache check: currently holds {0} events by global sequence number and {1} aggregate root streams", _eventsPerGlobalSequenceNumber.Count, _eventsPerAggregateRoot.Count); } catch (Exception exception) { _log.Error(exception, "An error ocurred while trimming the event cache"); } }; _trimTimer.Start(); } public int MaxCacheEntries { get { return _maxCacheEntries; } set { if (value < 0) { throw new ArgumentException(string.Format("Cannot set max cache entries to {0} - the value must be greater than or equal to 0!", value)); } _maxCacheEntries = value; } } public void Save(Guid batchId, IEnumerable<EventData> batch) { var eventList = batch.ToList(); _innerEventStore.Save(batchId, eventList); foreach (var e in eventList) { AddToCache(e); } } public long GetNextGlobalSequenceNumber() { return _innerEventStore.GetNextGlobalSequenceNumber(); } public IEnumerable<EventData> Load(string aggregateRootId, long firstSeq = 0) { var eventsForThisAggregateRoot = _eventsPerAggregateRoot.GetOrAdd(aggregateRootId, id => new ConcurrentDictionary<long, CacheEntry<EventData>>()); var nextSequenceNumberToGet = firstSeq; CacheEntry<EventData> cacheEntry; while (eventsForThisAggregateRoot.TryGetValue(nextSequenceNumberToGet, out cacheEntry)) { nextSequenceNumberToGet++; cacheEntry.MarkAsAccessed(); yield return cacheEntry.Data; } foreach (var loadedEvent in _innerEventStore.Load(aggregateRootId, nextSequenceNumberToGet)) { AddToCache(loadedEvent, eventsForThisAggregateRoot); yield return loadedEvent; } } public IEnumerable<EventData> Stream(long globalSequenceNumber = 0) { CacheEntry<EventData> cacheEntry; var nextGlobalSequenceNumberToGet = globalSequenceNumber; while (_eventsPerGlobalSequenceNumber.TryGetValue(nextGlobalSequenceNumberToGet, out cacheEntry)) { nextGlobalSequenceNumberToGet++; cacheEntry.MarkAsAccessed(); yield return cacheEntry.Data; } foreach (var loadedEvent in _innerEventStore.Stream(nextGlobalSequenceNumberToGet)) { AddToCache(loadedEvent); yield return loadedEvent; } } public void Dispose() { _trimTimer.Stop(); _trimTimer.Dispose(); } void PossiblyTrimCache() { // never trim in parallel if (_currentlyTrimmingCache) return; lock (_trimLock) { if (_currentlyTrimmingCache) return; _currentlyTrimmingCache = true; } // _currentlyTrimmingCache is set to false again in the finally clause try { if (_eventsPerGlobalSequenceNumber.Count <= _maxCacheEntries) return; _log.Debug("Trimming caches"); var stopwatch = Stopwatch.StartNew(); var entriesOldestFirst = _eventsPerGlobalSequenceNumber.Values .OrderByDescending(e => e.Age) .ToList(); foreach (var entryToRemove in entriesOldestFirst) { if (_eventsPerGlobalSequenceNumber.Count <= _maxCacheEntries) break; CacheEntry<EventData> removedCacheEntry; _eventsPerGlobalSequenceNumber.TryRemove(entryToRemove.Data.GetGlobalSequenceNumber(), out removedCacheEntry); var eventsForThisAggregateRoot = GetEventsForThisAggregateRoot(entryToRemove.Data.GetAggregateRootId()); eventsForThisAggregateRoot.TryRemove(entryToRemove.Data.GetSequenceNumber(), out removedCacheEntry); } var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; _log.Info("Trimming event cache took {0:0.0} s", elapsedSeconds); } catch (Exception exception) { _log.Error(exception, "Error while trimming event cache"); } finally { _currentlyTrimmingCache = false; } } void AddToCache(EventData eventData, ConcurrentDictionary<long, CacheEntry<EventData>> eventsForThisAggregateRoot = null) { var aggregateRootId = eventData.GetAggregateRootId(); if (eventsForThisAggregateRoot == null) { eventsForThisAggregateRoot = GetEventsForThisAggregateRoot(aggregateRootId); } eventsForThisAggregateRoot.AddOrUpdate(eventData.GetSequenceNumber(), seqNo => new CacheEntry<EventData>(eventData), (seqNo, existing) => existing.MarkAsAccessed()); _eventsPerGlobalSequenceNumber.AddOrUpdate(eventData.GetGlobalSequenceNumber(), globSeqNo => new CacheEntry<EventData>(eventData), (globSeqNo, existing) => existing.MarkAsAccessed()); } ConcurrentDictionary<long, CacheEntry<EventData>> GetEventsForThisAggregateRoot(string aggregateRootId) { return _eventsPerAggregateRoot.GetOrAdd(aggregateRootId, id => new ConcurrentDictionary<long, CacheEntry<EventData>>()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Microsoft.Msagl.Core.DataStructures { // TODO: Move and expand the commented tests below into PriorityQueueTests unit tests for all 3 PQ classes. // TODO: Reduce duplication with GenericBinaryHeapPriorityQueue by breaking most functionality out into a // GenericBinaryHeapPriorityQueue<T, THeapElement> class and using THeapElement.ComparePriority, keeping only Enqueue // and DecreasePriority in the derived classes as these must know about timestamp. /// <summary> /// A generic version priority queue based on the binary heap algorithm where /// the priority of each element is passed as a parameter and priority ties are broken by timestamp. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public class GenericBinaryHeapPriorityQueueWithTimestamp<T> : IEnumerable<T> { const int InitialHeapCapacity = 16; //indexing for A starts from 1 //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] //internal void Clear() //{ // if(heapSize>0) // { // for(int i=0;i<cache.Length;i++) // this.cache[i]=null; // heapSize=0; // } //} // ReSharper disable InconsistentNaming GenericHeapElementWithTimestamp<T>[] A;//array of heap elements // ReSharper restore InconsistentNaming UInt64 timestamp; UInt64 NextTimestamp { get { return ++this.timestamp; } } /// <summary> /// it is a mapping from queue elements and their correspondent HeapElements /// </summary> readonly Dictionary<T, GenericHeapElementWithTimestamp<T>> cache; internal int Count { get { return heapSize; } } int heapSize; internal GenericBinaryHeapPriorityQueueWithTimestamp() { cache = new Dictionary<T, GenericHeapElementWithTimestamp<T>>(); A = new GenericHeapElementWithTimestamp<T>[InitialHeapCapacity + 1]; } void SwapWithParent(int i) { var parent = A[i >> 1]; PutAtI(i >> 1, A[i]); PutAtI(i, parent); } internal void Enqueue(T element, double priority) { if (heapSize == A.Length - 1) { var newA = new GenericHeapElementWithTimestamp<T>[A.Length * 2]; Array.Copy(A, 1, newA, 1, heapSize); A = newA; } heapSize++; int i = heapSize; GenericHeapElementWithTimestamp<T> h; A[i] = cache[element] = h = new GenericHeapElementWithTimestamp<T>(i, priority, element, this.NextTimestamp); while (i > 1 && A[i >> 1].ComparePriority(A[i]) > 0) { SwapWithParent(i); i >>= 1; } System.Diagnostics.Debug.Assert(A[i] == h); A[i] = h; } void PutAtI(int i, GenericHeapElementWithTimestamp<T> h) { A[i] = h; h.indexToA = i; } #if TEST_MSAGL /// <summary> /// Gets the next element to be dequeued, without dequeueing it. /// </summary> internal T Peek() { if (heapSize == 0) { throw new InvalidOperationException(); } return A[1].v; } /// <summary> /// Gets the timestamp of the next element to be dequeued, without dequeueing it. /// </summary> internal UInt64 PeekTimestamp() { if (heapSize == 0) { throw new InvalidOperationException(); } return A[1].Timestamp; } #endif // TEST_MSAGL internal T Dequeue() { if (heapSize == 0) throw new InvalidOperationException(); var ret = A[1].v; MoveQueueOneStepForward(ret); return ret; } void MoveQueueOneStepForward(T ret) { cache.Remove(ret); PutAtI(1, A[heapSize]); int i = 1; while (true) { int smallest = i; int l = i << 1; if (l <= heapSize && A[l].ComparePriority(A[i]) < 0) smallest = l; int r = l + 1; if (r <= heapSize && A[r].ComparePriority(A[smallest]) < 0) smallest = r; if (smallest != i) SwapWithParent(smallest); else break; i = smallest; } heapSize--; } /// <summary> /// sets the object priority to c /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal void DecreasePriority(T element, double newPriority) { GenericHeapElementWithTimestamp<T> h; //ignore the element if it is not in the queue if (!cache.TryGetValue(element, out h)) return; //var h = cache[element]; h.priority = newPriority; int i = h.indexToA; while (i > 1) { if (A[i].ComparePriority(A[i >> 1]) < 0) SwapWithParent(i); else break; i >>= 1; } } ///<summary> ///</summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] // public static void Test() { // Timer nm = new Timer(); // var bound = 1000000; // nm.Start(); // { // var q = new BinaryHeapPriorityQueue(bound + 1); // Random random = new Random(); // for (int i = 0; i < bound; i++) { // q.Enqueue(i, random.NextDouble()); // } // for (int i = 0; i < bound; i++) { // q.DecreasePriority(i, -random.NextDouble()); // } // // while (q.IsEmpty() == false) { // q.Dequeue(); // } // // } // nm.Stop(); // Console.WriteLine(nm.Duration); // nm.Start(); // { // var q = new GenericBinaryHeapPriorityQueue<int>(); // Random random = new Random(); // for (int i = 0; i < bound; i++) { // q.Enqueue(i, random.NextDouble()); // } // for (int i = 0; i < bound; i++) { // q.DecreasePriority(i, -random.NextDouble()); // } // // while (q.IsEmpty() == false) { // q.Dequeue(); // } // // } // nm.Stop(); // Console.WriteLine(nm.Duration); //} [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void Test() { var q = new GenericBinaryHeapPriorityQueue<int>(); q.Enqueue(2, 2); q.Enqueue(1, 1); q.Enqueue(9, 9); q.Enqueue(8, 8); q.Enqueue(5, 5); q.Enqueue(3, 3); q.Enqueue(4, 4); q.Enqueue(7, 7); q.Enqueue(6, 6); q.Enqueue(0, 0); q.DecreasePriority(4, 2.5); while (q.IsEmpty() == false) Console.WriteLine(q.Dequeue()); } /// <summary> /// enumerator /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { for (int i = 1; i <= heapSize; i++) yield return A[i].v; } IEnumerator IEnumerable.GetEnumerator() { for (int i = 1; i <= heapSize; i++) yield return A[i].v; } #if TEST_MSAGL /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { var sb=new StringBuilder(); foreach (var i in this) sb.Append(i + ","); return sb.ToString(); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; #if !FEATURE_PORTABLE_SPAN using Internal.Runtime.CompilerServices; #endif // FEATURE_PORTABLE_SPAN namespace System { /// <summary> /// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>. /// Unlike <see cref="Span{T}"/>, it is not a byref-like type. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] [DebuggerTypeProxy(typeof(MemoryDebugView<>))] public readonly struct Memory<T> { // NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout, // as code uses Unsafe.As to cast between them. // The highest order bit of _index is used to discern whether _object is an array/string or an owned memory // if (_index >> 31) == 1, object _object is an OwnedMemory<T> // else, object _object is a T[] or a string. It can only be a string if the Memory<T> was created by // using unsafe / marshaling code to reinterpret a ReadOnlyMemory<char> wrapped around a string as // a Memory<T>. private readonly object _object; private readonly int _index; private readonly int _length; private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) { this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = array; _index = start; _length = array.Length - start; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = array; _index = start; _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(OwnedMemory<T> owner, int index, int length) { // No validation performed; caller must provide any necessary validation. _object = owner; _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private Memory(object obj, int index, int length) { // No validation performed; caller must provide any necessary validation. _object = obj; _index = index; _length = length; } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(T[] array) => new Memory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) => Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); //Debugger Display = {T[length]} private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); /// <summary> /// Returns an empty <see cref="Memory{T}"/> /// </summary> public static Memory<T> Empty => default; /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new Memory<T>(_object, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory<T>(_object, _index + start, length); } /// <summary> /// Returns a span from the memory. /// </summary> public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((OwnedMemory<T>)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length); } else if (typeof(T) == typeof(char) && _object is string s) { // This is dangerous, returning a writable span for a string that should be immutable. // However, we need to handle the case where a ReadOnlyMemory<char> was created from a string // and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code, // in which case that's the dangerous operation performed by the dev, and we're just following // suit here to make it work as best as possible. #if FEATURE_PORTABLE_SPAN return new Span<T>(Unsafe.As<Pinnable<T>>(s), MemoryExtensions.StringAdjustment, s.Length).Slice(_index, _length); #else return new Span<T>(ref Unsafe.As<char, T>(ref s.GetRawStringData()), s.Length).Slice(_index, _length); #endif // FEATURE_PORTABLE_SPAN } else if (_object != null) { return new Span<T>((T[])_object, _index, _length); } else { return default; } } } /// <summary> /// Copies the contents of the memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <param name="destination">The Memory to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination is shorter than the source. /// </exception> /// </summary> public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span); /// <summary> /// Copies the contents of the memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <returns>If the destination is shorter than the source, this method /// return false and no data is written to the destination.</returns> /// </summary> /// <param name="destination">The span to copy items into.</param> public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span); /// <summary> /// Returns a handle for the array. /// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param> /// </summary> public unsafe MemoryHandle Retain(bool pin = false) { MemoryHandle memoryHandle = default; if (pin) { if (_index < 0) { memoryHandle = ((OwnedMemory<T>)_object).Pin((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>()); } else if (typeof(T) == typeof(char) && _object is string s) { // This case can only happen if a ReadOnlyMemory<char> was created around a string // and then that was cast to a Memory<char> using unsafe / marshaling code. This needs // to work, however, so that code that uses a single Memory<char> field to store either // a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and // used for interop purposes. GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned); #if FEATURE_PORTABLE_SPAN void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); #else void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref s.GetRawStringData()), _index); #endif // FEATURE_PORTABLE_SPAN memoryHandle = new MemoryHandle(null, pointer, handle); } else if (_object is T[] array) { var handle = GCHandle.Alloc(array, GCHandleType.Pinned); #if FEATURE_PORTABLE_SPAN void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); #else void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); #endif // FEATURE_PORTABLE_SPAN memoryHandle = new MemoryHandle(null, pointer, handle); } } else { if (_index < 0) { ((OwnedMemory<T>)_object).Retain(); memoryHandle = new MemoryHandle((OwnedMemory<T>)_object); } } return memoryHandle; } /// <summary> /// Get an array segment from the underlying memory. /// If unable to get the array segment, return false with a default array segment. /// </summary> public bool TryGetArray(out ArraySegment<T> arraySegment) { if (_index < 0) { if (((OwnedMemory<T>)_object).TryGetArray(out var segment)) { arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length); return true; } } else if (_object is T[] arr) { arraySegment = new ArraySegment<T>(arr, _index, _length); return true; } if (_length == 0) { #if FEATURE_PORTABLE_SPAN arraySegment = new ArraySegment<T>(SpanHelpers.PerTypeValues<T>.EmptyArray); #else arraySegment = ArraySegment<T>.Empty; #endif // FEATURE_PORTABLE_SPAN return true; } arraySegment = default(ArraySegment<T>); return false; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); /// <summary> /// Determines whether the specified object is equal to the current object. /// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T>) { return ((ReadOnlyMemory<T>)obj).Equals(this); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(Memory<T> other) { return _object == other._object && _index == other._index && _length == other._length; } /// <summary> /// Serves as the default hash function. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return _object != null ? CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode()) : 0; } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } }
namespace GigyaSDK.iOS { using System; using UIKit; using Foundation; using ObjCRuntime; using CoreGraphics; // @interface GSSessionInfo : NSObject <NSCoding> [BaseType(typeof(NSObject))] interface GSSessionInfo : INSCoding { // @property (copy, nonatomic) NSDate * expiration; [Export("expiration", ArgumentSemantic.Copy)] NSDate Expiration { get; set; } // @property (copy, nonatomic) NSString * APIKey; [Export("APIKey")] string APIKey { get; set; } // -(GSSessionInfo *)initWithAPIKey:(NSString *)apikey expiration:(NSDate *)expiration; [Export("initWithAPIKey:expiration:")] IntPtr Constructor(string apikey, NSDate expiration); // -(BOOL)isValid; [Export("isValid")] bool IsValid(); } // @interface GSSession : NSObject <NSCoding> [BaseType(typeof(NSObject))] interface GSSession : INSCoding { // @property (copy, nonatomic) NSString * token; [Export("token")] string Token { get; set; } // @property (copy, nonatomic) NSString * secret; [Export("secret")] string Secret { get; set; } // @property (retain, nonatomic) GSSessionInfo * info; [Export("info", ArgumentSemantic.Retain)] GSSessionInfo Info { get; set; } // @property (copy, nonatomic) NSString * lastLoginProvider; [Export("lastLoginProvider")] string LastLoginProvider { get; set; } // -(GSSession *)initWithSessionToken:(NSString *)token secret:(NSString *)secret; [Export("initWithSessionToken:secret:")] IntPtr Constructor(string token, string secret); // -(GSSession *)initWithSessionToken:(NSString *)token secret:(NSString *)secret expiration:(NSDate *)expiration; [Export("initWithSessionToken:secret:expiration:")] IntPtr Constructor(string token, string secret, NSDate expiration); // -(GSSession *)initWithSessionToken:(NSString *)token secret:(NSString *)secret expiresIn:(NSString *)expiresIn; [Export("initWithSessionToken:secret:expiresIn:")] IntPtr Constructor(string token, string secret, string expiresIn); // -(BOOL)isValid; [Export("isValid")] bool IsValid(); } // @interface GSObject : NSObject [BaseType(typeof(NSObject))] interface GSObject { // @property (copy, nonatomic) NSString * source; [Export("source")] string Source { get; set; } // -(id)objectForKeyedSubscript:(NSString *)key; [Export("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript(string key); // -(void)setObject:(id)obj forKeyedSubscript:(NSString *)key; [Export("setObject:forKeyedSubscript:")] void SetObjectForKeyedSubscript(NSObject obj, string key); // -(id)objectForKey:(NSString *)key; [Export("objectForKey:")] NSObject ObjectForKey(string key); // -(void)setObject:(id)obj forKey:(NSString *)key; [Export("setObject:forKey:")] void SetObject(NSObject obj, string key); // -(void)removeObjectForKey:(NSString *)key; [Export("removeObjectForKey:")] void RemoveObjectForKey(string key); // -(NSArray *)allKeys; [Export("allKeys")] NSObject[] AllKeys { get; } // -(NSString *)JSONString; [Export("JSONString")] string JSONString { get; } } // typedef void (^ _Nullable)(GSResponse * _Nullable, NSError * _Nullable) GSResponseHandler; delegate void GSResponseHandler([NullAllowed] GSResponse arg0, [NullAllowed] NSError arg1); // @interface GSRequest : NSObject [BaseType(typeof(NSObject))] interface GSRequest { // +(GSRequest *)requestForMethod:(NSString * _Nonnull)method; [Static] [Export("requestForMethod:")] GSRequest RequestForMethod(string method); // +(GSRequest *)requestForMethod:(NSString * _Nonnull)method parameters:(NSDictionary * _Nullable)parameters; [Static] [Export("requestForMethod:parameters:")] GSRequest RequestForMethod(string method, [NullAllowed] NSDictionary parameters); // @property (copy, nonatomic) NSString * _Nonnull method; [Export("method")] string Method { get; set; } // @property (nonatomic, strong) NSMutableDictionary * _Nullable parameters; [NullAllowed, Export("parameters", ArgumentSemantic.Strong)] NSMutableDictionary Parameters { get; set; } // @property (nonatomic) BOOL useHTTPS; [Export("useHTTPS")] bool UseHTTPS { get; set; } // @property (nonatomic) NSTimeInterval requestTimeout; [Export("requestTimeout")] double RequestTimeout { get; set; } // -(void)sendWithResponseHandler:(GSResponseHandler)handler; [Export("sendWithResponseHandler:")] void SendWithResponseHandler([NullAllowed] GSResponseHandler handler); // -(void)cancel; [Export("cancel")] void Cancel(); // @property (nonatomic, strong) GSSession * session; [Export("session", ArgumentSemantic.Strong)] GSSession Session { get; set; } // @property (readonly, nonatomic, strong) NSString * requestID; [Export("requestID", ArgumentSemantic.Strong)] string RequestID { get; } // @property (nonatomic) BOOL includeAuthInfo; [Export("includeAuthInfo")] bool IncludeAuthInfo { get; set; } // @property (copy, nonatomic) NSString * source; [Export("source")] string Source { get; set; } } // @interface GSResponse : GSObject [BaseType(typeof(GSObject))] interface GSResponse { // +(void)responseForMethod:(NSString *)method data:(NSData *)data completionHandler:(GSResponseHandler)handler; [Static] [Export("responseForMethod:data:completionHandler:")] void ResponseForMethod(string method, NSData data, [NullAllowed] GSResponseHandler handler); // +(GSResponse *)responseWithError:(NSError *)error; [Static] [Export("responseWithError:")] GSResponse ResponseWithError(NSError error); // @property (readonly, weak) NSString * method; [Export("method", ArgumentSemantic.Weak)] string Method { get; } // @property (readonly) int errorCode; [Export("errorCode")] int ErrorCode { get; } // @property (readonly, weak) NSString * callId; [Export("callId", ArgumentSemantic.Weak)] string CallId { get; } // -(NSArray *)allKeys; [Export("allKeys")] NSObject[] AllKeys { get; } // -(id)objectForKey:(NSString *)key; [Export("objectForKey:")] NSObject ObjectForKey(string key); // -(id)objectForKeyedSubscript:(NSString *)key; [Export("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript(string key); // -(NSString *)JSONString; [Export("JSONString")] string JSONString { get; } } // @interface GSUser : GSResponse [BaseType(typeof(GSResponse))] interface GSUser { // @property (readonly, nonatomic, weak) NSString * UID; [Export("UID", ArgumentSemantic.Weak)] string UID { get; } // @property (readonly, nonatomic, weak) NSString * loginProvider; [Export("loginProvider", ArgumentSemantic.Weak)] string LoginProvider { get; } // @property (readonly, nonatomic, weak) NSString * nickname; [Export("nickname", ArgumentSemantic.Weak)] string Nickname { get; } // @property (readonly, nonatomic, weak) NSString * firstName; [Export("firstName", ArgumentSemantic.Weak)] string FirstName { get; } // @property (readonly, nonatomic, weak) NSString * lastName; [Export("lastName", ArgumentSemantic.Weak)] string LastName { get; } // @property (readonly, nonatomic, weak) NSString * email; [Export("email", ArgumentSemantic.Weak)] string Email { get; } // @property (readonly, nonatomic, weak) NSArray * identities; [Export("identities", ArgumentSemantic.Weak)] NSObject[] Identities { get; } // @property (readonly, nonatomic, weak) NSURL * photoURL; [Export("photoURL", ArgumentSemantic.Weak)] NSUrl PhotoURL { get; } // @property (readonly, nonatomic, weak) NSURL * thumbnailURL; [Export("thumbnailURL", ArgumentSemantic.Weak)] NSUrl ThumbnailURL { get; } // -(NSArray *)allKeys; [Export("allKeys")] NSObject[] AllKeys { get; } // -(id)objectForKey:(NSString *)key; [Export("objectForKey:")] NSObject ObjectForKey(string key); // -(id)objectForKeyedSubscript:(NSString *)key; [Export("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript(string key); // -(NSString *)JSONString; [Export("JSONString")] string JSONString { get; } } // @interface GSAccount : GSResponse [BaseType(typeof(GSResponse))] interface GSAccount { // @property (readonly, nonatomic, weak) NSString * UID; [Export("UID", ArgumentSemantic.Weak)] string UID { get; } // @property (readonly, nonatomic, weak) NSDictionary * profile; [Export("profile", ArgumentSemantic.Weak)] NSDictionary Profile { get; } // @property (readonly, nonatomic, weak) NSDictionary * data; [Export("data", ArgumentSemantic.Weak)] NSDictionary Data { get; } // @property (readonly, nonatomic, weak) NSString * nickname; [Export("nickname", ArgumentSemantic.Weak)] string Nickname { get; } // @property (readonly, nonatomic, weak) NSString * firstName; [Export("firstName", ArgumentSemantic.Weak)] string FirstName { get; } // @property (readonly, nonatomic, weak) NSString * lastName; [Export("lastName", ArgumentSemantic.Weak)] string LastName { get; } // @property (readonly, nonatomic, weak) NSString * email; [Export("email", ArgumentSemantic.Weak)] string Email { get; } // @property (readonly, nonatomic, weak) NSURL * photoURL; [Export("photoURL", ArgumentSemantic.Weak)] NSUrl PhotoURL { get; } // @property (readonly, nonatomic, weak) NSURL * thumbnailURL; [Export("thumbnailURL", ArgumentSemantic.Weak)] NSUrl ThumbnailURL { get; } // -(NSArray *)allKeys; [Export("allKeys")] NSObject[] AllKeys { get; } // -(id)objectForKey:(NSString *)key; [Export("objectForKey:")] NSObject ObjectForKey(string key); // -(id)objectForKeyedSubscript:(NSString *)key; [Export("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript(string key); // -(NSString *)JSONString; [Export("JSONString")] string JSONString { get; } } // @protocol GSSessionDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface GSSessionDelegate { // @optional -(void)userDidLogin:(GSUser *)user; [Export("userDidLogin:")] void UserDidLogin(GSUser user); // @optional -(void)userDidLogout; [Export("userDidLogout")] void UserDidLogout(); // @optional -(void)userInfoDidChange:(GSUser *)user; [Export("userInfoDidChange:")] void UserInfoDidChange(GSUser user); } // @protocol GSSocializeDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface GSSocializeDelegate { // @optional -(void)userDidLogin:(GSUser *)user; [Export("userDidLogin:")] void UserDidLogin(GSUser user); // @optional -(void)userDidLogout; [Export("userDidLogout")] void UserDidLogout(); // @optional -(void)userInfoDidChange:(GSUser *)user; [Export("userInfoDidChange:")] void UserInfoDidChange(GSUser user); } // @protocol GSAccountsDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface GSAccountsDelegate { // @optional -(void)accountDidLogin:(GSAccount *)account; [Export("accountDidLogin:")] void AccountDidLogin(GSAccount account); // @optional -(void)accountDidLogout; [Export("accountDidLogout")] void AccountDidLogout(); } // @protocol GSWebBridgeDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface GSWebBridgeDelegate { // @optional -(void)webView:(id)webView startedLoginForMethod:(NSString *)method parameters:(NSDictionary *)parameters; [Export("webView:startedLoginForMethod:parameters:")] void StartedLoginForMethod(NSObject webView, string method, NSDictionary parameters); // @optional -(void)webView:(id)webView finishedLoginWithResponse:(GSResponse *)response; [Export("webView:finishedLoginWithResponse:")] void FinishedLoginWithResponse(NSObject webView, GSResponse response); // @optional -(void)webView:(id)webView receivedPluginEvent:(NSDictionary *)event fromPluginInContainer:(NSString *)containerID; [Export("webView:receivedPluginEvent:fromPluginInContainer:")] void ReceivedPluginEvent(NSObject webView, NSDictionary @event, string containerID); // @optional -(void)webView:(id)webView receivedJsLog:(NSString *)logType logInfo:(NSDictionary *)logInfo; [Export("webView:receivedJsLog:logInfo:")] void ReceivedJsLog(NSObject webView, string logType, NSDictionary logInfo); } // @interface GSWebBridge : NSObject [BaseType(typeof(NSObject))] interface GSWebBridge { // +(void)registerWebView:(id)webView delegate:(id<GSWebBridgeDelegate>)delegate; [Static] [Export("registerWebView:delegate:")] void RegisterWebView(NSObject webView, GSWebBridgeDelegate @delegate); // +(void)registerWebView:(id)webView delegate:(id<GSWebBridgeDelegate>)delegate settings:(NSDictionary *)settings; [Static] [Export("registerWebView:delegate:settings:")] void RegisterWebView(NSObject webView, GSWebBridgeDelegate @delegate, NSDictionary settings); // +(void)unregisterWebView:(id)webView; [Static] [Export("unregisterWebView:")] void UnregisterWebView(NSObject webView); // +(void)webViewDidStartLoad:(id)webView; [Static] [Export("webViewDidStartLoad:")] void WebViewDidStartLoad(NSObject webView); // +(BOOL)handleRequest:(NSURLRequest *)request webView:(id)webView; [Static] [Export("handleRequest:webView:")] bool HandleRequest(NSUrlRequest request, NSObject webView); } // @protocol GSPluginViewDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface GSPluginViewDelegate { // @optional -(void)pluginView:(GSPluginView *)pluginView finishedLoadingPluginWithEvent:(NSDictionary *)event; [Export("pluginView:finishedLoadingPluginWithEvent:")] void FinishedLoadingPluginWithEvent(GSPluginView pluginView, NSDictionary @event); // @optional -(void)pluginView:(GSPluginView *)pluginView firedEvent:(NSDictionary *)event; [Export("pluginView:firedEvent:")] void FiredEvent(GSPluginView pluginView, NSDictionary @event); // @optional -(void)pluginView:(GSPluginView *)pluginView didFailWithError:(NSError *)error; [Export("pluginView:didFailWithError:")] void DidFailWithError(GSPluginView pluginView, NSError error); } // @interface GSPluginView : UIView [BaseType(typeof(UIView))] interface GSPluginView { [Wrap("WeakDelegate")] GSPluginViewDelegate Delegate { get; set; } // @property (nonatomic, weak) id<GSPluginViewDelegate> delegate; [NullAllowed, Export("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // -(void)loadPlugin:(NSString *)plugin; [Export("loadPlugin:")] void LoadPlugin(string plugin); // -(void)loadPlugin:(NSString *)plugin parameters:(NSDictionary *)parameters; [Export("loadPlugin:parameters:")] void LoadPlugin(string plugin, NSDictionary parameters); // @property (readonly, nonatomic) NSString * plugin; [Export("plugin")] string Plugin { get; } // @property (nonatomic) BOOL showLoginProgress; [Export("showLoginProgress")] bool ShowLoginProgress { get; set; } // @property (copy, nonatomic) NSString * loginProgressText; [Export("loginProgressText")] string LoginProgressText { get; set; } // @property (nonatomic) BOOL showLoadingProgress; [Export("showLoadingProgress")] bool ShowLoadingProgress { get; set; } // @property (copy, nonatomic) NSString * loadingProgressText; [Export("loadingProgressText")] string LoadingProgressText { get; set; } // @property (nonatomic) NSInteger javascriptLoadingTimeout; [Export("javascriptLoadingTimeout")] nint JavascriptLoadingTimeout { get; set; } } // typedef void (^ _Nullable)(GSUser * _Nullable, NSError * _Nullable) GSUserInfoHandler; delegate void GSUserInfoHandler([NullAllowed] GSUser arg0, [NullAllowed] NSError arg1); // typedef void (^ _Nullable)(BOOL, NSError * _Nullable, NSArray * _Nullable) GSPermissionRequestResultHandler; delegate void GSPermissionRequestResultHandler(bool arg0, [NullAllowed] NSError arg1, [NullAllowed] NSObject[] arg2); // typedef void (^GSPluginCompletionHandler)(BOOL, NSError * _Nullable); delegate void GSPluginCompletionHandler(bool arg0, [NullAllowed] NSError arg1); // typedef void (^GSGetSessionCompletionHandler)(GSSession * _Nullable); delegate void GSGetSessionCompletionHandler([NullAllowed] GSSession arg0); // @interface Gigya : NSObject [BaseType(typeof(NSObject))] interface Gigya { // +(void)initWithAPIKey:(NSString *)apiKey application:(UIApplication *)application launchOptions:(NSDictionary *)launchOptions; [Static] [Export("initWithAPIKey:application:launchOptions:")] void InitWithAPIKey(string apiKey, UIApplication application, NSDictionary launchOptions); // +(void)initWithAPIKey:(NSString *)apiKey application:(UIApplication *)application launchOptions:(NSDictionary *)launchOptions APIDomain:(NSString *)apiDomain; [Static] [Export("initWithAPIKey:application:launchOptions:APIDomain:")] void InitWithAPIKey(string apiKey, UIApplication application, NSDictionary launchOptions, string apiDomain); // +(NSString *)APIKey; [Static] [Export("APIKey")] string APIKey { get; } // +(NSString *)APIDomain; [Static] [Export("APIDomain")] string APIDomain { get; } // +(void)getSessionWithCompletionHandler:(GSGetSessionCompletionHandler _Nonnull)handler; [Static] [Export("getSessionWithCompletionHandler:")] void GetSessionWithCompletionHandler(GSGetSessionCompletionHandler handler); // +(BOOL)isSessionValid; [Static] [Export("isSessionValid")] bool IsSessionValid(); // +(void)setSession:(GSSession * _Nullable)session; [Static] [Export("setSession:")] void SetSession([NullAllowed] GSSession session); // +(id<GSSessionDelegate>)sessionDelegate; // +(void)setSessionDelegate:(id<GSSessionDelegate>)delegate __attribute__((deprecated("Use [Gigya setSocializeDelegate:] with a GSSocializeDelegate instead"))); [Static] [Export("sessionDelegate")] GSSessionDelegate SessionDelegate { get; set; } // +(id<GSSocializeDelegate> _Nullable)socializeDelegate; [Static] [Export("socializeDelegate")] [return: NullAllowed] GSSocializeDelegate SocializeDelegate(); // +(void)setSocializeDelegate:(id<GSSocializeDelegate> _Nullable)socializeDelegate; [Static] [Export("setSocializeDelegate:")] void SetSocializeDelegate([NullAllowed] GSSocializeDelegate socializeDelegate); // +(id<GSAccountsDelegate> _Nullable)accountsDelegate; [Static] [Export("accountsDelegate")] [return: NullAllowed] GSAccountsDelegate AccountsDelegate(); // +(void)setAccountsDelegate:(id<GSAccountsDelegate> _Nullable)accountsDelegate; [Static] [Export("setAccountsDelegate:")] void SetAccountsDelegate([NullAllowed] GSAccountsDelegate accountsDelegate); // +(void)loginToProvider:(NSString * _Nonnull)provider; [Static] [Export("loginToProvider:")] void LoginToProvider(string provider); // +(void)showLoginDialogOver:(UIViewController *)viewController provider:(NSString *)provider __attribute__((deprecated("Use loginToProvider: instead"))); [Static] [Export("showLoginDialogOver:provider:")] void ShowLoginDialogOver(UIViewController viewController, string provider); // +(void)loginToProvider:(NSString * _Nonnull)provider parameters:(NSDictionary * _Nullable)parameters completionHandler:(GSUserInfoHandler _Nullable)handler; [Static] [Export("loginToProvider:parameters:completionHandler:")] void LoginToProvider(string provider, [NullAllowed] NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)showLoginDialogOver:(UIViewController *)viewController provider:(NSString *)provider parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler __attribute__((deprecated("Use loginToProvider:parameters:completionHandler: instead"))); [Static] [Export("showLoginDialogOver:provider:parameters:completionHandler:")] void ShowLoginDialogOver(UIViewController viewController, string provider, NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)loginToProvider:(NSString * _Nonnull)provider parameters:(NSDictionary * _Nullable)parameters over:(UIViewController * _Nullable)viewController completionHandler:(GSUserInfoHandler _Nullable)handler; [Static] [Export("loginToProvider:parameters:over:completionHandler:")] void LoginToProvider(string provider, [NullAllowed] NSDictionary parameters, [NullAllowed] UIViewController viewController, [NullAllowed] GSUserInfoHandler handler); // +(void)showLoginProvidersDialogOver:(UIViewController *)viewController; [Static] [Export("showLoginProvidersDialogOver:")] void ShowLoginProvidersDialogOver(UIViewController viewController); // +(void)showLoginProvidersPopoverFrom:(UIView *)view; [Static] [Export("showLoginProvidersPopoverFrom:")] void ShowLoginProvidersPopoverFrom(UIView view); // +(void)showLoginProvidersDialogOver:(UIViewController *)viewController providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export("showLoginProvidersDialogOver:providers:parameters:completionHandler:")] void ShowLoginProvidersDialogOver(UIViewController viewController, string[] providers, NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)showLoginProvidersPopoverFrom:(UIView *)view providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export("showLoginProvidersPopoverFrom:providers:parameters:completionHandler:")] void ShowLoginProvidersPopoverFrom(UIView view, string[] providers, NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)logout; [Static] [Export("logout")] void Logout(); // +(void)logoutWithCompletionHandler:(GSResponseHandler)handler; [Static] [Export("logoutWithCompletionHandler:")] void LogoutWithCompletionHandler([NullAllowed] GSResponseHandler handler); // +(void)addConnectionToProvider:(NSString *)provider; [Static] [Export("addConnectionToProvider:")] void AddConnectionToProvider(string provider); // +(void)showAddConnectionDialogOver:(UIViewController *)viewController provider:(NSString *)provider __attribute__((deprecated("Use addConnectionToProvider: instead"))); [Static] [Export("showAddConnectionDialogOver:provider:")] void ShowAddConnectionDialogOver(UIViewController viewController, string provider); // +(void)addConnectionToProvider:(NSString *)provider parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export("addConnectionToProvider:parameters:completionHandler:")] void AddConnectionToProvider(string provider, NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)showAddConnectionDialogOver:(UIViewController *)viewController provider:(NSString *)provider parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler __attribute__((deprecated("Use addConnectionToProvider:parameters:completionHandler: instead"))); [Static] [Export("showAddConnectionDialogOver:provider:parameters:completionHandler:")] void ShowAddConnectionDialogOver(UIViewController viewController, string provider, NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)addConnectionToProvider:(NSString *)provider parameters:(NSDictionary *)parameters over:(UIViewController *)viewController completionHandler:(GSUserInfoHandler)handler; [Static] [Export("addConnectionToProvider:parameters:over:completionHandler:")] void AddConnectionToProvider(string provider, NSDictionary parameters, UIViewController viewController, [NullAllowed] GSUserInfoHandler handler); // +(void)showAddConnectionProvidersDialogOver:(UIViewController *)viewController; [Static] [Export("showAddConnectionProvidersDialogOver:")] void ShowAddConnectionProvidersDialogOver(UIViewController viewController); // +(void)showAddConnectionProvidersPopoverFrom:(UIView *)view; [Static] [Export("showAddConnectionProvidersPopoverFrom:")] void ShowAddConnectionProvidersPopoverFrom(UIView view); // +(void)showAddConnectionProvidersDialogOver:(UIViewController *)viewController providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export("showAddConnectionProvidersDialogOver:providers:parameters:completionHandler:")] void ShowAddConnectionProvidersDialogOver(UIViewController viewController, string[] providers, NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)showAddConnectionProvidersPopoverFrom:(UIView *)view providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export("showAddConnectionProvidersPopoverFrom:providers:parameters:completionHandler:")] void ShowAddConnectionProvidersPopoverFrom(UIView view, string[] providers, NSDictionary parameters, [NullAllowed] GSUserInfoHandler handler); // +(void)removeConnectionToProvider:(NSString *)provider; [Static] [Export("removeConnectionToProvider:")] void RemoveConnectionToProvider(string provider); // +(void)removeConnectionToProvider:(NSString *)provider completionHandler:(GSUserInfoHandler)handler; [Static] [Export("removeConnectionToProvider:completionHandler:")] void RemoveConnectionToProvider(string provider, [NullAllowed] GSUserInfoHandler handler); // +(void)showPluginDialogOver:(UIViewController *)viewController plugin:(NSString *)plugin parameters:(NSDictionary *)parameters; [Static] [Export("showPluginDialogOver:plugin:parameters:")] void ShowPluginDialogOver(UIViewController viewController, string plugin, NSDictionary parameters); // +(void)showPluginDialogOver:(UIViewController *)viewController plugin:(NSString *)plugin parameters:(NSDictionary *)parameters completionHandler:(GSPluginCompletionHandler)handler; [Static] [Export("showPluginDialogOver:plugin:parameters:completionHandler:")] void ShowPluginDialogOver(UIViewController viewController, string plugin, NSDictionary parameters, GSPluginCompletionHandler handler); // +(void)showPluginDialogOver:(UIViewController *)viewController plugin:(NSString *)plugin parameters:(NSDictionary *)parameters completionHandler:(GSPluginCompletionHandler)handler delegate:(id<GSPluginViewDelegate>)delegate; [Static] [Export("showPluginDialogOver:plugin:parameters:completionHandler:delegate:")] void ShowPluginDialogOver(UIViewController viewController, string plugin, NSDictionary parameters, GSPluginCompletionHandler handler, GSPluginViewDelegate @delegate); // +(void)requestNewFacebookPublishPermissions:(NSString *)permissions viewController:(UIViewController * _Nullable)viewController responseHandler:(GSPermissionRequestResultHandler)handler; [Static] [Export("requestNewFacebookPublishPermissions:viewController:responseHandler:")] void RequestNewFacebookPublishPermissions(string permissions, [NullAllowed] UIViewController viewController, [NullAllowed] GSPermissionRequestResultHandler handler); // +(void)requestNewFacebookReadPermissions:(NSString *)permissions viewController:(UIViewController * _Nullable)viewController responseHandler:(GSPermissionRequestResultHandler)handler; [Static] [Export("requestNewFacebookReadPermissions:viewController:responseHandler:")] void RequestNewFacebookReadPermissions(string permissions, [NullAllowed] UIViewController viewController, [NullAllowed] GSPermissionRequestResultHandler handler); // +(BOOL)handleOpenURL:(NSURL *)url app:(UIApplication *)app options:(NSDictionary<NSString *,id> *)options; [Static] [Export("handleOpenURL:app:options:")] bool HandleOpenURL(NSUrl url, UIApplication app, NSDictionary<NSString, NSObject> options); // +(BOOL)handleOpenURL:(NSURL *)url application:(UIApplication *)application sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; [Static] [Export("handleOpenURL:application:sourceApplication:annotation:")] bool HandleOpenURL(NSUrl url, UIApplication application, [NullAllowed] string sourceApplication, [NullAllowed] NSObject annotation); // +(void)handleDidBecomeActive; [Static] [Export("handleDidBecomeActive")] void HandleDidBecomeActive(); // +(BOOL)useHTTPS; [Static] [Export("useHTTPS")] bool UseHTTPS(); // +(void)setUseHTTPS:(BOOL)useHTTPS; [Static] [Export("setUseHTTPS:")] void SetUseHTTPS(bool useHTTPS); // +(BOOL)networkActivityIndicatorEnabled; [Static] [Export("networkActivityIndicatorEnabled")] bool NetworkActivityIndicatorEnabled(); // +(void)setNetworkActivityIndicatorEnabled:(BOOL)networkActivityIndicatorEnabled; [Static] [Export("setNetworkActivityIndicatorEnabled:")] void SetNetworkActivityIndicatorEnabled(bool networkActivityIndicatorEnabled); // +(NSTimeInterval)requestTimeout; [Static] [Export("requestTimeout")] double RequestTimeout(); // +(void)setRequestTimeout:(NSTimeInterval)requestTimeout; [Static] [Export("setRequestTimeout:")] void SetRequestTimeout(double requestTimeout); // +(BOOL)dontLeaveApp; [Static] [Export("dontLeaveApp")] bool DontLeaveApp(); // +(void)setDontLeaveApp:(BOOL)dontLeaveApp; [Static] [Export("setDontLeaveApp:")] void SetDontLeaveApp(bool dontLeaveApp); // +(BOOL)__debugOptionEnableTestNetworks; [Static] [Export("__debugOptionEnableTestNetworks")] bool __debugOptionEnableTestNetworks(); // +(void)__setDebugOptionEnableTestNetworks:(BOOL)debugOptionEnableTestNetworks; [Static] [Export("__setDebugOptionEnableTestNetworks:")] void __setDebugOptionEnableTestNetworks(bool debugOptionEnableTestNetworks); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RabbitTemplate.cs" company="The original author or authors."> // Copyright 2002-2012 the original author or authors. // // 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #region Using Directives using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using Common.Logging; using RabbitMQ.Client; using Spring.Messaging.Amqp.Core; using Spring.Messaging.Amqp.Rabbit.Connection; using Spring.Messaging.Amqp.Rabbit.Support; using Spring.Messaging.Amqp.Support.Converter; using Spring.Util; #endregion namespace Spring.Messaging.Amqp.Rabbit.Core { /// <summary> /// <para> /// Helper class that simplifies synchronous RabbitMQ access (sending and receiving messages). /// </para> /// <para> /// The default settings are for non-transactional messaging, which reduces the amount of data exchanged with the broker. /// To use a new transaction for every send or receive set the {@link #setChannelTransacted(boolean) channelTransacted} /// flag. To extend the transaction over multiple invocations (more efficient), you can use a Spring transaction to /// bracket the calls (with <code>channelTransacted=true</code> as well). /// </para> /// <para> /// The only mandatory property is the {@link #setConnectionFactory(ConnectionFactory) ConnectionFactory}. There are /// strategies available for converting messages to and from Java objects ( /// {@link #setMessageConverter(MessageConverter) MessageConverter}) and for converting message headers (known as message /// properties in AMQP, see {@link #setMessagePropertiesConverter(MessagePropertiesConverter) MessagePropertiesConverter} /// ). The defaults probably do something sensible for typical use cases, as long as the message content-type is set /// appropriately. /// </para> /// <para> /// The "send" methods all have overloaded versions that allow you to explicitly target an exchange and a routing key, or /// you can set default values to be used in all send operations. The plain "receive" methods allow you to explicitly /// target a queue to receive from, or you can set a default value for the template that applies to all explicit /// receives. The convenience methods for send <b>and</b> receive use the sender defaults if no exchange or routing key /// is specified, but they always use a temporary queue for the receive leg, so the default queue is ignored. /// </para> /// </summary> /// <author>Mark Pollack</author> /// <author>Mark Fisher</author> /// <author>Dave Syer</author> /// <author>Joe Fitzgerald (.NET)</author> public class RabbitTemplate : RabbitAccessor, IRabbitOperations, IMessageListener, IPublisherCallbackChannelListener { /// <summary> /// The Logger. /// </summary> protected new static readonly ILog Logger = LogManager.GetCurrentClassLogger(); /// <summary> /// The default exchange. /// </summary> private static readonly string DEFAULT_EXCHANGE = string.Empty; // alias for amq.direct default exchange /// <summary> /// The default routing key. /// </summary> private static readonly string DEFAULT_ROUTING_KEY = string.Empty; /// <summary> /// The default reply timeout. /// </summary> private static readonly long DEFAULT_REPLY_TIMEOUT = 5000; /// <summary> /// The default encoding. /// </summary> private static readonly string DEFAULT_ENCODING = "UTF-8"; #region Fields /// <summary> /// The exchange /// </summary> private volatile string exchange = DEFAULT_EXCHANGE; /// <summary> /// The routing key. /// </summary> private volatile string routingKey = DEFAULT_ROUTING_KEY; /// <summary> /// The default queue name that will be used for synchronous receives. /// </summary> private volatile string queue; /// <summary> /// The reply timeout. /// </summary> private long replyTimeout = DEFAULT_REPLY_TIMEOUT; /// <summary> /// The message converter. /// </summary> private volatile IMessageConverter messageConverter = new SimpleMessageConverter(); /// <summary> /// The message properties converter. /// </summary> private volatile IMessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter(); /// <summary> /// The encoding. /// </summary> private volatile string encoding = DEFAULT_ENCODING; private volatile Queue replyQueue; private readonly IDictionary<string, BlockingCollection<Message>> replyHolder = new ConcurrentDictionary<string, BlockingCollection<Message>>(); private volatile IConfirmCallback confirmCallback; private volatile IReturnCallback returnCallback; private readonly IDictionary<object, SortedDictionary<long, PendingConfirm>> pendingConfirms = new ConcurrentDictionary<object, SortedDictionary<long, PendingConfirm>>(); private volatile bool mandatory; private volatile bool immediate; private readonly string uuid = Guid.NewGuid().ToString(); public static readonly string STACKED_CORRELATION_HEADER = "spring_reply_correlation"; public static readonly string STACKED_REPLY_TO_HEADER = "spring_reply_to"; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="RabbitTemplate"/> class. /// Convenient constructor for use with setter injection. Don't forget to set the connection factory. /// </summary> public RabbitTemplate() { this.InitDefaultStrategies(); } /// <summary>Initializes a new instance of the <see cref="RabbitTemplate"/> class. /// Create a rabbit template with default strategies and settings.</summary> /// <param name="connectionFactory">The connection factory to use.</param> public RabbitTemplate(IConnectionFactory connectionFactory) : this() { this.ConnectionFactory = connectionFactory; this.AfterPropertiesSet(); } #endregion /// <summary> /// Set up the default strategies. Subclasses can override if necessary. /// </summary> protected virtual void InitDefaultStrategies() { this.MessageConverter = new SimpleMessageConverter(); } #region Properties /// <summary> /// Sets Exchange. The name of the default exchange to use for send operations when none is specified. Defaults to <code>""</code> /// which is the default exchange in the broker (per the AMQP specification). /// </summary> /// <value>The exchange.</value> public string Exchange { set { this.exchange = value; } } /// <summary> /// Sets RoutingKey. The value of a default routing key to use for send operations when none is specified. Default is empty which is /// not helpful when using the default (or any direct) exchange, but fine if the exchange is a headers exchange for /// instance. /// </summary> /// <value>The routing key.</value> public string RoutingKey { set { this.routingKey = value; } } /// <summary> /// Sets Queue. The name of the default queue to receive messages from when none is specified explicitly. /// </summary> /// <value>The queue.</value> public string Queue { set { this.queue = value; } } /// <summary> /// Sets Encoding. The encoding to use when inter-converting between byte arrays and Strings in message properties. /// </summary> /// <value>The encoding.</value> public string Encoding { set { this.encoding = value; } } /// <summary> /// A queue for replies; if not provided, a temporary exclusive, auto-delete queue will be used for each reply. /// </summary> public Queue ReplyQueue { set { this.replyQueue = value; } } /// <summary> /// Sets the reply timeout. Specify the timeout in milliseconds to be used when waiting for a reply Message when using one of the /// sendAndReceive methods. The default value is defined as {@link #DEFAULT_REPLY_TIMEOUT}. A negative value /// indicates an indefinite timeout. Not used in the plain receive methods because there is no blocking receive /// operation defined in the protocol. /// </summary> /// <value>The reply timeout.</value> public long ReplyTimeout { set { this.replyTimeout = value; } } /// <summary>Gets or sets the message converter.</summary> public IMessageConverter MessageConverter { get { return this.messageConverter; } set { this.messageConverter = value; } } /// <summary> /// Sets the message properties converter. /// </summary> /// <value>The message properties converter.</value> public IMessagePropertiesConverter MessagePropertiesConverter { set { AssertUtils.ArgumentNotNull(value, "messagePropertiesConverter must not be null"); this.messagePropertiesConverter = value; } } /// <summary>Sets the confirm callback.</summary> public IConfirmCallback ConfirmCallback { set { this.confirmCallback = value; } } /// <summary>Sets the return callback.</summary> public IReturnCallback ReturnCallback { set { this.returnCallback = value; } } /// <summary>Sets a value indicating whether mandatory.</summary> public bool Mandatory { set { this.mandatory = value; } } /// <summary>Sets a value indicating whether immediate.</summary> public bool Immediate { set { this.immediate = value; } } /// <summary>Gets unconfirmed correlation data older than age and removes them.</summary> /// <param name="age">Age in millseconds</param> /// <returns>The collection of correlation data for which confirms have not been received.</returns> public HashSet<CorrelationData> GetUnconfirmed(long age) { var unconfirmed = new HashSet<CorrelationData>(); lock (this.pendingConfirms) { var threshold = DateTime.UtcNow.ToMilliseconds() - age; foreach (var channelPendingConfirmEntry in this.pendingConfirms) { var channelPendingConfirms = channelPendingConfirmEntry.Value; PendingConfirm pendingConfirm; var itemsToRemove = new Dictionary<long, PendingConfirm>(); foreach (var item in channelPendingConfirms) { pendingConfirm = item.Value; if (pendingConfirm.Timestamp < threshold) { unconfirmed.Add(pendingConfirm.CorrelationData); itemsToRemove.Add(item.Key, item.Value); } else { break; } } foreach (var item in itemsToRemove) { channelPendingConfirms.Remove(item.Key); } } } return unconfirmed.Count > 0 ? unconfirmed : null; } #endregion #region Implementation of IAmqpTemplate /// <summary>Send a message, given the message.</summary> /// <param name="message">The message.</param> public void Send(Message message) { this.Send(this.exchange, this.routingKey, message); } /// <summary>Send a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> public void Send(string routingKey, Message message) { this.Send(this.exchange, routingKey, message); } /// <summary>The send.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> public void Send(string exchange, string routingKey, Message message) { this.Send(exchange, routingKey, message, null); } /// <summary>Send a message, given an exchange, a routing key, and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="correlationData">The correlation Data.</param> public void Send(string exchange, string routingKey, Message message, CorrelationData correlationData) { this.Execute<object>( channel => { this.DoSend(channel, exchange, routingKey, message, correlationData); return null; }); } /// <summary>Convert and send a message, given the message.</summary> /// <param name="message">The message.</param> public void ConvertAndSend(object message) { this.ConvertAndSend(this.exchange, this.routingKey, message, (CorrelationData)null); } /// <summary>The convert and send.</summary> /// <param name="message">The message.</param> /// <param name="correlationData">The correlation data.</param> public void ConvertAndSend(object message, CorrelationData correlationData) { this.ConvertAndSend(this.exchange, this.routingKey, message, correlationData); } /// <summary>Convert and send a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> public void ConvertAndSend(string routingKey, object message) { this.ConvertAndSend(this.exchange, routingKey, message, (CorrelationData)null); } /// <summary>The convert and send.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="correlationData">The correlation data.</param> public void ConvertAndSend(string routingKey, object message, CorrelationData correlationData) { this.ConvertAndSend(this.exchange, routingKey, message, correlationData); } /// <summary>Convert and send a message, given an exchange, a routing key, and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> public void ConvertAndSend(string exchange, string routingKey, object message) { this.ConvertAndSend(exchange, routingKey, message, (CorrelationData)null); } /// <summary>The convert and send.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="correlationData">The correlation data.</param> public void ConvertAndSend(string exchange, string routingKey, object message, CorrelationData correlationData) { this.Send(exchange, routingKey, this.ConvertMessageIfNecessary(message), correlationData); } /// <summary>Convert and send a message, given the message.</summary> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> public void ConvertAndSend(object message, Func<Message, Message> messagePostProcessor) { this.ConvertAndSend(this.exchange, this.routingKey, message, messagePostProcessor, null); } /// <summary>The convert and send.</summary> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <param name="correlationData">The correlation data.</param> public void ConvertAndSend(object message, Func<Message, Message> messagePostProcessor, CorrelationData correlationData) { this.ConvertAndSend(this.exchange, this.routingKey, message, messagePostProcessor, correlationData); } /// <summary>Convert and send a message, given the message.</summary> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> public void ConvertAndSend(object message, IMessagePostProcessor messagePostProcessor) { this.ConvertAndSend(this.exchange, this.routingKey, message, messagePostProcessor, null); } /// <summary>The convert and send.</summary> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <param name="correlationData">The correlation data.</param> public void ConvertAndSend(object message, IMessagePostProcessor messagePostProcessor, CorrelationData correlationData) { this.ConvertAndSend(this.exchange, this.routingKey, message, messagePostProcessor, correlationData); } /// <summary>Convert and send a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> public void ConvertAndSend(string routingKey, object message, Func<Message, Message> messagePostProcessor) { this.ConvertAndSend(this.exchange, routingKey, message, messagePostProcessor, null); } /// <summary>The convert and send.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <param name="correlationData">The correlation data.</param> public void ConvertAndSend(string routingKey, object message, Func<Message, Message> messagePostProcessor, CorrelationData correlationData) { this.ConvertAndSend(this.exchange, routingKey, message, messagePostProcessor, correlationData); } /// <summary>Convert and send a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> public void ConvertAndSend(string routingKey, object message, IMessagePostProcessor messagePostProcessor) { this.ConvertAndSend(this.exchange, routingKey, message, messagePostProcessor, null); } /// <summary>The convert and send.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <param name="correlationData">The correlation data.</param> public void ConvertAndSend(string routingKey, object message, IMessagePostProcessor messagePostProcessor, CorrelationData correlationData) { this.ConvertAndSend(this.exchange, routingKey, message, messagePostProcessor, correlationData); } /// <summary>The convert and send.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> public void ConvertAndSend(string exchange, string routingKey, object message, Func<Message, Message> messagePostProcessor) { this.ConvertAndSend(exchange, routingKey, message, messagePostProcessor, null); } /// <summary>Convert and send a message, given an exchange, a routing key, and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <param name="correlationData">The correlation Data.</param> public void ConvertAndSend(string exchange, string routingKey, object message, Func<Message, Message> messagePostProcessor, CorrelationData correlationData) { var messageToSend = this.ConvertMessageIfNecessary(message); messageToSend = messagePostProcessor.Invoke(messageToSend); this.Send(exchange, routingKey, this.Execute(channel => messageToSend), correlationData); } /// <summary>The convert and send.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> public void ConvertAndSend(string exchange, string routingKey, object message, IMessagePostProcessor messagePostProcessor) { this.ConvertAndSend(exchange, routingKey, message, messagePostProcessor, null); } /// <summary>Convert and send a message, given an exchange, a routing key, and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <param name="correlationData">The correlation Data.</param> public void ConvertAndSend(string exchange, string routingKey, object message, IMessagePostProcessor messagePostProcessor, CorrelationData correlationData) { var messageToSend = this.ConvertMessageIfNecessary(message); messageToSend = messagePostProcessor.PostProcessMessage(messageToSend); this.Send(exchange, routingKey, this.Execute(channel => messageToSend), correlationData); } /// <summary> /// Receive a message. /// </summary> /// <returns>The message.</returns> public Message Receive() { return this.Receive(this.GetRequiredQueue()); } /// <summary>Receive a message, given the name of a queue.</summary> /// <param name="queueName">The queue name.</param> /// <returns>The message.</returns> public Message Receive(string queueName) { return this.Execute( channel => { var response = channel.BasicGet(queueName, !this.ChannelTransacted); // Response can be null is the case that there is no message on the queue. if (response != null) { var deliveryTag = response.DeliveryTag; if (this.ChannelLocallyTransacted(channel)) { channel.BasicAck(deliveryTag, false); channel.TxCommit(); } else if (this.ChannelTransacted) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.RegisterDeliveryTag( this.ConnectionFactory, channel, (long)deliveryTag); } var messageProps = this.messagePropertiesConverter.ToMessageProperties( response.BasicProperties, response, this.encoding); messageProps.MessageCount = (int)response.MessageCount; return new Message(response.Body, messageProps); } return null; }); } /// <summary> /// Receive and convert a message. /// </summary> /// <returns>The object.</returns> public object ReceiveAndConvert() { return this.ReceiveAndConvert(this.GetRequiredQueue()); } /// <summary>Receive and covert a message, given the name of a queue.</summary> /// <param name="queueName">The queue name.</param> /// <returns>The object.</returns> public object ReceiveAndConvert(string queueName) { var response = this.Receive(queueName); if (response != null) { return this.GetRequiredMessageConverter().FromMessage(response); } return null; } /// <summary>Send and receive a message, given the message.</summary> /// <param name="message">The message to send.</param> /// <returns>The message received.</returns> public Message SendAndReceive(Message message) { return this.DoSendAndReceive(this.exchange, this.routingKey, message); } /// <summary>Send and receive a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <returns>The message received.</returns> public Message SendAndReceive(string routingKey, Message message) { return this.DoSendAndReceive(this.exchange, routingKey, message); } /// <summary>Send and receive a message, given an exchange, a routing key, and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <returns>The message received.</returns> public Message SendAndReceive(string exchange, string routingKey, Message message) { return this.DoSendAndReceive(exchange, routingKey, message); } /// <summary>Convert, send, and receive a message, given the message.</summary> /// <param name="message">The message to send.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(object message) { return this.ConvertSendAndReceive(this.exchange, this.routingKey, message, default(IMessagePostProcessor)); } /// <summary>Convert, send, and receive a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(string routingKey, object message) { return this.ConvertSendAndReceive(this.exchange, routingKey, message, default(IMessagePostProcessor)); } /// <summary>Convert, send, and receive a message, given an exchange, a routing key and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(string exchange, string routingKey, object message) { return this.ConvertSendAndReceive(exchange, routingKey, message, default(IMessagePostProcessor)); } /// <summary>Convert, send, and receive a message, given the message.</summary> /// <param name="message">The message to send.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(object message, Func<Message, Message> messagePostProcessor) { return this.ConvertSendAndReceive(this.exchange, this.routingKey, message, messagePostProcessor); } /// <summary>Convert, send, and receive a message, given the message.</summary> /// <param name="message">The message to send.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(object message, IMessagePostProcessor messagePostProcessor) { return this.ConvertSendAndReceive(this.exchange, this.routingKey, message, messagePostProcessor); } /// <summary>Convert, send, and receive a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(string routingKey, object message, Func<Message, Message> messagePostProcessor) { return this.ConvertSendAndReceive(this.exchange, routingKey, message, messagePostProcessor); } /// <summary>Convert, send, and receive a message, given a routing key and the message.</summary> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(string routingKey, object message, IMessagePostProcessor messagePostProcessor) { return this.ConvertSendAndReceive(this.exchange, routingKey, message, messagePostProcessor); } /// <summary>Convert, send, and receive a message, given an exchange, a routing key and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(string exchange, string routingKey, object message, Func<Message, Message> messagePostProcessor) { var requestMessage = this.ConvertMessageIfNecessary(message); if (messagePostProcessor != null) { requestMessage = messagePostProcessor.Invoke(requestMessage); } var replyMessage = this.DoSendAndReceive(exchange, routingKey, requestMessage); if (replyMessage == null) { return null; } return this.GetRequiredMessageConverter().FromMessage(replyMessage); } /// <summary>Convert, send, and receive a message, given an exchange, a routing key and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <param name="messagePostProcessor">The message post processor.</param> /// <returns>The message received.</returns> public object ConvertSendAndReceive(string exchange, string routingKey, object message, IMessagePostProcessor messagePostProcessor) { var requestMessage = this.ConvertMessageIfNecessary(message); if (messagePostProcessor != null) { requestMessage = messagePostProcessor.PostProcessMessage(requestMessage); } var replyMessage = this.DoSendAndReceive(exchange, routingKey, requestMessage); if (replyMessage == null) { return null; } return this.GetRequiredMessageConverter().FromMessage(replyMessage); } /// <summary>The convert message if necessary.</summary> /// <param name="message">The message.</param> /// <returns>The Spring.Messaging.Amqp.Core.Message.</returns> protected Message ConvertMessageIfNecessary(object message) { if (message is Message) { return (Message)message; } return this.GetRequiredMessageConverter().ToMessage(message, new MessageProperties()); } /// <summary>The do send and receive.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <returns>The Spring.Messaging.Amqp.Core.Message.</returns> protected Message DoSendAndReceive(string exchange, string routingKey, Message message) { if (this.replyQueue == null) { return this.DoSendAndReceiveWithTemporary(exchange, routingKey, message); } else { return this.DoSendAndReceiveWithFixed(exchange, routingKey, message); } } /// <summary>Do the send and receive operation, given an exchange, a routing key and the message.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message to send.</param> /// <returns>The message received.</returns> protected Message DoSendAndReceiveWithTemporary(string exchange, string routingKey, Message message) { var replyMessage = this.Execute( delegate(IModel channel) { var replyHandoff = new BlockingCollection<Message>(); AssertUtils.IsTrue(message.MessageProperties.ReplyTo == null, "Send-and-receive methods can only be used if the Message does not already have a replyTo property."); var queueDeclaration = channel.QueueDeclare(); var replyTo = queueDeclaration.QueueName; message.MessageProperties.ReplyTo = replyTo; var noAck = true; var consumerTag = Guid.NewGuid().ToString(); var noLocal = true; var exclusive = true; var consumer = new SendAndReceiveDefaultConsumer(channel, replyHandoff, this.encoding, this.messagePropertiesConverter); channel.BasicConsume(replyTo, noAck, consumerTag, noLocal, exclusive, null, consumer); this.DoSend(channel, exchange, routingKey, message, null); var reply = (this.replyTimeout < 0) ? replyHandoff.Take() : replyHandoff.Poll((int)this.replyTimeout); channel.BasicCancel(consumerTag); return reply; }); return replyMessage; } /// <summary>The do send and receive with fixed.</summary> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <returns>The Spring.Messaging.Amqp.Core.Message.</returns> protected Message DoSendAndReceiveWithFixed(string exchange, string routingKey, Message message) { var replyMessage = this.Execute( delegate(IModel channel) { var replyHandoff = new BlockingCollection<Message>(); var messageTag = Guid.NewGuid().ToString(); this.replyHolder.Add(messageTag, replyHandoff); var replyTo = message.MessageProperties.ReplyTo; if (!string.IsNullOrWhiteSpace(replyTo)) { Logger.Debug(m => m("Dropping replyTo header:{0} in favor of template's configured reply-queue:{1}", replyTo, this.replyQueue.Name)); } var springReplyTo = (string)message.MessageProperties.Headers.Get(STACKED_REPLY_TO_HEADER); message.MessageProperties.SetHeader(STACKED_REPLY_TO_HEADER, this.PushHeaderValue(replyTo, springReplyTo)); message.MessageProperties.ReplyTo = this.replyQueue.Name; var correlation = (string)message.MessageProperties.Headers.Get(STACKED_CORRELATION_HEADER); if (!string.IsNullOrWhiteSpace(correlation)) { message.MessageProperties.SetHeader(STACKED_CORRELATION_HEADER, this.PushHeaderValue(messageTag, correlation)); } else { message.MessageProperties.SetHeader("spring_reply_correlation", messageTag); } Logger.Debug("Sending message with tag " + messageTag); this.DoSend(channel, exchange, routingKey, message, null); var reply = (this.replyTimeout < 0) ? replyHandoff.Take() : replyHandoff.Poll((int)this.replyTimeout); this.replyHolder.Remove(messageTag); return reply; }); return replyMessage; } #endregion #region Implementation of IRabbitOperations /// <summary>Execute an action.</summary> /// <typeparam name="T">Type T</typeparam> /// <param name="action">The action.</param> /// <returns>An object of Type T</returns> public T Execute<T>(ChannelCallbackDelegate<T> action) { AssertUtils.ArgumentNotNull(action, "Callback object must not be null"); var resourceHolder = this.GetTransactionalResourceHolder(); var channel = resourceHolder.Channel; if (this.confirmCallback != null || this.returnCallback != null) { this.AddListener(channel); } try { Logger.Debug(m => m("Executing callback on RabbitMQ Channel: {0}", channel)); return action(channel); } catch (Exception ex) { if (this.ChannelLocallyTransacted(channel)) { resourceHolder.RollbackAll(); } throw this.ConvertRabbitAccessException(ex); } finally { ConnectionFactoryUtils.ReleaseResources(resourceHolder); } } /// <summary>Execute an action.</summary> /// <typeparam name="T">Type T</typeparam> /// <param name="action">The action.</param> /// <returns>An object of Type T</returns> public T Execute<T>(IChannelCallback<T> action) { return Execute(action.DoInRabbit); } #endregion /// <summary>Do the send operation.</summary> /// <param name="channel">The channel.</param> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="message">The message.</param> /// <param name="correlationData">The correlation Data.</param> protected void DoSend(IModel channel, string exchange, string routingKey, Message message, CorrelationData correlationData) { Logger.Debug(m => m("Publishing message on exchange [{0}], routingKey = [{1}]", exchange, routingKey)); if (exchange == null) { // try to send to configured exchange exchange = this.exchange; } if (routingKey == null) { // try to send to configured routing key routingKey = this.routingKey; } if (this.confirmCallback != null && channel is IPublisherCallbackChannel) { var publisherCallbackChannel = (IPublisherCallbackChannel)channel; publisherCallbackChannel.AddPendingConfirm(this, (long)channel.NextPublishSeqNo, new PendingConfirm(correlationData, DateTime.UtcNow.ToMilliseconds())); } var mandatory = this.returnCallback == null ? false : this.mandatory; var immediate = this.returnCallback == null ? false : this.immediate; var messageProperties = message.MessageProperties; if (mandatory || immediate) { messageProperties.Headers.Add("spring_return_correlation", this.uuid); } var convertedMessageProperties = this.messagePropertiesConverter.FromMessageProperties(channel, message.MessageProperties, this.encoding); channel.BasicPublish(exchange, routingKey, mandatory, immediate, convertedMessageProperties, message.Body); // Check commit is needed. if (this.ChannelLocallyTransacted(channel)) { // Transacted channel created by this template -> commit. RabbitUtils.CommitIfNecessary(channel); } } /// <summary>Flag indicating whether the channel is locally transacted.</summary> /// <param name="channel">The channel.</param> /// <returns>True if locally transacted, else false.</returns> protected bool ChannelLocallyTransacted(IModel channel) { return this.ChannelTransacted && !ConnectionFactoryUtils.IsChannelTransactional(channel, this.ConnectionFactory); } /// <summary> /// Get the required message converter. /// </summary> /// <returns>The message converter.</returns> private IMessageConverter GetRequiredMessageConverter() { var converter = this.MessageConverter; if (converter == null) { throw new AmqpIllegalStateException("No 'messageConverter' specified. Check configuration of RabbitTemplate."); } return converter; } /// <summary> /// Get the required queue. /// </summary> /// <returns>The name of the queue.</returns> private string GetRequiredQueue() { var name = this.queue; if (name == null) { throw new AmqpIllegalStateException("No 'queue' specified. Check configuration of RabbitTemplate."); } return name; } private void AddListener(IModel channel) { if (channel is IPublisherCallbackChannel) { var publisherCallbackChannel = (IPublisherCallbackChannel)channel; var pendingConfirm = publisherCallbackChannel.AddListener(this); if (!this.pendingConfirms.ContainsKey(channel)) { this.pendingConfirms.Add(channel, pendingConfirm); Logger.Debug(m => m("Added pending confirms for {0} to map, size now {1}", channel, this.pendingConfirms.Count)); } } else { throw new AmqpIllegalStateException("Channel does not support confirms or returns; is the connection factory configured for confirms or returns?"); } } /// <summary>The handle confirm.</summary> /// <param name="pendingConfirm">The pending confirm.</param> /// <param name="ack">The ack.</param> public void HandleConfirm(PendingConfirm pendingConfirm, bool ack) { if (this.confirmCallback != null) { this.confirmCallback.Confirm(pendingConfirm.CorrelationData, ack); } else { Logger.Warn(m => m("Confirm received but no callback available")); } } /// <summary>The handle return.</summary> /// <param name="replyCode">The reply code.</param> /// <param name="replyText">The reply text.</param> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="properties">The properties.</param> /// <param name="body">The body.</param> public void HandleReturn(int replyCode, string replyText, string exchange, string routingKey, IBasicProperties properties, byte[] body) { if (this.returnCallback == null) { Logger.Warn(m => m("Returned message but no callback available")); } else { properties.Headers.Remove("spring_return_correlation"); var messageProperties = this.messagePropertiesConverter.ToMessageProperties(properties, null, this.encoding); var returnedMessage = new Message(body, messageProperties); this.returnCallback.ReturnedMessage(returnedMessage, replyCode, replyText, exchange, routingKey); } } /// <summary>The is confirm listener.</summary> /// <returns>The System.Boolean.</returns> public bool IsConfirmListener { get { return this.confirmCallback != null; } } /// <summary>The is return listener.</summary> /// <returns>The System.Boolean.</returns> public bool IsReturnListener { get { return this.returnCallback != null; } } /// <summary>The remove pending confirms reference.</summary> /// <param name="channel">The channel.</param> /// <param name="unconfirmed">The unconfirmed.</param> public void RemovePendingConfirmsReference(IModel channel, SortedDictionary<long, PendingConfirm> unconfirmed) { this.pendingConfirms.Remove(channel); Logger.Debug(m => m("Removed pending confirms for {0} from map, size now {1}", channel, this.pendingConfirms.Count)); } /// <summary>Gets the uuid.</summary> public string Uuid { get { return this.uuid; } } /// <summary>The on message.</summary> /// <param name="message">The message.</param> public void OnMessage(Message message) { var messageTag = (string)message.MessageProperties.Headers.Get(STACKED_CORRELATION_HEADER); if (messageTag == null) { Logger.Error("No correlation header in reply"); return; } var poppedHeaderValue = this.PopHeaderValue(messageTag); messageTag = poppedHeaderValue.PoppedValue; message.MessageProperties.SetHeader(STACKED_CORRELATION_HEADER, poppedHeaderValue.NewValue); var springReplyTo = (string)message.MessageProperties.Headers.Get(STACKED_REPLY_TO_HEADER); if (springReplyTo != null) { poppedHeaderValue = this.PopHeaderValue(springReplyTo); springReplyTo = poppedHeaderValue.NewValue; message.MessageProperties.SetHeader(STACKED_REPLY_TO_HEADER, springReplyTo); message.MessageProperties.ReplyTo = null; } var queue = this.replyHolder.Get(messageTag); if (queue == null) { Logger.Warn(m => m("Reply received after timeout for {0}", messageTag)); return; } queue.Add(message); Logger.Debug(m => m("Reply received for {0}", messageTag)); } private string PushHeaderValue(string newValue, string oldValue) { if (oldValue == null) { return newValue; } else { return newValue + ":" + oldValue; } } private PoppedHeader PopHeaderValue(string value) { int index = value.IndexOf(":", StringComparison.Ordinal); if (index < 0) { return new PoppedHeader(value, null); } else { return new PoppedHeader(value.Substring(0, index), value.Substring(index + 1)); } } } internal class PoppedHeader { private readonly string poppedValue; private readonly string newValue; /// <summary>Initializes a new instance of the <see cref="PoppedHeader"/> class.</summary> /// <param name="poppedValue">The popped value.</param> /// <param name="newValue">The new value.</param> public PoppedHeader(string poppedValue, string newValue) { this.poppedValue = poppedValue; if (!string.IsNullOrWhiteSpace(newValue)) { this.newValue = newValue; } else { this.newValue = null; } } /// <summary>Gets the popped value.</summary> public string PoppedValue { get { return this.poppedValue; } } /// <summary>Gets the new value.</summary> public string NewValue { get { return this.newValue; } } } /// <summary> /// The admin default basic consumer. /// </summary> internal class SendAndReceiveDefaultConsumer : DefaultBasicConsumer { private static readonly ILog Logger = LogManager.GetCurrentClassLogger(); /// <summary> /// The reply handoff. /// </summary> private readonly BlockingCollection<Message> replyHandoff; /// <summary> /// The encoding. /// </summary> private readonly string encoding; /// <summary> /// The message properties converter. /// </summary> private readonly IMessagePropertiesConverter messagePropertiesConverter; /// <summary>Initializes a new instance of the <see cref="SendAndReceiveDefaultConsumer"/> class.</summary> /// <param name="channel">The channel.</param> /// <param name="replyHandoff">The reply handoff.</param> /// <param name="encoding">The encoding.</param> /// <param name="messagePropertiesConverter">The message properties converter.</param> public SendAndReceiveDefaultConsumer(IModel channel, BlockingCollection<Message> replyHandoff, string encoding, IMessagePropertiesConverter messagePropertiesConverter) : base(channel) { this.replyHandoff = replyHandoff; this.encoding = encoding; this.messagePropertiesConverter = messagePropertiesConverter; } /// <summary>Handle delivery.</summary> /// <param name="consumerTag">The consumer tag.</param> /// <param name="envelope">The envelope.</param> /// <param name="properties">The properties.</param> /// <param name="body">The body.</param> public void HandleDelivery(string consumerTag, BasicGetResult envelope, IBasicProperties properties, byte[] body) { var messageProperties = this.messagePropertiesConverter.ToMessageProperties(properties, envelope, this.encoding); var reply = new Message(body, messageProperties); Logger.Trace(m => m("Message received {0}", reply)); try { this.replyHandoff.Add(reply); } catch (ThreadInterruptedException e) { Thread.CurrentThread.Interrupt(); } } /// <summary>Handle basic deliver.</summary> /// <param name="consumerTag">The consumer tag.</param> /// <param name="deliveryTag">The delivery tag.</param> /// <param name="redelivered">The redelivered.</param> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="properties">The properties.</param> /// <param name="body">The body.</param> public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body) { var envelope = new BasicGetResult(deliveryTag, redelivered, exchange, routingKey, 1, properties, body); this.HandleDelivery(consumerTag, envelope, properties, body); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplyNoFlagsUInt64BinRes() { var test = new ScalarTernOpBinResTest__MultiplyNoFlagsUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ScalarTernOpBinResTest__MultiplyNoFlagsUInt64 { private struct TestStruct { public UInt64 _fld1; public UInt64 _fld2; public UInt64 _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld1 = UInt64.MaxValue; testStruct._fld2 = UInt64.MaxValue; testStruct._fld3 = 0; return testStruct; } public void RunStructFldScenario(ScalarTernOpBinResTest__MultiplyNoFlagsUInt64 testClass) { UInt64 buffer = 0; var result = Bmi2.X64.MultiplyNoFlags(_fld1, _fld2, &buffer); testClass.ValidateResult(_fld1, _fld2, buffer, result); } } private static UInt64 _data1; private static UInt64 _data2; private static UInt64 _data3; private static UInt64 _clsVar1; private static UInt64 _clsVar2; private static UInt64 _clsVar3; private UInt64 _fld1; private UInt64 _fld2; private UInt64 _fld3; static ScalarTernOpBinResTest__MultiplyNoFlagsUInt64() { _clsVar1 = UInt64.MaxValue; _clsVar2 = UInt64.MaxValue; _clsVar3 = 0; } public ScalarTernOpBinResTest__MultiplyNoFlagsUInt64() { Succeeded = true; _fld1 = UInt64.MaxValue; _fld2 = UInt64.MaxValue; _fld3 = 0; _data1 = UInt64.MaxValue; _data2 = UInt64.MaxValue; _data3 = 0; } public bool IsSupported => Bmi2.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); UInt64 buffer = 0; var result = Bmi2.X64.MultiplyNoFlags( Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)), Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2)), &buffer ); ValidateResult(_data1, _data2, buffer, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); UInt64 buffer = 0; var result = typeof(Bmi2.X64).GetMethod(nameof(Bmi2.X64.MultiplyNoFlags), new Type[] { typeof(UInt64), typeof(UInt64), typeof(UInt64*) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)), Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2)), Pointer.Box(&buffer, typeof(UInt64*)) }); ValidateResult(_data1, _data2, buffer, (UInt64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); UInt64 buffer = 0; var result = Bmi2.X64.MultiplyNoFlags( _clsVar1, _clsVar2, &buffer ); ValidateResult(_clsVar1, _clsVar2, buffer, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)); var data2 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2)); var data3 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data3)); var result = Bmi2.X64.MultiplyNoFlags(data1, data2, &data3); ValidateResult(data1, data2, data3, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); UInt64 buffer = 0; var test = new ScalarTernOpBinResTest__MultiplyNoFlagsUInt64(); var result = Bmi2.X64.MultiplyNoFlags(test._fld1, test._fld2, &buffer); ValidateResult(test._fld1, test._fld2, buffer, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); UInt64 buffer = 0; var result = Bmi2.X64.MultiplyNoFlags(_fld1, _fld2, &buffer); ValidateResult(_fld1, _fld2, buffer, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Bmi2.X64.MultiplyNoFlags(test._fld1, test._fld2, &test._fld3); ValidateResult(test._fld1, test._fld2, test._fld3, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(UInt64 op1, UInt64 op2, UInt64 lower, UInt64 higher, [CallerMemberName] string method = "") { var isUnexpectedResult = false; ulong expectedHigher = 18446744073709551614, expectedLower = 1; isUnexpectedResult = (expectedHigher != higher) || (expectedLower != lower); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(Bmi2.X64)}.{nameof(Bmi2.X64.MultiplyNoFlags)}<UInt64>(UInt64, UInt64, UInt64): MultiplyNoFlags failed:"); TestLibrary.TestFramework.LogInformation($" op1: {op1}"); TestLibrary.TestFramework.LogInformation($" op2: {op2}"); TestLibrary.TestFramework.LogInformation($" lower: {lower}"); TestLibrary.TestFramework.LogInformation($"higher: {higher}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) 2004-2017 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__ && !NETSTANDARD namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security; using System.Security.Principal; using Common; using Internal; /// <summary> /// Impersonates another user for the duration of the write. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/ImpersonatingWrapper-target">Documentation on NLog Wiki</seealso> [SecuritySafeCritical] [Target("ImpersonatingWrapper", IsWrapper = true)] public class ImpersonatingTargetWrapper : WrapperTargetBase { private WindowsIdentity newIdentity; private IntPtr duplicateTokenHandle = IntPtr.Zero; /// <summary> /// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class. /// </summary> public ImpersonatingTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public ImpersonatingTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public ImpersonatingTargetWrapper(Target wrappedTarget) { Domain = "."; LogOnType = SecurityLogOnType.Interactive; LogOnProvider = LogOnProviderType.Default; ImpersonationLevel = SecurityImpersonationLevel.Impersonation; WrappedTarget = wrappedTarget; } /// <summary> /// Gets or sets username to change context to. /// </summary> /// <docgen category='Impersonation Options' order='10' /> public string UserName { get; set; } /// <summary> /// Gets or sets the user account password. /// </summary> /// <docgen category='Impersonation Options' order='10' /> public string Password { get; set; } /// <summary> /// Gets or sets Windows domain name to change context to. /// </summary> /// <docgen category='Impersonation Options' order='10' /> [DefaultValue(".")] public string Domain { get; set; } /// <summary> /// Gets or sets the Logon Type. /// </summary> /// <docgen category='Impersonation Options' order='10' /> public SecurityLogOnType LogOnType { get; set; } /// <summary> /// Gets or sets the type of the logon provider. /// </summary> /// <docgen category='Impersonation Options' order='10' /> public LogOnProviderType LogOnProvider { get; set; } /// <summary> /// Gets or sets the required impersonation level. /// </summary> /// <docgen category='Impersonation Options' order='10' /> public SecurityImpersonationLevel ImpersonationLevel { get; set; } /// <summary> /// Gets or sets a value indicating whether to revert to the credentials of the process instead of impersonating another user. /// </summary> /// <docgen category='Impersonation Options' order='10' /> [DefaultValue(false)] public bool RevertToSelf { get; set; } /// <summary> /// Initializes the impersonation context. /// </summary> protected override void InitializeTarget() { if (!RevertToSelf) { newIdentity = CreateWindowsIdentity(out duplicateTokenHandle); } using (DoImpersonate()) { base.InitializeTarget(); } } /// <summary> /// Closes the impersonation context. /// </summary> protected override void CloseTarget() { using (DoImpersonate()) { base.CloseTarget(); } if (duplicateTokenHandle != IntPtr.Zero) { NativeMethods.CloseHandle(duplicateTokenHandle); duplicateTokenHandle = IntPtr.Zero; } if (newIdentity != null) { newIdentity.Dispose(); newIdentity = null; } } /// <summary> /// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write() /// and switches the context back to original. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { using (DoImpersonate()) { WrappedTarget.WriteAsyncLogEvent(logEvent); } } /// <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> /// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write() /// and switches the context back to original. /// </summary> /// <param name="logEvents">Log events.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { using (DoImpersonate()) { WrappedTarget.WriteAsyncLogEvents(logEvents); } } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { using (DoImpersonate()) { WrappedTarget.Flush(asyncContinuation); } } private IDisposable DoImpersonate() { if (RevertToSelf) { return new ContextReverter(WindowsIdentity.Impersonate(IntPtr.Zero)); } return new ContextReverter(newIdentity.Impersonate()); } // // adapted from: // http://www.codeproject.com/csharp/cpimpersonation1.asp // private WindowsIdentity CreateWindowsIdentity(out IntPtr handle) { // initialize tokens IntPtr logonHandle; if (!NativeMethods.LogonUser( UserName, Domain, Password, (int)LogOnType, (int)LogOnProvider, out logonHandle)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } if (!NativeMethods.DuplicateToken(logonHandle, (int)ImpersonationLevel, out handle)) { NativeMethods.CloseHandle(logonHandle); throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } NativeMethods.CloseHandle(logonHandle); // create new identity using new primary token) return new WindowsIdentity(handle); } /// <summary> /// Helper class which reverts the given <see cref="WindowsImpersonationContext"/> /// to its original value as part of <see cref="IDisposable.Dispose"/>. /// </summary> internal class ContextReverter : IDisposable { private WindowsImpersonationContext wic; /// <summary> /// Initializes a new instance of the <see cref="ContextReverter" /> class. /// </summary> /// <param name="windowsImpersonationContext">The windows impersonation context.</param> public ContextReverter(WindowsImpersonationContext windowsImpersonationContext) { wic = windowsImpersonationContext; } /// <summary> /// Reverts the impersonation context. /// </summary> public void Dispose() { wic.Undo(); } } } } #endif
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using System.Threading.Tasks; using System.Threading; using Cassandra.IntegrationTests.TestBase; using Cassandra.Tests; using NUnit.Framework; namespace Cassandra.IntegrationTests.Core { /// <summary> /// Validates that the Session.GetRequest (called within ExecuteAsync) method uses the paging size under different scenarios /// </summary> [Category(TestCategory.Short), Category(TestCategory.RealCluster), Category(TestCategory.ServerApi)] public class PagingTests : SharedClusterTest { public override void OneTimeSetUp() { base.OneTimeSetUp(); CreateSimpleTableAndInsert(300, "tbl_parallel_paging_read"); } [Test] [TestCassandraVersion(2, 0)] public void Should_NotUseDefaultPageSize_When_SetOnClusterBulder() { var pageSize = 10; var queryOptions = new QueryOptions().SetPageSize(pageSize); var builder = ClusterBuilder().WithQueryOptions(queryOptions).WithDefaultKeyspace(KeyspaceName); builder.AddContactPoint(TestCluster.InitialContactPoint); const int totalRowLength = 1003; using (var session = builder.Build().Connect()) { var tableNameAndStaticKeyVal = CreateTableWithCompositeIndexAndInsert(session, totalRowLength); var statementToBeBound = $"SELECT * from {tableNameAndStaticKeyVal.Item1} where label=?"; var preparedStatementWithoutPaging = session.Prepare(statementToBeBound); var preparedStatementWithPaging = session.Prepare(statementToBeBound); var boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(tableNameAndStaticKeyVal.Item2); var boundStatemetWithPaging = preparedStatementWithPaging.Bind(tableNameAndStaticKeyVal.Item2); var rsWithSessionPagingInherited = session.ExecuteAsync(boundStatemetWithPaging).Result; var rsWithoutPagingInherited = Session.Execute(boundStatemetWithoutPaging); //Check that the internal list of items count is pageSize Assert.AreEqual(pageSize, rsWithSessionPagingInherited.InnerQueueCount); Assert.AreEqual(totalRowLength, rsWithoutPagingInherited.InnerQueueCount); var allTheRowsPaged = rsWithSessionPagingInherited.ToList(); Assert.AreEqual(totalRowLength, allTheRowsPaged.Count); } } [Test] [TestCassandraVersion(2, 0)] public void Should_PagingOnBoundStatement_When_ReceivedNumberOfRowsIsHigherThanPageSize() { var pageSize = 10; var totalRowLength = 1003; var tableNameAndStaticKeyVal = CreateTableWithCompositeIndexAndInsert(Session, totalRowLength); var statementToBeBound = $"SELECT * from {tableNameAndStaticKeyVal.Item1} where label=?"; var preparedStatementWithoutPaging = Session.Prepare(statementToBeBound); var preparedStatementWithPaging = Session.Prepare(statementToBeBound); var boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(tableNameAndStaticKeyVal.Item2); var boundStatemetWithPaging = preparedStatementWithPaging.Bind(tableNameAndStaticKeyVal.Item2); boundStatemetWithPaging.SetPageSize(pageSize); var rsWithPaging = Session.Execute(boundStatemetWithPaging); var rsWithoutPaging = Session.Execute(boundStatemetWithoutPaging); //Check that the internal list of items count is pageSize Assert.AreEqual(pageSize, rsWithPaging.InnerQueueCount); Assert.AreEqual(totalRowLength, rsWithoutPaging.InnerQueueCount); var allTheRowsPaged = rsWithPaging.ToList(); Assert.AreEqual(totalRowLength, allTheRowsPaged.Count); } [Test] [TestCassandraVersion(2, 0)] public void Should_PagingOnBoundStatement_When_ReceivedNumberOfRowsIsOne() { var pageSize = 10; var totalRowLength = 11; var tableName = CreateSimpleTableAndInsert(totalRowLength); // insert a guid that we'll keep track of var guid = Guid.NewGuid(); Session.Execute(string.Format("INSERT INTO {2} (id, label) VALUES({0},'{1}')", guid, "LABEL_12345", tableName)); var statementToBeBound = "SELECT * from " + tableName + " where id=?"; var preparedStatementWithoutPaging = Session.Prepare(statementToBeBound); var preparedStatementWithPaging = Session.Prepare(statementToBeBound); var boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(guid); var boundStatemetWithPaging = preparedStatementWithPaging.Bind(guid); boundStatemetWithPaging.SetPageSize(pageSize); var rsWithPaging = Session.Execute(boundStatemetWithPaging); var rsWithoutPaging = Session.Execute(boundStatemetWithoutPaging); //Check that the internal list of items count is pageSize Assert.AreEqual(1, rsWithPaging.InnerQueueCount); Assert.AreEqual(1, rsWithoutPaging.InnerQueueCount); var allTheRowsPaged = rsWithPaging.ToList(); Assert.AreEqual(1, allTheRowsPaged.Count); } [Test] [TestCassandraVersion(4, 0)] public void Should_PagingOnBoundStatement_When_NewResultMetadataIsSet() { if (Session.Cluster.Metadata.ControlConnection.Serializer.CurrentProtocolVersion < ProtocolVersion.V5) { Assert.Ignore("This test requires protocol v5+"); return; } var pageSize = 10; var totalRowLength = 25; var tableName = CreateSimpleTableAndInsert(totalRowLength); var statementToBeBound = "SELECT * from " + tableName; var ps = Session.Prepare(statementToBeBound); var allRows = Session.Execute(ps.Bind()).ToList(); var previousResultMetadata = ps.ResultMetadata; Assert.AreEqual(totalRowLength, allRows.Count); Assert.IsTrue(allRows.All(r => !r.ContainsColumn("new_column"))); Assert.AreEqual(2, previousResultMetadata.RowSetMetadata.Columns.Length); var boundStatementManualPaging = ps.Bind().SetPageSize(pageSize).SetAutoPage(false); var rs = Session.Execute(boundStatementManualPaging); var firstPage = rs.ToList(); Session.Execute($"ALTER TABLE {tableName} ADD (new_column text)"); Assert.AreSame(previousResultMetadata, ps.ResultMetadata); Assert.AreEqual(previousResultMetadata.ResultMetadataId, ps.ResultMetadata.ResultMetadataId); Assert.AreEqual(2, ps.ResultMetadata.RowSetMetadata.Columns.Length); rs = Session.Execute(boundStatementManualPaging.SetPagingState(rs.PagingState)); var secondPage = rs.ToList(); Assert.AreNotSame(previousResultMetadata, ps.ResultMetadata); Assert.AreNotEqual(previousResultMetadata.ResultMetadataId, ps.ResultMetadata.ResultMetadataId); Assert.AreEqual(3, ps.ResultMetadata.RowSetMetadata.Columns.Length); rs = Session.Execute(boundStatementManualPaging.SetPagingState(rs.PagingState)); var thirdPage = rs.ToList(); var allRowsAfterAlter = Session.Execute(ps.Bind()).ToList(); Assert.AreEqual(totalRowLength, allRowsAfterAlter.Count); Assert.AreEqual(pageSize, firstPage.Count); Assert.AreEqual(pageSize, secondPage.Count); Assert.AreEqual(totalRowLength-(pageSize*2), thirdPage.Count); Assert.IsTrue(firstPage.All(r => !r.ContainsColumn("new_column"))); Assert.IsTrue(secondPage.All(r => r.ContainsColumn("new_column") && r.GetValue<string>("new_column") == null)); Assert.IsTrue(allRowsAfterAlter.All(r => r.ContainsColumn("new_column") && r.GetValue<string>("new_column") == null)); } [Test] [TestCassandraVersion(2, 0)] public void Should_PagingOnBoundStatement_When_ReceivedNumberOfRowsIsZero() { var pageSize = 10; var totalRowLength = 11; var tableName = CreateSimpleTableAndInsert(totalRowLength); // insert a guid that we'll keep track of var guid = Guid.NewGuid(); var statementToBeBound = $"SELECT * from {tableName} where id=?"; var preparedStatementWithoutPaging = Session.Prepare(statementToBeBound); var preparedStatementWithPaging = Session.Prepare(statementToBeBound); var boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(guid); var boundStatemetWithPaging = preparedStatementWithPaging.Bind(guid); boundStatemetWithPaging.SetPageSize(pageSize); var rsWithPaging = Session.Execute(boundStatemetWithPaging); var rsWithoutPaging = Session.Execute(boundStatemetWithoutPaging); //Check that the internal list of items count is pageSize Assert.AreEqual(0, rsWithPaging.InnerQueueCount); Assert.AreEqual(0, rsWithoutPaging.InnerQueueCount); var allTheRowsPaged = rsWithPaging.ToList(); Assert.AreEqual(0, allTheRowsPaged.Count); } [Test] [TestCassandraVersion(2, 0)] public void Should_PagingOnSimpleStatement_When_ReceivedNumberOfRowsIsHigherThanPageSize() { var pageSize = 10; var totalRowLength = 1003; var table = CreateSimpleTableAndInsert(totalRowLength); var statementWithPaging = new SimpleStatement($"SELECT * FROM {table}"); var statementWithoutPaging = new SimpleStatement($"SELECT * FROM {table}"); statementWithoutPaging.SetPageSize(int.MaxValue); statementWithPaging.SetPageSize(pageSize); var rsWithPaging = Session.Execute(statementWithPaging); var rsWithoutPaging = Session.Execute(statementWithoutPaging); //Check that the internal list of items count is pageSize Assert.True(rsWithPaging.InnerQueueCount == pageSize); Assert.True(rsWithoutPaging.InnerQueueCount == totalRowLength); var allTheRowsPaged = rsWithPaging.ToList(); Assert.True(allTheRowsPaged.Count == totalRowLength); } [Test] [TestCassandraVersion(2, 0)] public void Should_PagingOnQuery_When_ReceivedNumberOfRowsIsHigherThanPageSize() { var pageSize = 10; var totalRowLength = 1003; var table = CreateSimpleTableAndInsert(totalRowLength); var rsWithoutPaging = Session.Execute($"SELECT * FROM {table}", int.MaxValue); //It should have all the rows already in the inner list Assert.AreEqual(totalRowLength, rsWithoutPaging.InnerQueueCount); var rs = Session.Execute($"SELECT * FROM {table}", pageSize); //Check that the internal list of items count is pageSize Assert.AreEqual(pageSize, rs.InnerQueueCount); //Use Linq to iterate through all the rows var allTheRowsPaged = rs.ToList(); Assert.AreEqual(totalRowLength, allTheRowsPaged.Count); } [Test] [TestCassandraVersion(2, 0), Repeat(10)] public void Should_IteratePaging_When_ParallelClientsReadRowSet() { const int pageSize = 25; const int totalRowLength = 300; const string table = "tbl_parallel_paging_read"; var query = new SimpleStatement($"SELECT * FROM {table} LIMIT 10000").SetPageSize(pageSize); var rs = Session.Execute(query); Assert.AreEqual(pageSize, rs.GetAvailableWithoutFetching()); var counter = 0; void Iterate() { Interlocked.Add(ref counter, rs.Count()); } //Iterate in parallel the RowSet Parallel.Invoke(Iterate, Iterate, Iterate, Iterate); //Check that the sum of all rows in different threads is the same as total rows Assert.AreEqual(totalRowLength, Volatile.Read(ref counter)); } [Test] [TestCassandraVersion(2, 0)] public void Should_IteratePaging_When_SerialReadRowSet() { var pageSize = 25; var totalRowLength = 300; var times = 10; var table = CreateSimpleTableAndInsert(totalRowLength); var statement = new SimpleStatement($"SELECT * FROM {table} LIMIT 10000") .SetPageSize(pageSize); var counter = 0; for (var i = 0; i < times; i++) { var rs = Session.Execute(statement); counter += rs.Count(); } //Check that the sum of all rows in same thread is the same as total rows Assert.AreEqual(totalRowLength * times, counter); } [Test] [TestCassandraVersion(2, 0)] public void Should_ReturnNextPage_When_SetPagingStateManually() { var pageSize = 10; var totalRowLength = 15; var table = CreateSimpleTableAndInsert(totalRowLength); var rs = Session.Execute(new SimpleStatement("SELECT * FROM " + table).SetAutoPage(false).SetPageSize(pageSize)); Assert.NotNull(rs.PagingState); //It should have just the first page of rows Assert.AreEqual(pageSize, rs.InnerQueueCount); //Linq iteration should not make it to page Assert.AreEqual(pageSize, rs.Count()); rs = Session.Execute(new SimpleStatement("SELECT * FROM " + table).SetAutoPage(false).SetPageSize(pageSize).SetPagingState(rs.PagingState)); //It should only contain the following page rows Assert.AreEqual(totalRowLength - pageSize, rs.Count()); } //////////////////////////////////// /// Test Helpers //////////////////////////////////// /// <summary> /// Creates a table and inserts a number of records synchronously. /// </summary> /// <returns>The name of the table</returns> private string CreateSimpleTableAndInsert(int rowsInTable, string tableName = null) { if (tableName == null) { tableName = TestUtils.GetUniqueTableName(); } QueryTools.ExecuteSyncNonQuery(Session, $@" CREATE TABLE {tableName}( id uuid PRIMARY KEY, label text);"); for (var i = 0; i < rowsInTable; i++) { Session.Execute(string.Format("INSERT INTO {2} (id, label) VALUES({0},'{1}')", Guid.NewGuid(), "LABEL" + i, tableName)); } return tableName; } /// <summary> /// Creates a table with a composite index and inserts a number of records synchronously. /// </summary> /// <returns>The name of the table</returns> private Tuple<string, string> CreateTableWithCompositeIndexAndInsert(ISession session, int rowsInTable) { var tableName = TestUtils.GetUniqueTableName(); var staticClusterKeyStr = "staticClusterKeyStr"; QueryTools.ExecuteSyncNonQuery(session, $@" CREATE TABLE {tableName} ( id text, label text, PRIMARY KEY (label, id));"); for (var i = 0; i < rowsInTable; i++) { session.Execute(string.Format("INSERT INTO {2} (label, id) VALUES('{0}','{1}')", staticClusterKeyStr, Guid.NewGuid().ToString(), tableName)); } var infoTuple = new Tuple<string, string>(tableName, staticClusterKeyStr); return infoTuple; } } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using Debug = UnityEngine.Debug; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Object = UnityEngine.Object; namespace Ink.UnityIntegration { // Information about the current state of an ink file [System.Serializable] public sealed class InkMetaFile { public DefaultAsset inkAsset; // Used for when the data gets lost. public string inkAssetPath; public string masterInkAssetPath; [System.NonSerialized] private InkFile _inkFile = null; public InkFile inkFile { get { if(_inkFile == null) _inkFile = InkLibrary.GetInkFileWithFile(inkAsset); return _inkFile; } } // Fatal unhandled errors that should be reported as compiler bugs. public List<string> compileErrors = new List<string>(); public bool hasCompileErrors { get { return compileErrors.Count > 0; } } // Fatal errors caused by errors in the user's ink script. public List<InkFileLog> errors = new List<InkFileLog>(); public bool hasErrors { get { return errors.Count > 0; } } public List<InkFileLog> warnings = new List<InkFileLog>(); public bool hasWarnings { get { return warnings.Count > 0; } } public List<InkFileLog> todos = new List<InkFileLog>(); public bool hasTodos { get { return todos.Count > 0; } } public bool requiresCompile { get { if(masterInkFileIncludingSelf.jsonAsset == null || masterInkFileIncludingSelf.metaInfo == null) return true; var inkFilesInIncludeHierarchy = masterInkFileIncludingSelf.metaInfo.inkFilesInIncludeHierarchy; if (inkFilesInIncludeHierarchy == null) return true; foreach(InkFile inkFile in inkFilesInIncludeHierarchy) { if(inkFile.metaInfo.hasCompileErrors) { return true; } else if(inkFile.metaInfo.hasErrors) { return true; } else if(inkFile.metaInfo.hasWarnings) { return true; } else if(inkFile.metaInfo.lastEditDate > lastCompileDate) { return true; } } return false; } } /// <summary> /// Gets the last compile date of the story. /// </summary> /// <value>The last compile date of the story.</value> public DateTime lastCompileDate { get { string fullJSONFilePath = InkEditorUtils.UnityRelativeToAbsolutePath(AssetDatabase.GetAssetPath(masterInkFileIncludingSelf.jsonAsset)); return File.GetLastWriteTime(fullJSONFilePath); } } /// <summary> /// Gets the last edit date of the file. /// </summary> /// <value>The last edit date of the file.</value> public DateTime lastEditDate { get { return File.GetLastWriteTime(inkFile.absoluteFilePath); } } [System.Serializable] public class InkFileLog { public string content; public int lineNumber; public InkFileLog (string content, int lineNumber = -1) { this.content = content; this.lineNumber = lineNumber; } } public InkMetaFile (InkFile inkFile) { _inkFile = inkFile; inkAsset = inkFile.inkAsset; ParseContent(); } // File that contains this file as an include, if one exists. public DefaultAsset parent; public InkFile parentInkFile { get { if(parent == null) return null; else return InkLibrary.GetInkFileWithFile(parent); } } // Is this ink file a parent file? public bool isParent { get { return includes.Count > 0; } } public DefaultAsset masterInkAsset; public InkFile masterInkFile { get { if(masterInkAsset == null) return null; else return InkLibrary.GetInkFileWithFile(masterInkAsset); } } public InkFile masterInkFileIncludingSelf { get { return isMaster ? inkFile : masterInkFile; } } // Is this ink file a master file? public bool isMaster { get { return masterInkAsset == null; } } // The files included by this file // We cache the paths of the files to be included for performance, giving us more freedom to refresh the actual includes list without needing to parse all the text. public List<string> includePaths = new List<string>(); public List<DefaultAsset> includes = new List<DefaultAsset>(); // The InkFiles of the includes of this file public List<InkFile> includesInkFiles { get { List<InkFile> _includesInkFiles = new List<InkFile>(); foreach(var child in includes) { if(child == null) { Debug.LogError("Error compiling ink: Ink file include in "+inkFile.filePath+" is null."); continue; } _includesInkFiles.Add(InkLibrary.GetInkFileWithFile(child)); } return _includesInkFiles; } } // The InkFiles in the include hierarchy of this file. public List<InkFile> inkFilesInIncludeHierarchy { get { List<InkFile> _includesInkFiles = new List<InkFile>(); _includesInkFiles.Add(inkFile); foreach(var child in includesInkFiles) { if (child.metaInfo == null) return null; _includesInkFiles.AddRange(child.metaInfo.inkFilesInIncludeHierarchy); } return _includesInkFiles; } } // public string content; // The contents of the .ink file public string GetFileContents () { return File.OpenText(inkFile.absoluteFilePath).ReadToEnd(); } public void ParseContent () { InkIncludeParser includeParser = new InkIncludeParser(GetFileContents()); includePaths = includeParser.includeFilenames; } public void FindIncludedFiles () { includes.Clear(); foreach(string includePath in includePaths) { string localIncludePath = InkEditorUtils.CombinePaths(Path.GetDirectoryName(inkFile.filePath), includePath); DefaultAsset includedInkFileAsset = AssetDatabase.LoadAssetAtPath<DefaultAsset>(localIncludePath); InkFile includedInkFile = InkLibrary.GetInkFileWithFile(includedInkFileAsset); if(includedInkFile == null) { Debug.LogError(inkFile.filePath+ " expected child Ink file at "+localIncludePath+" but file was not found."); } else if (includedInkFile.metaInfo.includes.Contains(inkAsset)) { Debug.LogError("Circular INCLUDE reference between "+inkFile.filePath+" and "+includedInkFile.metaInfo.inkFile.filePath+"."); } else includes.Add(includedInkFileAsset); } } public class InkIncludeParser { public InkIncludeParser (string inkContents) { _text = inkContents; } void Process() { _text = EliminateComments (_text); FindIncludes (_text); } string EliminateComments(string inkStr) { var sb = new StringBuilder (); int idx = 0; while(idx < inkStr.Length) { var commentStarterIdx = inkStr.IndexOf ('/', idx); // Final string? if (commentStarterIdx == -1 || commentStarterIdx >= inkStr.Length-2 ) { sb.Append (inkStr.Substring (idx, inkStr.Length - idx)); break; } sb.Append (inkStr.Substring (idx, commentStarterIdx - idx)); var commentStarter = inkStr.Substring (commentStarterIdx, 2); if (commentStarter == "//" || commentStarter == "/*") { int endOfCommentIdx = -1; // Single line comments if (commentStarter == "//") { endOfCommentIdx = inkStr.IndexOf ('\n', commentStarterIdx); if (endOfCommentIdx == -1) endOfCommentIdx = inkStr.Length; else if (inkStr [endOfCommentIdx - 1] == '\r') endOfCommentIdx = endOfCommentIdx - 1; } // Block comments else if (commentStarter == "/*") { endOfCommentIdx = inkStr.IndexOf ("*/", idx); if (endOfCommentIdx == -1) endOfCommentIdx = inkStr.Length; else endOfCommentIdx += 2; // If there are *any* newlines, we should add one in here, // so that lines are spit up correctly if (inkStr.IndexOf ('\n', commentStarterIdx, endOfCommentIdx - commentStarterIdx) != -1) sb.Append ("\n"); } // Skip over comment if (endOfCommentIdx > -1) idx = endOfCommentIdx; } // Normal slash we need, not a comment else { sb.Append ("/"); idx = commentStarterIdx + 1; } } return sb.ToString (); } void FindIncludes(string str) { _includeFilenames = new List<string> (); var includeRegex = new Regex (@"^\s*INCLUDE\s+([^\r\n]+)\r*$", RegexOptions.Multiline); MatchCollection matches = includeRegex.Matches(str); foreach (Match match in matches) { var capture = match.Groups [1].Captures [0]; _includeFilenames.Add (capture.Value); } } public List<string> includeFilenames { get { if (_includeFilenames == null) { Process (); } return _includeFilenames; } } List<string> _includeFilenames; string _text; } } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Cassandra.IntegrationTests.Core; using Cassandra.IntegrationTests.TestClusterManagement; using NUnit.Framework; namespace Cassandra.IntegrationTests.TestBase { /// <summary> /// A number of static fields/methods handy for tests. /// </summary> internal static class TestUtils { private const int DefaultSleepIterationMs = 1000; public static readonly string CreateKeyspaceSimpleFormat = "CREATE KEYSPACE \"{0}\" WITH replication = {{ 'class' : 'SimpleStrategy', 'replication_factor' : {1} }}"; public static readonly string CreateKeyspaceGenericFormat = "CREATE KEYSPACE {0} WITH replication = {{ 'class' : '{1}', {2} }}"; public static readonly string CreateTableSimpleFormat = "CREATE TABLE {0} (k text PRIMARY KEY, t text, i int, f float)"; public const string CreateTableAllTypes = @" create table {0} ( id uuid primary key, ascii_sample ascii, text_sample text, int_sample int, bigint_sample bigint, float_sample float, double_sample double, decimal_sample decimal, blob_sample blob, boolean_sample boolean, timestamp_sample timestamp, inet_sample inet, timeuuid_sample timeuuid, map_sample map<text, text>, list_sample list<text>, set_sample set<text>); "; public const string CREATE_TABLE_TIME_SERIES = @" create table {0} ( id uuid, event_time timestamp, text_sample text, int_sample int, bigint_sample bigint, float_sample float, double_sample double, decimal_sample decimal, blob_sample blob, boolean_sample boolean, timestamp_sample timestamp, inet_sample inet, PRIMARY KEY(id, event_time)); "; public static readonly string INSERT_FORMAT = "INSERT INTO {0} (k, t, i, f) VALUES ('{1}', '{2}', {3}, {4})"; public static readonly string SELECT_ALL_FORMAT = "SELECT * FROM {0}"; public static readonly string SELECT_WHERE_FORMAT = "SELECT * FROM {0} WHERE {1}"; public static string GetTestClusterNameBasedOnTime() { return "test_" + (DateTimeOffset.UtcNow.Ticks / TimeSpan.TicksPerSecond); } public static string GetUniqueKeyspaceName() { return "TestKeySpace_" + Randomm.RandomAlphaNum(12); } public static string GetUniqueTableName() { return "TestTable_" + Randomm.RandomAlphaNum(12); } public static void TryToDeleteKeyspace(ISession session, string keyspaceName) { if (session != null) session.DeleteKeyspaceIfExists(keyspaceName); } public static bool TableExists(ISession session, string keyspaceName, string tableName) { // SELECT columnfamily_name FROM system.schema_columnfamilies WHERE keyspace_name='TestKeySpace_c3052b44be8b'; string cql = "SELECT columnfamily_name FROM system.schema_columnfamilies WHERE keyspace_name='" + keyspaceName + "'"; RowSet rowSet = session.Execute(cql); List<Row> rows = rowSet.GetRows().ToList(); if (rows != null && rows.Count > 0) { foreach (var row in rows) { string cfName = (string)row["columnfamily_name"]; if (cfName == tableName) return true; } } return false; } public static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length*sizeof (char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } /// <summary> /// Validates that the bootstrapped node was added to the cluster and was queried. /// </summary> public static void ValidateBootStrappedNodeIsQueried(ITestCluster testCluster, int expectedTotalNodeCount, string newlyBootstrappedHost) { var hostsQueried = new List<string>(); DateTime timeInTheFuture = DateTime.Now.AddSeconds(120); while (testCluster.Cluster.Metadata.AllHosts().ToList().Count() < expectedTotalNodeCount && DateTime.Now < timeInTheFuture) { var rs = testCluster.Session.Execute("SELECT * FROM system.schema_columnfamilies"); rs.Count(); hostsQueried.Add(rs.Info.QueriedHost.Address.ToString()); Thread.Sleep(500); } Assert.That(testCluster.Cluster.Metadata.AllHosts().ToList().Count, Is.EqualTo(expectedTotalNodeCount)); timeInTheFuture = DateTime.Now.AddSeconds(120); while (!hostsQueried.Contains(newlyBootstrappedHost) && DateTime.Now < timeInTheFuture) { var rs = testCluster.Session.Execute("SELECT * FROM system.schema_columnfamilies"); rs.Count(); hostsQueried.Add(rs.Info.QueriedHost.Address.ToString()); Thread.Sleep(500); } // Validate host was queried Assert.True(hostsQueried.Any(ip => ip.ToString() == newlyBootstrappedHost), "Newly bootstrapped node was not queried!"); } /// <summary> /// Determines if the test should use a remote ccm instance /// </summary> public static bool UseRemoteCcm { get { return ConfigurationManager.AppSettings["UseRemote"] == "true"; } } public static void WaitForUp(string nodeHost, int nodePort, int maxSecondsToKeepTrying) { int msSleepPerIteration = 500; DateTime futureDateTime = DateTime.Now.AddSeconds(maxSecondsToKeepTrying); while (DateTime.Now < futureDateTime) { TcpClient tcpClient = new TcpClient(); try { tcpClient.Connect(nodeHost, nodePort); tcpClient.Close(); Trace.TraceInformation("Verified that node " + nodeHost + ":" + nodePort + " is UP (success) via manual socket connection check, exiting now ..."); return; } catch (Exception e) { Trace.TraceInformation(string.Format("Caught expected exception, with message: {0}. Still waiting for node host: {1} to be available for connection, " + " waiting another {2} MS ... ", e.Message, nodeHost + ":" + nodePort, msSleepPerIteration)); tcpClient.Close(); Thread.Sleep(msSleepPerIteration); } } throw new Exception("Could not connect to node: " + nodeHost + ":" + nodePort + " after " + maxSecondsToKeepTrying + " seconds!"); } public static void WaitForDown(string nodeHost, int nodePort, int maxSecondsToKeepTrying) { int msSleepPerIteration = 500; DateTime futureDateTime = DateTime.Now.AddSeconds(maxSecondsToKeepTrying); while (DateTime.Now < futureDateTime) { TcpClient tcpClient = new TcpClient(); try { tcpClient.Connect(nodeHost, nodePort); tcpClient.Close(); Trace.TraceInformation(string.Format("Still waiting for node host: {0} to be UNavailable for connection to default Cassandra port, waiting another {1} MS ... ", nodeHost + ":" + nodePort, msSleepPerIteration)); Thread.Sleep(msSleepPerIteration); } catch (Exception) { Trace.TraceInformation("Verified that node " + nodeHost + ":" + nodePort + " is DOWN (success) via manual socket connection check, exiting now ..."); tcpClient.Close(); return; } } throw new Exception("Node: " + nodeHost + ":" + nodePort + " was still available for connection after " + maxSecondsToKeepTrying + " seconds, but should have been UNavailable by now!"); } private static void WaitForMeta(string nodeHost, Cluster cluster, int maxTry, bool waitForUp) { string expectedFinalNodeState = "UP"; if (!waitForUp) expectedFinalNodeState = "DOWN"; for (int i = 0; i < maxTry; ++i) { try { // Are all nodes in the cluster accounted for? bool disconnected = !cluster.RefreshSchema(); if (disconnected) { string warnStr = "While waiting for host " + nodeHost + " to be " + expectedFinalNodeState + ", the cluster is now totally down, returning now ... "; Trace.TraceWarning(warnStr); return; } Metadata metadata = cluster.Metadata; foreach (Host host in metadata.AllHosts()) { bool hostFound = false; if (host.Address.ToString() == nodeHost) { hostFound = true; if (host.IsUp && waitForUp) { Trace.TraceInformation("Verified according to cluster meta that host " + nodeHost + " is " + expectedFinalNodeState + ", returning now ... "); return; } Trace.TraceWarning("We're waiting for host " + nodeHost + " to be " + expectedFinalNodeState); } // Is the host even in the meta list? if (!hostFound) { if (!waitForUp) { Trace.TraceInformation("Verified according to cluster meta that host " + host.Address + " is not available in the MetaData hosts list, returning now ... "); return; } else Trace.TraceWarning("We're waiting for host " + nodeHost + " to be " + expectedFinalNodeState + ", but this host was not found in the MetaData hosts list!"); } } } catch (Exception e) { if (e.Message.Contains("None of the hosts tried for query are available") && !waitForUp) { Trace.TraceInformation("Verified according to cluster meta that host " + nodeHost + " is not available in the MetaData hosts list, returning now ... "); return; } Trace.TraceInformation("Exception caught while waiting for meta data: " + e.Message); } Trace.TraceWarning("Waiting for node host: " + nodeHost + " to be " + expectedFinalNodeState); Thread.Sleep(DefaultSleepIterationMs); } string errStr = "Node host should have been " + expectedFinalNodeState + " but was not after " + maxTry + " tries!"; Trace.TraceError(errStr); } public static void WaitFor(string node, Cluster cluster, int maxTry) { WaitFor(node, cluster, maxTry, false, false); } public static void WaitForDown(string node, Cluster cluster, int maxTry) { WaitFor(node, cluster, maxTry, true, false); } public static void waitForDecommission(string node, Cluster cluster, int maxTry) { WaitFor(node, cluster, maxTry, true, true); } public static void WaitForDownWithWait(String node, Cluster cluster, int waitTime) { WaitFor(node, cluster, 90, true, false); // FIXME: Once stop() works, remove this line try { Thread.Sleep(waitTime * 1000); } catch (InvalidQueryException e) { Debug.Write(e.StackTrace); } } private static void WaitFor(string node, Cluster cluster, int maxTry, bool waitForDead, bool waitForOut) { WaitForMeta(node, cluster, maxTry, !waitForDead); } /// <summary> /// Spawns a new process (platform independent) /// </summary> public static ProcessOutput ExecuteProcess(string processName, string args, int timeout = 300000) { var output = new ProcessOutput(); using (var process = new Process()) { process.StartInfo.FileName = processName; process.StartInfo.Arguments = args; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; //Hide the python window if possible process.StartInfo.UseShellExecute = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = true; using (var outputWaitHandle = new AutoResetEvent(false)) using (var errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { try { outputWaitHandle.Set(); } catch { //probably is already disposed } } else { output.OutputText.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { try { errorWaitHandle.Set(); } catch { //probably is already disposed } } else { output.OutputText.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // Process completed. output.ExitCode = process.ExitCode; } else { // Timed out. output.ExitCode = -1; } } } return output; } public static ProcessOutput ExecuteLocalCcm(string ccmArgs, string ccmConfigDir, int timeout = 300000, bool throwOnProcessError = false) { ccmConfigDir = EscapePath(ccmConfigDir); var args = ccmArgs + " --config-dir=" + ccmConfigDir; Trace.TraceInformation("Executing ccm: " + ccmArgs); var processName = "/usr/local/bin/ccm"; if (IsWin) { processName = "cmd.exe"; args = "/c ccm " + args; } var output = ExecuteProcess(processName, args, timeout); if (throwOnProcessError) { ValidateOutput(output); } return output; } public static bool IsWin { get { switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: return true; } return false; } } private static void ValidateOutput(ProcessOutput output) { if (output.ExitCode != 0) { throw new TestInfrastructureException(string.Format("Process exited in error {0}", output.ToString())); } } /// <summary> /// Starts a Cassandra cluster with the name, version and amount of nodes provided. /// </summary> /// <param name="ccmConfigDir">Path to the location where the cluster will be created</param> /// <param name="cassandraVersion">Cassandra version in the form of MAJOR.MINOR.PATCH semver</param> /// <param name="nodeLength">amount of nodes in the cluster</param> /// <param name="secondDcNodeLength">amount of nodes to add the second DC</param> /// <param name="clusterName"></param> /// <returns></returns> public static ProcessOutput ExecuteLocalCcmClusterStart(string ccmConfigDir, string cassandraVersion, int nodeLength = 1, int secondDcNodeLength = 0, string clusterName = "test") { //Starting ccm cluster involves: // 1.- Getting the Apache Cassandra Distro // 2.- Compiling it // 3.- Fill the config files // 4.- Starting each node. //Considerations: // As steps 1 and 2 can take a while, try to fail fast (2 sec) by doing a "ccm list" // Also, the process can exit before the nodes are actually up: Execute ccm status until they are up var totalNodeLength = nodeLength + secondDcNodeLength; //Only if ccm list succedes, create the cluster and continue. var output = TestUtils.ExecuteLocalCcm("list", ccmConfigDir, 2000); if (output.ExitCode != 0) { return output; } var ccmCommand = String.Format("create {0} -v {1}", clusterName, cassandraVersion); //When creating a cluster, it could download the Cassandra binaries from the internet. //Give enough time = 3 minutes. var timeout = 180000; output = TestUtils.ExecuteLocalCcm(ccmCommand, ccmConfigDir, timeout); if (output.ExitCode != 0) { return output; } if (secondDcNodeLength > 0) { ccmCommand = String.Format("populate -n {0}:{1}", nodeLength, secondDcNodeLength); } else { ccmCommand = "populate -n " + nodeLength; } var populateOutput = TestUtils.ExecuteLocalCcm(ccmCommand, ccmConfigDir, 300000); if (populateOutput.ExitCode != 0) { return populateOutput; } output.OutputText.AppendLine(populateOutput.ToString()); var startOutput = TestUtils.ExecuteLocalCcm("start", ccmConfigDir); if (startOutput.ExitCode != 0) { return startOutput; } output.OutputText.AppendLine(startOutput.ToString()); //Nodes are starting, but we dont know for sure if they are have started. var allNodesAreUp = false; var safeCounter = 0; while (!allNodesAreUp && safeCounter < 10) { var statusOutput = TestUtils.ExecuteLocalCcm("status", ccmConfigDir, 1000); if (statusOutput.ExitCode != 0) { //Something went wrong output = statusOutput; break; } //Analyze the status output to see if all nodes are up if (Regex.Matches(statusOutput.OutputText.ToString(), "UP", RegexOptions.Multiline).Count == totalNodeLength) { //All nodes are up for (int x = 1; x <= totalNodeLength; x++) { var foundText = false; var sw = new Stopwatch(); sw.Start(); while (sw.ElapsedMilliseconds < 180000) { var logFileText = TryReadAllTextNoLock(Path.Combine(ccmConfigDir, clusterName, String.Format("node{0}\\logs\\system.log", x))); if (Regex.IsMatch(logFileText, "listening for CQL clients", RegexOptions.Multiline)) { foundText = true; break; } } if (!foundText) { throw new TestInfrastructureException(String.Format("node{0} did not properly start", x)); } } allNodesAreUp = true; } safeCounter++; } return output; } /// <summary> /// Stops the cluster and removes the config files /// </summary> /// <returns></returns> public static ProcessOutput ExecuteLocalCcmClusterRemove(string ccmConfigDir) { var output = TestUtils.ExecuteLocalCcm("stop", ccmConfigDir); if (output.ExitCode != 0) { return output; } return TestUtils.ExecuteLocalCcm("remove", ccmConfigDir); } /// <summary> /// Reads a text file without file locking /// </summary> /// <returns></returns> public static string TryReadAllTextNoLock(string fileName) { string fileText = ""; try { using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var reader = new StreamReader(file)) { fileText = reader.ReadToEnd(); } } } catch { //We tried and failed, dont mind } return fileText; } private static Dictionary<string, bool> _existsCache = new Dictionary<string, bool>(); /// <summary> /// Checks that the file exists and caches the result in a static variable /// </summary> public static bool FileExists(string path) { if (!_existsCache.ContainsKey(path)) { _existsCache[path] = File.Exists(path); } return _existsCache[path]; } /// <summary> /// Adds double quotes to the path in case it contains spaces. /// </summary> public static string EscapePath(string path) { if (path == null) { throw new ArgumentNullException("path"); } if (path.Contains(" ")) { return "\"" + path + "\""; } return path; } /// <summary> /// Create a temporary directory inside OS temp path and returns the name of path of the newly created directory /// </summary> /// <returns></returns> public static string CreateTempDirectory() { var basePath = Path.GetTempPath(); if (ConfigurationManager.AppSettings["TempDir"] != null) { basePath = ConfigurationManager.AppSettings["TempDir"]; } var tempDirectory = Path.Combine(basePath, "ccm-" + Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } //public static void CcmBootstrapNode(CcmCluster ccmCluster, int node, string dc = null) //{ // ProcessOutput output = null; // if (dc == null) // { // output = ccmCluster.CcmBridge.ExecuteCcm(string.Format("add node{0} -i {1}{2} -j {3} -b", node, Options.Default.IP_PREFIX, node, 7000 + 100 * node)); // } // else // { // output = ccmCluster.CcmBridge.ExecuteCcm(string.Format("add node{0} -i {1}{2} -j {3} -b -d {4}", node, Options.Default.IP_PREFIX, node, 7000 + 100 * node, dc)); // } // if (output.ExitCode != 0) // { // throw new TestInfrastructureException("Local ccm could not add node: " + output.ToString()); // } //} public static void CcmDecommissionNode(CcmClusterInfo info, int node) { ExecuteLocalCcm(string.Format("node{0} decommission", node), info.ConfigDir); } /// <summary> /// Determines if a connection can be made to a node at port 9042 /// </summary> public static bool IsNodeReachable(IPAddress ip) { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { var connectResult = socket.BeginConnect(new IPEndPoint(ip, 9042), null, null); var connectSignaled = connectResult.AsyncWaitHandle.WaitOne(1000); if (!connectSignaled) { //It timed out: Close the socket return false; } try { socket.EndConnect(connectResult); return true; } catch { return false; } } } public static void WaitForSchemaAgreement(ICluster cluster) { const int maxRetries = 20; var hostsLength = cluster.AllHosts().Count; if (hostsLength == 1) { return; } var cc = cluster.Metadata.ControlConnection; var counter = 0; var nodesDown = cluster.AllHosts().Count(h => !h.IsConsiderablyUp); while (counter++ < maxRetries) { Trace.TraceInformation("Waiting for test schema agreement"); Thread.Sleep(500); var hosts = new List<Guid>(); //peers hosts.AddRange(cc.Query("SELECT peer, schema_version FROM system.peers").Select(r => r.GetValue<Guid>("schema_version"))); //local hosts.Add(cc.Query("SELECT schema_version FROM system.local").Select(r => r.GetValue<Guid>("schema_version")).First()); var differentSchemas = hosts.GroupBy(v => v).Count(); if (differentSchemas <= 1 + nodesDown) { //There is 1 schema version or 1 + nodes that are considered as down break; } } } public static void WaitForSchemaAgreement(CcmClusterInfo clusterInfo) { WaitForSchemaAgreement(clusterInfo.Cluster); } } /// <summary> /// Represents a result from executing an external process. /// </summary> public class ProcessOutput { public int ExitCode { get; set; } public StringBuilder OutputText { get; set; } public ProcessOutput() { OutputText = new StringBuilder(); ExitCode = Int32.MinValue; } public override string ToString() { return "Exit Code: " + this.ExitCode + Environment.NewLine + "Output Text: " + this.OutputText.ToString() + Environment.NewLine; } } public class CcmClusterInfo { public Cluster Cluster { get; set; } public ISession Session { get; set; } public string ConfigDir { get; set; } } }
namespace Evelyn.Core.Tests.WriteModel.Project.DeleteToggle { using System; using System.Collections.Generic; using System.Linq; using AutoFixture; using Core.WriteModel.Project.Commands.DeleteToggle; using Core.WriteModel.Project.Events; using FluentAssertions; using TestStack.BDDfy; using Xunit; public class CommandSpecs : ProjectCommandHandlerSpecs<Handler, Command> { private Guid _projectId; private string _environment1Key; private string _environment2Key; private string _toggle1Key; private int _toggle1Version = -1; private string _toggle2Key; private int _toggle2Version = -1; private string _toggleToDeleteKey; private int _toggleToDeleteVersion; public CommandSpecs() { IgnoreCollectionOrderDuringComparison = true; } [Fact] public void ProjectHasBeenDeleted() { this.Given(_ => GivenWeHaveCreatedAProject()) .And(_ => GivenWeHaveAddedAToggle()) .And(_ => GivenWeHaveAddedAnotherToggle()) .And(_ => GivenWeWillBeDeletingTheFirstToggle()) .And(_ => GivenWeHaveDeletedTheProject()) .When(_ => WhenWeDeleteTheToggle()) .Then(_ => ThenNoEventIsPublished()) .And(_ => ThenAProjectDeletedExceptionIsThrownFor(_projectId)) .And(_ => ThenThereAreNoChangesOnTheAggregate()) .BDDfy(); } [Fact] public void ToggleDoesNotExist() { this.Given(_ => GivenWeHaveCreatedAProject()) .And(_ => GivenOurToggleDoesNotExist()) .When(_ => WhenWeDeleteTheToggle()) .Then(_ => ThenNoEventIsPublished()) .And(_ => ThenAnUnknownToggleExceptionIsThrown()) .And(_ => ThenThereAreNoChangesOnTheAggregate()) .BDDfy(); } [Fact] public void StaleExpectedToggleVersion() { this.Given(_ => GivenWeHaveCreatedAProject()) .And(_ => GivenWeHaveAddedAToggle()) .And(_ => GivenWeHaveAddedAnotherToggle()) .And(_ => GivenWeWillBeDeletingTheFirstToggle()) .And(_ => GivenTheExpectedToggleVersionForOurNextCommandIsOffsetBy(-1)) .When(_ => WhenWeDeleteTheToggle()) .Then(_ => ThenNoEventIsPublished()) .And(_ => ThenAConcurrencyExceptionIsThrown()) .And(_ => ThenThereAreNoChangesOnTheAggregate()) .BDDfy(); } [Theory] [InlineData(0)] [InlineData(1)] public void ToggleExistsAndThereAreNoEnvironments(int expectedVersionOffset) { this.Given(_ => GivenWeHaveCreatedAProject()) .And(_ => GivenWeHaveAddedAToggle()) .And(_ => GivenWeHaveAddedAnotherToggle()) .And(_ => GivenWeWillBeDeletingTheFirstToggle()) .And(_ => GivenTheExpectedToggleVersionForOurNextCommandIsOffsetBy(expectedVersionOffset)) .When(_ => WhenWeDeleteTheToggle()) .Then(_ => ThenOneEventIsPublished()) .And(_ => ThenAToggleDeletedEventIsPublished()) .And(_ => ThenTheNumberOfChangesOnTheAggregateIs(6)) .And(_ => ThenTheAggregateRootHasOneFewerToggles()) .And(_ => ThenTheAggregateRootHasHadTheCorrectToggleRemoved()) .And(_ => ThenTheAggregateRootLastModifiedVersionIs(NewAggregate.Version)) .And(_ => ThenTheAggregateRootLastModifiedTimeHasBeenUpdated()) .And(_ => ThenTheAggregateRootLastModifiedByHasBeenUpdated()) .And(_ => ThenTheAggregateRootVersionHasBeenIncreasedBy(1)) .BDDfy(); } [Theory] [InlineData(0)] [InlineData(1)] public void ToggleExistsAndThereAreMultipleEnvironments(int expectedVersionOffset) { this.Given(_ => GivenWeHaveCreatedAProject()) .And(_ => GivenWeHaveAddedAToggle()) .And(_ => GivenWeHaveAddedAnotherToggle()) .And(_ => GivenWeHaveAddedTwoEnvironments()) .And(_ => GivenWeWillBeDeletingTheFirstToggle()) .And(_ => GivenTheExpectedToggleVersionForOurNextCommandIsOffsetBy(expectedVersionOffset)) .When(_ => WhenWeDeleteTheToggle()) .Then(_ => ThenThreeEventsArePublished()) .And(_ => ThenAToggleDeletedEventIsPublished()) .And(_ => ThenAnToggleStateDeletedEventsIsPublishedForEnvironment1()) .And(_ => ThenAnToggleStateDeletedEventsIsPublishedForEnvironment2()) .And(_ => ThenTheNumberOfChangesOnTheAggregateIs(16)) .And(_ => ThenTheAggregateRootHasOneFewerToggles()) .And(_ => ThenTheAggregateRootHasHadTheCorrectToggleRemoved()) .And(_ => ThenTheFirstEnvironmentStateHasOneFewerToggleStates()) .And(_ => ThenTheFirstEnvironmentStateHasHadTheCorrectToggleStateDeleted()) .And(_ => ThenTheFirstEnvironmentLastModifiedVersionIs(OriginalAggregate.Version + 2)) .And(_ => ThenTheFirstEnvironmentStateLastModifiedTimeHasBeenUpdated()) .And(_ => ThenTheFirstEnvironmentStateLastModifiedByHasBeenUpdated()) .And(_ => ThenTheSecondEnvironmentStateHasOneFewerToggleStates()) .And(_ => ThenTheSecondEnvironmentStateHasHadTheCorrectToggleStateDeleted()) .And(_ => ThenTheSecondEnvironmentLastModifiedVersionIs(OriginalAggregate.Version + 3)) .And(_ => ThenTheSecondEnvironmentStateLastModifiedTimeHasBeenUpdated()) .And(_ => ThenTheSecondEnvironmentStateLastModifiedByHasBeenUpdated()) .And(_ => ThenTheAggregateRootLastModifiedVersionIs(OriginalAggregate.Version + 1)) .And(_ => ThenTheAggregateRootLastModifiedTimeHasBeenUpdated()) .And(_ => ThenTheAggregateRootLastModifiedByHasBeenUpdated()) .And(_ => ThenTheAggregateRootVersionHasBeenIncreasedBy(3)) .BDDfy(); } protected override Handler BuildHandler() { return new Handler(Logger, Session); } private void GivenWeHaveCreatedAProject() { _projectId = DataFixture.Create<Guid>(); GivenWeHaveCreatedAProjectWith(_projectId); } private void GivenWeHaveAddedTwoEnvironments() { _environment1Key = DataFixture.Create<string>(); _environment2Key = DataFixture.Create<string>(); GivenWeHaveAddedAnEnvironmentWith(_projectId, _environment1Key); GivenWeHaveAddedAnEnvironmentStateWith( _projectId, _environment1Key, new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(_toggle1Key, default), new KeyValuePair<string, string>(_toggle2Key, default) }); GivenWeHaveAddedAnEnvironmentWith(_projectId, _environment2Key); GivenWeHaveAddedAnEnvironmentStateWith( _projectId, _environment2Key, new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(_toggle1Key, default), new KeyValuePair<string, string>(_toggle2Key, default) }); } private void GivenOurToggleDoesNotExist() { _toggleToDeleteKey = DataFixture.Create<string>(); _toggleToDeleteVersion = DataFixture.Create<int>(); } private void GivenWeWillBeDeletingTheFirstToggle() { _toggleToDeleteKey = _toggle1Key; _toggleToDeleteVersion = _toggle1Version; } private void GivenWeHaveAddedAToggle() { _toggle1Key = DataFixture.Create<string>(); HistoricalEvents.Add(new ToggleAdded(UserId, _projectId, _toggle1Key, DataFixture.Create<string>(), DateTimeOffset.UtcNow) { Version = HistoricalEvents.Count }); _toggle1Version = HistoricalEvents.Count - 1; } private void GivenWeHaveAddedAnotherToggle() { _toggle2Key = DataFixture.Create<string>(); HistoricalEvents.Add(new ToggleAdded(UserId, _projectId, _toggle2Key, DataFixture.Create<string>(), DateTimeOffset.UtcNow) { Version = HistoricalEvents.Count }); _toggle2Version = HistoricalEvents.Count - 1; } private void GivenWeHaveDeletedTheProject() { HistoricalEvents.Add(new ProjectDeleted(UserId, _projectId, DateTime.UtcNow) { Version = HistoricalEvents.Count }); } private void GivenTheExpectedToggleVersionForOurNextCommandIsOffsetBy(int toggleVersionOffset) { _toggleToDeleteVersion += toggleVersionOffset; } private void WhenWeDeleteTheToggle() { UserId = DataFixture.Create<string>(); var command = new Command(UserId, _projectId, _toggleToDeleteKey, _toggleToDeleteVersion); WhenWeHandle(command); } private void ThenAToggleDeletedEventIsPublished() { var ev = (ToggleDeleted)PublishedEvents.First(e => e.GetType() == typeof(ToggleDeleted)); ev.UserId.Should().Be(UserId); ev.Key.Should().Be(_toggleToDeleteKey); ev.OccurredAt.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling); } private void ThenAnToggleStateDeletedEventsIsPublishedForEnvironment1() { ThenAnToggleStateDeletedEventsIsPublishedForEnvironment(_environment1Key); } private void ThenAnToggleStateDeletedEventsIsPublishedForEnvironment2() { ThenAnToggleStateDeletedEventsIsPublishedForEnvironment(_environment2Key); } private void ThenAnToggleStateDeletedEventsIsPublishedForEnvironment(string environmentKey) { var ev = (ToggleStateDeleted)PublishedEvents .First(e => e.GetType() == typeof(ToggleStateDeleted) && ((ToggleStateDeleted)e).EnvironmentKey == environmentKey); ev.ToggleKey.Should().Be(_toggleToDeleteKey); ev.OccurredAt.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling); ev.UserId.Should().Be(UserId); } private void ThenAnUnknownToggleExceptionIsThrown() { ThenAnInvalidOperationExceptionIsThrownWithMessage($"There is no toggle with the key {_toggleToDeleteKey}"); } private void ThenTheAggregateRootHasOneFewerToggles() { NewAggregate.Toggles.Count().Should().Be(OriginalAggregate.Toggles.Count() - 1); } private void ThenTheAggregateRootHasHadTheCorrectToggleRemoved() { NewAggregate.Toggles.Any(t => t.Key == _toggleToDeleteKey).Should().BeFalse(); } private void ThenTheFirstEnvironmentStateHasOneFewerToggleStates() { ThenTheEnvironmentStateHasOneFewerToggleStated(_environment1Key); } private void ThenTheSecondEnvironmentStateHasOneFewerToggleStates() { ThenTheEnvironmentStateHasOneFewerToggleStated(_environment2Key); } private void ThenTheEnvironmentStateHasOneFewerToggleStated(string environmentKey) { var environmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey); var oldEnvironmentState = OriginalAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey); environmentState.ToggleStates.Count().Should().Be(oldEnvironmentState.ToggleStates.Count() - 1); } private void ThenTheFirstEnvironmentStateHasHadTheCorrectToggleStateDeleted() { ThenTheEnvironmentStateHasHadTheToggleStateDeleted(_environment1Key); } private void ThenTheSecondEnvironmentStateHasHadTheCorrectToggleStateDeleted() { ThenTheEnvironmentStateHasHadTheToggleStateDeleted(_environment2Key); } private void ThenTheEnvironmentStateHasHadTheToggleStateDeleted(string environmentKey) { var environmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey); environmentState.ToggleStates.Any(ts => ts.Key == _toggleToDeleteKey).Should().BeFalse(); } private void ThenTheFirstEnvironmentStateLastModifiedTimeHasBeenUpdated() { ThenTheEnvironmentStateLastModifiedTimeHasBeenUpdated(_environment1Key); } private void ThenTheSecondEnvironmentStateLastModifiedTimeHasBeenUpdated() { ThenTheEnvironmentStateLastModifiedTimeHasBeenUpdated(_environment2Key); } private void ThenTheEnvironmentStateLastModifiedTimeHasBeenUpdated(string environmentKey) { var environmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey); environmentState.LastModified.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling); } private void ThenTheFirstEnvironmentStateLastModifiedByHasBeenUpdated() { ThenTheEnvironmentStateLastModifiedByHasBeenUpdated(_environment1Key); } private void ThenTheSecondEnvironmentStateLastModifiedByHasBeenUpdated() { ThenTheEnvironmentStateLastModifiedByHasBeenUpdated(_environment2Key); } private void ThenTheEnvironmentStateLastModifiedByHasBeenUpdated(string environmentKey) { var environmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey); environmentState.LastModifiedBy.Should().Be(UserId); } private void ThenTheFirstEnvironmentLastModifiedVersionIs(int expectedLastModifiedVersion) { ThenTheEnvironmentLastModifiedVersionIs(_environment1Key, expectedLastModifiedVersion); } private void ThenTheSecondEnvironmentLastModifiedVersionIs(int expectedLastModifiedVersion) { ThenTheEnvironmentLastModifiedVersionIs(_environment2Key, expectedLastModifiedVersion); } private void ThenTheEnvironmentLastModifiedVersionIs(string environmentKey, int expectedLastModifiedVersion) { var newEnvironmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey); newEnvironmentState.LastModifiedVersion.Should().Be(expectedLastModifiedVersion); } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CrystalDecisions.Shared; namespace WebApplication2 { /// <summary> /// Summary description for frmResourcesInfo. /// </summary> public partial class frmServiceTypes : System.Web.UI.Page { /*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+ "uid=tauheed;pwd=tauheed;");*/ private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn = new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here loadForm(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand); } #endregion private void loadForm() { if (Session["startForm"].ToString() == "frmMainControl") { DataGrid1.Columns[5].Visible = false; if (Session["CServiceTypes"].ToString() == "frmMainControl") { DataGrid1.Columns[3].Visible = false; btnAddAll.Visible = true; } else { DataGrid1.Columns[1].Visible = false; DataGrid1.Columns[3].Visible =true; DataGrid1.Columns[4].Visible = false; btnAddAll.Visible = false; } } else if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["CServiceTypes"].ToString() == "frmProfileServiceTypes") { btnRpt1.Visible = false; btnRpt5.Visible = false; btnRpt6.Visible = false; lblTitle.Text = "Service List"; DataGrid1.Columns[1].Visible = false; DataGrid1.Columns[3].Visible = false; DataGrid1.Columns[4].Visible = false; DataGrid1.Columns[5].Visible = false; btnAddAll.Visible = false; lblProcs.Visible = false; btnRpt2.Visible = false; lblStaff.Visible = false; btnRpt3.Visible = false; btnRpt4.Visible = false; DataGrid1.Columns[13].Visible = true; btnExit.Text = "OK"; lblContents.Text = "Please select services you wish to add to the business model then click 'OK'."; } else if (Session["CServiceTypes"].ToString() == "frmProfiles") { lblTitle.Text = "EcoSys: Individual/Household Characteristics"; lblTitle1.Text = "Type of Characteristic: " + Session["ProfilesName"].ToString(); lblContents.Text = "To continue, click on 'Select' for the appropriate stage below."; DataGrid1.Columns[2].HeaderText = "Stage"; DataGrid1.Columns[1].Visible = false; DataGrid1.Columns[4].Visible = false; DataGrid1.Columns[5].Visible = false; DataGrid1.Columns[13].Visible = false; btnAddAll.Visible = false; lblProcs.Visible = false; btnRpt1.Visible = false; btnRpt2.Visible = false; lblStaff.Visible = false; btnRpt3.Visible = false; btnRpt4.Visible = false; btnRpt5.Visible = false; btnRpt6.Visible = false; btnExit.Text = "OK"; lblContents.Text = ""; } else { lblContents.Text = "As indicated earlier, a service model" + " identifies the full set of service" + " deliverables, as well as related delivery procedures, staffing and other resource requirements." + " Listed below are the service models for which you are one of the designated authors." + " In the over-all EcoSys suite of systems, these service models, serve as building blocks for" + " business models."; DataGrid1.Columns[1].Visible = false; DataGrid1.Columns[3].Visible = false; DataGrid1.Columns[4].Visible = false; btnAddAll.Visible = false; } } else { DataGrid1.Columns[4].Visible = false; } if (!IsPostBack) { /*if (Session["startForm"].ToString() == "frmMainControl") { lblContent1.Text = "Update this service, including business processes " + " normally associated with this service" + ". You may identify services not included in this list by clicking" + " on the 'Add Services' button."; } else if (Session["startForm"].ToString() == "frmMainProfileMgr") { lblContent1.Text = ""; lblProcs.Text = ""; lblStaff.Text = ""; lblOther.Text = ""; lblUpdate.Text = "To update/add to the process models described by the reports above, click on the appropriate button" + " against the list of services below."; }*/ loadData(); } } private void loadData() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = this.epsDbConn; cmd.CommandText = "wms_RetrieveServiceTypes"; cmd.Parameters.Add("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString(); if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["CServiceTypes"].ToString() == "frmMainProfileMgr") { cmd.Parameters.Add("@PeopleId", SqlDbType.Int); cmd.Parameters["@PeopleId"].Value = Session["PeopleId"].ToString(); } else if (Session["ProfileType"].ToString() == "Consumer") { cmd.Parameters.Add("@HHFlag", SqlDbType.Int); cmd.Parameters["@HHFlag"].Value = 1; } } else { cmd.Parameters.Add("@OrgIdP", SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value = Session["OrgIdP"].ToString(); cmd.Parameters.Add("@LicenseId", SqlDbType.Int); cmd.Parameters["@LicenseId"].Value = Session["LicenseId"].ToString(); cmd.Parameters.Add("@DomainId", SqlDbType.Int); cmd.Parameters["@DomainId"].Value = Session["DomainId"].ToString(); } if (Session["startForm"].ToString() == "frmMainControl") { if (Session["ProfileType"].ToString() == "Consumer") { cmd.Parameters.Add("@HHFlag", SqlDbType.Int); cmd.Parameters["@HHFlag"].Value = "1"; } } DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ST"); Session["ds"] = ds; DataGrid1.DataSource = ds; DataGrid1.DataBind(); refreshGrid(); if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["CServiceTypes"].ToString() == "frmProfileServiceTypes") { refreshGrid1(); } } else if (Session["startForm"].ToString() == "frmMainControl") { refreshGrid3(); } } private void refreshGrid() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tb = (TextBox)(i.Cells[1].FindControl("txtSeq")); if (i.Cells[8].Text == "&nbsp;") { tb.Text = "99"; } else tb.Text = i.Cells[8].Text; } } private void refreshGrid1() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[13].FindControl("cbxSel")); SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.Text; cmd.CommandText = "Select Id from ProfileServiceTypes" + " Where ServiceTypesId = " + i.Cells[0].Text + " and ProfilesId = " + Session["ProfilesId"].ToString(); cmd.Connection.Open(); if (cmd.ExecuteScalar() != null) { cb.Checked = true; cb.Enabled = false; } cmd.Connection.Close(); } } /* private void refreshGrid2() { foreach (DataGridItem i in DataGrid1.Items) if (i.Cells[14].Text == "1") { Button btnD = (Button)(i.Cells[5].FindControl("btnDeliver")); Button btnP = (Button)(i.Cells[5].FindControl("btnProcess")); btnD.BackColor = Color.Cyan; btnD.Text = ""; btnP.ForeColor = Color.White; btnP.BackColor = Color.Cyan; btnP.Text = "Profiles"; btnP.CommandName="Profiles"; i.BackColor = Color.Cyan; i.ForeColor = Color.White; if (Session["startForm"].ToString() == "frmMainControl") { btnP.Enabled = false; } } }*/ private void refreshGrid3() { foreach (DataGridItem i in DataGrid1.Items) { if (i.Cells[14].Text == "1") { Button btnD = (Button)(i.Cells[5].FindControl("btnDeliver")); Button btnP = (Button)(i.Cells[5].FindControl("btnProcess")); btnD.BackColor = Color.Azure; btnD.Text = ""; btnP.BackColor = Color.Aqua; btnP.Text = "Profiles"; btnP.CommandName = "Profiles"; i.BackColor = Color.Aqua; } } } private void btnOK_Click(object sender, System.EventArgs e) { Exit(); } /*private void updateGrid() { if (Session["CServiceTypes"].ToString() == "frmProfileServiceTypes") { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox) (i.Cells[2].FindControl("cbxSel")); if ((cb.Checked == true) & (cb.Enabled==true)) { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_UpdateProfileServiceTypes"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int); cmd.Parameters ["@ServiceTypesId"].Value=i.Cells[0].Text; cmd.Parameters.Add("@ProfilesId", SqlDbType.Int); cmd.Parameters ["@ProfilesId"].Value=Session["ProfilesId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } else if (Session["CServiceTypes"].ToString() == "frmPSEPSer") { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox) (i.Cells[2].FindControl("cbxSel")); if ((cb.Checked == true) & (cb.Enabled==true)) { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_UpdatePSEPSer"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int); cmd.Parameters ["@ServiceTypesId"].Value=i.Cells[0].Text; cmd.Parameters.Add("@PSEPID", SqlDbType.Int); cmd.Parameters ["@PSEPID"].Value=Session["PSEPID"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } }*/ private void Exit() { Response.Redirect(strURL + Session["CServiceTypes"].ToString() + ".aspx?"); } protected void btnLogoff_Click(object sender, EventArgs e) { Response.Redirect("frmEnd.aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { if (Session["CServiceTypes"].ToString() == "frmMainControl") { updateGrid(); } else if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["CServiceTypes"].ToString() == "frmProfileServiceTypes") { updateGrid1(); } } Response.Redirect(strURL + Session["CServiceTypes"].ToString() + ".aspx?"); } private void updateGrid1() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[13].FindControl("cbxSel")); if ((cb.Checked) & (cb.Enabled)) { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_UpdateProfileServiceTypes"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@ProfilesId", SqlDbType.Int); cmd.Parameters["@ProfilesId"].Value = Session["ProfilesId"].ToString(); cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int); cmd.Parameters["@ServiceTypesId"].Value = i.Cells[0].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } private void updateGrid() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tb = (TextBox)(i.Cells[2].FindControl("txtSeq")); { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_UpdateSSeqNo"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = i.Cells[0].Text; cmd.Parameters.Add("@Seq", SqlDbType.Int); cmd.Parameters["@Seq"].Value = Int32.Parse(tb.Text); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } protected void btnAddAll_Click(object sender, System.EventArgs e) { Session["CUpdServiceTypes"] = "frmServiceTypes"; Response.Redirect(strURL + "frmUpdServiceType.aspx?" + "&btnAction=" + "Add"); } private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { } private void rpts() { Session["cRG"] = "frmServiceTypes"; Response.Redirect(strURL + "frmReportGen.aspx?"); } protected void btnRpt1_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "PeopleId"; if (Session["startForm"].ToString() == "frmMainControl") { discreteval.Value = "0"; } else { discreteval.Value = Session["PeopleId"].ToString(); } paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptServiceDeliverables.rpt"; rpts(); } protected void btnRpt2_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "PeopleId"; if (Session["startForm"].ToString() == "frmMainControl") { discreteval.Value = "0"; } else { discreteval.Value = Session["PeopleId"].ToString(); } paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptServiceProcs.rpt"; rpts(); } protected void btnRpt3_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "PeopleId"; if (Session["startForm"].ToString() == "frmMainControl") { discreteval.Value = "0"; } else { discreteval.Value = Session["PeopleId"].ToString(); } paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProcStaff.rpt"; rpts(); } protected void btnRpt4_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "PeopleId"; if (Session["startForm"].ToString() == "frmMainControl") { discreteval.Value = "0"; } else { discreteval.Value = Session["PeopleId"].ToString(); } paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProcOther.rpt"; rpts(); } protected void btnRpt5_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "PeopleId"; if (Session["startForm"].ToString() == "frmMainControl") { discreteval.Value = "0"; } else { discreteval.Value = Session["PeopleId"].ToString(); } paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProcOutputs.rpt"; rpts(); } protected void btnRpt6_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "PeopleId"; if (Session["startForm"].ToString() == "frmMainControl") { discreteval.Value = "0"; } else { discreteval.Value = Session["PeopleId"].ToString(); } paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProcClientImpacts.rpt"; rpts(); } protected void DataGrid1_SelectedIndexChanged(object sender, EventArgs e) { } protected void DataGrid1_ItemCommand1(object source, DataGridCommandEventArgs e) { if (e.CommandName == "Update") { Session["CUpdServiceTypes"] = "frmServiceTypes"; Response.Redirect(strURL + "frmUpdServiceType.aspx?" + "&btnAction=" + "Update" + "&Id=" + e.Item.Cells[0].Text + "&Name=" + e.Item.Cells[2].Text + "&ParentId=" + e.Item.Cells[6].Text + "&QtyMeasuresId=" + e.Item.Cells[7].Text + "&Seq=" + e.Item.Cells[8].Text + "&PJName=" + e.Item.Cells[9].Text + "&PJNameS=" + e.Item.Cells[10].Text + "&FunctionId=" + e.Item.Cells[11].Text + "&Desc=" + e.Item.Cells[12].Text + "&HHFlag=" + e.Item.Cells[14].Text ); } else if (e.CommandName == "Supply") { Session["CSEvents"] = "frmServiceTypes"; Session["ServicesId"] = e.Item.Cells[0].Text; Session["ServiceName"] = e.Item.Cells[2].Text; Response.Redirect(strURL + "frmServiceEvents.aspx?"); } else if (e.CommandName == "Profiles") { Session["CProfiles"] = "frmServiceTypes"; Session["ServicesId"] = e.Item.Cells[0].Text; Session["ServiceName"] = e.Item.Cells[2].Text; Session["ProfileType"] = "Consumer"; Session["Mode"] = "Profiles"; Response.Redirect(strURL + "frmProfiles.aspx?"); } else if (e.CommandName == "Processes") { Session["CProcs"] = "frmServiceTypes"; Session["ServicesId"] = e.Item.Cells[0].Text; Session["ServiceName"] = e.Item.Cells[2].Text; Response.Redirect(strURL + "frmProcs.aspx?"); } else if (e.CommandName == "Select") { if (Session["startForm"].ToString() == "frmMainControl") { if (Session["CServiceTypes"].ToString() == "frmProfileServiceTypes") { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_UpdateProfileServiceTypes"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@ProfilesId", SqlDbType.Int); cmd.Parameters["@ProfilesId"].Value = Session["ProfilesId"].ToString(); cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int); cmd.Parameters["@ServiceTypesId"].Value = Int32.Parse(e.Item.Cells[0].Text); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); /*SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_UpdatePSEPSer"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int); cmd.Parameters["@ServiceTypesId"].Value = Int32.Parse(e.Item.Cells[0].Text); cmd.Parameters.Add("@ProcsId", SqlDbType.Int); cmd.Parameters["@ProcsId"].Value = Session["ProcsId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close();*/ Exit(); } else { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_UpdatePeopleServiceTypes"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@ResTypesId", SqlDbType.Int); cmd.Parameters["@ResTypesId"].Value = Int32.Parse(e.Item.Cells[0].Text); cmd.Parameters.Add("@PeopleId", SqlDbType.Int); cmd.Parameters["@PeopleId"].Value = Session["PeopleId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Exit(); } } else // i.e. frmProfileServiceTypes { if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["ProfileType"].ToString() == "Consumer") { Session["CEventsAll"] = "frmServiceTypes"; Session["ServicesId"] = e.Item.Cells[0].Text; Session["ServiceName"] = e.Item.Cells[2].Text; Response.Redirect(strURL + "frmEventsAll.aspx?"); } } } //Exit(); } else if (e.CommandName == "Delete") { //SqlCommand cmd=new SqlCommand(); //cmd.CommandType=CommandType.StoredProcedure; //cmd.CommandText="wms_DeleteServiceType"; //cmd.Connection=this.epsDbConn; //cmd.Parameters.Add ("@Id", SqlDbType.Int); //cmd.Parameters["@Id"].Value=Int32.Parse (e.Item.Cells[0].Text); //cmd.Connection.Open(); //cmd.ExecuteNonQuery(); //cmd.Connection.Close(); //loadData(); } } } }
/******************************************************************************* * Copyright 2008-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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Submits feedback about an instance's status. /// </summary> /// <remarks> /// This action works only for instances that are in the running state. /// If your experience with the instance differs from the instance status returned by the /// DescribeInstanceStatus action, use ReportInstanceStatus to report your experience with the instance. /// Amazon EC2 collects this information to improve the accuracy of status checks. /// Use of this action does not change the value returned by DescribeInstanceStatus. /// </remarks> [XmlRootAttribute(IsNullable = false)] public class ReportInstanceStatusRequest : EC2Request { private List<string> instanceIdField; private string statusField; private string startTimeField; private string endTimeField; private List<string> reasonCodeField; private string descriptionField; /// <summary> /// One or more instance IDs. /// </summary> [XmlElementAttribute(ElementName = "InstanceId")] public List<string> InstanceId { get { if (this.instanceIdField == null) { this.instanceIdField = new List<string>(); } return this.instanceIdField; } set { this.instanceIdField = value; } } /// <summary> /// Sets one or more instance IDs. /// </summary> /// <param name="list">Instance IDs to report on.</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 ReportInstanceStatusRequest WithInstanceId(params string[] list) { foreach (string item in list) { InstanceId.Add(item); } return this; } /// <summary> /// Checks if the InstanceId property is set /// </summary> /// <returns>true if the InstanceId property is set</returns> public bool IsSetInstanceId() { return (InstanceId.Count > 0); } /// <summary> /// The status of all submitted instances. /// </summary> /// <remarks> /// Valid Values: ok | impaired /// </remarks> [XmlElementAttribute(ElementName = "Status")] public string Status { get { return this.statusField; } set { this.statusField = value; } } /// <summary> /// Sets the status of all submitted instances. /// </summary> /// <param name="status">Status for the instances.</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 ReportInstanceStatusRequest WithStatus(string status) { this.statusField = status; return this; } /// <summary> /// Checks if the Status property is set /// </summary> /// <returns>true if the Status property is set</returns> public bool IsSetStatus() { return !string.IsNullOrEmpty(this.Status); } /// <summary> /// The time at which the reported instance health state began. /// </summary> [XmlElementAttribute(ElementName = "StartTime")] public string StartTime { get { return this.startTimeField; } set { this.startTimeField = value; } } /// <summary> /// Sets the time at which the reported instance health state began. /// </summary> /// <param name="startTime">The start time of the health state</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 ReportInstanceStatusRequest WithStartTime(string startTime) { this.startTimeField = startTime; return this; } /// <summary> /// Checks if the StartTime property is set. /// </summary> /// <returns>True if the StartTime property is set</returns> public bool IsSetStartTime() { return !string.IsNullOrEmpty(this.StartTime); } /// <summary> /// The time at which the reported instance health state ended. /// </summary> [XmlElementAttribute(ElementName = "EndTime")] public string EndTime { get { return this.endTimeField; } set { this.endTimeField = value; } } /// <summary> /// Sets the time at which the reported instance health state ended. /// </summary> /// <param name="endTime">The end time of the health state</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 ReportInstanceStatusRequest WithEndTime(string endTime) { this.endTimeField = endTime; return this; } /// <summary> /// Checks if the EndTime property is set. /// </summary> /// <returns>true if the EndTime property is set</returns> public bool IsSetEndTime() { return !string.IsNullOrEmpty(this.EndTime); } /// <summary> /// Reason codes that describe the specified instances health states. /// </summary> /// <remarks> /// Each code you supply corresponds to an instance ID that you supply in the InstanceID /// collection. /// Valid Values: instance-stuck-in-state | unresponsive | not-accepting-credentials | /// password-not-available | performance-network | performance-instance-store | /// performance-ebs-volume | performance-other | other /// </remarks> [XmlElementAttribute(ElementName = "ReasonCode")] public List<string> ReasonCode { get { if (this.reasonCodeField == null) { this.reasonCodeField = new List<string>(); } return this.reasonCodeField; } set { this.reasonCodeField = value; } } /// <summary> /// Sets the reason codes that describe the specified instances health states /// </summary> /// <param name="list">One or more reason codes</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 ReportInstanceStatusRequest WithReasonCode(params string[] list) { foreach (string item in list) { ReasonCode.Add(item); } return this; } /// <summary> /// Checks if the ReasonCode property is set /// </summary> /// <returns>true if the ReasonCode property is set</returns> public bool IsSetReasonCode() { return (ReasonCode.Count > 0); } /// <summary> /// Description text about the instance health state. /// </summary> [XmlElementAttribute(ElementName = "Description")] public string Description { get { return this.descriptionField; } set { this.descriptionField = value; } } /// <summary> /// Sets the description text about the instance health state. /// </summary> /// <param name="description"></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 ReportInstanceStatusRequest WithDescription(string description) { this.descriptionField = description; return this; } /// <summary> /// Checks if the Description property is set /// </summary> /// <returns>true if the Description property is set</returns> public bool IsSetDescription() { return !string.IsNullOrEmpty(this.Description); } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Microsoft.VisualStudio.TestTools.UnitTesting; using MLifter.DAL; using MLifter.DAL.Interfaces; using MLifter.DAL.XML; using MLifter.BusinessLayer; using ICSharpCode.SharpZipLib.Zip; using MLifterTest.BusinessLayer; namespace MLifterTest.BusinessLayer { /// <summary> /// Summary Description for CopyTest /// </summary> [TestClass] public class CopyToTest { private TestContext testContextInstance; public static string TestDic { get; set; } public static string TestFolder { get; set; } /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { TestFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(TestFolder); MyClassCleanup(); //in case the LM is still open from another test ExtractTestDictionary(); InitializeDictionary(); } // //Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] public static void MyClassCleanup() { try { Directory.Delete(TestFolder, true); } catch { } TestInfrastructure.MyClassCleanup(); } // //Use TestInitialize to run code before running each test // //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run // [TestCleanup()] public void MyTestCleanup() { } // /// <summary> /// Extracts the test dictionary. /// </summary> /// <remarks>Documented by Dev02, 2008-05-16</remarks> public static void ExtractTestDictionary() { //extract test LM MemoryStream zipStream = new MemoryStream(Properties.Resources.StartupFolders); ZipInputStream zipFile = new ZipInputStream(zipStream); ZipEntry entry; while ((entry = zipFile.GetNextEntry()) != null) { string directoryName = Path.Combine(TestFolder, Path.GetDirectoryName(entry.Name)); string fileName = Path.GetFileName(entry.Name); if (directoryName.Length > 0) Directory.CreateDirectory(directoryName); if (fileName.Length > 0) { if (Path.GetExtension(fileName).ToLowerInvariant() == Helper.OdxExtension) TestDic = Path.Combine(directoryName, fileName); FileStream stream = File.Open(Path.Combine(directoryName, fileName), FileMode.Create, FileAccess.Write, FileShare.None); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (bufferSize > 0) { bufferSize = zipFile.Read(buffer, 0, buffer.Length); if (bufferSize > 0) stream.Write(buffer, 0, bufferSize); } stream.Close(); } } zipFile.Close(); } /// <summary> /// Initializes the dictionary. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-05-16</remarks> public static void InitializeDictionary() { } #endregion /// <summary> /// Simples the test. /// Create an Instance of a IDictionary, check if reference is != null and verify the typ of the object. /// </summary> /// <remarks>Documented by Dev10, 2008-28-07</remarks> [TestMethod] [TestProperty("BusinessLayer", "Matbre00"), DataSource("TestSources")] public void CopyToBasicTest() { //Perform Test only if we use a db connection otherwise test case makes no sense if (TestInfrastructure.IsActive(TestContext) && TestInfrastructure.ConnectionType(TestContext) != "File") { IUser sourceUser = null; IUser targetUser = null; try { string repositoryNameFinal = "finalTargetForCopyTest" + System.Environment.MachineName.ToLower(); //Do we have a target to copy from Assert.IsTrue(File.Exists(TestDic), "Test Learning Module file cannot be found."); ConnectionStringStruct sourceConnection = new ConnectionStringStruct(DatabaseType.Xml, CopyToTest.TestDic, false); sourceUser = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return u; }, sourceConnection, (DataAccessErrorDelegate)delegate { return; }, this); if (!authenticationUsers.ContainsKey(sourceConnection.ConnectionString)) authenticationUsers.Add(sourceConnection.ConnectionString, sourceUser.AuthenticationStruct); //Copy the reference LM to the new persistent LM ConnectionStringStruct dbConnection; using (Dictionary dbTarget = TestInfrastructure.GetConnection(TestContext)) { IUser dbUser = dbTarget.DictionaryDAL.Parent.CurrentUser; dbConnection = dbUser.ConnectionString; if (!authenticationUsers.ContainsKey(dbConnection.ConnectionString)) authenticationUsers.Add(dbConnection.ConnectionString, dbUser.AuthenticationStruct); dbTarget.Dispose(); finished = false; LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished); LearnLogic.CopyLearningModule(sourceConnection, dbConnection, GetUser, (MLifter.DAL.Tools.CopyToProgress)delegate(string m, double p) { return; }, (DataAccessErrorDelegate)delegate { return; }, null); while (!finished) { System.Threading.Thread.Sleep(100); }; LearnLogic.CopyToFinished -= new EventHandler(LearnLogic_CopyToFinished); } //copy to another persistent LM where we use Save to store as odx again ConnectionStringStruct targetConnection; using (Dictionary target = TestInfrastructure.GetPersistentLMConnection(TestContext, "sqlce")) { targetUser = target.DictionaryDAL.Parent.CurrentUser; targetConnection = targetUser.ConnectionString; if (!authenticationUsers.ContainsKey(targetConnection.ConnectionString)) authenticationUsers.Add(targetConnection.ConnectionString, targetUser.AuthenticationStruct); target.Dispose(); finished = false; LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished); LearnLogic.CopyLearningModule(dbConnection, targetConnection, GetUser, (MLifter.DAL.Tools.CopyToProgress)delegate(string m, double p) { return; }, (DataAccessErrorDelegate)delegate { return; }, null); while (!finished) { System.Threading.Thread.Sleep(100); }; LearnLogic.CopyToFinished -= new EventHandler(LearnLogic_CopyToFinished); } using (Dictionary source = new Dictionary(sourceUser.Open(), null)) using (Dictionary target = new Dictionary(targetUser.Open(), null)) { CompareChapters(source.Chapters.Chapters, target.Chapters.Chapters); //Verification Code compare finalTarget with the reference target CompareCards(source.Cards.Cards, target.Cards.Cards, source, target); //Compare Settings CompareSettings(source.Settings, target.Settings); if ((source.Settings != null) && (target.Settings != null)) { //Compare Styles CompareStyles(source.Settings.Style, target.Settings.Style); } } } finally { if (sourceUser != null) sourceUser.Logout(); if (targetUser != null) targetUser.Logout(); } } } private bool finished = false; void LearnLogic_CopyToFinished(object sender, EventArgs e) { finished = true; } private System.Collections.Generic.Dictionary<string, UserStruct> authenticationUsers = new System.Collections.Generic.Dictionary<string, UserStruct>(); private UserStruct? GetUser(UserStruct user, ConnectionStringStruct connection) { return authenticationUsers[connection.ConnectionString]; } /// <summary> /// Compares the cards. /// </summary> /// <param name="reference">The reference.</param> /// <param name="copy">The copy.</param> /// <remarks>Documented by Dev03, 2008-09-26</remarks> private void CompareCards(IList<ICard> reference, IList<ICard> copy, Dictionary referenceDic, Dictionary copyDic) { Assert.AreEqual<int>(reference.Count, copy.Count, "Numbers of cards are not equal"); //create Lists to work on List<ICard> referenceList = new List<ICard>(); List<ICard> copyList = new List<ICard>(); referenceList.AddRange(reference); copyList.AddRange(copy); //compare the cards foreach (ICard card in reference) { ICard match = copyList.Find( delegate(ICard cardCopy) { bool isMatch = true; isMatch = isMatch && (card.Active == cardCopy.Active); isMatch = isMatch && (card.Answer.ToString() == cardCopy.Answer.ToString()); isMatch = isMatch && (card.Question.ToString() == cardCopy.Question.ToString()); isMatch = isMatch && (card.AnswerExample.ToString() == cardCopy.AnswerExample.ToString()); isMatch = isMatch && (card.QuestionExample.ToString() == cardCopy.QuestionExample.ToString()); isMatch = isMatch && (card.AnswerDistractors.ToString() == cardCopy.AnswerDistractors.ToString()); isMatch = isMatch && (card.QuestionDistractors.ToString() == cardCopy.QuestionDistractors.ToString()); isMatch = isMatch && (card.Box == cardCopy.Box); IChapter chapter2search = FindChapter(referenceDic.Chapters.Chapters, card.Chapter); isMatch = isMatch && (FindChapter(copyDic.Chapters.Chapters, chapter2search) != null); Debug.WriteLine("#####" + card.Id); Debug.WriteLine("########" + card.Answer); Debug.WriteLine("########" + cardCopy.Answer); Debug.WriteLine("########" + isMatch); return isMatch; } ); Assert.IsTrue(match != null, String.Format("Card not found:\n{0}", card.ToString())); //CompareMedia(card, match); //AAB_MBR not implemented for XML# CompareSettings(card.Settings, match.Settings); if ((card.Settings != null) && (match.Settings != null)) { CompareStyles(card.Settings.Style, match.Settings.Style); } } } /// <summary> /// Compares the chapters. /// </summary> /// <param name="reference">The reference.</param> /// <param name="copy">The copy.</param> /// <remarks>Documented by Dev03, 2008-09-26</remarks> private void CompareChapters(IList<IChapter> reference, IList<IChapter> copy) { Assert.AreEqual<int>(reference.Count, copy.Count, "Numbers of chapters are not equal"); //create Lists to work on List<IChapter> referenceList = new List<IChapter>(); List<IChapter> copyList = new List<IChapter>(); referenceList.AddRange(reference); copyList.AddRange(copy); //compare the cards foreach (IChapter chapter in reference) { IChapter match = copyList.Find( delegate(IChapter chapterCopy) { bool isMatch = true; isMatch = isMatch && (chapter.Title == chapterCopy.Title); isMatch = isMatch && (chapter.Description == chapterCopy.Description); Debug.WriteLine("#####" + chapter.Id); Debug.WriteLine("########" + chapter.Title); Debug.WriteLine("########" + chapter.Description); Debug.WriteLine("########" + chapterCopy.Title); Debug.WriteLine("########" + chapterCopy.Description); Debug.WriteLine("########" + isMatch); return isMatch; } ); Assert.IsTrue(match != null, "Chapter not found"); //AAB_MBR not implemented for XML# CompareSettings(chapter.Settings, match.Settings); if ((chapter.Settings != null) && (match.Settings != null)) { CompareStyles(chapter.Settings.Style, match.Settings.Style); } } } /// <summary> /// Finds the chapter. /// </summary> /// <param name="list">The list chapters to search.</param> /// <param name="chapter2find">The chapter to find.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2008-09-26</remarks> private IChapter FindChapter(IList<IChapter> chapters2search, IChapter chapter2find) { List<IChapter> list = new List<IChapter>(); list.AddRange(chapters2search); IChapter match = list.Find( delegate(IChapter chapter) { bool isMatch = true; isMatch = isMatch && (chapter2find.Title == chapter.Title); isMatch = isMatch && (chapter2find.Description == chapter.Description); return isMatch; } ); return match; } /// <summary> /// Finds the chapter. /// </summary> /// <param name="chapters2search">The list chapters to search.</param> /// <param name="chapter2find">The chapter id to find.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2008-09-26</remarks> private IChapter FindChapter(IList<IChapter> chapters2search, int chapter2find) { List<IChapter> list = new List<IChapter>(); list.AddRange(chapters2search); IChapter match = list.Find( delegate(IChapter chapter) { bool isMatch = true; isMatch = isMatch && (chapter2find == chapter.Id); return isMatch; } ); return match; } /// <summary> /// Compares two objects that implement ISettings. /// </summary> /// <param name="one">The first ISettings object.</param> /// <param name="two">The second ISettings object.</param> /// <remarks>Documented by Dev03, 2008-09-26</remarks> private void CompareSettings(ISettings one, ISettings two) { if ((one == null) || (two == null)) { Assert.AreEqual(one, two, "Both settings should be null!"); return; } if ((one != null) && (two != null)) { //Basic type properties Assert.AreEqual<string>(one.AnswerCaption, two.AnswerCaption, "AnswerCaption do not match"); Assert.AreEqual<bool?>(one.AutoBoxSize, two.AutoBoxSize, "AutoBoxSize do not match"); Assert.AreEqual<bool?>(one.AutoplayAudio, two.AutoplayAudio, "AutoplayAudio do not match"); Assert.AreEqual<bool?>(one.CaseSensitive, two.CaseSensitive, "CaseSensitive do not match"); Assert.AreEqual<bool?>(one.IgnoreAccentChars, two.IgnoreAccentChars, "IgnoreAccentChars do not match"); Assert.AreEqual<bool?>(one.ConfirmDemote, two.ConfirmDemote, "ConfirmDemote do not match"); Assert.AreEqual<bool?>(one.CorrectOnTheFly, two.CorrectOnTheFly, "CorrectOnTheFly do not match"); Assert.AreEqual<bool?>(one.EnableCommentary, two.EnableCommentary, "EnableCommentary do not match"); Assert.AreEqual<bool?>(one.EnableTimer, two.EnableTimer, "EnableTimer do not match"); Assert.AreEqual<bool?>(one.PoolEmptyMessageShown, two.PoolEmptyMessageShown, "PoolEmptyMessageShown do not match"); Assert.AreEqual<string>(one.QuestionCaption, two.QuestionCaption, "QuestionCaption do not match"); Assert.AreEqual<bool?>(one.RandomPool, two.RandomPool, "RandomPool do not match"); Assert.AreEqual<bool?>(one.SelfAssessment, two.SelfAssessment, "SelfAssessment do not match"); Assert.AreEqual<bool?>(one.ShowImages, two.ShowImages, "ShowImages do not match"); Assert.AreEqual<bool?>(one.ShowStatistics, two.ShowStatistics, "ShowStatistics do not match"); Assert.AreEqual<bool?>(one.SkipCorrectAnswers, two.SkipCorrectAnswers, "SkipCorrectAnswers do not match"); Assert.AreEqual<string>(one.StripChars, two.StripChars, "StripChars do not match"); Assert.AreEqual<string>(one.ToString(), two.ToString(), ".ToString() do not match"); Assert.AreEqual<bool?>(one.UseLMStylesheets, two.UseLMStylesheets, "UseLMStylesheets do not match"); //Other Types Assert.IsTrue(one.AnswerCulture.Equals(two.AnswerCulture), "AnswerCulture do not match"); Assert.IsTrue(one.QuestionCulture.Equals(two.QuestionCulture), "QuestionCulture do not match"); Assert.IsTrue(one.GradeSynonyms.Equals(two.GradeSynonyms), "GradeSynonyms do not match"); Assert.IsTrue(one.GradeTyping.Equals(two.GradeTyping), "GradeTyping do not match"); Assert.IsTrue(checkMedia(one.Logo, two.Logo), "Logo do not match"); Assert.IsTrue(one.MultipleChoiceOptions.Equals(two.MultipleChoiceOptions), "MultipleChoiceOptions do not match"); Assert.IsTrue(one.QueryDirections.Equals(two.QueryDirections), "QueryDirections do not match"); Assert.IsTrue(one.QueryTypes.Equals(two.QueryTypes), "QueryTypes do not match"); Assert.IsTrue(checkStyleSheet(one.AnswerStylesheet, two.AnswerStylesheet), "AnswerStylesheet do not match"); Assert.IsTrue(checkStyleSheet(one.QuestionStylesheet, two.QuestionStylesheet), "QuestionStylesheet do not match"); checkSelectedLearnChapters(one.SelectedLearnChapters, two.SelectedLearnChapters); checkCommentarySounds(one.CommentarySounds, two.CommentarySounds); //Snooze Options Assert.AreEqual<bool?>(one.SnoozeOptions.IsCardsEnabled, two.SnoozeOptions.IsCardsEnabled, "SnoozeOptions.IsCardsEnabled do not match"); Assert.AreEqual<bool?>(one.SnoozeOptions.IsRightsEnabled, two.SnoozeOptions.IsRightsEnabled, "SnoozeOptions.IsRightsEnabled do not match"); Assert.AreEqual<bool?>(one.SnoozeOptions.IsTimeEnabled, two.SnoozeOptions.IsTimeEnabled, "SnoozeOptions.IsTimeEnabled do not match"); Assert.AreEqual<int?>(one.SnoozeOptions.SnoozeCards, two.SnoozeOptions.SnoozeCards, "SnoozeOptions.SnoozeCards do not match"); Assert.AreEqual<int?>(one.SnoozeOptions.SnoozeHigh, two.SnoozeOptions.SnoozeHigh, "SnoozeOptions.SnoozeHigh do not match"); Assert.AreEqual<int?>(one.SnoozeOptions.SnoozeLow, two.SnoozeOptions.SnoozeLow, "SnoozeOptions.SnoozeLow do not match"); Assert.AreEqual<int?>(one.SnoozeOptions.SnoozeRights, two.SnoozeOptions.SnoozeRights, "SnoozeOptions.SnoozeRights do not match"); Assert.AreEqual<int?>(one.SnoozeOptions.SnoozeTime, two.SnoozeOptions.SnoozeTime, "SnoozeOptions.SnoozeTime do not match"); Assert.AreEqual<string>(one.SnoozeOptions.SnoozeMode.ToString(), two.SnoozeOptions.SnoozeMode.ToString(), "SnoozeOptions.SnoozeMode.ToString() do not match"); Assert.AreEqual<ESnoozeMode>(one.SnoozeOptions.SnoozeMode.Value, one.SnoozeOptions.SnoozeMode.Value, "SnoozeOptions.SnoozeMode.Value do not match"); //Styles CompareStyles(one.Style, two.Style); } } /// <summary> /// Checks the commentary sounds. /// </summary> /// <param name="one">The one.</param> /// <param name="two">The two.</param> /// <remarks>Documented by Dev10, 2008-29-09</remarks> private void checkCommentarySounds(Dictionary<CommentarySoundIdentifier, IMedia> one, Dictionary<CommentarySoundIdentifier, IMedia> two) { Assert.AreEqual<int>(one.Count, two.Count, "Number of commentary Sounds do not match"); foreach (KeyValuePair<CommentarySoundIdentifier, IMedia> kvp in one) { if (two.ContainsKey(kvp.Key)) { Assert.IsTrue(checkMedia(two[kvp.Key], kvp.Value), "Media do not match"); } else Assert.Fail("Key is missing in one directory, in commentary Sounds"); } } /// <summary> /// Checks Media. /// </summary> /// <param name="one">The one.</param> /// <param name="two">The two.</param> /// <returns></returns> /// <remarks>Documented by Dev10, 2008-29-09</remarks> private bool checkMedia(IMedia one, IMedia two) { if (one != null && two != null) { bool isMatch = true; isMatch = isMatch && (one.Active == two.Active); isMatch = isMatch && (one.Default == two.Default); isMatch = isMatch && (one.Example == two.Example); isMatch = isMatch && (one.MimeType == two.MimeType); isMatch = isMatch && (one.MediaType == two.MediaType); isMatch = isMatch && (one.Stream.Length == two.Stream.Length); return isMatch; } else if (one == null && two == null) return true; else return false; } /// <summary> /// Checks the selected learn chapters, whether they are available in both LMs. /// </summary> /// <param name="one">The one.</param> /// <param name="two">The two.</param> /// <remarks>Documented by Dev10, 2008-29-09</remarks> private void checkSelectedLearnChapters(IList<int> one, IList<int> two) { //List<int> twoSelectedLearnChapters = new List<int>(); //twoSelectedLearnChapters.AddRange(two); //foreach (int chapter in one) //{ // Assert.IsTrue(twoSelectedLearnChapters.Exists(c => c == chapter), string.Format("Chapter {0} not found in both.", chapter)); //} Assert.AreEqual<int>(one.Count, two.Count, "Selected learning chapters are not equal"); return; } /// <summary> /// Checks the style sheet for e.g. Answer StyleSheet or Question StyleSheet. /// </summary> /// <param name="one">The one.</param> /// <param name="two">The two.</param> /// <returns></returns> /// <remarks>Documented by Dev10, 2008-29-09</remarks> private bool checkStyleSheet(CompiledTransform? one, CompiledTransform? two) { if (one.HasValue && two.HasValue) return one.Value.Equals(two.Value); else if (!one.HasValue && !two.HasValue) return true; else if (!one.HasValue && two.Value.XslContent == string.Empty) return true; else if (!two.HasValue && one.Value.XslContent == string.Empty) return true; else return false; } /// <summary> /// Compares the Media of card one with those of card two. /// </summary> /// <param name="one">The card one.</param> /// <param name="two">The card two.</param> /// <remarks>Documented by Dev03, 2008-09-29</remarks> private void CompareMedia(ICard one, ICard two) { List<IMedia> answerMedia = new List<IMedia>(); answerMedia.AddRange(two.AnswerMedia); foreach (IMedia media in one.AnswerMedia) { Assert.IsTrue( answerMedia.Exists( delegate(IMedia m) { bool isMatch = true; isMatch = isMatch && (m.Active == media.Active); isMatch = isMatch && (m.Default == media.Default); isMatch = isMatch && (m.Example == media.Example); isMatch = isMatch && (m.MimeType == media.MimeType); isMatch = isMatch && (m.MediaType == media.MediaType); isMatch = isMatch && (m.Stream.Length == media.Stream.Length); return isMatch; } ), String.Format("No match for answer Media item found in card {0}.", one.ToString())); } List<IMedia> questionMedia = new List<IMedia>(); questionMedia.AddRange(two.QuestionMedia); foreach (IMedia media in one.QuestionMedia) { Assert.IsTrue( questionMedia.Exists( delegate(IMedia m) { bool isMatch = true; isMatch = isMatch && (m.Active == media.Active); isMatch = isMatch && (m.Default == media.Default); isMatch = isMatch && (m.Example == media.Example); isMatch = isMatch && (m.MimeType == media.MimeType); isMatch = isMatch && (m.MediaType == media.MediaType); isMatch = isMatch && (m.Stream.Length == media.Stream.Length); return isMatch; } ), String.Format("No match for question Media item found in card {0}.", one.ToString())); } } /// <summary> /// Compares two objects that implement ICardStyle. /// </summary> /// <param name="one">The first ICardStyle object one.</param> /// <param name="two">The second ICardStyle object.</param> /// <remarks>Documented by Dev03, 2008-09-26</remarks> private void CompareStyles(ICardStyle one, ICardStyle two) { if ((one == null) || (two == null)) { Assert.IsTrue(IsEmptyStyle(one), "Both styles should be null! (one)"); Assert.IsTrue(IsEmptyStyle(two), "Both styles should be null! (two)"); return; } Type typeCardStyle = one.GetType(); foreach (PropertyInfo property in typeCardStyle.GetProperties()) { if (property.GetType().Equals(typeof(ITextStyle))) { ITextStyle textStyleOne = property.GetValue(one, null) as ITextStyle; ITextStyle textStyleTwo = property.GetValue(two, null) as ITextStyle; Type typeTextStyle = textStyleOne.GetType(); foreach (PropertyInfo prop in typeTextStyle.GetProperties()) { if (prop.GetType().Equals(typeof(int))) { int valueOne = (int)prop.GetValue(textStyleOne, null); int valueTwo = (int)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.GetType().Equals(typeof(string))) { string valueOne = (string)prop.GetValue(textStyleOne, null); string valueTwo = (string)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.GetType().Equals(typeof(System.Drawing.Color))) { System.Drawing.Color valueOne = (System.Drawing.Color)prop.GetValue(textStyleOne, null); System.Drawing.Color valueTwo = (System.Drawing.Color)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.GetType().Equals(typeof(System.Drawing.FontFamily))) { System.Drawing.FontFamily valueOne = (System.Drawing.FontFamily)prop.GetValue(textStyleOne, null); System.Drawing.FontFamily valueTwo = (System.Drawing.FontFamily)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.GetType().Equals(typeof(FontSizeUnit))) { FontSizeUnit valueOne = (FontSizeUnit)prop.GetValue(textStyleOne, null); FontSizeUnit valueTwo = (FontSizeUnit)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.GetType().Equals(typeof(CSSFontStyle))) { CSSFontStyle valueOne = (CSSFontStyle)prop.GetValue(textStyleOne, null); CSSFontStyle valueTwo = (CSSFontStyle)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.GetType().Equals(typeof(HorizontalAlignment))) { HorizontalAlignment valueOne = (HorizontalAlignment)prop.GetValue(textStyleOne, null); HorizontalAlignment valueTwo = (HorizontalAlignment)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.GetType().Equals(typeof(VerticalAlignment))) { VerticalAlignment valueOne = (VerticalAlignment)prop.GetValue(textStyleOne, null); VerticalAlignment valueTwo = (VerticalAlignment)prop.GetValue(textStyleTwo, null); Assert.AreEqual(valueOne, valueOne, String.Format("Both values for {0} should be equal!", prop.Name)); } else if (prop.Name == "OtherElements") { SerializableDictionary<string, string> otherElementsOne = prop.GetValue(textStyleOne, null) as SerializableDictionary<string, string>; SerializableDictionary<string, string> otherElementsTwo = prop.GetValue(textStyleTwo, null) as SerializableDictionary<string, string>; foreach (string key in otherElementsOne.Keys) { Assert.IsTrue((otherElementsTwo.ContainsKey(key) && otherElementsOne[key].Equals(otherElementsTwo[key])), String.Format("Both values for {0}[{1}] should be equal!", prop.Name, key)); } } } } } } /// <summary> /// Determines whether [is empty style] [the specified style]. /// </summary> /// <param name="style">The style.</param> /// <returns> /// <c>true</c> if [is empty style] [the specified style]; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev03, 2008-09-29</remarks> private bool IsEmptyStyle(ICardStyle style) { if (style == null) return true; bool result = true; Type typeCardStyle = style.GetType(); foreach (PropertyInfo property in typeCardStyle.GetProperties()) { if (property.GetType().Equals(typeof(ITextStyle))) { ITextStyle textStyle = property.GetValue(style, null) as ITextStyle; Type typeTextStyle = textStyle.GetType(); foreach (PropertyInfo prop in typeTextStyle.GetProperties()) { if (prop.GetType().Equals(typeof(int))) { int value = (int)prop.GetValue(textStyle, null); result = result && (value == 0); } else if (prop.GetType().Equals(typeof(string))) { string value = (string)prop.GetValue(textStyle, null); result = result && (value.Length == 0); } else if (prop.GetType().Equals(typeof(System.Drawing.Color))) { System.Drawing.Color value = (System.Drawing.Color)prop.GetValue(textStyle, null); result = result && (value == System.Drawing.Color.Empty); } else if (prop.GetType().Equals(typeof(System.Drawing.FontFamily))) { System.Drawing.FontFamily value = (System.Drawing.FontFamily)prop.GetValue(textStyle, null); result = result && (value == null); } else if (prop.GetType().Equals(typeof(FontSizeUnit))) { FontSizeUnit value = (FontSizeUnit)prop.GetValue(textStyle, null); result = result && (value == FontSizeUnit.Pixel); } else if (prop.GetType().Equals(typeof(CSSFontStyle))) { CSSFontStyle value = (CSSFontStyle)prop.GetValue(textStyle, null); result = result && (value == CSSFontStyle.None); } else if (prop.GetType().Equals(typeof(HorizontalAlignment))) { HorizontalAlignment value = (HorizontalAlignment)prop.GetValue(textStyle, null); result = result && (value == HorizontalAlignment.None); } else if (prop.GetType().Equals(typeof(VerticalAlignment))) { VerticalAlignment value = (VerticalAlignment)prop.GetValue(textStyle, null); result = result && (value == VerticalAlignment.None); } else if (prop.Name == "OtherElements") { SerializableDictionary<string, string> otherElements = prop.GetValue(textStyle, null) as SerializableDictionary<string, string>; result = result && (otherElements.Count == 0); } } } } 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.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography.Apple; using System.Security.Cryptography.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography { internal sealed class EccSecurityTransforms : IDisposable { private SecKeyPair _keys; public void Dispose() { _keys?.Dispose(); _keys = null; } internal int GenerateKey(ECCurve curve) { curve.Validate(); if (!curve.IsNamed) { throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly); } int keySize; switch (curve.Oid.Value) { case Oids.secp256r1: keySize = 256; break; case Oids.secp384r1: keySize = 384; break; case Oids.secp521r1: keySize = 521; break; default: throw new PlatformNotSupportedException( SR.Format(SR.Cryptography_CurveNotSupported, curve.Oid.Value)); } GenerateKey(keySize); return keySize; } private SecKeyPair GenerateKey(int keySizeInBits) { SafeSecKeyRefHandle publicKey; SafeSecKeyRefHandle privateKey; Interop.AppleCrypto.EccGenerateKey(keySizeInBits, out publicKey, out privateKey); SecKeyPair newPair = SecKeyPair.PublicPrivatePair(publicKey, privateKey); SetKey(newPair); return newPair; } internal SecKeyPair GetOrGenerateKeys(int keySizeInBits) { SecKeyPair current = _keys; if (current != null) { return current; } return GenerateKey(keySizeInBits); } internal int SetKeyAndGetSize(SecKeyPair keyPair) { int size = GetKeySize(keyPair); SetKey(keyPair); return size; } private void SetKey(SecKeyPair keyPair) { SecKeyPair current = _keys; _keys = keyPair; current?.Dispose(); } internal ECParameters ExportParameters(bool includePrivateParameters, int keySizeInBits) { // Apple requires all private keys to be exported encrypted, but since we're trying to export // as parsed structures we will need to decrypt it for the user. const string ExportPassword = "DotnetExportPassphrase"; SecKeyPair keys = GetOrGenerateKeys(keySizeInBits); if (keys.PublicKey == null || (includePrivateParameters && keys.PrivateKey == null)) { throw new CryptographicException(SR.Cryptography_OpenInvalidHandle); } byte[] keyBlob = Interop.AppleCrypto.SecKeyExport( includePrivateParameters ? keys.PrivateKey : keys.PublicKey, exportPrivate: includePrivateParameters, password: ExportPassword); try { if (!includePrivateParameters) { EccKeyFormatHelper.ReadSubjectPublicKeyInfo( keyBlob, out int localRead, out ECParameters key); return key; } else { EccKeyFormatHelper.ReadEncryptedPkcs8( keyBlob, ExportPassword, out int localRead, out ECParameters key); return key; } } finally { CryptographicOperations.ZeroMemory(keyBlob); } } internal int ImportParameters(ECParameters parameters) { parameters.Validate(); bool isPrivateKey = parameters.D != null; SecKeyPair newKeys; if (isPrivateKey) { // Start with the private key, in case some of the private key fields don't // match the public key fields and the system determines an integrity failure. // // Public import should go off without a hitch. SafeSecKeyRefHandle privateKey = ImportKey(parameters); ECParameters publicOnly = parameters; publicOnly.D = null; SafeSecKeyRefHandle publicKey; try { publicKey = ImportKey(publicOnly); } catch { privateKey.Dispose(); throw; } newKeys = SecKeyPair.PublicPrivatePair(publicKey, privateKey); } else { SafeSecKeyRefHandle publicKey = ImportKey(parameters); newKeys = SecKeyPair.PublicOnly(publicKey); } int size = GetKeySize(newKeys); SetKey(newKeys); return size; } private static int GetKeySize(SecKeyPair newKeys) { long size = Interop.AppleCrypto.EccGetKeySizeInBits(newKeys.PublicKey); Debug.Assert(size == 256 || size == 384 || size == 521, $"Unknown keysize ({size})"); return (int)size; } private static SafeSecKeyRefHandle ImportKey(ECParameters parameters) { if (parameters.D != null) { using (AsnWriter privateKey = EccKeyFormatHelper.WriteECPrivateKey(parameters)) { return Interop.AppleCrypto.ImportEphemeralKey(privateKey.EncodeAsSpan(), true); } } else { using (AsnWriter publicKey = EccKeyFormatHelper.WriteSubjectPublicKeyInfo(parameters)) { return Interop.AppleCrypto.ImportEphemeralKey(publicKey.EncodeAsSpan(), false); } } } internal unsafe int ImportSubjectPublicKeyInfo( ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { // Validate the DER value and get the number of bytes. EccKeyFormatHelper.ReadSubjectPublicKeyInfo( manager.Memory, out int localRead); SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.ImportEphemeralKey(source.Slice(0, localRead), false); SecKeyPair newKeys = SecKeyPair.PublicOnly(publicKey); int size = GetKeySize(newKeys); SetKey(newKeys); bytesRead = localRead; return size; } } } } }
using System.IO; using System.Threading.Tasks; using Cake.Common.Build.GitHubActions.Commands; using Cake.Common.Tests.Fixtures.Build; using Cake.Core; using Cake.Core.IO; using Cake.Testing; using NSubstitute; using Xunit; namespace Cake.Common.Tests.Unit.Build.GitHubActions.Commands { public sealed class GitHubActionsCommandsTests { public sealed class TheConstructor { [Fact] public void Should_Throw_If_Environment_Is_Null() { // Given, When var result = Record.Exception(() => new GitHubActionsCommands(null, null, null, null)); // Then AssertEx.IsArgumentNullException(result, "environment"); } [Fact] public void Should_Throw_If_FileSystem_Is_Null() { // Given var environment = Substitute.For<ICakeEnvironment>(); // When var result = Record.Exception(() => new GitHubActionsCommands(environment, null, null, null)); // Then AssertEx.IsArgumentNullException(result, "fileSystem"); } [Fact] public void Should_Throw_If_ActionsEnvironment_Is_Null() { // Given var environment = Substitute.For<ICakeEnvironment>(); var filesystem = Substitute.For<IFileSystem>(); // When var result = Record.Exception(() => new GitHubActionsCommands(environment, filesystem, null, null)); // Then AssertEx.IsArgumentNullException(result, "actionsEnvironment"); } [Fact] public void Should_Throw_If_CreateHttpClient_Is_Null() { // Given var environment = Substitute.For<ICakeEnvironment>(); var filesystem = Substitute.For<IFileSystem>(); var actionsEnvironment = new GitHubActionsInfoFixture().CreateEnvironmentInfo(); // When var result = Record.Exception(() => new GitHubActionsCommands(environment, filesystem, actionsEnvironment, null)); // Then AssertEx.IsArgumentNullException(result, "createHttpClient"); } } public sealed class TheAddPathMethod { [Fact] public void Should_Throw_If_Path_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); // When var result = Record.Exception(() => commands.AddPath(null)); // Then AssertEx.IsArgumentNullException(result, "path"); } [Fact] public void Should_Throw_If_SystemPath_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture() .WithNoGitHubPath() .CreateGitHubActionsCommands(); var path = "/temp/dev/bin"; // When var result = Record.Exception(() => commands.AddPath(path)); // Then AssertEx.IsCakeException(result, "GitHub Actions Runtime SystemPath missing."); } [Fact] public void Should_AddPath() { // Given var gitHubActionsCommandsFixture = new GitHubActionsCommandsFixture(); var commands = gitHubActionsCommandsFixture.CreateGitHubActionsCommands(); var path = "/temp/dev/bin"; // When commands.AddPath(path); // Then Assert.Equal( (path + System.Environment.NewLine).NormalizeLineEndings(), gitHubActionsCommandsFixture.FileSystem.GetFile("/opt/github.path").GetTextContent().NormalizeLineEndings()); } } public sealed class TheSetEnvironmentVariableMethod { [Fact] public void Should_Throw_If_Key_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); // When var result = Record.Exception(() => commands.SetEnvironmentVariable(null, null)); // Then AssertEx.IsArgumentNullException(result, "key"); } [Fact] public void Should_Throw_If_Value_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var key = "Key"; // When var result = Record.Exception(() => commands.SetEnvironmentVariable(key, null)); // Then AssertEx.IsArgumentNullException(result, "value"); } [Fact] public void Should_Throw_If_EnvPath_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture() .WithNoGitHubEnv() .CreateGitHubActionsCommands(); var key = "Key"; var value = "Value"; // When var result = Record.Exception(() => commands.SetEnvironmentVariable(key, value)); // Then AssertEx.IsCakeException(result, "GitHub Actions Runtime EnvPath missing."); } [Fact] public void Should_SetEnvironmentVariable() { // Given var gitHubActionsCommandsFixture = new GitHubActionsCommandsFixture(); var commands = gitHubActionsCommandsFixture.CreateGitHubActionsCommands(); var key = "Key"; var value = "Value"; // When commands.SetEnvironmentVariable(key, value); // Then Assert.Equal( @"Key<<CAKEEOF Value CAKEEOF ".NormalizeLineEndings(), gitHubActionsCommandsFixture.FileSystem.GetFile("/opt/github.env").GetTextContent().NormalizeLineEndings()); } } public sealed class TheUploadArtifactMethod { public sealed class File { [Fact] public async Task Should_Throw_If_Path_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); FilePath path = null; // When var result = await Record.ExceptionAsync(() => commands.UploadArtifact(path, null)); // Then AssertEx.IsArgumentNullException(result, "path"); } [Fact] public async Task Should_Throw_If_ArtifactName_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var path = FilePath.FromString("/artifacts/artifact.zip"); // When var result = await Record.ExceptionAsync(() => commands.UploadArtifact(path, null)); // Then AssertEx.IsArgumentNullException(result, "artifactName"); } [Fact] public async Task Should_Throw_If_File_Missing() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var path = FilePath.FromString("/artifacts/artifact.zip"); var artifactName = "artifact"; // When var result = await Record.ExceptionAsync(() => commands.UploadArtifact(path, artifactName)); // Then AssertEx.IsExceptionWithMessage<FileNotFoundException>(result, "Artifact file not found."); } [Theory] [InlineData("/", "/artifacts/artifact.txt")] [InlineData("/artifacts", "artifact.txt")] public async Task Should_Upload(string workingDirectory, string testPath) { // Given var gitHubActionsCommandsFixture = new GitHubActionsCommandsFixture() .WithWorkingDirectory(workingDirectory); var testFilePath = FilePath.FromString(testPath); var artifactName = "artifact"; gitHubActionsCommandsFixture .FileSystem .CreateFile("/artifacts/artifact.txt") .SetContent(artifactName); var commands = gitHubActionsCommandsFixture.CreateGitHubActionsCommands(); // When await commands.UploadArtifact(testFilePath, artifactName); } } public sealed class Directory { [Fact] public async Task Should_Throw_If_Path_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); DirectoryPath path = null; // When var result = await Record.ExceptionAsync(() => commands.UploadArtifact(path, null)); // Then AssertEx.IsArgumentNullException(result, "path"); } [Fact] public async Task Should_Throw_If_ArtifactName_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var path = DirectoryPath.FromString("/artifacts"); // When var result = await Record.ExceptionAsync(() => commands.UploadArtifact(path, null)); // Then AssertEx.IsArgumentNullException(result, "artifactName"); } [Fact] public async Task Should_Throw_If_Directory_Missing() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var path = DirectoryPath.FromString("/artifacts"); var artifactName = "artifact"; // When var result = await Record.ExceptionAsync(() => commands.UploadArtifact(path, artifactName)); // Then AssertEx.IsExceptionWithMessage<DirectoryNotFoundException>(result, "Artifact directory /artifacts not found."); } [Theory] [InlineData("/", "/src/artifacts")] [InlineData("/src", "artifacts")] public async Task Should_Upload(string workingDirectory, string testPath) { // Given var gitHubActionsCommandsFixture = new GitHubActionsCommandsFixture() .WithWorkingDirectory(workingDirectory); var testDirectoryPath = DirectoryPath.FromString(testPath); var artifactName = "artifacts"; var directory = DirectoryPath.FromString("/src/artifacts"); gitHubActionsCommandsFixture .FileSystem .CreateFile(directory.CombineWithFilePath("artifact.txt")) .SetContent(artifactName); gitHubActionsCommandsFixture .FileSystem .CreateFile(directory.Combine("folder_a").CombineWithFilePath("artifact.txt")) .SetContent(artifactName); gitHubActionsCommandsFixture .FileSystem .CreateFile(directory.Combine("folder_b").CombineWithFilePath("artifact.txt")) .SetContent(artifactName); gitHubActionsCommandsFixture .FileSystem .CreateFile(directory.Combine("folder_b").Combine("folder_c").CombineWithFilePath("artifact.txt")) .SetContent(artifactName); var commands = gitHubActionsCommandsFixture.CreateGitHubActionsCommands(); // When await commands.UploadArtifact(testDirectoryPath, artifactName); } } } public sealed class TheDownloadArtifactMethod { [Fact] public async Task Should_Throw_If_ArtifactName_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var path = DirectoryPath.FromString("/artifacts"); // When var result = await Record.ExceptionAsync(() => commands.DownloadArtifact(null, path)); // Then AssertEx.IsArgumentNullException(result, "artifactName"); } [Fact] public async Task Should_Throw_If_Path_Is_Null() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var artifactName = "artifactName"; // When var result = await Record.ExceptionAsync(() => commands.DownloadArtifact(artifactName, null)); // Then AssertEx.IsArgumentNullException(result, "path"); } [Fact] public async Task Should_Throw_If_Directory_Missing() { // Given var commands = new GitHubActionsCommandsFixture().CreateGitHubActionsCommands(); var path = DirectoryPath.FromString("/artifacts"); var artifactName = "artifact"; // When var result = await Record.ExceptionAsync(() => commands.DownloadArtifact(artifactName, path)); // Then AssertEx.IsExceptionWithMessage<DirectoryNotFoundException>(result, "Local directory /artifacts not found."); } [Theory] [InlineData("/", "/src/artifacts")] [InlineData("/src", "artifacts")] public async Task Should_Download(string workingDirectory, string testPath) { // Given var gitHubActionsCommandsFixture = new GitHubActionsCommandsFixture() .WithWorkingDirectory(workingDirectory); var testDirectoryPath = DirectoryPath.FromString(testPath); var artifactName = "artifact"; var directory = DirectoryPath.FromString("/src/artifacts"); var filePath = directory.CombineWithFilePath("test.txt"); gitHubActionsCommandsFixture .FileSystem .CreateDirectory(directory); var commands = gitHubActionsCommandsFixture.CreateGitHubActionsCommands(); // When await commands.DownloadArtifact(artifactName, testDirectoryPath); var file = gitHubActionsCommandsFixture .FileSystem .GetFile(filePath); // Then Assert.True(file.Exists, $"{filePath.FullPath} doesn't exist."); Assert.Equal("Cake", file.GetTextContent()); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using System.Linq; using Android.Content; using Android.Util; using Android.Widget; using Java.Lang; using DroidListView = Android.Widget.ListView; namespace Xamarin.Forms.Calendar.Platform.Droid { public class CalendarPickerView : DroidListView { public enum SelectionMode { Single, Multi, Range }; private readonly Context _context; internal readonly MonthAdapter MyAdapter; internal readonly List<MonthDescriptor> Months = new List<MonthDescriptor>(); internal readonly List<List<List<MonthCellDescriptor>>> Cells = new List<List<List<MonthCellDescriptor>>>(); internal List<MonthCellDescriptor> SelectedCells = new List<MonthCellDescriptor>(); private readonly List<MonthCellDescriptor> _highlightedCells = new List<MonthCellDescriptor>(); internal List<DateTime> SelectedCals = new List<DateTime>(); private readonly List<DateTime> _highlightedCals = new List<DateTime>(); internal readonly DateTime Today = DateTime.Now; internal DateTime MinDate; internal DateTime MaxDate; private DateTime _monthCounter; internal readonly string MonthNameFormat; internal readonly string WeekdayNameFormat; internal readonly string FullDateFormat; internal ClickHandler ClickHandler; public event EventHandler<DateSelectedEventArgs> OnInvalidDateSelected; public event EventHandler<DateSelectedEventArgs> OnDateSelected; public event EventHandler<DateSelectedEventArgs> OnDateUnselected; public event DateSelectableHandler OnDateSelectable; public SelectionMode Mode { get; set; } public DateTime SelectedDate { get { return SelectedCals.Count > 0 ? SelectedCals[0] : DateTime.MinValue; } } public List<DateTime> SelectedDates { get { var selectedDates = SelectedCells.Select(cal => cal.DateTime).ToList(); selectedDates.Sort(); return selectedDates; } } public CalendarPickerView(Context context, IAttributeSet attrs) : base(context, attrs) { ResourceIdManager.UpdateIdValues(); _context = context; MyAdapter = new MonthAdapter(context, this); base.Adapter = MyAdapter; base.Divider = null; base.DividerHeight = 0; var bgColor = base.Resources.GetColor(Resource.Color.calendar_bg); base.SetBackgroundColor(bgColor); base.CacheColorHint = bgColor; MonthNameFormat = base.Resources.GetString(Resource.String.month_name_format); WeekdayNameFormat = base.Resources.GetString(Resource.String.day_name_format); FullDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern; ClickHandler += OnCellClicked; OnInvalidDateSelected += OnInvalidateDateClicked; if (base.IsInEditMode) { Init(DateTime.Now, DateTime.Now.AddYears(1)).WithSelectedDate(DateTime.Now); } } private void OnCellClicked(MonthCellDescriptor cell) { var clickedDate = cell.DateTime; if (!IsBetweenDates(clickedDate, MinDate, MaxDate) || !IsSelectable(clickedDate)) { if (OnInvalidDateSelected != null) { OnInvalidDateSelected(this, new DateSelectedEventArgs(clickedDate)); } } else { bool wasSelected = DoSelectDate(clickedDate, cell); if (OnDateSelected != null) { if (wasSelected) { OnDateSelected(this, new DateSelectedEventArgs(clickedDate)); } else if (OnDateUnselected != null) { OnDateUnselected(this, new DateSelectedEventArgs(clickedDate)); } } } } private void OnInvalidateDateClicked(object sender, DateSelectedEventArgs e) { string fullDateFormat = _context.Resources.GetString(Resource.String.full_date_format); string errorMsg = _context.Resources.GetString(Resource.String.invalid_date); errorMsg = string.Format(errorMsg, MinDate.ToString(fullDateFormat), MaxDate.ToString(fullDateFormat)); Toast.MakeText(_context, errorMsg, ToastLength.Short).Show(); } public FluentInitializer Init(DateTime minDate, DateTime maxDate) { if (minDate == DateTime.MinValue || maxDate == DateTime.MinValue) { throw new IllegalArgumentException("minDate and maxDate must be non-zero. " + Debug(minDate, maxDate)); } if (minDate.CompareTo(maxDate) > 0) { throw new IllegalArgumentException("minDate must be before maxDate. " + Debug(minDate, maxDate)); } Mode = SelectionMode.Single; //Clear out any previously selected dates/cells. SelectedCals.Clear(); SelectedCells.Clear(); _highlightedCals.Clear(); _highlightedCells.Clear(); //Clear previous state. Cells.Clear(); Months.Clear(); MinDate = minDate; MaxDate = maxDate; MinDate = SetMidnight(MinDate); MaxDate = SetMidnight(MaxDate); // maxDate is exclusive: bump back to the previous day so if maxDate is the first of a month, // We don't accidentally include that month in the view. MaxDate = MaxDate.AddMinutes(-1); //Now iterate between minCal and maxCal and build up our list of months to show. _monthCounter = MinDate; int maxMonth = MaxDate.Month; int maxYear = MaxDate.Year; while ((_monthCounter.Month <= maxMonth || _monthCounter.Year < maxYear) && _monthCounter.Year < maxYear + 1) { var month = new MonthDescriptor(_monthCounter.Month, _monthCounter.Year, _monthCounter, _monthCounter.ToString(MonthNameFormat)); Cells.Add(GetMonthCells(month, _monthCounter)); Logr.D("Adding month {0}", month); Months.Add(month); _monthCounter = _monthCounter.AddMonths(1); } ValidateAndUpdate(); return new FluentInitializer(this); } internal List<List<MonthCellDescriptor>> GetMonthCells(MonthDescriptor month, DateTime startCal) { var cells = new List<List<MonthCellDescriptor>>(); var cal = new DateTime(startCal.Year, startCal.Month, 1); var firstDayOfWeek = (int) cal.DayOfWeek; cal = cal.AddDays((int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - firstDayOfWeek); var minSelectedCal = GetMinDate(SelectedCals); var maxSelectedCal = GetMaxDate(SelectedCals); while ((cal.Month < month.Month + 1 || cal.Year < month.Year) && cal.Year <= month.Year) { Logr.D("Building week row starting at {0}", cal); var weekCells = new List<MonthCellDescriptor>(); cells.Add(weekCells); for (int i = 0; i < 7; i++) { var date = cal; bool isCurrentMonth = cal.Month == month.Month; bool isSelected = isCurrentMonth && ContatinsDate(SelectedCals, cal); bool isSelectable = isCurrentMonth && IsBetweenDates(cal, MinDate, MaxDate); bool isToday = IsSameDate(cal, Today); bool isHighlighted = ContatinsDate(_highlightedCals, cal); int value = cal.Day; var rangeState = RangeState.None; if (SelectedCals.Count > 1) { if (IsSameDate(minSelectedCal, cal)) { rangeState = RangeState.First; } else if (IsSameDate(maxSelectedCal, cal)) { rangeState = RangeState.Last; } else if (IsBetweenDates(cal, minSelectedCal, maxSelectedCal)) { rangeState = RangeState.Middle; } } weekCells.Add(new MonthCellDescriptor(date, isCurrentMonth, isSelectable, isSelected, isToday, isHighlighted, value, rangeState)); cal = cal.AddDays(1); } } return cells; } internal void ScrollToSelectedMonth(int selectedIndex) { ScrollToSelectedMonth(selectedIndex, false); } internal void ScrollToSelectedMonth(int selectedIndex, bool smoothScroll) { Task.Factory.StartNew(() => { if (smoothScroll) { SmoothScrollToPosition(selectedIndex); } else { SetSelection(selectedIndex); } }); } private MonthCellWithMonthIndex GetMonthCellWithIndexByDate(DateTime date) { int index = 0; foreach (var monthCell in Cells) { foreach (var actCell in from weekCell in monthCell from actCell in weekCell where IsSameDate(actCell.DateTime, date) && actCell.IsSelectable select actCell) return new MonthCellWithMonthIndex(actCell, index); index++; } return null; } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (Months.Count == 0) { throw new InvalidOperationException( "Must have at least one month to display. Did you forget to call Init()?"); } base.OnMeasure(widthMeasureSpec, heightMeasureSpec); } private static DateTime SetMidnight(DateTime date) { return date.Subtract(date.TimeOfDay); } private bool IsSelectable(DateTime date) { return OnDateSelectable == null || OnDateSelectable(date); } private DateTime ApplyMultiSelect(DateTime date, DateTime selectedCal) { foreach (var selectedCell in SelectedCells) { if (selectedCell.DateTime == date) { //De-select the currently selected cell. selectedCell.IsSelected = false; SelectedCells.Remove(selectedCell); date = DateTime.MinValue; break; } } foreach (var cal in SelectedCals) { if (IsSameDate(cal, selectedCal)) { SelectedCals.Remove(cal); break; } } return date; } private void ClearOldSelection() { foreach (var selectedCell in SelectedCells) { //De-select the currently selected cell. selectedCell.IsSelected = false; } SelectedCells.Clear(); SelectedCals.Clear(); } internal bool DoSelectDate(DateTime date, MonthCellDescriptor cell) { var newlySelectedDate = date; SetMidnight(newlySelectedDate); //Clear any remaining range state. foreach (var selectedCell in SelectedCells) { selectedCell.RangeState = RangeState.None; } switch (Mode) { case SelectionMode.Range: if (SelectedCals.Count > 1) { //We've already got a range selected: clear the old one. ClearOldSelection(); } else if (SelectedCals.Count == 1 && newlySelectedDate.CompareTo(SelectedCals[0]) < 0) { //We're moving the start of the range back in time: clear the old start date. ClearOldSelection(); } break; case SelectionMode.Multi: date = ApplyMultiSelect(date, newlySelectedDate); break; case SelectionMode.Single: ClearOldSelection(); break; default: throw new IllegalStateException("Unknown SelectionMode " + Mode); } if (date > DateTime.MinValue) { if (SelectedCells.Count == 0 || !SelectedCells[0].Equals(cell)) { SelectedCells.Add(cell); cell.IsSelected = true; } SelectedCals.Add(newlySelectedDate); if (Mode == SelectionMode.Range && SelectedCells.Count > 1) { //Select all days in between start and end. var startDate = SelectedCells[0].DateTime; var endDate = SelectedCells[1].DateTime; SelectedCells[0].RangeState = RangeState.First; SelectedCells[1].RangeState = RangeState.Last; foreach (var month in Cells) { foreach (var week in month) { foreach (var singleCell in week) { var singleCellDate = singleCell.DateTime; if (singleCellDate.CompareTo(startDate) >= 0 && singleCellDate.CompareTo(endDate) <= 0 && singleCell.IsSelectable) { singleCell.IsSelected = true; singleCell.RangeState = RangeState.Middle; SelectedCells.Add(singleCell); } } } } } } ValidateAndUpdate(); return date > DateTime.MinValue; } internal void ValidateAndUpdate() { if (Adapter == null) { Adapter = MyAdapter; } MyAdapter.NotifyDataSetChanged(); } internal bool SelectDate(DateTime date) { return SelectDate(date, false); } private bool SelectDate(DateTime date, bool smoothScroll) { ValidateDate(date); var cell = GetMonthCellWithIndexByDate(date); if (cell == null || !IsSelectable(date)) { return false; } bool wasSelected = DoSelectDate(date, cell.Cell); if (wasSelected) { ScrollToSelectedMonth(cell.MonthIndex, smoothScroll); } return wasSelected; } private void ValidateDate(DateTime date) { if (date == DateTime.MinValue) { throw new IllegalArgumentException("Selected date must be non-zero."); } if (date.CompareTo(MinDate) < 0 || date.CompareTo(MaxDate) > 0) { throw new IllegalArgumentException( string.Format("Selected date must be between minDate and maxDate. " + "minDate: {0}, maxDate: {1}, selectedDate: {2}.", MinDate.ToShortDateString(), MaxDate.ToShortDateString(), date.ToShortDateString())); } } private static DateTime GetMinDate(List<DateTime> selectedCals) { if (selectedCals == null || selectedCals.Count == 0) { return DateTime.MinValue; } selectedCals.Sort(); return selectedCals[0]; } private static DateTime GetMaxDate(List<DateTime> selectedCals) { if (selectedCals == null || selectedCals.Count == 0) { return DateTime.MinValue; } selectedCals.Sort(); return selectedCals[selectedCals.Count - 1]; } private static bool IsBetweenDates(DateTime date, DateTime minCal, DateTime maxCal) { return (date.Equals(minCal) || date.CompareTo(minCal) > 0) // >= minCal && date.CompareTo(maxCal) < 0; // && < maxCal } private static bool IsSameDate(DateTime cal, DateTime selectedDate) { return cal.Month == selectedDate.Month && cal.Year == selectedDate.Year && cal.Day == selectedDate.Day; } internal static bool IsSameMonth(DateTime cal, MonthDescriptor month) { return (cal.Month == month.Month && cal.Year == month.Year); } private static bool ContatinsDate(IEnumerable<DateTime> selectedCals, DateTime cal) { return selectedCals.Any(selectedCal => IsSameDate(cal, selectedCal)); } public void HighlightDates(ICollection<DateTime> dates) { foreach (var date in dates) { ValidateDate(date); var monthCellWithMonthIndex = GetMonthCellWithIndexByDate(date); if (monthCellWithMonthIndex != null) { var cell = monthCellWithMonthIndex.Cell; _highlightedCells.Add(cell); _highlightedCals.Add(date); cell.IsHighlighted = true; } } MyAdapter.NotifyDataSetChanged(); Adapter = MyAdapter; } private static string Debug(DateTime minDate, DateTime maxDate) { return "minDate: " + minDate + "\nmaxDate: " + maxDate; } private class MonthCellWithMonthIndex { public readonly MonthCellDescriptor Cell; public readonly int MonthIndex; public MonthCellWithMonthIndex(MonthCellDescriptor cell, int monthIndex) { Cell = cell; MonthIndex = monthIndex; } } } public class FluentInitializer { private readonly CalendarPickerView _calendar; public FluentInitializer(CalendarPickerView calendar) { _calendar = calendar; } public FluentInitializer InMode(CalendarPickerView.SelectionMode mode) { _calendar.Mode = mode; _calendar.ValidateAndUpdate(); return this; } public FluentInitializer WithSelectedDate(DateTime selectedDate) { return WithSelectedDates(new List<DateTime> {selectedDate}); } public FluentInitializer WithSelectedDates(ICollection<DateTime> selectedDates) { if (_calendar.Mode == CalendarPickerView.SelectionMode.Single && _calendar.SelectedDates.Count > 1) { throw new IllegalArgumentException("SINGLE mode can't be used with multiple selectedDates"); } if (_calendar.SelectedDates != null) { foreach (var date in selectedDates) { _calendar.SelectDate(date); } } int selectedIndex = -1; int todayIndex = -1; for (int i = 0; i < _calendar.Months.Count; i++) { var month = _calendar.Months[i]; if (selectedIndex == -1) { if (_calendar.SelectedCals.Any( selectedCal => CalendarPickerView.IsSameMonth(selectedCal, month))) { selectedIndex = i; } if (selectedIndex == -1 && todayIndex == -1 && CalendarPickerView.IsSameMonth(DateTime.Now, month)) { todayIndex = i; } } } if (selectedIndex != -1) { _calendar.ScrollToSelectedMonth(selectedIndex); } else if (todayIndex != -1) { _calendar.ScrollToSelectedMonth(todayIndex); } _calendar.ValidateAndUpdate(); return this; } public FluentInitializer WithLocale(Java.Util.Locale locale) { //Not sure how to translate this to C# flavor. //Leave it later. throw new NotImplementedException(); } public FluentInitializer WithHighlightedDates(ICollection<DateTime> dates) { _calendar.HighlightDates(dates); return this; } public FluentInitializer WithHighlightedDate(DateTime date) { return WithHighlightedDates(new List<DateTime> {date}); } } public delegate void ClickHandler(MonthCellDescriptor cell); public delegate bool DateSelectableHandler(DateTime date); public class DateSelectedEventArgs : EventArgs { public DateSelectedEventArgs(DateTime date) { SelectedDate = date; } public DateTime SelectedDate { get; private set; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F03Level11ReChild (editable child object).<br/> /// This is a generated base class of <see cref="F03Level11ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F02Level1"/> collection. /// </remarks> [Serializable] public partial class F03Level11ReChild : BusinessBase<F03Level11ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int cParentID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_Child_Name, "Level_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1 Child Name. /// </summary> /// <value>The Level_1_1 Child Name.</value> public string Level_1_1_Child_Name { get { return GetProperty(Level_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F03Level11ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="F03Level11ReChild"/> object.</returns> internal static F03Level11ReChild NewF03Level11ReChild() { return DataPortal.CreateChild<F03Level11ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="F03Level11ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F03Level11ReChild"/> object.</returns> internal static F03Level11ReChild GetF03Level11ReChild(SafeDataReader dr) { F03Level11ReChild obj = new F03Level11ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F03Level11ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private F03Level11ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F03Level11ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F03Level11ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_Child_NameProperty, dr.GetString("Level_1_1_Child_Name")); cParentID2 = dr.GetInt32("CParentID2"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F03Level11ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddF03Level11ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_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="F03Level11ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateF03Level11ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="F03Level11ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteF03Level11ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* * Copyright (2011) Intel Corporation and Sandia Corporation. Under the * terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * -- Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * -- Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * -- Neither the name of the Intel Corporation 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 INTEL OR ITS * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using OpenMetaverse; using OpenSim.Region.CoreModules.World.Land; using OpenSim.Region.Framework.Interfaces; using OpenSim.Tests.Common; using WaterWars.Models; using WaterWars.Models.Roles; using WaterWars.Rules; using WaterWars.States; using WaterWars.Tests; using WaterWars.WebServices; namespace WaterWars.WebServices.Tests { /// <summary> /// These tests concentrate on the Water Wars web services and required parameter validation. /// </summary> /// Game logic tests should take place in GameTests. [TestFixture] public class PlayerServicesTests : AbstractWebServiceTests { [Test] public void TestGetLastSelected() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); AddBuyPoints(); AddPlayers(Developer.Singleton, Manufacturer.Singleton); StartGame(); m_controller.ViewerWebServices.PlayerServices.SetLastSelected(p1.Uuid, bp1); string uri = string.Format("{0}{1}/{2}/{3}", WaterWarsConstants.WEB_SERVICE_PREFIX, PlayerServices.PLAYER_PATH, p1.Uuid, PlayerServices.SELECTED_PATH); string reply = (string)SubmitRequest(uri, "get")["str_response_string"]; UUID bpId = default(UUID); JsonReader jr = new JsonTextReader(new StringReader(reply)); while (jr.Read()) { //System.Console.WriteLine(string.Format("{0},{1},{2},{3}", jr.TokenType, jr.ValueType, jr.Depth, jr.Value)); if (jr.TokenType == JsonToken.PropertyName && (string)jr.Value == "Guid" && jr.Depth == 3) { jr.Read(); bpId = new UUID((string)jr.Value); break; } } Assert.That(bpId, Is.EqualTo(bp1.Uuid)); } [Test] public void TestHandleSetLastSelected() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); AddBuyPoints(); AddPlayers(Developer.Singleton, Manufacturer.Singleton); StartGame(); string uri = string.Format("{0}{1}/{2}/{3}/{4}/{5}", WaterWarsConstants.WEB_SERVICE_PREFIX, PlayerServices.PLAYER_PATH, p1.Uuid, PlayerServices.SELECTED_PATH, PlayerServices.PLAYER_PATH, p1.Uuid); SubmitRequest(uri, "put"); Assert.That( m_controller.ViewerWebServices.PlayerServices.GetLastSelected(p1.Uuid, false).Uuid, Is.EqualTo(p1.Uuid)); } [Test] public void TestGetPlayer() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); AddPlayers(Developer.Singleton, Manufacturer.Singleton); StartGame(); string uri = string.Format("{0}{1}/{2}", WaterWarsConstants.WEB_SERVICE_PREFIX, PlayerServices.PLAYER_PATH, p1.Uuid); string reply = (string)SubmitRequest(uri, "get")["str_response_string"]; UUID returnedId = UUID.Zero; int returnedRole = -999; JsonReader jr = new JsonTextReader(new StringReader(reply)); while (jr.Read()) { // System.Console.WriteLine(string.Format("{0},{1},{2},{3}", jr.TokenType, jr.ValueType, jr.Depth, jr.Value)); if (jr.TokenType == JsonToken.PropertyName) { if ((string)jr.Value == "Guid" && jr.Depth == 3) { jr.Read(); returnedId = new UUID((string)jr.Value); } else if ((string)jr.Value == "Type" && returnedRole == -999) // Yes, this isn't the only type! Poor way of getting values, I know { jr.Read(); returnedRole = (int)(long)jr.Value; } } } Assert.That(returnedId, Is.EqualTo(p1.Uuid)); Assert.That(returnedRole, Is.EqualTo((int)RoleType.Developer)); } [Test] public void TestGetPlayers() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); AddPlayers(Developer.Singleton, Manufacturer.Singleton); StartGame(); string uri = string.Format("{0}{1}", WaterWarsConstants.WEB_SERVICE_PREFIX, PlayerServices.PLAYER_PATH); string reply = (string)SubmitRequest(uri, "get")["str_response_string"]; HashSet<UUID> returnedIds = new HashSet<UUID>(); JsonReader jr = new JsonTextReader(new StringReader(reply)); while (jr.Read()) { //System.Console.WriteLine(string.Format("{0},{1},{2},{3}", jr.TokenType, jr.ValueType, jr.Depth, jr.Value)); if (jr.TokenType == JsonToken.PropertyName && (string)jr.Value == "Guid" && jr.Depth == 4) { jr.Read(); returnedIds.Add(new UUID((string)jr.Value)); } } Assert.That( returnedIds.Remove(p1.Uuid), Is.True, string.Format("p1's uuid {0} was not in the set of returned ids", p1.Uuid)); Assert.That( returnedIds.Remove(p2.Uuid), Is.True, string.Format("p2's uuid {0} was not in the set of returned ids", p2.Uuid)); Assert.That( returnedIds.Count, Is.EqualTo(0), "Received extras ids that do not belong to any registered player"); } [Test] public void TestSellWaterRights() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); AddBuyPoints(); AddPlayers(Developer.Singleton, Manufacturer.Singleton); StartGame(); m_controller.State.BuyLandRights(bp1, p1); int amount = 17; int waterRightsPrice = 43; int p1ProjectedMoney = p1.Money + waterRightsPrice; int p2ProjectedMoney = p2.Money - waterRightsPrice; int p1ProjectedWaterRights = p1.WaterEntitlement - amount; int p2ProjectedWaterRights = p2.WaterEntitlement + amount; JObject json = new JObject( new JProperty("WaterRightsBuyer", new JObject(new JProperty("Uuid", new JObject(new JProperty("Guid", p2.Uuid.ToString()))))), new JProperty("DeltaMoney", -waterRightsPrice), new JProperty("DeltaWaterEntitlement", amount)); string uri = Path.Combine(WaterWarsConstants.WEB_SERVICE_PREFIX, Path.Combine(PlayerServices.PLAYER_PATH, p1.Uuid.ToString())); SubmitRequest(uri, "put", json.ToString()); Assert.That(p1.Money, Is.EqualTo(p1ProjectedMoney)); Assert.That(p2.Money, Is.EqualTo(p2ProjectedMoney)); Assert.That(p1.WaterEntitlement, Is.EqualTo(p1ProjectedWaterRights)); Assert.That(p2.WaterEntitlement, Is.EqualTo(p2ProjectedWaterRights)); } [Test] public void TestSellWater() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); AddBuyPoints(); AddPlayers(Developer.Singleton, Manufacturer.Singleton); StartGame(); m_controller.State.BuyLandRights(bp1, p1); m_controller.State.BuyLandRights(bp2, p2); EndTurns(1); int p1StartMoney = p1.Money; int p2StartMoney = p2.Money; int p1StartWater = p1.Water; int p2StartWater = p2.Water; // Selling 200 water for 500 money int water = 200; int price = 500; JObject json = new JObject( new JProperty("WaterBuyer", new JObject(new JProperty("Uuid", new JObject(new JProperty("Guid", p2.Uuid.ToString()))))), new JProperty("DeltaMoney", -price), new JProperty("DeltaWater", water)); string uri = Path.Combine(WaterWarsConstants.WEB_SERVICE_PREFIX, Path.Combine(PlayerServices.PLAYER_PATH, p1.Uuid.ToString())); SubmitRequest(uri, "put", json.ToString()); Assert.That(p1.Money, Is.EqualTo(p1StartMoney + price)); Assert.That(p2.Money, Is.EqualTo(p2StartMoney - price)); Assert.That(p1.Water, Is.EqualTo(p1StartWater - water)); Assert.That(p2.Water, Is.EqualTo(p2StartWater + water)); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Diagnostics; // needed for Debug.Assert (etc.) using System.Runtime.Serialization; // needed for defining exception .ctors using System.Compiler; using System.Diagnostics.Contracts; namespace Microsoft.Contracts.Foxtrot { public static class RewriteHelper { internal static readonly TypeNode flagsAttributeNode = TypeNode.GetTypeNode(typeof(System.FlagsAttribute)); internal static Block CreateTryFinallyBlock(Method method, Block tryBody, Block finallyBody) { Contract.Requires(method != null); Contract.Requires(tryBody != null); Contract.Requires(finallyBody != null); if (method.ExceptionHandlers == null) method.ExceptionHandlers = new ExceptionHandlerList(); Block result = new Block(new StatementList()); Block afterFinally = new Block(new StatementList()); tryBody.Statements.Add(new Branch(null, afterFinally, false, true, true)); finallyBody.Statements.Add(new EndFinally()); result.Statements.Add(tryBody); result.Statements.Add(finallyBody); result.Statements.Add(afterFinally); ExceptionHandler fb = new ExceptionHandler(); fb.TryStartBlock = tryBody; fb.BlockAfterTryEnd = finallyBody; fb.HandlerStartBlock = finallyBody; fb.BlockAfterHandlerEnd = afterFinally; fb.HandlerType = NodeType.Finally; method.ExceptionHandlers.Add(fb); return result; } internal static Statement GenerateForLoop(Variable loopVariable, Expression lowerBound, Expression upperBound, Statement body) { Block bodyAsBlock = body as Block ?? new Block(new StatementList(body)); Block init = new Block(new StatementList(2)); Block increment = new Block(new StatementList(1)); Block test = new Block(new StatementList(new Branch( new BinaryExpression(loopVariable, upperBound, NodeType.Lt), bodyAsBlock))); //, false, true, false))); init.Statements.Add(new AssignmentStatement(loopVariable, lowerBound)); init.Statements.Add(new Branch(null, test)); increment.Statements.Add(new AssignmentStatement(loopVariable, new BinaryExpression(loopVariable, Literal.Int32One, NodeType.Add))); Block forLoop = new Block(new StatementList(4)); forLoop.Statements.Add(init); forLoop.Statements.Add(bodyAsBlock); forLoop.Statements.Add(increment); forLoop.Statements.Add(test); return forLoop; } internal static bool Implements(Method concreteMethod, Method abstractMethod) { Contract.Requires(concreteMethod != null); MethodList ml = concreteMethod.ImplicitlyImplementedInterfaceMethods; for (int i = 0, n = ml == null ? 0 : ml.Count; i < n; i++) { Method ifaceMethod = ml[i]; if (ifaceMethod == null) continue; if (ifaceMethod == abstractMethod) return true; } ml = concreteMethod.ImplementedInterfaceMethods; for (int i = 0, n = ml == null ? 0 : ml.Count; i < n; i++) { Method ifaceMethod = ml[i]; if (ifaceMethod == null) continue; if (ifaceMethod == abstractMethod) return true; } return false; } internal static bool IsFinalizer(Method method) { Contract.Requires(method != null); return method.Name.Name == "Finalize" && method.Parameters.Count == 0 && HelperMethods.IsVoidType(method.ReturnType) && method.IsVirtualAndNotDeclaredInStruct && ((method.Flags & MethodFlags.NewSlot) == 0); } #if DEBUG /// <summary> /// Used to determine if a method body is just a sequence of non-nested blocks. Ignores any PreambleBlocks at the beginning of the body /// </summary> /// <param name="method">Any method</param> /// <returns>method != null &amp;&amp; method.Body != null ==> IsClump(method.Body.Statements) (except for PreambleBlocks) /// </returns> internal static bool PostNormalizedFormat(Method method) { if (method == null) return true; if (method.Body == null) return true; // skip over any PreambleBlocks, they don't need to be in post-normalized format int i = 0; StatementList sl = method.Body.Statements; while (i < sl.Count) { PreambleBlock pb = sl[i] as PreambleBlock; if (pb == null) break; i++; } while (i < sl.Count) { if (!HelperMethods.IsBasicBlock(sl[i] as Block)) return false; i++; } return true; } #endif /// <summary> /// Scans the entire block to find 0 or more closure initializations. For each, it adds an entry to the dictionary /// mapping the closure type to the closure local. /// </summary> internal static void RecordClosureInitialization(Method containing, Block b, Dictionary<TypeNode, Local> closureLocalMap) { Contract.Requires(closureLocalMap != null); Local closureLocal = null; if (b == null || b.Statements == null || !(b.Statements.Count > 0)) { return; } for (int i = 0; i < b.Statements.Count; i++) { Statement s = b.Statements[i]; if (s == null || s.NodeType == NodeType.Nop) continue; if (HelperMethods.IsClosureCreation(containing, s, out closureLocal)) { if (closureLocal != null) { closureLocalMap.Add(closureLocal.Type, closureLocal); } } } } /// <summary> /// Replaces any MemberBindings of the form (this,x) in the methodContract with a method call where the method /// being called is P where x is a private field of the source type that has been marked as [ContractPublicPropertyName("P")]. /// </summary> /// <param name="targetType"></param> /// <param name="sourceType"></param> /// <param name="methodContract"></param> internal static void ReplacePrivateFieldsThatHavePublicProperties(TypeNode targetType, TypeNode sourceType, MethodContract methodContract, ContractNodes contractNodes ) { Contract.Requires(sourceType != null); Dictionary<Field, Method> field2Getter = new Dictionary<Field, Method>(); for (int i = 0, n = /*sourceType.Members == null ? 0 : */ sourceType.Members.Count; i < n; i++) { Field f = sourceType.Members[i] as Field; if (f == null) continue; string propertyName = HelperMethods.GetStringFromAttribute(f, ContractNodes.SpecPublicAttributeName); if (propertyName != null) { Property p = sourceType.GetProperty(Identifier.For(propertyName)); if (p != null) { field2Getter.Add(f, p.Getter); } } } if (0 < field2Getter.Count) { SubstitutePropertyGetterForField s = new SubstitutePropertyGetterForField(field2Getter); s.Visit(methodContract); } return; } private class SubstitutePropertyGetterForField : StandardVisitor { readonly Dictionary<Field, Method> substitution; public SubstitutePropertyGetterForField(Dictionary<Field, Method> substitutionTable) { substitution = substitutionTable; } public override Expression VisitMemberBinding(MemberBinding memberBinding) { if (memberBinding == null) return null; Field f = memberBinding.BoundMember as Field; if (f == null || !this.substitution.ContainsKey(f)) return base.VisitMemberBinding(memberBinding); Method m = this.substitution[f]; return new MethodCall( new MemberBinding(memberBinding.TargetObject, m), null, m.IsVirtual ? NodeType.Callvirt : NodeType.Call, f.Type ); } } internal static void TryAddCompilerGeneratedAttribute(Class Class) { Contract.Requires(Class != null); TryAddCompilerGeneratedAttribute(Class, System.AttributeTargets.Class); } internal static void TryAddCompilerGeneratedAttribute(EnumNode Enum) { Contract.Requires(Enum != null); TryAddCompilerGeneratedAttribute(Enum, System.AttributeTargets.Enum); } internal static void TryAddCompilerGeneratedAttribute(Method method) { Contract.Requires(method != null); TryAddCompilerGeneratedAttribute(method, System.AttributeTargets.Method); } internal static void TryAddCompilerGeneratedAttribute(Field field) { Contract.Requires(field != null); TryAddCompilerGeneratedAttribute(field, System.AttributeTargets.Field); } internal static void TryAddDebuggerBrowsableNeverAttribute(Field field) { Contract.Requires(field != null); TryAddDebuggerBrowsableNeverAttribute(field, System.AttributeTargets.Field); } internal static void TryAddCompilerGeneratedAttribute(Member member, System.AttributeTargets targets) { Contract.Requires(member != null); if (HelperMethods.compilerGeneratedAttributeNode == null) return; Member compilerGenerated = HelperMethods.compilerGeneratedAttributeNode.GetConstructor(); AttributeNode compilerGeneratedAttribute = new AttributeNode(new MemberBinding(null, compilerGenerated), null, targets); member.Attributes.Add(compilerGeneratedAttribute); } internal static void TryAddDebuggerBrowsableNeverAttribute(Member member, System.AttributeTargets targets) { Contract.Requires(member != null); try { if (HelperMethods.debuggerBrowsableAttributeNode == null) return; if (HelperMethods.debuggerBrowsableStateType == null) return; var ctor = HelperMethods.debuggerBrowsableAttributeNode.GetConstructor(HelperMethods.debuggerBrowsableStateType); var args = new ExpressionList(Literal.Int32Zero); var attribute = new AttributeNode(new MemberBinding(null, ctor), args, targets); member.Attributes.Add(attribute); } catch { } } } }
using System; using System.Collections.Generic; namespace NRules.RuleModel.Builders { /// <summary> /// Builder to compose a rule definition. /// Contains methods to specify rule's metadata, as well as create child builders for rule's left-hand side and right-hand side. /// Creates <see cref="IRuleDefinition"/>. /// </summary> /// <threadsafety instance="false" /> public class RuleBuilder { private string _name; private string _description = string.Empty; private int _priority = RuleDefinition.DefaultPriority; private RuleRepeatability _repeatability = RuleDefinition.DefaultRepeatability; private readonly List<string> _tags = new(); private readonly List<RuleProperty> _properties = new(); private DependencyGroupBuilder _dependencyGroupBuilder; private GroupBuilder _lhsBuilder; private FilterGroupBuilder _filterGroupBuilder; private ActionGroupBuilder _rhsBuilder; /// <summary> /// Constructs an empty rule builder. /// </summary> public RuleBuilder() { } /// <summary> /// Sets rule's name. /// </summary> /// <param name="name">Rule name value.</param> public void Name(string name) { _name = name; } /// <summary> /// Sets rule's description. /// </summary> /// <param name="description">Rule description value.</param> public void Description(string description) { _description = description; } /// <summary> /// Adds rule's tags. /// </summary> /// <param name="tags">Rule tag values.</param> public void Tags(IEnumerable<string> tags) { _tags.AddRange(tags); } /// <summary> /// Adds rule's tag. /// </summary> /// <param name="tag">Rule tag value.</param> public void Tag(string tag) { _tags.Add(tag); } /// <summary> /// Adds rule's properties. /// </summary> /// <param name="properties">Rule property.</param> public void Properties(IEnumerable<RuleProperty> properties) { _properties.AddRange(properties); } /// <summary> /// Adds rule's property. /// </summary> /// <param name="name">Property name.</param> /// <param name="value">Property value.</param> public void Property(string name, object value) { var property = new RuleProperty(name, value); _properties.Add(property); } /// <summary> /// Sets rule's priority. /// Default priority is 0. /// </summary> /// <param name="priority">Rule priority value.</param> public void Priority(int priority) { _priority = priority; } /// <summary> /// Sets rule's repeatability. /// Default repeatability is <see cref="RuleRepeatability.Repeatable"/>. /// </summary> public void Repeatability(RuleRepeatability repeatability) { _repeatability = repeatability; } /// <summary> /// Retrieves dependencies builder. /// </summary> /// <returns>Dependencies builder.</returns> public DependencyGroupBuilder Dependencies() { if (_dependencyGroupBuilder == null) _dependencyGroupBuilder = new DependencyGroupBuilder(); return _dependencyGroupBuilder; } /// <summary> /// Sets dependencies builder. /// </summary> /// <param name="builder">Builder to set.</param> public void Dependencies(DependencyGroupBuilder builder) { if (_dependencyGroupBuilder != null) throw new ArgumentException("Builder for dependencies is already set", nameof(builder)); _dependencyGroupBuilder = builder; } /// <summary> /// Retrieves left-hand side builder (conditions). /// </summary> /// <returns>Left hand side builder.</returns> public GroupBuilder LeftHandSide() { if (_lhsBuilder == null) _lhsBuilder = new GroupBuilder(); return _lhsBuilder; } /// <summary> /// Sets left-hand side builder (conditions). /// </summary> /// <param name="builder">Builder to set.</param> public void LeftHandSide(GroupBuilder builder) { if (_lhsBuilder != null) throw new ArgumentException("Builder for left-hand side is already set", nameof(builder)); _lhsBuilder = builder; } /// <summary> /// Retrieves filters builder. /// </summary> /// <returns>Filters builder.</returns> public FilterGroupBuilder Filters() { if (_filterGroupBuilder == null) _filterGroupBuilder = new FilterGroupBuilder(); return _filterGroupBuilder; } /// <summary> /// Sets filters builder. /// </summary> /// <param name="builder">Builder to set.</param> public void Filters(FilterGroupBuilder builder) { if (_filterGroupBuilder != null) throw new ArgumentException($"Builder for filters is already set", nameof(builder)); _filterGroupBuilder = builder; } /// <summary> /// Retrieves right-hand side builder (actions). /// </summary> /// <returns>Right hand side builder.</returns> public ActionGroupBuilder RightHandSide() { if (_rhsBuilder == null) _rhsBuilder = new ActionGroupBuilder(); return _rhsBuilder; } /// <summary> /// Sets right-hand side builder. /// </summary> /// <param name="builder">Builder to set.</param> public void RightHandSide(ActionGroupBuilder builder) { if (_rhsBuilder != null) throw new ArgumentException($"Builder for right-hand side is already set", nameof(builder)); _rhsBuilder = builder; } /// <summary> /// Creates rule definition using current state of the builder. /// </summary> /// <returns>Rule definition.</returns> public IRuleDefinition Build() { IBuilder<DependencyGroupElement> dependencyGroupBuilder = _dependencyGroupBuilder; DependencyGroupElement dependencies = dependencyGroupBuilder?.Build() ?? Element.DependencyGroup(); IBuilder<FilterGroupElement> filterGroupBuilder = _filterGroupBuilder; FilterGroupElement filters = filterGroupBuilder?.Build() ?? Element.FilterGroup(); IBuilder<GroupElement> lhsBuilder = _lhsBuilder; GroupElement lhs = lhsBuilder?.Build() ?? Element.AndGroup(); IBuilder<ActionGroupElement> rhsBuilder = _rhsBuilder; ActionGroupElement rhs = rhsBuilder?.Build() ?? Element.ActionGroup(); var ruleDefinition = Element.RuleDefinition(_name, _description, _priority, _repeatability, _tags, _properties, dependencies, lhs, filters, rhs); return ruleDefinition; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace App.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }