context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.PythonTools; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; using TestUtilities; using TestUtilities.UI; namespace PythonToolsUITests { public class ErrorListTaskListTests { internal struct TaskItemInfo { public int Line, Column; public string Document, Message; public VSTASKCATEGORY Category; public VSTASKPRIORITY Priority; public __VSERRORCATEGORY? ErrorCategory; public TaskItemInfo(string document, int line, int column, VSTASKPRIORITY priority, VSTASKCATEGORY category, __VSERRORCATEGORY? errorCategory, string message) { Document = document; Line = line; Column = column; Priority = priority; Category = category; ErrorCategory = errorCategory; Message = message; } public TaskItemInfo(IVsTaskItem taskItem) { ErrorHandler.ThrowOnFailure(taskItem.Document(out Document)); ErrorHandler.ThrowOnFailure(taskItem.get_Text(out Message)); ErrorHandler.ThrowOnFailure(taskItem.Line(out Line)); ErrorHandler.ThrowOnFailure(taskItem.Column(out Column)); // TODO: get_Priority and Category are not implemented by VS LSC (returns E_FAIL) Priority = VSTASKPRIORITY.TP_HIGH; Category = VSTASKCATEGORY.CAT_CODESENSE; ErrorCategory = null; //var priority = new VSTASKPRIORITY[1]; //ErrorHandler.ThrowOnFailure(taskItem.get_Priority(priority)); //Priority = priority[0]; //var category = new VSTASKCATEGORY[1]; //ErrorHandler.ThrowOnFailure(taskItem.Category(category)); //Category = category[0]; //var errorItem = taskItem as IVsErrorItem; //if (errorItem != null) { // uint errorCategory; // try { // ErrorHandler.ThrowOnFailure(errorItem.GetCategory(out errorCategory)); // ErrorCategory = (__VSERRORCATEGORY)errorCategory; // } catch (NotImplementedException) { // ErrorCategory = null; // } //} else { // ErrorCategory = null; //} } public override string ToString() { var errorCategory = ErrorCategory != null ? "__VSERRORCATEGORY." + ErrorCategory : "null"; return string.Format("new TaskItemInfo(\"{0}\", {1}, {2}, VSTASKPRIORITY.{3}, VSTASKCATEGORY.{4}, {5}, \"{6}\")", Document, Line, Column, Priority, Category, errorCategory, Message); } } internal void TaskListTest(VisualStudioApp app, Type taskListService, IList<TaskItemInfo> expectedItems, int[] navigateTo = null) { var items = app.WaitForTaskListItems(taskListService, expectedItems.Count); var actualItems = items.Select(item => new TaskItemInfo(item)).ToList(); Assert.AreEqual(expectedItems.Count, actualItems.Count); AssertUtil.ContainsExactly(actualItems, expectedItems.ToSet()); if (navigateTo != null) { foreach (var i in navigateTo) { Console.WriteLine("Trying to navigate to " + expectedItems[i]); var j = actualItems.IndexOf(expectedItems[i]); Assert.IsTrue(j >= 0); app.ServiceProvider.GetUIThread().Invoke((Action)delegate { items[j].NavigateTo(); }); var doc = app.Dte.ActiveDocument; Assert.IsNotNull(doc); Assert.AreEqual(expectedItems[i].Document, doc.FullName); var textDoc = (EnvDTE.TextDocument)doc.Object("TextDocument"); Assert.AreEqual(expectedItems[i].Line + 1, textDoc.Selection.ActivePoint.Line); Assert.AreEqual(expectedItems[i].Column + 1, textDoc.Selection.ActivePoint.DisplayColumn); } } } /// <summary> /// Make sure errors in a file show up in the error list window. /// </summary> public void ErrorList(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\ErrorProject.sln")); var projectNode = project.GetPythonProject(); var expectedDocument = Path.Combine(projectNode.ProjectHome, "Program.py"); var expectedCategory = VSTASKCATEGORY.CAT_CODESENSE; var expectedItems = new[] { new TaskItemInfo(expectedDocument, 2, 8, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "unexpected indent"), new TaskItemInfo(expectedDocument, 2, 13, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "unexpected token '('"), new TaskItemInfo(expectedDocument, 2, 30, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "unexpected token ')'"), new TaskItemInfo(expectedDocument, 2, 31, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "unexpected token '<newline>'"), new TaskItemInfo(expectedDocument, 3, 0, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "unexpected token '<NL>'"), new TaskItemInfo(expectedDocument, 3, 0, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "unexpected token '<dedent>'"), new TaskItemInfo(expectedDocument, 4, 0, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "unexpected token 'pass'"), }; app.OpenDocument(expectedDocument); app.OpenErrorList(); TaskListTest(app, typeof(SVsErrorList), expectedItems, navigateTo: new[] { 0, 1, 2, 3, 4, 5, 6 }); } /// <summary> /// Make sure task comments in a file show up in the task list window. /// </summary> public void CommentTaskList(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\ErrorProject.sln")); var projectNode = project.GetPythonProject(); var expectedDocument = Path.Combine(projectNode.ProjectHome, "Program.py"); var expectedCategory = VSTASKCATEGORY.CAT_COMMENTS; var expectedItems = new[] { new TaskItemInfo(expectedDocument, 4, 5, VSTASKPRIORITY.TP_NORMAL, expectedCategory, null, "TODO 123"), new TaskItemInfo(expectedDocument, 5, 0, VSTASKPRIORITY.TP_HIGH, expectedCategory, null, "456 UnresolvedMergeConflict"), }; app.OpenDocument(expectedDocument); app.OpenTaskList(); TaskListTest(app, typeof(SVsTaskList), expectedItems, navigateTo: new[] { 0, 1 }); } /// <summary> /// Make sure deleting a project clears the error list /// </summary> public void ErrorListAndTaskListAreClearedWhenProjectIsDeleted(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\ErrorProjectDelete.sln")); var projectNode = project.GetPythonProject(); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "Program.py")); app.OpenErrorList(); //app.OpenTaskList(); app.WaitForTaskListItems(typeof(SVsErrorList), 7); //app.WaitForTaskListItems(typeof(SVsTaskList), 2); Console.WriteLine("Deleting project"); app.Dte.Solution.Remove(project); app.WaitForTaskListItems(typeof(SVsErrorList), 0); //app.WaitForTaskListItems(typeof(SVsTaskList), 0); } /// <summary> /// Make sure deleting a project clears the error list /// </summary> public void ErrorListAndTaskListAreClearedWhenProjectIsUnloaded(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\ErrorProjectDelete.sln")); var projectNode = project.GetPythonProject(); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "Program.py")); app.OpenErrorList(); //app.OpenTaskList(); app.WaitForTaskListItems(typeof(SVsErrorList), 7); //app.WaitForTaskListItems(typeof(SVsTaskList), 2); IVsSolution solutionService = app.GetService<IVsSolution>(typeof(SVsSolution)); Assert.IsNotNull(solutionService); IVsHierarchy selectedHierarchy; ErrorHandler.ThrowOnFailure(solutionService.GetProjectOfUniqueName(project.UniqueName, out selectedHierarchy)); Assert.IsNotNull(selectedHierarchy); Console.WriteLine("Unloading project"); ErrorHandler.ThrowOnFailure(solutionService.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, selectedHierarchy, 0)); app.WaitForTaskListItems(typeof(SVsErrorList), 0); //app.WaitForTaskListItems(typeof(SVsTaskList), 0); } /// <summary> /// Make sure deleting a project clears the error list when there are errors in multiple files /// /// Take 2 of https://pytools.codeplex.com/workitem/1523 /// </summary> public void ErrorListAndTaskListAreClearedWhenProjectWithMultipleFilesIsUnloaded(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\ErrorProjectMultipleFiles.sln")); var projectNode = project.GetPythonProject(); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "Program.py")); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "Program2.py")); app.OpenErrorList(); //app.OpenTaskList(); app.WaitForTaskListItems(typeof(SVsErrorList), 14); //app.WaitForTaskListItems(typeof(SVsTaskList), 4); var solutionService = app.GetService<IVsSolution>(typeof(SVsSolution)); Assert.IsNotNull(solutionService); IVsHierarchy selectedHierarchy; ErrorHandler.ThrowOnFailure(solutionService.GetProjectOfUniqueName(project.UniqueName, out selectedHierarchy)); Assert.IsNotNull(selectedHierarchy); Console.WriteLine("Unloading project"); ErrorHandler.ThrowOnFailure(solutionService.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, selectedHierarchy, 0)); app.WaitForTaskListItems(typeof(SVsErrorList), 0); //app.WaitForTaskListItems(typeof(SVsTaskList), 0); } /// <summary> /// Make sure deleting a file w/ errors clears the error list /// </summary> public void ErrorListAndTaskListAreClearedWhenFileIsDeleted(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\ErrorProjectDeleteFile.sln")); var projectNode = project.GetPythonProject(); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "Program.py")); app.OpenErrorList(); //app.OpenTaskList(); app.WaitForTaskListItems(typeof(SVsErrorList), 7); //app.WaitForTaskListItems(typeof(SVsTaskList), 2); Console.WriteLine("Deleting file"); project.ProjectItems.Item("Program.py").Delete(); app.WaitForTaskListItems(typeof(SVsErrorList), 0); //app.WaitForTaskListItems(typeof(SVsTaskList), 0); } /// <summary> /// Make sure deleting a file w/ errors clears the error list /// </summary> public void ErrorListAndTaskListAreClearedWhenOpenFileIsDeleted(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\ErrorProjectDeleteFile.sln")); var projectNode = project.GetPythonProject(); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "Program.py")); app.OpenErrorList(); //app.OpenTaskList(); project.ProjectItems.Item("Program.py").Open(); app.WaitForTaskListItems(typeof(SVsErrorList), 7); //app.WaitForTaskListItems(typeof(SVsTaskList), 2); Console.WriteLine("Deleting file"); project.ProjectItems.Item("Program.py").Delete(); app.WaitForTaskListItems(typeof(SVsErrorList), 0); //app.WaitForTaskListItems(typeof(SVsTaskList), 0); } /// <summary> /// Make sure *.pyi files ignore the active Python version /// </summary> public void ErrorListEmptyForValidTypingFile(VisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\Typings.sln")); var projectNode = project.GetPythonProject(); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "mymod.pyi")); app.OpenDocument(Path.Combine(projectNode.ProjectHome, "usermod.py")); app.OpenErrorList(); var actual = app.WaitForTaskListItems(typeof(SVsErrorList), 1); Assert.AreEqual(1, actual.Count); ErrorHandler.ThrowOnFailure(actual[0].Document(out var doc)); Assert.AreEqual("usermod.py", Path.GetFileName(doc)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using DotVVM.Framework.Binding; using DotVVM.Framework.Hosting; using DotVVM.Framework.Runtime; namespace DotVVM.Framework.Controls { /// <summary> /// A base class for all control that support data-binding. /// </summary> public abstract class DotvvmBindableControl : DotvvmControl { private Dictionary<string, object> controlState; /// <summary> /// Gets or sets the data context. /// </summary> public object DataContext { get { return (object)GetValue(DataContextProperty); } set { SetValue(DataContextProperty, value); } } public static readonly DotvvmProperty DataContextProperty = DotvvmProperty.Register<object, DotvvmBindableControl>(c => c.DataContext, isValueInherited: true); private Dictionary<DotvvmProperty, BindingExpression> dataBindings = new Dictionary<DotvvmProperty, BindingExpression>(); /// <summary> /// Gets a collection of all data-bindings set on this control. /// </summary> protected internal IReadOnlyDictionary<DotvvmProperty, BindingExpression> DataBindings { get { return dataBindings; } } /// <summary> /// Gets the collection of properties used to persist control state for postbacks. /// </summary> [MarkupOptions(MappingMode = MappingMode.Exclude)] public Dictionary<string, object> ControlState { get { if (controlState == null) { controlState = new Dictionary<string, object>(); } return controlState; } } /// <summary> /// Gets a value indication whether the control requires the control state. /// </summary> protected internal virtual bool RequiresControlState { get { return false; } } /// <summary> /// Gets or sets whether this control should be rendered on the server. /// </summary> protected internal virtual bool RenderOnServer { get { return (RenderMode)GetValue(RenderSettings.ModeProperty) == RenderMode.Server; } } /// <summary> /// Gets the value from control state. /// </summary> protected internal virtual T GetControlStateValue<T>(string key, T defaultValue = default(T)) { if (!RequiresControlState) return defaultValue; object value; return ControlState.TryGetValue(key, out value) ? (T)value : defaultValue; } /// <summary> /// Sets the value for specified control state item. /// </summary> protected internal virtual void SetControlStateValue(string key, object value) { ControlState[key] = value; } /// <summary> /// Gets the value of a specified property. /// </summary> public override object GetValue(DotvvmProperty property, bool inherit = true) { var value = base.GetValue(property, inherit); while (value is IBinding) { if (value is IStaticValueBinding) { // handle binding var binding = (IStaticValueBinding)value; value = binding.Evaluate(this, property); } if (value is CommandBindingExpression) { var binding = (CommandBindingExpression)value; value = (Action)(() => binding.Evaluate(this, property)); } } return value; } /// <summary> /// Sets the value of a specified property. /// </summary> public override void SetValue(DotvvmProperty property, object value) { var originalValue = base.GetValue(property, false); if (originalValue is IUpdatableValueBinding && !(value is BindingExpression)) { // if the property contains a binding and we are not passing another binding, update the value ((IUpdatableValueBinding)originalValue).UpdateSource(value, this, property); } else { // register data-bindings when they are applied to the property dataBindings.Remove(property); if (value is BindingExpression) { dataBindings[property] = (BindingExpression)value; } else { base.SetValue(property, value); } } } /// <summary> /// Gets the binding set to a specified property. /// </summary> public BindingExpression GetBinding(DotvvmProperty property, bool inherit = true) { var binding = base.GetValue(property, inherit) as BindingExpression; //// if there is a controlProperty or controlCommand binding, evaluate it //while (binding != null && !(binding is ValueBindingExpression || binding is CommandBindingExpression || binding is StaticCommandBindingExpression)) //{ // binding = binding.Evaluate(this, property) as BindingExpression; //} return binding; } /// <summary> /// Gets the value binding set to a specified property. /// </summary> public IValueBinding GetValueBinding(DotvvmProperty property, bool inherit = true) { var binding = GetBinding(property, inherit); if (binding != null && !(binding is IValueBinding)) { throw new Exception("ValueBindingExpression was expected!"); // TODO: exception handling } return binding as IValueBinding; } /// <summary> /// Gets the command binding set to a specified property. /// </summary> public CommandBindingExpression GetCommandBinding(DotvvmProperty property, bool inherit = true) { var binding = GetBinding(property, inherit); if (binding != null && !(binding is CommandBindingExpression)) { throw new Exception("CommandBindingExpression was expected!"); // TODO: exception handling } return binding as CommandBindingExpression; } /// <summary> /// Sets the binding to a specified property. /// </summary> public void SetBinding(DotvvmProperty property, IBinding binding) { base.SetValue(property, binding); } /// <summary> /// Renders the control into the specified writer. /// </summary> public override sealed void Render(IHtmlWriter writer, RenderContext context) { if (Properties.ContainsKey(PostBack.UpdateProperty)) { // the control might be updated on postback, add the control ID EnsureControlHasId(); } if (context.RequestContext.IsInPartialRenderingMode && (bool)GetValue(PostBack.UpdateProperty) && !(writer is MultiHtmlWriter)) { // render the control and capture the HTML using (var htmlBuilder = new StringWriter()) { var controlWriter = new HtmlWriter(htmlBuilder, context.RequestContext); var multiWriter = new MultiHtmlWriter(writer, controlWriter); base.Render(multiWriter, context); context.RequestContext.PostBackUpdatedControls[ID] = htmlBuilder.ToString(); } } else { // render the control directly to the output base.Render(writer, context); } } /// <summary> /// Renders the control into the specified writer. /// </summary> protected override void RenderControl(IHtmlWriter writer, RenderContext context) { // if the DataContext is set, render the "with" binding var dataContextBinding = GetValueBinding(DataContextProperty, false); if (dataContextBinding != null) { writer.WriteKnockoutWithComment(dataContextBinding.GetKnockoutBindingExpression()); } base.RenderControl(writer, context); if (dataContextBinding != null) { writer.WriteKnockoutDataBindEndComment(); } } /// <summary> /// Gets the hierarchy of all DataContext bindings from the root to current control. /// </summary> internal IEnumerable<IValueBinding> GetDataContextHierarchy() { var bindings = new List<IValueBinding>(); DotvvmControl current = this; do { if (current is DotvvmBindableControl) { var binding = ((DotvvmBindableControl)current).GetValueBinding(DataContextProperty, false); if (binding != null) { bindings.Add(binding); } } current = current.Parent; } while (current != null); bindings.Reverse(); return bindings; } /// <summary> /// Gets the closest control binding target. /// </summary> public DotvvmControl GetClosestControlBindingTarget() { int numberOfDataContextChanges; return GetClosestControlBindingTarget(out numberOfDataContextChanges); } /// <summary> /// Gets the closest control binding target and returns number of DataContext changes since the target. /// </summary> public DotvvmControl GetClosestControlBindingTarget(out int numberOfDataContextChanges) { var result = GetClosestWithPropertyValue(out numberOfDataContextChanges, control => (bool)control.GetValue(Internal.IsControlBindingTargetProperty)); if (result == null) { throw new Exception("The {controlProperty: ...} binding can be only used in a markup control."); // TODO: exception handling } return result; } /// <summary> /// Gets the closest control with specified property value and returns number of DataContext changes since the target. /// </summary> public DotvvmControl GetClosestWithPropertyValue(out int numberOfDataContextChanges, Func<DotvvmControl, bool> filterFunction) { var current = (DotvvmControl)this; numberOfDataContextChanges = 0; while (current != null) { if (current is DotvvmBindableControl && ((DotvvmBindableControl)current).GetValueBinding(DataContextProperty, false) != null) { var bindable = (DotvvmBindableControl)current; if (bindable.HasBinding(DataContextProperty) || bindable.HasBinding(Internal.PathFragmentProperty)) { numberOfDataContextChanges++; } } if (filterFunction(current)) { break; } current = current.Parent; } return current; } protected internal bool HasBinding(DotvvmProperty property) { object value; return Properties.TryGetValue(property, out value) && value is BindingExpression; } /// <summary> /// Gets all bindings set on the control. /// </summary> internal IEnumerable<KeyValuePair<DotvvmProperty, BindingExpression>> GetAllBindings() { return Properties.Where(p => p.Value is BindingExpression) .Select(p => new KeyValuePair<DotvvmProperty, BindingExpression>(p.Key, (BindingExpression)p.Value)); } } }
//! \file ImagePRS.cs //! \date Sat Mar 28 00:15:43 2015 //! \brief Marble engine image format. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.Marble { internal class PrsMetaData : ImageMetaData { public byte Flag; public uint PackedSize; } [Export(typeof(ImageFormat))] public class PrsFormat : ImageFormat { public override string Tag { get { return "PRS"; } } public override string Description { get { return "Marble engine image format"; } } public override uint Signature { get { return 0; } } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("PrsFormat.Write not implemented"); } public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[0x10]; if (header.Length != stream.Read (header, 0, header.Length)) return null; if (header[0] != 'Y' || header[1] != 'B' || header[3] != 3) return null; return new PrsMetaData { Width = LittleEndian.ToUInt16 (header, 12), Height = LittleEndian.ToUInt16 (header, 14), BPP = 24, Flag = header[2], PackedSize = LittleEndian.ToUInt32 (header, 4), }; } public override ImageData Read (Stream stream, ImageMetaData info) { var meta = info as PrsMetaData; if (null == meta) throw new ArgumentException ("PrsFormat.Read should be supplied with PrsMetaData", "info"); stream.Position = 0x10; using (var reader = new Reader (stream, meta)) { reader.Unpack(); return ImageData.Create (meta, PixelFormats.Bgr24, null, reader.Data, (int)meta.Width*3); } } internal class Reader : IDisposable { BinaryReader m_input; byte[] m_output; uint m_size; byte m_flag; public byte[] Data { get { return m_output; } } public Reader (Stream file, PrsMetaData info) { m_input = new BinaryReader (file, Encoding.ASCII, true); m_output = new byte[info.Width*info.Height*3]; m_size = info.PackedSize; m_flag = info.Flag; } static readonly int[] LengthTable = InitLengthTable(); private static int[] InitLengthTable () { var length_table = new int[256]; for (int i = 0; i < 0xfe; ++i) length_table[i] = i + 3; length_table[0xfe] = 0x400; length_table[0xff] = 0x1000; return length_table; } public void Unpack () { int dst = 0; int remaining = (int)m_size; int bit = 0; int ctl = 0; while (remaining > 0 && dst < m_output.Length) { bit >>= 1; if (0 == bit) { ctl = m_input.ReadByte(); --remaining; bit = 0x80; } if (remaining <= 0) break; if (0 == (ctl & bit)) { m_output[dst++] = m_input.ReadByte(); --remaining; continue; } int b = m_input.ReadByte(); --remaining; int length = 0; int shift = 0; if (0 != (b & 0x80)) { if (remaining <= 0) break; shift = m_input.ReadByte(); --remaining; shift |= (b & 0x3f) << 8; if (0 != (b & 0x40)) { if (remaining <= 0) break; int offset = m_input.ReadByte(); --remaining; length = LengthTable[offset]; } else { length = (shift & 0xf) + 3; shift >>= 4; } } else { length = b >> 2; b &= 3; if (3 == b) { length += 9; int read = m_input.Read (m_output, dst, length); if (read < length) break; remaining -= length; dst += length; continue; } shift = length; length = b + 2; } ++shift; if (dst < shift) throw new InvalidFormatException ("Invalid offset value"); Binary.CopyOverlapped (m_output, dst-shift, dst, length); dst += length; } if ((m_flag & 0x80) != 0) { for (int i = 3; i < m_output.Length; ++i) m_output[i] += m_output[i-3]; } } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) { m_input.Dispose(); } disposed = true; } } #endregion } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace System.Management.Automation.Internal { using System; using System.Threading; using System.Runtime.InteropServices; using System.Collections.ObjectModel; using System.Management.Automation.Runspaces; using System.Management.Automation; /// <summary> /// A PipelineReader for an ObjectStream. /// </summary> /// <remarks> /// This class is not safe for multi-threaded operations. /// </remarks> internal abstract class ObjectReaderBase<T> : PipelineReader<T>, IDisposable { /// <summary> /// Construct with an existing ObjectStream. /// </summary> /// <param name="stream">The stream to read.</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception> public ObjectReaderBase([In, Out] ObjectStreamBase stream) { if (stream == null) { throw new ArgumentNullException("stream", "stream may not be null"); } _stream = stream; } #region Events /// <summary> /// Event fired when objects are added to the underlying stream. /// </summary> public override event EventHandler DataReady { add { lock (_monitorObject) { bool firstRegistrant = (InternalDataReady == null); InternalDataReady += value; if (firstRegistrant) { _stream.DataReady += new EventHandler(this.OnDataReady); } } } remove { lock (_monitorObject) { InternalDataReady -= value; if (InternalDataReady == null) { _stream.DataReady -= new EventHandler(this.OnDataReady); } } } } public event EventHandler InternalDataReady = null; #endregion Events #region Public Properties /// <summary> /// Waitable handle for caller's to block until data is ready to read from the underlying stream. /// </summary> public override WaitHandle WaitHandle { get { return _stream.ReadHandle; } } /// <summary> /// Check if the stream is closed and contains no data. /// </summary> /// <value>True if the stream is closed and contains no data, otherwise; false.</value> /// <remarks> /// Attempting to read from the underlying stream if EndOfPipeline is true returns /// zero objects. /// </remarks> public override bool EndOfPipeline { get { return _stream.EndOfPipeline; } } /// <summary> /// Check if the stream is open for further writes. /// </summary> /// <value>true if the underlying stream is open, otherwise; false.</value> /// <remarks> /// The underlying stream may be readable after it is closed if data remains in the /// internal buffer. Check <see cref="EndOfPipeline"/> to determine if /// the underlying stream is closed and contains no data. /// </remarks> public override bool IsOpen { get { return _stream.IsOpen; } } /// <summary> /// Returns the number of objects in the underlying stream. /// </summary> public override int Count { get { return _stream.Count; } } /// <summary> /// Get the capacity of the stream. /// </summary> /// <value> /// The capacity of the stream. /// </value> /// <remarks> /// The capacity is the number of objects that stream may contain at one time. Once this /// limit is reached, attempts to write into the stream block until buffer space /// becomes available. /// </remarks> public override int MaxCapacity { get { return _stream.MaxCapacity; } } #endregion Public Properties #region Public Methods /// <summary> /// Close the stream. /// </summary> /// <remarks> /// Causes subsequent calls to IsOpen to return false and calls to /// a write operation to throw an ObjectDisposedException. /// All calls to Close() after the first call are silently ignored. /// </remarks> /// <exception cref="ObjectDisposedException"> /// The stream is already disposed /// </exception> public override void Close() { // 2003/09/02-JonN added call to close underlying stream _stream.Close(); } #endregion Public Methods #region Private Methods /// <summary> /// Handle DataReady events from the underlying stream. /// </summary> /// <param name="sender">The stream raising the event.</param> /// <param name="args">Standard event args.</param> private void OnDataReady(object sender, EventArgs args) { // call any event handlers on this, replacing the // ObjectStream sender with 'this' since receivers // are expecting a PipelineReader<object> InternalDataReady.SafeInvoke(this, args); } #endregion Private Methods #region Private fields /// <summary> /// The underlying stream. /// </summary> /// <remarks>Can never be null</remarks> protected ObjectStreamBase _stream; /// <summary> /// This object is used to acquire an exclusive lock /// on event handler registration. /// </summary> /// <remarks> /// Note that we lock _monitorObject rather than "this" so that /// we are protected from outside code interfering in our /// critical section. Thanks to Wintellect for the hint. /// </remarks> private object _monitorObject = new Object(); #endregion Private fields #region IDisposable /// <summary> /// Public method for dispose. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Release all resources. /// </summary> /// <param name="disposing">If true, release all managed resources.</param> protected abstract void Dispose(bool disposing); #endregion IDisposable } /// <summary> /// A PipelineReader reading objects from an ObjectStream. /// </summary> /// <remarks> /// This class is not safe for multi-threaded operations. /// </remarks> internal class ObjectReader : ObjectReaderBase<object> { #region ctor /// <summary> /// Construct with an existing ObjectStream. /// </summary> /// <param name="stream">The stream to read.</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception> public ObjectReader([In, Out] ObjectStream stream) : base(stream) { } #endregion ctor /// <summary> /// Read at most <paramref name="count"/> objects. /// </summary> /// <param name="count">The maximum number of objects to read.</param> /// <returns>The objects read.</returns> /// <remarks> /// This method blocks if the number of objects in the stream is less than <paramref name="count"/> /// and the stream is not closed. /// </remarks> public override Collection<object> Read(int count) { return _stream.Read(count); } /// <summary> /// Read a single object from the stream. /// </summary> /// <returns>The next object in the stream.</returns> /// <remarks>This method blocks if the stream is empty</remarks> public override object Read() { return _stream.Read(); } /// <summary> /// Blocks until the pipeline closes and reads all objects. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// If the stream is empty, an empty collection is returned. /// </remarks> public override Collection<object> ReadToEnd() { return _stream.ReadToEnd(); } /// <summary> /// Reads all objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of all objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> public override Collection<object> NonBlockingRead() { return _stream.NonBlockingRead(Int32.MaxValue); } /// <summary> /// Reads objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<object> NonBlockingRead(int maxRequested) { return _stream.NonBlockingRead(maxRequested); } /// <summary> /// Peek the next object. /// </summary> /// <returns>The next object in the stream or ObjectStream.EmptyObject if the stream is empty.</returns> public override object Peek() { return _stream.Peek(); } /// <summary> /// Release all resources. /// </summary> /// <param name="disposing">If true, release all managed resources.</param> protected override void Dispose(bool disposing) { if (disposing) { _stream.Close(); } } } /// <summary> /// A PipelineReader reading PSObjects from an ObjectStream. /// </summary> /// <remarks> /// This class is not safe for multi-threaded operations. /// </remarks> internal class PSObjectReader : ObjectReaderBase<PSObject> { #region ctor /// <summary> /// Construct with an existing ObjectStream. /// </summary> /// <param name="stream">The stream to read.</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception> public PSObjectReader([In, Out] ObjectStream stream) : base(stream) { } #endregion ctor /// <summary> /// Read at most <paramref name="count"/> objects. /// </summary> /// <param name="count">The maximum number of objects to read.</param> /// <returns>The objects read.</returns> /// <remarks> /// This method blocks if the number of objects in the stream is less than <paramref name="count"/> /// and the stream is not closed. /// </remarks> public override Collection<PSObject> Read(int count) { return MakePSObjectCollection(_stream.Read(count)); } /// <summary> /// Read a single PSObject from the stream. /// </summary> /// <returns>The next PSObject in the stream.</returns> /// <remarks>This method blocks if the stream is empty</remarks> public override PSObject Read() { return MakePSObject(_stream.Read()); } /// <summary> /// Blocks until the pipeline closes and reads all objects. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// If the stream is empty, an empty collection is returned. /// </remarks> public override Collection<PSObject> ReadToEnd() { return MakePSObjectCollection(_stream.ReadToEnd()); } /// <summary> /// Reads all objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of all objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> public override Collection<PSObject> NonBlockingRead() { return MakePSObjectCollection(_stream.NonBlockingRead(Int32.MaxValue)); } /// <summary> /// Reads objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<PSObject> NonBlockingRead(int maxRequested) { return MakePSObjectCollection(_stream.NonBlockingRead(maxRequested)); } /// <summary> /// Peek the next PSObject. /// </summary> /// <returns>The next PSObject in the stream or ObjectStream.EmptyObject if the stream is empty.</returns> public override PSObject Peek() { return MakePSObject(_stream.Peek()); } /// <summary> /// Release all resources. /// </summary> /// <param name="disposing">If true, release all managed resources.</param> protected override void Dispose(bool disposing) { if (disposing) { _stream.Close(); } } #region Private private static PSObject MakePSObject(object o) { if (o == null) return null; return PSObject.AsPSObject(o); } // It might ultimately be more efficient to // make ObjectStream generic and convert the objects to PSObject // before inserting them into the initial Collection, so that we // don't have to convert the collection later. private static Collection<PSObject> MakePSObjectCollection( Collection<object> coll) { if (coll == null) return null; Collection<PSObject> retval = new Collection<PSObject>(); foreach (object o in coll) { retval.Add(MakePSObject(o)); } return retval; } #endregion Private } /// <summary> /// A ObjectReader for a PSDataCollection ObjectStream. /// </summary> /// <remarks> /// PSDataCollection is introduced after 1.0. PSDataCollection is /// used to store data which can be used with different /// commands concurrently. /// Only Read() operation is supported currently. /// </remarks> internal class PSDataCollectionReader<DataStoreType, ReturnType> : ObjectReaderBase<ReturnType> { #region Private Data private PSDataCollectionEnumerator<DataStoreType> _enumerator; #endregion #region ctor /// <summary> /// Construct with an existing ObjectStream. /// </summary> /// <param name="stream">The stream to read.</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception> public PSDataCollectionReader(PSDataCollectionStream<DataStoreType> stream) : base(stream) { System.Management.Automation.Diagnostics.Assert(stream.ObjectStore != null, "Stream should have a valid data store"); _enumerator = (PSDataCollectionEnumerator<DataStoreType>)stream.ObjectStore.GetEnumerator(); } #endregion ctor /// <summary> /// This method is not supported. /// </summary> /// <param name="count">The maximum number of objects to read.</param> /// <returns>The objects read.</returns> public override Collection<ReturnType> Read(int count) { throw new NotSupportedException(); } /// <summary> /// Read a single object from the stream. /// </summary> /// <returns> /// The next object in the buffer or AutomationNull if buffer is closed /// and data is not available. /// </returns> /// <remarks> /// This method blocks if the buffer is empty. /// </remarks> public override ReturnType Read() { object result = AutomationNull.Value; if (_enumerator.MoveNext()) { result = _enumerator.Current; } return ConvertToReturnType(result); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> ReadToEnd() { throw new NotSupportedException(); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> NonBlockingRead() { return NonBlockingRead(Int32.MaxValue); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } if (maxRequested == 0) { return new Collection<ReturnType>(); } Collection<ReturnType> results = new Collection<ReturnType>(); int readCount = maxRequested; while (readCount > 0) { if (_enumerator.MoveNext(false)) { results.Add(ConvertToReturnType(_enumerator.Current)); continue; } break; } return results; } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> public override ReturnType Peek() { throw new NotSupportedException(); } /// <summary> /// Release all resources. /// </summary> /// <param name="disposing">If true, release all managed resources.</param> protected override void Dispose(bool disposing) { if (disposing) { _stream.Close(); } } private ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) { ReturnType result; LanguagePrimitives.TryConvertTo(inputObject, out result); return result; } System.Management.Automation.Diagnostics.Assert(false, "ReturnType should be either object or PSObject only"); throw PSTraceSource.NewNotSupportedException(); } } /// <summary> /// A ObjectReader for a PSDataCollection ObjectStream. /// </summary> /// <remarks> /// PSDataCollection is introduced after 1.0. PSDataCollection is /// used to store data which can be used with different /// commands concurrently. /// Only Read() operation is supported currently. /// </remarks> internal class PSDataCollectionPipelineReader<DataStoreType, ReturnType> : ObjectReaderBase<ReturnType> { #region Private Data private PSDataCollection<DataStoreType> _datastore; #endregion Private Data #region ctor /// <summary> /// Construct with an existing ObjectStream. /// </summary> /// <param name="stream">The stream to read.</param> /// <param name="computerName"></param> /// <param name="runspaceId"></param> internal PSDataCollectionPipelineReader(PSDataCollectionStream<DataStoreType> stream, string computerName, Guid runspaceId) : base(stream) { System.Management.Automation.Diagnostics.Assert(stream.ObjectStore != null, "Stream should have a valid data store"); _datastore = stream.ObjectStore; ComputerName = computerName; RunspaceId = runspaceId; } #endregion ctor /// <summary> /// Computer name passed in by the pipeline which /// created this reader. /// </summary> internal string ComputerName { get; } /// <summary> /// Runspace Id passed in by the pipeline which /// created this reader. /// </summary> internal Guid RunspaceId { get; } /// <summary> /// This method is not supported. /// </summary> /// <param name="count">The maximum number of objects to read.</param> /// <returns>The objects read.</returns> public override Collection<ReturnType> Read(int count) { throw new NotSupportedException(); } /// <summary> /// Read a single object from the stream. /// </summary> /// <returns> /// The next object in the buffer or AutomationNull if buffer is closed /// and data is not available. /// </returns> /// <remarks> /// This method blocks if the buffer is empty. /// </remarks> public override ReturnType Read() { object result = AutomationNull.Value; if (_datastore.Count > 0) { Collection<DataStoreType> resultCollection = _datastore.ReadAndRemove(1); // ReadAndRemove returns a Collection<DataStoreType> type but we // just want the single object contained in the collection. if (resultCollection.Count == 1) { result = resultCollection[0]; } } return ConvertToReturnType(result); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> ReadToEnd() { throw new NotSupportedException(); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> NonBlockingRead() { return NonBlockingRead(Int32.MaxValue); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } if (maxRequested == 0) { return new Collection<ReturnType>(); } Collection<ReturnType> results = new Collection<ReturnType>(); int readCount = maxRequested; while (readCount > 0) { if (_datastore.Count > 0) { results.Add(ConvertToReturnType((_datastore.ReadAndRemove(1))[0])); readCount--; continue; } break; } return results; } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> public override ReturnType Peek() { throw new NotSupportedException(); } /// <summary> /// Converts to the return type based on language primitives. /// </summary> /// <param name="inputObject">Input object to convert.</param> /// <returns>Input object converted to the specified return type.</returns> private ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) { ReturnType result; LanguagePrimitives.TryConvertTo(inputObject, out result); return result; } System.Management.Automation.Diagnostics.Assert(false, "ReturnType should be either object or PSObject only"); throw PSTraceSource.NewNotSupportedException(); } #region IDisposable /// <summary> /// Release all resources. /// </summary> /// <param name="disposing">If true, release all managed resources.</param> protected override void Dispose(bool disposing) { if (disposing) { _datastore.Dispose(); } } #endregion IDisposable } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Signum.Engine.Maps; using Signum.Entities; using Signum.Entities.Reflection; using Signum.Utilities; using Signum.Utilities.DataStructures; using Signum.Utilities.ExpressionTrees; using Signum.Utilities.Reflection; namespace Signum.Engine.Cache { class ToStringExpressionVisitor : ExpressionVisitor { Dictionary<ParameterExpression, Expression> replacements = new Dictionary<ParameterExpression, Expression>(); CachedEntityExpression root; public ToStringExpressionVisitor(ParameterExpression param, CachedEntityExpression root) { this.root = root; this.replacements = new Dictionary<ParameterExpression, Expression> { { param, root } }; } public static Expression<Func<PrimaryKey, string>> GetToString<T>(CachedTableConstructor constructor, Expression<Func<T, string>> lambda) { Table table = (Table)constructor.table; var param = lambda.Parameters.SingleEx(); if (param.Type != table.Type) throw new InvalidOperationException("incorrect lambda paramer type"); var pk = Expression.Parameter(typeof(PrimaryKey), "pk"); var root = new CachedEntityExpression(pk, typeof(T), constructor, null, null); var visitor = new ToStringExpressionVisitor(param, root); var result = visitor.Visit(lambda.Body); return Expression.Lambda<Func<PrimaryKey, string>>(result, pk); } protected override Expression VisitMember(MemberExpression node) { var exp = this.Visit(node.Expression); if (exp is CachedEntityExpression cee) { Field field = cee.FieldEmbedded != null ? cee.FieldEmbedded.GetField(node.Member) : cee.FieldMixin != null ? cee.FieldMixin.GetField(node.Member) : ((Table)cee.Constructor.table).GetField(node.Member); return BindMember(cee, field, cee.PrimaryKey); } return node.Update(exp); } private Expression BindMember(CachedEntityExpression n, Field field, Expression? prevPrimaryKey) { Expression body = GetField(field, n.Constructor, prevPrimaryKey); ConstantExpression tab = Expression.Constant(n.Constructor.cachedTable, typeof(CachedTable<>).MakeGenericType(((Table)n.Constructor.table).Type)); Expression origin = Expression.Convert(Expression.Property(Expression.Call(tab, "GetRows", null), "Item", n.PrimaryKey.UnNullify()), n.Constructor.tupleType); var result = ExpressionReplacer.Replace(body, new Dictionary<ParameterExpression, Expression> { { n.Constructor.origin, origin } }); if (!n.PrimaryKey.Type.IsNullable()) return result; return Expression.Condition( Expression.Equal(n.PrimaryKey, Expression.Constant(null, n.PrimaryKey.Type)), Expression.Constant(null, result.Type.Nullify()), result.Nullify()); } private Expression GetField(Field field, CachedTableConstructor constructor, Expression? previousPrimaryKey) { if (field is FieldValue) { var value = constructor.GetTupleProperty((IColumn)field); return value.Type == field.FieldType ? value : Expression.Convert(value, field.FieldType); } if (field is FieldEnum) return Expression.Convert(constructor.GetTupleProperty((IColumn)field), field.FieldType); if (field is FieldPrimaryKey) return constructor.GetTupleProperty((IColumn)field); if (field is IFieldReference) { bool isLite = ((IFieldReference)field).IsLite; if (field is FieldReference) { IColumn column = (IColumn)field; return GetEntity(isLite, column, field.FieldType.CleanType(), constructor); } if (field is FieldImplementedBy ib) { var nullRef = Expression.Constant(null, field.FieldType); var call = ib.ImplementationColumns.Aggregate((Expression)nullRef, (acum, kvp) => { IColumn column = (IColumn)kvp.Value; var entity = GetEntity(isLite, column, kvp.Key, constructor); return Expression.Condition(Expression.NotEqual(constructor.GetTupleProperty(column), Expression.Constant(column.Type)), Expression.Convert(entity, field.FieldType), acum); }); return call; } if (field is FieldImplementedByAll) { throw new NotImplementedException("FieldImplementedByAll not supported in cached ToString"); } } if (field is FieldEmbedded fe) { return new CachedEntityExpression(previousPrimaryKey!, fe.FieldType, constructor, fe, null); } if (field is FieldMixin fm) { return new CachedEntityExpression(previousPrimaryKey!, fm.FieldType, constructor, null, fm); } if (field is FieldMList) { throw new NotImplementedException("FieldMList not supported in cached ToString"); } throw new InvalidOperationException("Unexpected {0}".FormatWith(field.GetType().Name)); } private Expression GetEntity(bool isLite, IColumn column, Type entityType, CachedTableConstructor constructor) { Expression id = constructor.GetTupleProperty(column); var pk = CachedTableConstructor.WrapPrimaryKey(id); CachedTableConstructor typeConstructor = CacheLogic.GetCacheType(entityType) == CacheType.Cached ? CacheLogic.GetCachedTable(entityType).Constructor : constructor.cachedTable.SubTables!.SingleEx(a => a.ParentColumn == column).Constructor; return new CachedEntityExpression(pk, entityType, typeConstructor, null, null); } protected override Expression VisitUnary(UnaryExpression node) { var operand = Visit(node.Operand); if (operand != node.Operand && node.NodeType == ExpressionType.Convert) { return Expression.Convert(operand, node.Type); } return node.Update(operand); } static readonly MethodInfo miToString = ReflectionTools.GetMethodInfo((object o) => o.ToString()); protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Method.DeclaringType == typeof(string) && node.Method.Name == nameof(string.Format) || node.Method.DeclaringType == typeof(StringExtensions) && node.Method.Name == nameof(StringExtensions.FormatWith)) { var formatStr = Visit(node.Arguments[0]); var remainging = node.Arguments.Skip(1).Select(a => Visit(ToString(a))).ToList(); return node.Update(null, new Sequence<Expression> { formatStr, remainging }); } var obj = base.Visit(node.Object); var args = base.Visit(node.Arguments); if (node.Method.Name == "ToString" && node.Arguments.IsEmpty() && obj is CachedEntityExpression ce && ce.Type.IsEntity()) { var table = (Table)ce.Constructor.table; if (table.ToStrColumn != null) { return BindMember(ce, (FieldValue)table.ToStrColumn, null); } else if(this.root != ce) { var cachedTableType = typeof(CachedTable<>).MakeGenericType(table.Type); ConstantExpression tab = Expression.Constant(ce.Constructor.cachedTable, cachedTableType); var mi = cachedTableType.GetMethod(nameof(CachedTable<Entity>.GetToString)); return Expression.Call(tab, mi, ce.PrimaryKey.UnNullify()); } } LambdaExpression? lambda = ExpressionCleaner.GetFieldExpansion(obj?.Type, node.Method); if (lambda != null) { var replace = ExpressionReplacer.Replace(Expression.Invoke(lambda, obj == null ? args : args.PreAnd(obj))); return this.Visit(replace); } if (node.Method.Name == nameof(Entity.Mixin) && obj is CachedEntityExpression cee) { var mixin = ((Table)cee.Constructor.table).GetField(node.Method); return GetField(mixin, cee.Constructor, cee.PrimaryKey); } return node.Update(obj, args); } protected override Expression VisitParameter(ParameterExpression node) { return this.replacements.TryGetC(node) ?? node; } protected override Expression VisitBinary(BinaryExpression node) { var result = (BinaryExpression)base.VisitBinary(node); if (result.NodeType == ExpressionType.Equal || result.NodeType == ExpressionType.NotEqual) { if (result.Left is CachedEntityExpression ceLeft && ceLeft.FieldEmbedded?.HasValue == null || result.Right is CachedEntityExpression ceRight && ceRight.FieldEmbedded?.HasValue == null) { var left = GetPrimaryKey(result.Left); var right = GetPrimaryKey(result.Right); if (left.Type.IsNullable() || right.Type.IsNullable()) return Expression.MakeBinary(node.NodeType, left.Nullify(), right.Nullify()); else return Expression.MakeBinary(node.NodeType, left, right); } if (result.Left is CachedEntityExpression ceLeft2 && ceLeft2.FieldEmbedded?.HasValue != null || result.Right is CachedEntityExpression ceRight2 && ceRight2.FieldEmbedded?.HasValue != null) { var left = GetHasValue(result.Left); var right = GetHasValue(result.Right); return Expression.MakeBinary(node.NodeType, left, right); } } if(result.NodeType == ExpressionType.Add && (result.Left.Type == typeof(string) || result.Right.Type == typeof(string))) { var lefto = this.Visit(ToString(result.Left)); var righto = this.Visit(ToString(result.Right)); return Expression.Add(lefto, righto, result.Method); } return result; } private Expression ToString(Expression node) { if (node.Type == typeof(string)) return node; return Expression.Condition( Expression.Equal(node.Nullify(), Expression.Constant(null, node.Type.Nullify())), Expression.Constant(null, typeof(string)), Expression.Call(node, miToString)); } private Expression GetPrimaryKey(Expression exp) { if (exp is ConstantExpression && ((ConstantExpression)exp).Value == null) return Expression.Constant(null, typeof(PrimaryKey?)); if (exp is CachedEntityExpression cee && cee.FieldEmbedded?.HasValue == null) return cee.PrimaryKey; throw new InvalidOperationException(""); } private Expression GetHasValue(Expression exp) { if (exp is ConstantExpression && ((ConstantExpression)exp).Value == null) return Expression.Constant(false, typeof(bool)); if (exp is CachedEntityExpression n && n.FieldEmbedded?.HasValue != null) { var body = n.Constructor.GetTupleProperty(n.FieldEmbedded.HasValue); ConstantExpression tab = Expression.Constant(n.Constructor.cachedTable, typeof(CachedTable<>).MakeGenericType(((Table)n.Constructor.table).Type)); Expression origin = Expression.Convert(Expression.Property(Expression.Call(tab, "GetRows", null), "Item", n.PrimaryKey.UnNullify()), n.Constructor.tupleType); var result = ExpressionReplacer.Replace(body, new Dictionary<ParameterExpression, Expression> { { n.Constructor.origin, origin } }); return result; } throw new InvalidOperationException(""); } } internal class CachedEntityExpression : Expression { public override ExpressionType NodeType { get { return ExpressionType.Extension; } } public readonly CachedTableConstructor Constructor; public readonly Expression PrimaryKey; public readonly FieldEmbedded? FieldEmbedded; public readonly FieldMixin? FieldMixin; public readonly Type type; public override Type Type { get { return type; } } public CachedEntityExpression(Expression primaryKey, Type type, CachedTableConstructor constructor, FieldEmbedded? embedded, FieldMixin? mixin) { if (primaryKey == null) throw new ArgumentNullException(nameof(primaryKey)); if (primaryKey.Type.UnNullify() != typeof(PrimaryKey)) throw new InvalidOperationException("primaryKey should be a PrimaryKey"); if (type.IsEmbeddedEntity()) { this.FieldEmbedded = embedded ?? throw new ArgumentNullException(nameof(embedded)); } else if (type.IsMixinEntity()) { this.FieldMixin = mixin ?? throw new ArgumentNullException(nameof(mixin)); } else { if (((Table)constructor.table).Type != type.CleanType()) throw new InvalidOperationException("Wrong type"); } this.PrimaryKey = primaryKey; this.type = type; this.Constructor = constructor; } protected override Expression VisitChildren(ExpressionVisitor visitor) { if (this.PrimaryKey == null) return this; var pk = visitor.Visit(this.PrimaryKey); if (pk == this.PrimaryKey) return this; return new CachedEntityExpression(pk, type, Constructor, FieldEmbedded, FieldMixin); } public override string ToString() { return $"CachedEntityExpression({Type.TypeName()}, {PrimaryKey})"; } } }
/* ----------------------------------------------------------------------------- This source file is part of ViewpointComputationLib (a viewpoint computation library) For more info on the project, contact Roberto Ranon at roberto.ranon@uniud.it. Copyright (c) 2013- University of Udine, Italy - http://hcilab.uniud.it ----------------------------------------------------------------------------- CLSolver.cs: file defining classes to solve a VC problem ----------------------------------------------------------------------------- */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /// <summary> /// Candidate. A particle in the PSO solver, or a firefly in the Firefly solver /// </summary> public class CLCandidate : IComparable<CLCandidate> { /// <summary> /// Dimension of the candidate. /// </summary> public int dimension { get; set; } /// <summary> /// Position of the candidate. /// </summary> public float[] position { get; set; } /// <summary> /// Velocity of the candidate. /// </summary> public float[] velocity { get; set; } //// <summary> /// Best position reached so far by the candidate /// </summary> public float[] bestPosition { get; set; } //// <summary> /// Candidate best evaluation so far /// </summary> public float bestEvaluation; //// <summary> /// Candidate last evaluation /// </summary> public float evaluation; //// <summary> /// True if candidate position inside search space /// </summary> public bool inSearchSpace; //// <summary> /// Times the candidate was out of search space /// </summary> public int timesOutOfSearchSpace; //// <summary> /// index of leader Candidate /// </summary> public int leader; public int bestIteration; /// <summary> /// Initializes a new instance of the <see cref="Candidate"/> class. /// </summary> /// <param name='_dimension'> /// dimensions of the candidate /// </param> public CLCandidate (int _dimension) { dimension = _dimension; bestEvaluation = 0; position = new float[dimension]; velocity = new float[dimension]; bestPosition = new float[dimension]; } //// <summary> /// Returns objective function value for the candidate, or -2 if candidate not in search space /// </summary> public float EvaluateSatisfaction (CLCameraMan evaluator, bool lazy) { // if we are not in search space there is no point evaluating the objective function if (!InSearchSpace (evaluator)) { timesOutOfSearchSpace++; return -2.0f; // give penalty to out-of-bounds candidates } inSearchSpace = true; if (lazy) { evaluation = evaluator.EvaluateSatisfaction (position, bestEvaluation); } else evaluation = evaluator.EvaluateSatisfaction (position, -0.001f); return evaluation; } /// <summary> /// Check if candidate is in problem search space /// </summary> /// <returns><c>true</c>, if search space was ined, <c>false</c> otherwise.</returns> /// <param name="evaluator">CLCameraMan evaluator</param> /// <param name="checkGeometry">If set to <c>true</c> check geometry.</param> public bool InSearchSpace (CLCameraMan evaluator) { return evaluator.InSearchSpace (position); } public int CompareTo(CLCandidate other) { // allow auto sort high sat to low sat if (this.evaluation > other.evaluation) return -1; else if (this.evaluation < other.evaluation) return +1; else return 0; } public float Distance( CLCandidate other, bool useBestPosition) { float ssd = 0.0f; // sum squared differences (Euclidean) float[] position1, position2; if (useBestPosition) { position1 = bestPosition; position2 = other.bestPosition; } else { position1 = position; position2 = other.position; } for (int i = 0; i < dimension; i++) ssd += (position1[i] - position2[i]) * (position1[i] - position2[i]); return Mathf.Sqrt(ssd); } } /// <summary> /// Abstract class representing a solver of VC problems. /// </summary> public abstract class CLSolver { /** dimensionality of a candidate, (e.g. 8 for position, look-at point, roll, fov; 6 for position, look-at point, etc ) */ protected int candidateDimension; /** array of candidates used by the solver, up to 300 */ public CLCandidate[] candidates = new CLCandidate[300]; /** Number of candidates actually used by the search */ public int numberOfCandidates; /** Camera used to evaluate a candidate satisfaction */ public CLCameraMan evaluator; /** fraction of randomly initialized candidates (the other are initialized smartly depending on the problem) */ protected float randomPart=0.3f; /** max sat reachable (normalized) */ protected float maxSatisfaction; /** exit condition code (0 = time elapsed, 1 = accuracy reached, 2 = continue execution) */ public int exitCondition; /** internal random generator */ protected System.Random rnd; /** current solver iteration */ public int iterations; /** best iteration so far */ public int iterOfBest; /** max time allowed for search, in seconds */ protected float timeLimit; /** begin time of search, in seconds */ protected float beginTime; /** time elapsed since beginning of search, in seconds */ protected float elapsedTime; /** list of best viewpoints found by search, last is usually the best */ public List<CLViewpoint> globalBestViewpoints; /** min value of search space */ public float[] minSearchRange; /** max value of search space */ public float[] maxSearchRange; /** max value of search space */ public float[] searchRanges; /** average range of search space */ public float averageRange; /** constructor */ public CLSolver ( int _candidateDimension ) { candidateDimension = _candidateDimension; // we init all candidates once and for all for (int i = 0; i<candidates.Length; i++) { candidates[i] = new CLCandidate( candidateDimension ); } } //// <summary> /// Returns the best found CLViewpoint given the allowed time in milliseconds, /// the required satisfaction threshold in [0,1], a CLCameraMan for evaluating a /// candidate satisfaction. If init is true, we start search from scratch, i.e. by /// first initializing candidates; otherwise, we use the current candidates /// </summary> public CLViewpoint SearchOptimal (float _timeLimit, float _satisfactionThreshold, CLCameraMan _evaluator, List<CLCandidate> initialCandidates, bool checkGeometry=false, bool init=true) { //if init, initialize n candidates ( with r_part candidates randomly initialized ) beginTime = Time.realtimeSinceStartup; elapsedTime = 0.0f; timeLimit = _timeLimit / 1000.0f; if (init) { rnd = new System.Random (); iterations = 0; iterOfBest = 0; this.evaluator = _evaluator; this.maxSatisfaction = _satisfactionThreshold; globalBestViewpoints = new List<CLViewpoint> (); minSearchRange = evaluator.GetMinCameraParameters(candidateDimension); maxSearchRange = evaluator.GetMaxCameraParameters(candidateDimension); searchRanges = evaluator.GetParametersRange(candidateDimension); averageRange = 0.0f; for (int i=0; i<candidateDimension; i++) { averageRange += searchRanges[i]; } averageRange = averageRange / candidateDimension; InitializeCandidates (initialCandidates); InitSolverParameters (_timeLimit); elapsedTime = Time.realtimeSinceStartup - beginTime; } if (elapsedTime > timeLimit) exitCondition = 0; else exitCondition = 2; while (DoAnotherIteration()) { iterations++; // we start from 1 // execute loop body (dependent on method). exitCondition = ExecuteSearchIteration (); } //elaborate results and return best solution (access to other solutions should be provided) // this is for handling the case where no optima have been found at all (e.g. not enough time) if (globalBestViewpoints.Count == 0) { CLViewpoint noSolution = new CLViewpoint(); noSolution.satisfaction = new List<float>(); noSolution.properties = new List<CLVisualProperty> (evaluator.properties); foreach ( CLVisualProperty p in noSolution.properties ) { noSolution.satisfaction.Add ( -1.0f ); } noSolution.psoRepresentation = new float[]{0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 60.0f}; globalBestViewpoints.Add ( noSolution); } // this returns only one solution !!!! return globalBestViewpoints[globalBestViewpoints.Count-1]; } /** Sets solver parameter; the first two are the number of candidates and the percentage of randomly initialized candidates, the others are subclass-specific */ public virtual void SetSolverParameters( int _nCandidates, float r_part, float[] otherParams ) { numberOfCandidates = _nCandidates; randomPart = r_part; } /** Updates solver parameters, e.g. after a search iteration */ protected abstract void UpdateSolverParameters (float elapsedTime); /** Inits solver parameters */ protected abstract void InitSolverParameters (float timeLimit); /** Inits solver candidates */ public abstract void InitializeCandidates (List<CLCandidate> initialCandidates); /** Executes a search iteration - to be implemented in subclasses */ protected abstract int ExecuteSearchIteration (); /** Returns true of search has to continue after an iteration. Actually tests max number of iterations and maximum elapsed time. */ protected bool DoAnotherIteration () { return ((iterations < 3000) && (exitCondition==2)); } /** Performs candidates clustering */ public HierarchicalClustering PerformCandidateClustering (float minSat, bool useBestPosition) { return new HierarchicalClustering (this, minSat, useBestPosition); } public void ComputeNRandomCandidates (int startingCandidate, int numberOfCandidates) { // if r_part = 1.0 : fully random initialization bool smart = false; if (randomPart < 0.99f) smart = true; int currentCandidate; // init numberOfCandidates * r_part random candidates for (currentCandidate = startingCandidate; currentCandidate < numberOfCandidates * randomPart; currentCandidate++) { candidates [currentCandidate].position = evaluator.ComputeRandomViewpoint (candidates[0].dimension,false); } if (smart) { // now, if we have just one target, all remaining candidates are initialized according to its properties. Otherwise, // we split the remaining candidates into two parts: one, to be initialized per target (70%), and a second part, // to be initialized per allTargets (30%) int candidatesToBeInitializedPerTarget, candidatesToBeInitializedGlobally; //if (targets.Count == 1) { candidatesToBeInitializedPerTarget = numberOfCandidates - (currentCandidate - startingCandidate); candidatesToBeInitializedGlobally = 0; //} else { // candidatesToBeInitializedPerTarget = (int)Math.Ceiling ((numberOfCandidates - (currentCandidate - startingCandidate)) * 0.7f); // candidatesToBeInitializedGlobally = (int)Math.Floor ((numberOfCandidates - (currentCandidate - startingCandidate)) * 0.3f); //} float partitionFactor = candidatesToBeInitializedPerTarget / evaluator.targets.Count; foreach (CLTarget t in evaluator.targets) { // init partitionFactor * t.contribution particles according to target for (int i = 0; i < partitionFactor; i++) { candidates [currentCandidate].position = evaluator.ComputeRandomViewpoint (candidates[0].dimension,smart, t); currentCandidate++; } } // remaining candidates to be initialized globally //for (int i = 0; i < candidatesToBeInitializedGlobally; i++) { // candidates [currentCandidate].position = ComputeRandomCandidate (smart, null); // currentCandidate++; // //} } } } /// <summary> /// PSO solver for VC problems /// </summary> public class PSOSolver : CLSolver { public PSOSolver ( int _candidateDimension ) : base ( _candidateDimension ) { } /** Updates solver parameters, e.g. after a search iteration */ protected override void UpdateSolverParameters (float elapsedTime) { if (elapsedTime <= weightIterations) { w = maxInertiaWeight - elapsedTime * weightDecrement; //linear } //w = 0.4f; } //// <summary> /// Returns the best found Candidate given the allowed time in milliseconds, /// the required satisfaction threshold in [0,1], and a SmartCamera defining the /// problem with its properties and targets /// </summary> protected override int ExecuteSearchIteration () { UpdateSolverParameters (elapsedTime); steadyParticles = true; // we hypothesize particles are steady at the beginning of each iteration for (int currentCandidate=0; currentCandidate<numberOfCandidates; currentCandidate++) { // update current candidate, from second iteration if (iterations != 1) UpdateCandidate (currentCandidate); else steadyParticles = false; // evaluate current candidate candidates[currentCandidate].EvaluateSatisfaction (evaluator, true); // update leaders UpdateLeaders (currentCandidate, candidates[currentCandidate].evaluation); if (candidates[currentCandidate].evaluation >= maxSatisfaction) { // we have reached the required satisfaction threshold, goto EXIT; } // check time elapsed condition elapsedTime = Time.realtimeSinceStartup - beginTime; if (elapsedTime >= timeLimit) { // we have used all the time at disposal goto EXIT; } } // end iteration EXIT: if (elapsedTime >= timeLimit) return 0; else if (candidates [bestCandidate].bestEvaluation >= maxSatisfaction) return 1; else return 2; } //// <summary> /// Sets PSO solver parameters /// </summary> public override void SetSolverParameters (int _nCandidates, float r_part, float[] otherParams ) { base.SetSolverParameters ( _nCandidates, r_part, otherParams ); this.c1 = otherParams[0]; this.c2 = otherParams[1]; this.maxInertiaWeight = otherParams[2]; this.minInertiaWeight = otherParams[3]; } ///// <summary> /// Updates i-th candidate description /// </summary> private void UpdateCandidate (int i) { //float random_w = (float)rnd.NextDouble () / 2 + 0.5f; bool tinyVelocity = true; // we hypothesize particle velocity is tiny for (int j = 0; j < candidates[i].dimension; j++) { candidates [i].velocity [j] = w * candidates [i].velocity [j] + c1 * (float)rnd.NextDouble() * (candidates [i].bestPosition [j] - candidates [i].position [j]) + c2 * (float)rnd.NextDouble() * (candidates [bestCandidate].bestPosition [j] - candidates [i].position [j]); if ( candidates[i].velocity[j] > maxSearchRange[j] ) candidates[i].velocity[j] = maxSearchRange[j]; if ( candidates[i].velocity[j] < -maxSearchRange[j] ) candidates[i].velocity[j] = -maxSearchRange[j]; if ( candidates[i].velocity[j] > 0.001f * maxSearchRange[j] ) tinyVelocity = false; // as soon as the particle has no tiny velocity in one dimension, the particle has no tiny velocity candidates [i].position [j] = candidates [i].velocity [j] + candidates [i].position [j]; } if (!tinyVelocity) // if the particle has no tiny velocity, the swarm is not in a steady state steadyParticles = false; } /** updates a candidate leaders @param i index of the candidate whose leaders are updated @param evaluation evaluation of the current candidate */ private void UpdateLeaders (int i, float evaluation) { if (evaluation > candidates [i].bestEvaluation) { // new local optimum for (int j=0; j<candidates[i].dimension; j++) candidates [i].bestPosition [j] = candidates [i].position [j]; candidates [i].bestEvaluation = evaluation; if ((evaluation > candidates [bestCandidate].bestEvaluation) || ((i == bestCandidate) && (evaluation >= candidates [bestCandidate].bestEvaluation))) { // new global optimum bestCandidate = i; iterOfBest = iterations; //Debug.Log ( "New global optimum with sat: " + evaluation + " and position" + //new Vector3(candidates[i].bestPosition[0], candidates[i].bestPosition[1], candidates[i].bestPosition[2] ).ToString("F5")); StoreNewGlobalLeader (i); } } candidates [i].leader = bestCandidate; } /** Initializes specific solver parameters */ protected override void InitSolverParameters (float maxTime) { maxSearchRange = this.evaluator.GetParametersRange (candidateDimension); w = maxInertiaWeight; // initally w is set to the max inertia value // w decrement based on time weightIterations = 0.85f * maxTime; weightDecrement = (maxInertiaWeight - minInertiaWeight) / weightIterations; steadyParticles = false; bestCandidate = 0; } /** Initializes the candidates @remark does not need to compute each candidate satisfaction, but needs to set each candidate bestEvaluation to 0 and bestPosition to current position @note this implments fully random initialization inside search space, with zero velocity */ public override void InitializeCandidates (List<CLCandidate> initialCandidates) { int k = 0; foreach (CLCandidate c in initialCandidates) { candidates[k].position = c.position; k++; } ComputeNRandomCandidates (k, numberOfCandidates - initialCandidates.Count); for (int i=0; i<numberOfCandidates; i++) { for (int j=0; j<candidates[i].dimension; j++) { candidates [i].bestPosition [j] = candidates [i].position [j]; candidates [i].velocity [j] = 0.0f; } candidates [i].bestEvaluation = -1.0f; candidates [i].inSearchSpace = true; candidates [i].leader = 0; candidates [i].timesOutOfSearchSpace = 0; } maxSearchRange = this.evaluator.GetParametersRange (candidateDimension); } protected void StoreNewGlobalLeader (int leader) { CLViewpoint newLeaderViewpoint = new CLViewpoint (); CLCandidate leaderCandidate = new CLCandidate (candidateDimension); leaderCandidate.bestEvaluation = candidates [leader].bestEvaluation; leaderCandidate.bestPosition = candidates [leader].bestPosition; leaderCandidate.evaluation = candidates [leader].evaluation; leaderCandidate.inSearchSpace = candidates [leader].inSearchSpace; leaderCandidate.leader = candidates [leader].leader; newLeaderViewpoint.psoRepresentation = leaderCandidate.bestPosition; newLeaderViewpoint.properties = new List<CLVisualProperty> (evaluator.properties); newLeaderViewpoint.satisfaction = new List<float> (evaluator.properties.Count); newLeaderViewpoint.inScreenRatio = new List<float> (evaluator.properties.Count); foreach (CLVisualProperty p in newLeaderViewpoint.properties) { newLeaderViewpoint.satisfaction.Add (p.satisfaction); newLeaderViewpoint.inScreenRatio.Add (p.inScreenRatio); } globalBestViewpoints.Add (newLeaderViewpoint); } /** PSO cognitive parameter */ private float c1; /** PSO social parameter */ private float c2; /** Initial value of inertia weight */ public float maxInertiaWeight; /** Final value of inertia weight */ private float minInertiaWeight; /** Number of iterations for which we decrease the inertia weight */ private float weightIterations; /** Inertia weight decrement per iteration */ private float weightDecrement; /** current inertia weight */ public float w; /** true if particles are steady */ public bool steadyParticles; /** index of the best candidate */ private int bestCandidate; }
/* ==================================================================== 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 NPOI.SS.UserModel { using System; using System.Collections.Generic; using NPOI.SS.Util; /// <summary> /// Indicate the position of the margin. One of left, right, top and bottom. /// </summary> internal enum MarginType : short { /// <summary> /// referes to the left margin /// </summary> LeftMargin = 0, /// <summary> /// referes to the right margin /// </summary> RightMargin = 1, /// <summary> /// referes to the top margin /// </summary> TopMargin = 2, /// <summary> /// referes to the bottom margin /// </summary> BottomMargin = 3, HeaderMargin = 4, FooterMargin = 5 } /// <summary> /// Define the position of the pane. One of lower/right, upper/right, lower/left and upper/left. /// </summary> internal enum PanePosition : byte { /// <summary> /// referes to the lower/right corner /// </summary> LOWER_RIGHT = 0, /// <summary> /// referes to the upper/right corner /// </summary> UPPER_RIGHT = 1, /// <summary> /// referes to the lower/left corner /// </summary> LOWER_LEFT = 2, /// <summary> /// referes to the upper/left corner /// </summary> UPPER_LEFT = 3, } /// <summary> /// High level representation of a Excel worksheet. /// </summary> /// <remarks> /// Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. /// The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can /// contain text, numbers, dates, and formulas. Cells can also be formatted. /// </remarks> internal interface ISheet { /// <summary> /// Create a new row within the sheet and return the high level representation /// </summary> /// <param name="rownum">The row number.</param> /// <returns>high level Row object representing a row in the sheet</returns> /// <see>RemoveRow(Row)</see> IRow CreateRow(int rownum); /// <summary> /// Remove a row from this sheet. All cells Contained in the row are Removed as well /// </summary> /// <param name="row">a row to Remove.</param> void RemoveRow(IRow row); /// <summary> /// Returns the logical row (not physical) 0-based. If you ask for a row that is not /// defined you get a null. This is to say row 4 represents the fifth row on a sheet. /// </summary> /// <param name="rownum">row to get (0-based).</param> /// <returns>the rownumber or null if its not defined on the sheet</returns> IRow GetRow(int rownum); /// <summary> /// Returns the number of physically defined rows (NOT the number of rows in the sheet) /// </summary> /// <value>the number of physically defined rows in this sheet.</value> int PhysicalNumberOfRows { get; } /// <summary> /// Gets the first row on the sheet /// </summary> /// <value>the number of the first logical row on the sheet (0-based).</value> int FirstRowNum { get; } /// <summary> /// Gets the last row on the sheet /// </summary> /// <value>last row contained n this sheet (0-based)</value> int LastRowNum { get; } /// <summary> /// whether force formula recalculation. /// </summary> bool ForceFormulaRecalculation { get; set; } /// <summary> /// Get the visibility state for a given column /// </summary> /// <param name="columnIndex">the column to get (0-based)</param> /// <param name="hidden">the visiblity state of the column</param> void SetColumnHidden(int columnIndex, bool hidden); /// <summary> /// Get the hidden state for a given column /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <returns>hidden - <c>false</c> if the column is visible</returns> bool IsColumnHidden(int columnIndex); /// <summary> /// Set the width (in units of 1/256th of a character width) /// /// The maximum column width for an individual cell is 255 characters. /// This value represents the number of characters that can be displayed /// in a cell that is formatted with the standard font. /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <param name="width">the width in units of 1/256th of a character width</param> void SetColumnWidth(int columnIndex, int width); /// <summary> /// get the width (in units of 1/256th of a character width ) /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <returns>the width in units of 1/256th of a character width</returns> int GetColumnWidth(int columnIndex); /// <summary> /// Get the default column width for the sheet (if the columns do not define their own width) /// in characters /// </summary> /// <value>default column width measured in characters.</value> int DefaultColumnWidth { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// twips (1/20 of a point) /// </summary> /// <value>default row height measured in twips (1/20 of a point)</value> int DefaultRowHeight { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// points. /// </summary> /// <value>The default row height in points.</value> float DefaultRowHeightInPoints { get; set; } /// <summary> /// Returns the CellStyle that applies to the given /// (0 based) column, or null if no style has been /// set for that column /// </summary> /// <param name="column">The column.</param> ICellStyle GetColumnStyle(int column); /// <summary> /// Adds a merged region of cells (hence those cells form one) /// </summary> /// <param name="region">(rowfrom/colfrom-rowto/colto) to merge.</param> /// <returns>index of this region</returns> int AddMergedRegion(NPOI.SS.Util.CellRangeAddress region); /// <summary> /// Determine whether printed output for this sheet will be horizontally centered. /// </summary> bool HorizontallyCenter { get; set; } /// <summary> /// Determine whether printed output for this sheet will be vertically centered. /// </summary> bool VerticallyCenter { get; set; } /// <summary> /// Removes a merged region of cells (hence letting them free) /// </summary> /// <param name="index">index of the region to unmerge</param> void RemoveMergedRegion(int index); /// <summary> /// Returns the number of merged regions /// </summary> int NumMergedRegions { get; } /// <summary> /// Returns the merged region at the specified index /// </summary> /// <param name="index">The index.</param> NPOI.SS.Util.CellRangeAddress GetMergedRegion(int index); /// <summary> /// Gets the row enumerator. /// </summary> /// <returns> /// an iterator of the PHYSICAL rows. Meaning the 3rd element may not /// be the third row if say for instance the second row is undefined. /// Call <see cref="NPOI.SS.UserModel.IRow.RowNum"/> on each row /// if you care which one it is. /// </returns> System.Collections.IEnumerator GetRowEnumerator(); /// <summary> /// Alias for GetRowEnumerator() to allow <c>foreach</c> loops. /// </summary> /// <returns> /// an iterator of the PHYSICAL rows. Meaning the 3rd element may not /// be the third row if say for instance the second row is undefined. /// Call <see cref="NPOI.SS.UserModel.IRow.RowNum"/> on each row /// if you care which one it is. /// </returns> System.Collections.IEnumerator GetEnumerator(); /// <summary> /// Gets the flag indicating whether the window should show 0 (zero) in cells Containing zero value. /// When false, cells with zero value appear blank instead of showing the number zero. /// </summary> /// <value>whether all zero values on the worksheet are displayed.</value> bool DisplayZeros { get; set; } /// <summary> /// Gets or sets a value indicating whether the sheet displays Automatic Page Breaks. /// </summary> bool Autobreaks { get; set; } /// <summary> /// Get whether to display the guts or not, /// </summary> /// <value>default value is true</value> bool DisplayGuts { get; set; } /// <summary> /// Flag indicating whether the Fit to Page print option is enabled. /// </summary> bool FitToPage { get; set; } /// <summary> /// Flag indicating whether summary rows appear below detail in an outline, when applying an outline. /// /// /// When true a summary row is inserted below the detailed data being summarized and a /// new outline level is established on that row. /// /// /// When false a summary row is inserted above the detailed data being summarized and a new outline level /// is established on that row. /// /// </summary> /// <returns><c>true</c> if row summaries appear below detail in the outline</returns> bool RowSumsBelow { get; set; } /// <summary> /// Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. /// /// /// When true a summary column is inserted to the right of the detailed data being summarized /// and a new outline level is established on that column. /// /// /// When false a summary column is inserted to the left of the detailed data being /// summarized and a new outline level is established on that column. /// /// </summary> /// <returns><c>true</c> if col summaries appear right of the detail in the outline</returns> bool RowSumsRight { get; set; } /// <summary> /// Gets the flag indicating whether this sheet displays the lines /// between rows and columns to make editing and reading easier. /// </summary> /// <returns><c>true</c> if this sheet displays gridlines.</returns> bool IsPrintGridlines { get; set; } /// <summary> /// Gets the print Setup object. /// </summary> /// <returns>The user model for the print Setup object.</returns> IPrintSetup PrintSetup { get; } /// <summary> /// Gets the user model for the default document header. /// <p/> /// Note that XSSF offers more kinds of document headers than HSSF does /// /// </summary> /// <returns>the document header. Never <code>null</code></returns> IHeader Header { get; } /// <summary> /// Gets the user model for the default document footer. /// <p/> /// Note that XSSF offers more kinds of document footers than HSSF does. /// </summary> /// <returns>the document footer. Never <code>null</code></returns> IFooter Footer { get; } /// <summary> /// Gets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <returns>the size of the margin</returns> double GetMargin(MarginType margin); /// <summary> /// Sets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <param name="size">the size of the margin</param> void SetMargin(MarginType margin, double size); /// <summary> /// Answer whether protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool Protect { get; } /// <summary> /// Sets the protection enabled as well as the password /// </summary> /// <param name="password">to set for protection. Pass <code>null</code> to remove protection</param> void ProtectSheet(String password); /// <summary> /// Answer whether scenario protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool ScenarioProtect { get; } /// <summary> /// Gets or sets the tab color of the _sheet /// </summary> short TabColorIndex { get; set; } /// <summary> /// Returns the top-level drawing patriach, if there is one. /// This will hold any graphics or charts for the _sheet. /// WARNING - calling this will trigger a parsing of the /// associated escher records. Any that aren't supported /// (such as charts and complex drawing types) will almost /// certainly be lost or corrupted when written out. Only /// use this with simple drawings, otherwise call /// HSSFSheet#CreateDrawingPatriarch() and /// start from scratch! /// </summary> /// <value>The drawing patriarch.</value> IDrawing DrawingPatriarch { get; } /// <summary> /// Sets the zoom magnication for the sheet. The zoom is expressed as a /// fraction. For example to express a zoom of 75% use 3 for the numerator /// and 4 for the denominator. /// </summary> /// <param name="numerator">The numerator for the zoom magnification.</param> /// <param name="denominator">denominator for the zoom magnification.</param> void SetZoom(int numerator, int denominator); /// <summary> /// The top row in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row.</value> short TopRow { get; set; } /// <summary> /// The left col in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row</value> short LeftCol { get; set; } /// <summary> /// Sets desktop window pane display area, when the /// file is first opened in a viewer. /// </summary> /// <param name="toprow"> the top row to show in desktop window pane</param> /// <param name="leftcol"> the left column to show in desktop window pane</param> void ShowInPane(short toprow, short leftcol); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around. /// /// Calls shiftRows(startRow, endRow, n, false, false); /// /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> void ShiftRows(int startRow, int endRow, int n); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> /// <param name="copyRowHeight">whether to copy the row height during the shift</param> /// <param name="resetOriginalRowHeight">whether to set the original row's height to the default</param> void ShiftRows(int startRow, int endRow, int n, bool copyRowHeight, bool resetOriginalRowHeight); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split</param> /// <param name="rowSplit">Vertical position of split</param> /// <param name="leftmostColumn">Top row visible in bottom pane</param> /// <param name="topRow">Left column visible in right pane</param> void CreateFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split.</param> /// <param name="rowSplit">Vertical position of split.</param> void CreateFreezePane(int colSplit, int rowSplit); /// <summary> /// Creates a split pane. Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="xSplitPos">Horizonatal position of split (in 1/20th of a point)</param> /// <param name="ySplitPos">Vertical position of split (in 1/20th of a point)</param> /// <param name="leftmostColumn">Left column visible in right pane</param> /// <param name="topRow">Top row visible in bottom pane</param> /// <param name="activePane">Active pane. One of: PANE_LOWER_RIGHT, PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT</param> /// @see #PANE_LOWER_LEFT /// @see #PANE_LOWER_RIGHT /// @see #PANE_UPPER_LEFT /// @see #PANE_UPPER_RIGHT void CreateSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, PanePosition activePane); /// <summary> /// Returns the information regarding the currently configured pane (split or freeze) /// </summary> /// <value>if no pane configured returns <c>null</c> else return the pane information.</value> PaneInformation PaneInformation { get; } /// <summary> /// Returns if gridlines are displayed /// </summary> bool DisplayGridlines { get; set; } /// <summary> /// Returns if formulas are displayed /// </summary> bool DisplayFormulas { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool DisplayRowColHeadings { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool IsActive { get; set; } /// <summary> /// Determines if there is a page break at the indicated row /// </summary> /// <param name="row">The row.</param> bool IsRowBroken(int row); /// <summary> /// Removes the page break at the indicated row /// </summary> /// <param name="row">The row index.</param> void RemoveRowBreak(int row); /// <summary> /// Retrieves all the horizontal page breaks /// </summary> /// <value>all the horizontal page breaks, or null if there are no row page breaks</value> int[] RowBreaks { get; } /// <summary> /// Retrieves all the vertical page breaks /// </summary> /// <value>all the vertical page breaks, or null if there are no column page breaks.</value> int[] ColumnBreaks { get; } /// <summary> /// Sets the active cell. /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> void SetActiveCell(int row, int column); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="firstRow">The firstrow.</param> /// <param name="lastRow">The lastrow.</param> /// <param name="firstColumn">The firstcolumn.</param> /// <param name="lastColumn">The lastcolumn.</param> void SetActiveCellRange(int firstRow, int lastRow, int firstColumn, int lastColumn); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="cellranges">The cellranges.</param> /// <param name="activeRange">The index of the active range.</param> /// <param name="activeRow">The active row in the active range</param> /// <param name="activeColumn">The active column in the active range</param> void SetActiveCellRange(List<CellRangeAddress8Bit> cellranges, int activeRange, int activeRow, int activeColumn); /// <summary> /// Sets a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void SetColumnBreak(int column); /// <summary> /// Sets the row break. /// </summary> /// <param name="row">The row.</param> void SetRowBreak(int row); /// <summary> /// Determines if there is a page break at the indicated column /// </summary> /// <param name="column">The column index.</param> bool IsColumnBroken(int column); /// <summary> /// Removes a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void RemoveColumnBreak(int column); /// <summary> /// Expands or collapses a column group. /// </summary> /// <param name="columnNumber">One of the columns in the group.</param> /// <param name="collapsed">if set to <c>true</c>collapse group.<c>false</c>expand group.</param> void SetColumnGroupCollapsed(int columnNumber, bool collapsed); /// <summary> /// Create an outline for the provided column range. /// </summary> /// <param name="fromColumn">beginning of the column range.</param> /// <param name="toColumn">end of the column range.</param> void GroupColumn(int fromColumn, int toColumn); /// <summary> /// Ungroup a range of columns that were previously groupped /// </summary> /// <param name="fromColumn">start column (0-based).</param> /// <param name="toColumn">end column (0-based).</param> void UngroupColumn(int fromColumn, int toColumn); /// <summary> /// Tie a range of rows toGether so that they can be collapsed or expanded /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void GroupRow(int fromRow, int toRow); /// <summary> /// Ungroup a range of rows that were previously groupped /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void UngroupRow(int fromRow, int toRow); /// <summary> /// Set view state of a groupped range of rows /// </summary> /// <param name="row">start row of a groupped range of rows (0-based).</param> /// <param name="collapse">whether to expand/collapse the detail rows.</param> void SetRowGroupCollapsed(int row, bool collapse); /// <summary> /// Sets the default column style for a given column. POI will only apply this style to new cells Added to the sheet. /// </summary> /// <param name="column">the column index</param> /// <param name="style">the style to set</param> void SetDefaultColumnStyle(int column, ICellStyle style); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index.</param> /// <param name="useMergedCells">whether to use the contents of merged cells when /// calculating the width of the column. Default is to ignore merged cells.</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column, bool useMergedCells); /// <summary> /// Returns cell comment for the specified row and column /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> IComment GetCellComment(int row, int column); /// <summary> /// Creates the top-level drawing patriarch. /// </summary> IDrawing CreateDrawingPatriarch(); /// <summary> /// Gets the parent workbook. /// </summary> IWorkbook Workbook { get; } /// <summary> /// Gets the name of the sheet. /// </summary> String SheetName { get; } /// <summary> /// Gets or sets a value indicating whether this sheet is currently selected. /// </summary> bool IsSelected { get; set; } /// <summary> /// Sets whether sheet is selected. /// </summary> /// <param name="sel">Whether to select the sheet or deselect the sheet.</param> void SetActive(bool sel); /// <summary> /// Sets array formula to specified region for result. /// </summary> /// <param name="formula">text representation of the formula</param> /// <param name="range">Region of array formula for result</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> SetArrayFormula(String formula, CellRangeAddress range); /// <summary> /// Remove a Array Formula from this sheet. All cells contained in the Array Formula range are removed as well /// </summary> /// <param name="cell">any cell within Array Formula range</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> RemoveArrayFormula(ICell cell); /// <summary> /// Checks if the provided region is part of the merged regions. /// </summary> /// <param name="mergedRegion">Region searched in the merged regions</param> /// <returns><c>true</c>, when the region is contained in at least one of the merged regions</returns> bool IsMergedRegion(CellRangeAddress mergedRegion); /// <summary> /// Create an instance of a DataValidationHelper. /// </summary> /// <returns>Instance of a DataValidationHelper</returns> IDataValidationHelper GetDataValidationHelper(); /// <summary> /// Creates a data validation object /// </summary> /// <param name="dataValidation">The data validation object settings</param> void AddValidationData(IDataValidation dataValidation); /// <summary> /// Enable filtering for a range of cells /// </summary> /// <param name="range">the range of cells to filter</param> IAutoFilter SetAutoFilter(CellRangeAddress range); /// <summary> /// The 'Conditional Formatting' facet for this <c>Sheet</c> /// </summary> /// <returns>conditional formatting rule for this sheet</returns> ISheetConditionalFormatting SheetConditionalFormatting { get; } } }
// 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.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Test.Common { public sealed partial class LoopbackServer : GenericLoopbackServer, IDisposable { private Socket _listenSocket; private Options _options; private Uri _uri; // Use CreateServerAsync or similar to create private LoopbackServer(Socket listenSocket, Options options) { _listenSocket = listenSocket; _options = options; var localEndPoint = (IPEndPoint)listenSocket.LocalEndPoint; string host = options.Address.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{localEndPoint.Address}]" : localEndPoint.Address.ToString(); string scheme = options.UseSsl ? "https" : "http"; if (options.WebSocketEndpoint) { scheme = options.UseSsl ? "wss" : "ws"; } _uri = new Uri($"{scheme}://{host}:{localEndPoint.Port}/"); } public override void Dispose() { if (_listenSocket != null) { _listenSocket.Dispose(); _listenSocket = null; } } public Socket ListenSocket => _listenSocket; public Uri Uri => _uri; public static async Task CreateServerAsync(Func<LoopbackServer, Task> funcAsync, Options options = null) { options = options ?? new Options(); using (var listenSocket = new Socket(options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { listenSocket.Bind(new IPEndPoint(options.Address, 0)); listenSocket.Listen(options.ListenBacklog); using (var server = new LoopbackServer(listenSocket, options)) { await funcAsync(server); } } } public static Task CreateServerAsync(Func<LoopbackServer, Uri, Task> funcAsync, Options options = null) { return CreateServerAsync(server => funcAsync(server, server.Uri), options); } public static Task CreateClientAndServerAsync(Func<Uri, Task> clientFunc, Func<LoopbackServer, Task> serverFunc, Options options = null) { return CreateServerAsync(async server => { Task clientTask = clientFunc(server.Uri); Task serverTask = serverFunc(server); await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed(); }, options); } public async Task AcceptConnectionAsync(Func<Connection, Task> funcAsync) { using (Socket s = await _listenSocket.AcceptAsync().ConfigureAwait(false)) { s.NoDelay = true; Stream stream = new NetworkStream(s, ownsSocket: false); if (_options.UseSsl) { var sslStream = new SslStream(stream, false, delegate { return true; }); using (var cert = Configuration.Certificates.GetServerCertificate()) { await sslStream.AuthenticateAsServerAsync( cert, clientCertificateRequired: true, // allowed but not required enabledSslProtocols: _options.SslProtocols, checkCertificateRevocation: false).ConfigureAwait(false); } stream = sslStream; } if (_options.StreamWrapper != null) { stream = _options.StreamWrapper(stream); } using (var connection = new Connection(s, stream)) { await funcAsync(connection); } } } public async Task<List<string>> AcceptConnectionSendCustomResponseAndCloseAsync(string response) { List<string> lines = null; // Note, we assume there's no request body. // We'll close the connection after reading the request header and sending the response. await AcceptConnectionAsync(async connection => { lines = await connection.ReadRequestHeaderAndSendCustomResponseAsync(response); }); return lines; } public async Task<List<string>> AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) { List<string> lines = null; // Note, we assume there's no request body. // We'll close the connection after reading the request header and sending the response. await AcceptConnectionAsync(async connection => { lines = await connection.ReadRequestHeaderAndSendResponseAsync(statusCode, additionalHeaders + "Connection: close\r\n", content); }); return lines; } public static string GetRequestHeaderValue(List<string> headers, string name) { var sep = new char[] { ':' }; foreach (string line in headers) { string[] tokens = line.Split(sep, 2); if (name.Equals(tokens[0], StringComparison.InvariantCultureIgnoreCase)) { return tokens[1].Trim(); } } return null; } public static string GetRequestMethod(List<string> headers) { if (headers != null && headers.Count > 1) { return headers[0].Split()[1].Trim(); } return null; } // Stolen from HttpStatusDescription code in the product code private static string GetStatusDescription(HttpStatusCode code) { switch ((int)code) { case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-Uri Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 426: return "Upgrade Required"; // RFC 2817 case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "Http Version Not Supported"; case 507: return "Insufficient Storage"; } return null; } public enum ContentMode { ContentLength, SingleChunk, BytePerChunk, ConnectionClose } public static string GetContentModeResponse(ContentMode mode, string content, bool connectionClose = false) { switch (mode) { case ContentMode.ContentLength: return GetHttpResponse(content: content, connectionClose: connectionClose); case ContentMode.SingleChunk: return GetSingleChunkHttpResponse(content: content, connectionClose: connectionClose); case ContentMode.BytePerChunk: return GetBytePerChunkHttpResponse(content: content, connectionClose: connectionClose); case ContentMode.ConnectionClose: Assert.True(connectionClose); return GetConnectionCloseResponse(content: content); default: Assert.True(false, $"Unknown content mode: {mode}"); return null; } } public static string GetHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + (connectionClose ? "Connection: close\r\n" : "") + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {(content == null ? 0 : content.Length)}\r\n" + additionalHeaders + "\r\n" + content; public static string GetSingleChunkHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + (connectionClose ? "Connection: close\r\n" : "") + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Transfer-Encoding: chunked\r\n" + additionalHeaders + "\r\n" + (string.IsNullOrEmpty(content) ? "" : $"{content.Length:X}\r\n" + $"{content}\r\n") + $"0\r\n" + $"\r\n"; public static string GetBytePerChunkHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + (connectionClose ? "Connection: close\r\n" : "") + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Transfer-Encoding: chunked\r\n" + additionalHeaders + "\r\n" + (string.IsNullOrEmpty(content) ? "" : string.Concat(content.Select(c => $"1\r\n{c}\r\n"))) + $"0\r\n" + $"\r\n"; public static string GetConnectionCloseResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + "Connection: close\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + additionalHeaders + "\r\n" + content; public class Options { public IPAddress Address { get; set; } = IPAddress.Loopback; public int ListenBacklog { get; set; } = 1; public bool UseSsl { get; set; } = false; public SslProtocols SslProtocols { get; set; } = #if !netstandard SslProtocols.Tls13 | #endif SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; public bool WebSocketEndpoint { get; set; } = false; public Func<Stream, Stream> StreamWrapper { get; set; } public string Username { get; set; } public string Domain { get; set; } public string Password { get; set; } public bool IsProxy { get; set; } = false; } public sealed class Connection : IDisposable { private Socket _socket; private Stream _stream; private StreamReader _reader; private StreamWriter _writer; public Connection(Socket socket, Stream stream) { _socket = socket; _stream = stream; _reader = new StreamReader(stream, Encoding.ASCII); _writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; } public Socket Socket => _socket; public Stream Stream => _stream; public StreamReader Reader => _reader; public StreamWriter Writer => _writer; public void Dispose() { try { // Try to shutdown the send side of the socket. // This seems to help avoid connection reset issues caused by buffered data // that has not been sent/acked when the graceful shutdown timeout expires. // This may throw if the socket was already closed, so eat any exception. _socket.Shutdown(SocketShutdown.Send); } catch (Exception) { } _reader.Dispose(); _writer.Dispose(); _stream.Dispose(); _socket.Dispose(); } public async Task<List<string>> ReadRequestHeaderAsync() { var lines = new List<string>(); string line; while (!string.IsNullOrEmpty(line = await _reader.ReadLineAsync().ConfigureAwait(false))) { lines.Add(line); } if (line == null) { throw new Exception("Unexpected EOF trying to read request header"); } return lines; } public async Task SendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) { await _writer.WriteAsync(GetHttpResponse(statusCode, additionalHeaders, content)); } public async Task<List<string>> ReadRequestHeaderAndSendCustomResponseAsync(string response) { List<string> lines = await ReadRequestHeaderAsync().ConfigureAwait(false); await _writer.WriteAsync(response); return lines; } public async Task<List<string>> ReadRequestHeaderAndSendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) { List<string> lines = await ReadRequestHeaderAsync().ConfigureAwait(false); await SendResponseAsync(statusCode, additionalHeaders, content); return lines; } } // // GenericLoopbackServer implementation // public override async Task<HttpRequestData> HandleRequestAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = null) { string headerString = null; if (headers != null) { foreach (HttpHeaderData headerData in headers) { headerString = headerString + $"{headerData.Name}: {headerData.Value}\r\n"; } } List<string> headerLines = await AcceptConnectionSendResponseAndCloseAsync(statusCode, headerString, content); HttpRequestData requestData = new HttpRequestData(); // Parse method and path string[] splits = headerLines[0].Split(' '); requestData.Method = splits[0]; requestData.Path = splits[1]; // TODO: Add handling for request body. // In the meantime, just fail any request that's not a GET so that we don't confuse // the client by not consuming the request body. if (requestData.Method != "GET") { throw new NotImplementedException("Request body not supported"); } // Convert header lines to key/value pairs // Skip first line since it's the status line foreach (var line in headerLines.Skip(1)) { int offset = line.IndexOf(':'); string name = line.Substring(0, offset); string value = line.Substring(offset + 1).TrimStart(); requestData.Headers.Add(new HttpHeaderData(name, value)); } return requestData; } } public sealed class Http11LoopbackServerFactory : LoopbackServerFactory { public static readonly Http11LoopbackServerFactory Singleton = new Http11LoopbackServerFactory(); public override Task CreateServerAsync(Func<GenericLoopbackServer, Uri, Task> funcAsync) { return LoopbackServer.CreateServerAsync((server, uri) => funcAsync(server, uri)); } public override bool IsHttp11 => true; public override bool IsHttp2 => false; } }
using System; using System.Collections.Generic; using System.Linq; using Ical.Net.DataTypes; using Ical.Net.Utility; using NodaTime; using NodaTime.TimeZones; namespace Ical.Net.CalendarComponents { /// <summary> /// Represents an RFC 5545 VTIMEZONE component. /// </summary> public class VTimeZone : CalendarComponent { public static VTimeZone FromLocalTimeZone() => FromDateTimeZone(DateUtil.LocalDateTimeZone.Id); public static VTimeZone FromLocalTimeZone(DateTime earlistDateTimeToSupport, bool includeHistoricalData) => FromDateTimeZone(DateUtil.LocalDateTimeZone.Id, earlistDateTimeToSupport, includeHistoricalData); public static VTimeZone FromSystemTimeZone(TimeZoneInfo tzinfo) => FromSystemTimeZone(tzinfo, new DateTime(DateTime.Now.Year, 1, 1), false); public static VTimeZone FromSystemTimeZone(TimeZoneInfo tzinfo, DateTime earlistDateTimeToSupport, bool includeHistoricalData) => FromDateTimeZone(tzinfo.Id, earlistDateTimeToSupport, includeHistoricalData); public static VTimeZone FromDateTimeZone(string tzId) => FromDateTimeZone(tzId, new DateTime(DateTime.Now.Year, 1, 1), includeHistoricalData: false); public static VTimeZone FromDateTimeZone(string tzId, DateTime earlistDateTimeToSupport, bool includeHistoricalData) { var vTimeZone = new VTimeZone(tzId); var earliestYear = 1900; // Support date/times for January 1st of the previous year by default. if (earlistDateTimeToSupport.Year > 1900) { earliestYear = earlistDateTimeToSupport.Year - 1; } var earliest = Instant.FromUtc(earliestYear, earlistDateTimeToSupport.Month, earlistDateTimeToSupport.Day, earlistDateTimeToSupport.Hour, earlistDateTimeToSupport.Minute); // Only include historical data if asked to do so. Otherwise, // use only the most recent adjustment rules available. var intervals = vTimeZone._nodaZone.GetZoneIntervals(earliest, Instant.FromDateTimeOffset(DateTimeOffset.Now)) .Where(z => z.HasStart && z.Start != Instant.MinValue && z.HasEnd) .ToList(); var matchingDaylightIntervals = new List<ZoneInterval>(); var matchingStandardIntervals = new List<ZoneInterval>(); // if there are no intervals, create at least one standard interval if (!intervals.Any()) { var start = new DateTimeOffset(new DateTime(earliestYear, 1, 1), new TimeSpan(vTimeZone._nodaZone.MaxOffset.Ticks)); var interval = new ZoneInterval( name: vTimeZone._nodaZone.Id, start: Instant.FromDateTimeOffset(start), end: Instant.FromDateTimeOffset(start) + Duration.FromHours(1), wallOffset: vTimeZone._nodaZone.MinOffset, savings: Offset.Zero); intervals.Add(interval); var zoneInfo = CreateTimeZoneInfo(intervals, new List<ZoneInterval>(), true, true); vTimeZone.AddChild(zoneInfo); } else { // first, get the latest standard and daylight intervals, find the oldest recurring date in both, set the RRULES for it, and create a VTimeZoneInfos out of them. //standard var standardIntervals = intervals.Where(x => x.Savings.ToTimeSpan() == new TimeSpan(0)).ToList(); var latestStandardInterval = standardIntervals.OrderByDescending(x => x.Start).FirstOrDefault(); matchingStandardIntervals = GetMatchingIntervals(standardIntervals, latestStandardInterval, true); var latestStandardTimeZoneInfo = CreateTimeZoneInfo(matchingStandardIntervals, intervals); vTimeZone.AddChild(latestStandardTimeZoneInfo); // check to see if there is no active, future daylight savings (ie, America/Phoenix) if (latestStandardInterval != null && latestStandardInterval.End != Instant.MaxValue) { //daylight var daylightIntervals = intervals.Where(x => x.Savings.ToTimeSpan() != new TimeSpan(0)).ToList(); if (daylightIntervals.Any()) { var latestDaylightInterval = daylightIntervals.OrderByDescending(x => x.Start).FirstOrDefault(); matchingDaylightIntervals = GetMatchingIntervals(daylightIntervals, latestDaylightInterval, true); var latestDaylightTimeZoneInfo = CreateTimeZoneInfo(matchingDaylightIntervals, intervals); vTimeZone.AddChild(latestDaylightTimeZoneInfo); } } } if (!includeHistoricalData || intervals.Count == 1) { return vTimeZone; } // then, do the historic intervals, using RDATE for them var historicIntervals = intervals.Where(x => !matchingDaylightIntervals.Contains(x) && !matchingStandardIntervals.Contains(x)).ToList(); while (historicIntervals.Any(x => x.Start != Instant.MinValue)) { var interval = historicIntervals.FirstOrDefault(x => x.Start != Instant.MinValue); if (interval == null) { break; } var matchedIntervals = GetMatchingIntervals(historicIntervals, interval); var timeZoneInfo = CreateTimeZoneInfo(matchedIntervals, intervals, false); vTimeZone.AddChild(timeZoneInfo); historicIntervals = historicIntervals.Where(x => !matchedIntervals.Contains(x)).ToList(); } return vTimeZone; } private static VTimeZoneInfo CreateTimeZoneInfo(List<ZoneInterval> matchedIntervals, List<ZoneInterval> intervals, bool isRRule = true, bool isOnlyInterval = false) { if (matchedIntervals == null || !matchedIntervals.Any()) { throw new ArgumentException("No intervals found in matchedIntervals"); } var oldestInterval = matchedIntervals.OrderBy(x => x.Start).FirstOrDefault(); if (oldestInterval == null) { throw new InvalidOperationException("oldestInterval was not found"); } var previousInterval = intervals.SingleOrDefault(x => x.End == oldestInterval.Start); var delta = new TimeSpan(1, 0, 0); if (previousInterval != null) { delta = (previousInterval.WallOffset - oldestInterval.WallOffset).ToTimeSpan(); } else if (isOnlyInterval) { delta = new TimeSpan(); } var utcOffset = oldestInterval.StandardOffset.ToTimeSpan(); var timeZoneInfo = new VTimeZoneInfo(); var isDaylight = oldestInterval.Savings.Ticks > 0; if (isDaylight) { timeZoneInfo.Name = "DAYLIGHT"; timeZoneInfo.OffsetFrom = new UtcOffset(utcOffset); timeZoneInfo.OffsetTo = new UtcOffset(utcOffset - delta); } else { timeZoneInfo.Name = "STANDARD"; timeZoneInfo.OffsetFrom = new UtcOffset(utcOffset + delta); timeZoneInfo.OffsetTo = new UtcOffset(utcOffset); } timeZoneInfo.TimeZoneName = oldestInterval.Name; var start = oldestInterval.IsoLocalStart.ToDateTimeUnspecified() + delta; timeZoneInfo.Start = new CalDateTime(start) { HasTime = true }; if (isRRule) { PopulateTimeZoneInfoRecurrenceRules(timeZoneInfo, oldestInterval); } else { PopulateTimeZoneInfoRecurrenceDates(timeZoneInfo, matchedIntervals, delta); } return timeZoneInfo; } private static List<ZoneInterval> GetMatchingIntervals(List<ZoneInterval> intervals, ZoneInterval intervalToMatch, bool consecutiveOnly = false) { var matchedIntervals = intervals .Where(x => x.Start != Instant.MinValue) .Where(x => x.IsoLocalStart.Month == intervalToMatch.IsoLocalStart.Month && x.IsoLocalStart.Hour == intervalToMatch.IsoLocalStart.Hour && x.IsoLocalStart.Minute == intervalToMatch.IsoLocalStart.Minute && x.IsoLocalStart.ToDateTimeUnspecified().DayOfWeek == intervalToMatch.IsoLocalStart.ToDateTimeUnspecified().DayOfWeek && x.WallOffset == intervalToMatch.WallOffset && x.Name == intervalToMatch.Name) .ToList(); if (!consecutiveOnly) { return matchedIntervals; } var consecutiveIntervals = new List<ZoneInterval>(); var currentYear = 0; // return only the intervals where there are no gaps in years foreach (var interval in matchedIntervals.OrderByDescending(x => x.IsoLocalStart.Year)) { if (currentYear == 0) { currentYear = interval.IsoLocalStart.Year; } if (currentYear != interval.IsoLocalStart.Year) { break; } consecutiveIntervals.Add(interval); currentYear--; } return consecutiveIntervals; } private static void PopulateTimeZoneInfoRecurrenceDates(VTimeZoneInfo tzi, List<ZoneInterval> intervals, TimeSpan delta) { foreach (var interval in intervals) { var periodList = new PeriodList(); var time = interval.IsoLocalStart.ToDateTimeUnspecified(); var date = new CalDateTime(time).Add(delta) as CalDateTime; if (date == null) { continue; } date.HasTime = true; periodList.Add(date); tzi.RecurrenceDates.Add(periodList); } } private static void PopulateTimeZoneInfoRecurrenceRules(VTimeZoneInfo tzi, ZoneInterval interval) { var recurrence = new IntervalRecurrencePattern(interval); tzi.RecurrenceRules.Add(recurrence); } private class IntervalRecurrencePattern : RecurrencePattern { public IntervalRecurrencePattern(ZoneInterval interval) { Frequency = FrequencyType.Yearly; ByMonth.Add(interval.IsoLocalStart.Month); var date = interval.IsoLocalStart.ToDateTimeUnspecified(); var weekday = date.DayOfWeek; var num = DateUtil.WeekOfMonth(date); ByDay.Add(num != 5 ? new WeekDay(weekday, num) : new WeekDay(weekday, -1)); } } public VTimeZone() { Name = Components.Timezone; } public VTimeZone(string tzId) : this() { if (string.IsNullOrWhiteSpace(tzId)) { return; } TzId = tzId; Location = _nodaZone.Id; } private DateTimeZone _nodaZone; private string _tzId; public virtual string TzId { get { if (string.IsNullOrWhiteSpace(_tzId)) { _tzId = Properties.Get<string>("TZID"); } return _tzId; } set { if (string.Equals(_tzId, value, StringComparison.OrdinalIgnoreCase)) { return; } if (string.IsNullOrWhiteSpace(value)) { _tzId = null; Properties.Remove("TZID"); } _nodaZone = DateUtil.GetZone(value, useLocalIfNotFound: false); var id = _nodaZone.Id; if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentException($"Unrecognized time zone id: {value}"); } if (!string.Equals(id, value, StringComparison.OrdinalIgnoreCase)) { //It was a BCL time zone, so we should use the original value id = value; } _tzId = id; Properties.Set("TZID", value); } } private Uri _url; public virtual Uri Url { get => _url ?? (_url = Properties.Get<Uri>("TZURL")); set { _url = value; Properties.Set("TZURL", _url); } } private string _location; public string Location { get => _location ?? (_location = Properties.Get<string>("X-LIC-LOCATION")); set { _location = value; Properties.Set("X-LIC-LOCATION", _location); } } public HashSet<VTimeZoneInfo> TimeZoneInfos { get; set; } protected bool Equals(VTimeZone other) => string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(TzId, other.TzId, StringComparison.OrdinalIgnoreCase) && Equals(Url, other.Url); public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((VTimeZone)obj); } public override int GetHashCode() { unchecked { var hashCode = Name.GetHashCode(); hashCode = (hashCode * 397) ^ (TzId?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Url?.GetHashCode() ?? 0); return hashCode; } } } }
using UnityEngine; using System.Collections; namespace UMA { /// <summary> /// Human male DNA converter behaviour. /// </summary> /// <remarks> /// Although intended for Humans this DNA converter includes ranges /// far outside Human norms and can also be used for other Humanoid charatcers /// such as Elves, Giants, Halflings, et al. /// </remarks> public class HumanMaleDNAConverterBehaviour : HumanoidDNAConverterBehaviour { public HumanMaleDNAConverterBehaviour() { this.ApplyDnaAction = UpdateUMAMaleDNABones; this.DNAType = typeof(UMADnaHumanoid); } /// <summary> /// Adjusts a skeleton to reflect the DNA values from UMA character data. /// </summary> /// <remarks> /// This will set the postion, rotation, and scale of the various adjustment /// bones used by the UMA human rigs to generate a unique character shape. /// Also calculates a somewhat realistic mass for the character and the /// height and radius of their default collider. /// </remarks> /// <param name="umaData">UMA data.</param> /// <param name="skeleton">Skeleton.</param> public static void UpdateUMAMaleDNABones(UMAData umaData, UMASkeleton skeleton) { var umaDna = umaData.GetDna<UMADnaHumanoid>(); skeleton.SetScale(headAdjustHash, new Vector3( Mathf.Clamp(1, 1, 1), Mathf.Clamp(1 + (umaDna.headWidth - 0.5f) * 0.30f, 0.5f, 1.6f), Mathf.Clamp(1 , 1, 1))); skeleton.SetScale(neckAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.neckThickness - 0.5f) * 0.80f, 0.5f, 1.6f), Mathf.Clamp(1 + (umaDna.neckThickness - 0.5f) * 1.2f, 0.5f, 1.6f))); skeleton.SetScale(leftOuterBreastHash, new Vector3( Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f), Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f), Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f))); skeleton.SetScale(rightOuterBreastHash, new Vector3( Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f), Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f), Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f))); skeleton.SetScale(leftEyeHash, new Vector3( Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f), Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f), Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f))); skeleton.SetScale(rightEyeHash, new Vector3( Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f), Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f), Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f))); skeleton.SetRotation(leftEyeAdjustHash, Quaternion.Euler(new Vector3((umaDna.eyeRotation - 0.5f) * 20, 0, 0))); skeleton.SetRotation(rightEyeAdjustHash, Quaternion.Euler(new Vector3(-(umaDna.eyeRotation - 0.5f) * 20, 0, 0))); skeleton.SetScale(spine1AdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(0.9f + (umaDna.upperWeight - 0.5f) * 0.10f + (umaDna.upperMuscle - 0.5f) * 0.5f, 0.45f, 1.50f), Mathf.Clamp(0.7f + (umaDna.upperWeight - 0.5f) * 0.45f + (umaDna.upperMuscle - 0.5f) * 0.45f, 0.55f, 1.15f))); skeleton.SetScale(spineAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(0.9f + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.45f, 0.75f, 1.350f), Mathf.Clamp(0.8f + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.25f, 0.75f, 1.350f))); skeleton.SetScale(lowerBackBellyHash, new Vector3( Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 1.0f, 0.35f, 1.75f), Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 0.35f, 0.35f, 1.75f), Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 1.25f, 0.35f, 1.75f))); skeleton.SetScale(lowerBackAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f, 0.85f, 1.5f), Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.waist - 0.5f) * 0.45f, 0.65f, 1.75f), Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f, 0.85f, 1.5f))); skeleton.SetScale(leftTrapeziusHash, new Vector3( Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f), Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f), Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f))); skeleton.SetScale(rightTrapeziusHash, new Vector3( Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f), Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f), Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f))); skeleton.SetScale(leftArmAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f), Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f))); skeleton.SetScale(rightArmAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f), Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f))); skeleton.SetScale(leftForeArmAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f))); skeleton.SetScale(rightForeArmAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f))); skeleton.SetScale(leftForeArmTwistAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f))); skeleton.SetScale(rightForeArmTwistAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f), Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f))); skeleton.SetScale(leftShoulderAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f), Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f))); skeleton.SetScale(rightShoulderAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f), Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f))); skeleton.SetScale(leftUpLegAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f))); skeleton.SetScale(rightUpLegAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f))); skeleton.SetScale(leftLegAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.95f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.75f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f))); skeleton.SetScale(rightLegAdjustHash, new Vector3( Mathf.Clamp(1, 0.6f, 2), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.95f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f), Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.75f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f))); skeleton.SetScale(leftGluteusHash, new Vector3( Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f), Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f), Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f))); skeleton.SetScale(rightGluteusHash, new Vector3( Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f), Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f), Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f))); skeleton.SetScale(leftEarAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f), Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f), Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f))); skeleton.SetScale(rightEarAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f), Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f), Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f))); skeleton.SetPositionRelative(leftEarAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * -0.01f, -0.01f, 0.01f), Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * -0.03f, -0.03f, 0.03f), Mathf.Clamp(0 + (umaDna.earsPosition - 0.5f) * 0.02f, -0.02f, 0.02f))); skeleton.SetPositionRelative(rightEarAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * -0.01f, -0.01f, 0.01f), Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * 0.03f, -0.03f, 0.03f), Mathf.Clamp(0 + (umaDna.earsPosition - 0.5f) * 0.02f, -0.02f, 0.02f))); skeleton.SetRotation(leftEarAdjustHash, Quaternion.Euler(new Vector3( Mathf.Clamp(0, -30, 80), Mathf.Clamp(0, -30, 80), Mathf.Clamp((umaDna.earsRotation - 0.5f) * 40, -15, 40)))); skeleton.SetRotation(rightEarAdjustHash, Quaternion.Euler(new Vector3( Mathf.Clamp(0, -30, 80), Mathf.Clamp(0, -30, 80), Mathf.Clamp((umaDna.earsRotation - 0.5f) * -40, -40, 15)))); skeleton.SetScale(noseBaseAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.noseSize - 0.5f) * 1.5f, 0.25f, 3.0f), Mathf.Clamp(1 + (umaDna.noseSize - 0.5f) * 0.15f + (umaDna.noseWidth - 0.5f) * 1.0f, 0.25f, 3.0f), Mathf.Clamp(1 + (umaDna.noseSize - 0.5f) * 0.15f + (umaDna.noseFlatten - 0.5f) * 0.75f, 0.25f, 3.0f))); skeleton.SetScale(noseMiddleAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.noseCurve - 0.5f) * 1.5f + (umaDna.noseSize - 0.5f) * 1.0f, 0.5f, 3.0f), Mathf.Clamp(1 + (umaDna.noseCurve - 0.5f) * 0.15f + (umaDna.noseSize - 0.5f) * 0.25f + (umaDna.noseWidth - 0.5f) * 0.5f, 0.5f, 3.0f), Mathf.Clamp(1 + (umaDna.noseCurve - 0.5f) * 0.15f + (umaDna.noseSize - 0.5f) * 0.10f, 0.5f, 3.0f))); skeleton.SetRotation(noseBaseAdjustHash, Quaternion.Euler(new Vector3( Mathf.Clamp(0, -30, 80), Mathf.Clamp((umaDna.noseInclination - 0.5f) * 60, -60, 30), Mathf.Clamp(0, -30, 80)))); skeleton.SetPositionRelative(noseBaseAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.025f, -0.025f, 0.025f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.025f, -0.025f, 0.025f))); skeleton.SetPositionRelative(noseMiddleAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.012f, -0.012f, 0.012f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.015f, -0.015f, 0.015f))); skeleton.SetPositionRelative(leftNoseAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.025f, -0.025f, 0.025f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.025f, -0.025f, 0.025f))); skeleton.SetPositionRelative(rightNoseAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.025f, -0.025f, 0.025f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.025f, -0.025f, 0.025f))); skeleton.SetPositionRelative(upperLipsAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.0045f, -0.0045f, 0.0045f))); skeleton.SetScale(mandibleAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.chinPronounced - 0.5f) * 0.18f, 0.55f, 1.75f), Mathf.Clamp(1 + (umaDna.chinSize - 0.5f) * 1.3f, 0.75f, 1.3f), Mathf.Clamp(1, 0.4f, 1.5f))); skeleton.SetPositionRelative(mandibleAdjustHash, new Vector3( Mathf.Clamp(0, -0.0125f, 0.0125f), Mathf.Clamp(0, -0.0125f, 0.0125f), Mathf.Clamp(0 + (umaDna.chinPosition - 0.5f) * 0.0075f, -0.0075f, 0.0075f))); skeleton.SetPositionRelative(leftLowMaxilarAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.jawsSize - 0.5f) * 0.025f, -0.025f, 0.025f), Mathf.Clamp(0 + (umaDna.jawsPosition - 0.5f) * 0.03f, -0.03f, 0.03f))); skeleton.SetPositionRelative(rightLowMaxilarAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.jawsSize - 0.5f) * -0.025f, -0.025f, 0.025f), Mathf.Clamp(0 + (umaDna.jawsPosition - 0.5f) * 0.03f, -0.03f, 0.03f))); skeleton.SetScale(leftCheekAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f), Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f), Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f))); skeleton.SetScale(rightCheekAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f), Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f), Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f))); skeleton.SetPositionRelative(leftCheekAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.cheekPosition - 0.5f) * 0.03f, -0.03f, 0.03f))); skeleton.SetPositionRelative(rightCheekAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.cheekPosition - 0.5f) * 0.03f, -0.03f, 0.03f))); skeleton.SetPositionRelative(leftLowCheekAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.lowCheekPronounced - 0.5f) * -0.07f, -0.07f, 0.07f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.lowCheekPosition - 0.5f) * 0.06f, -0.06f, 0.06f))); skeleton.SetPositionRelative(rightLowCheekAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.lowCheekPronounced - 0.5f) * -0.07f, -0.07f, 0.07f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.lowCheekPosition - 0.5f) * 0.06f, -0.06f, 0.06f))); skeleton.SetPositionRelative(noseTopAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.025f + (umaDna.foreheadSize - 0.5f) * -0.0015f, -0.015f, 0.0025f))); skeleton.SetPositionRelative(leftEyebrowLowAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.02f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.015f, 0.005f))); skeleton.SetPositionRelative(leftEyebrowMiddleAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.05f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.025f, 0.005f))); skeleton.SetPositionRelative(leftEyebrowUpAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.007f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.010f, 0.005f))); skeleton.SetPositionRelative(rightEyebrowLowAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.02f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.015f, 0.005f))); skeleton.SetPositionRelative(rightEyebrowMiddleAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.05f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.025f, 0.005f))); skeleton.SetPositionRelative(rightEyebrowUpAdjustHash, new Vector3( Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.007f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.010f, 0.005f))); skeleton.SetScale(lipsSuperiorAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f))); skeleton.SetScale(lipsInferiorAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 1.0f, 0.65f, 1.5f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 1.0f, 0.65f, 1.5f))); skeleton.SetScale(leftLipsSuperiorMiddleAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f))); skeleton.SetScale(rightLipsSuperiorMiddleAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f))); skeleton.SetScale(leftLipsInferiorAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f))); skeleton.SetScale(rightLipsInferiorAdjustHash, new Vector3( Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f), Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f))); skeleton.SetPositionRelative(lipsInferiorAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.lipsSize - 0.5f) * -0.008f, -0.1f, 0.1f))); skeleton.SetPositionRelative(leftLipsAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * 0.03f, -0.02f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f))); skeleton.SetPositionRelative(rightLipsAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * -0.03f, -0.005f, 0.02f), Mathf.Clamp(0, -0.05f, 0.05f))); skeleton.SetPositionRelative(leftLipsSuperiorMiddleAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * 0.007f, -0.02f, 0.005f), Mathf.Clamp(0, -0.05f, 0.05f))); skeleton.SetPositionRelative(rightLipsSuperiorMiddleAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * -0.007f, -0.005f, 0.02f), Mathf.Clamp(0, -0.05f, 0.05f))); skeleton.SetPositionRelative(leftLipsInferiorAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * 0.007f, -0.02f, 0.005f), Mathf.Clamp(0 + (umaDna.lipsSize - 0.5f) * -0.008f, -0.1f, 0.1f))); skeleton.SetPositionRelative(rightLipsInferiorAdjustHash, new Vector3( Mathf.Clamp(0, -0.05f, 0.05f), Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * -0.007f, -0.005f, 0.02f), Mathf.Clamp(0 + (umaDna.lipsSize - 0.5f) * -0.008f, -0.1f, 0.1f))); ////Bone structure change float overallScale = 0.88f + (umaDna.height - 0.5f) * 1.0f + (umaDna.legsSize - 0.5f) * 1.0f; overallScale = Mathf.Clamp(overallScale, 0.5f, 2f); skeleton.SetScale(positionHash, new Vector3(overallScale, overallScale, overallScale)); skeleton.SetPositionRelative(positionHash, new Vector3( Mathf.Clamp((umaDna.feetSize - 0.5f) * -0.20f, -0.15f, 0.0675f), Mathf.Clamp(0, -10, 10), Mathf.Clamp(0, -10, 10))); float lowerBackScale = Mathf.Clamp(1 - (umaDna.legsSize - 0.5f) * 1.0f, 0.5f, 3.0f); skeleton.SetScale(lowerBackHash, new Vector3(lowerBackScale, lowerBackScale, lowerBackScale)); skeleton.SetScale(headHash, new Vector3( Mathf.Clamp(1 + (umaDna.headSize - 0.5f) * 2.0f, 0.5f, 2), Mathf.Clamp(1 + (umaDna.headSize - 0.5f) * 2.0f, 0.5f, 2), Mathf.Clamp(1 + (umaDna.headSize - 0.5f) * 2.0f, 0.5f, 2))); skeleton.SetScale(leftArmHash, new Vector3( Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetScale(rightArmHash, new Vector3( Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetScale(leftForeArmHash, new Vector3( Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetScale(rightForeArmHash, new Vector3( Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetScale(leftHandHash, new Vector3( Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetScale(rightHandHash, new Vector3( Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetScale(leftFootHash, new Vector3( Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetScale(rightFootHash, new Vector3( Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f), Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f))); skeleton.SetPositionRelative(leftUpLegHash, new Vector3( Mathf.Clamp(0, -10, 10), Mathf.Clamp((umaDna.legSeparation - 0.5f) * -0.15f + (umaDna.lowerWeight - 0.5f) * -0.035f + (umaDna.legsSize - 0.5f) * 0.1f, -0.055f, 0.055f), Mathf.Clamp(0, -10, 10))); skeleton.SetPositionRelative(rightUpLegHash, new Vector3( Mathf.Clamp(0, -10, 10), Mathf.Clamp((umaDna.legSeparation - 0.5f) * 0.15f + (umaDna.lowerWeight - 0.5f) * 0.035f + (umaDna.legsSize - 0.5f) * -0.1f, -0.055f, 0.055f), Mathf.Clamp(0, -10, 10))); skeleton.SetPositionRelative(leftShoulderHash, new Vector3( Mathf.Clamp(0, -10, 10), Mathf.Clamp(-0.003f + (umaDna.upperMuscle - 0.5f) * -0.265f, -0.085f, 0.015f), Mathf.Clamp(0, -10, 10))); skeleton.SetPositionRelative(rightShoulderHash, new Vector3( Mathf.Clamp(0, -10, 10), Mathf.Clamp(0.003f + (umaDna.upperMuscle - 0.5f) * 0.265f, -0.015f, 0.085f), Mathf.Clamp(0, -10, 10))); skeleton.SetScale(mandibleHash, new Vector3( Mathf.Clamp(1 + (umaDna.mandibleSize - 0.5f) * 0.35f, 0.35f, 1.35f), Mathf.Clamp(1 + (umaDna.mandibleSize - 0.5f) * 0.35f, 0.35f, 1.35f), Mathf.Clamp(1 + (umaDna.mandibleSize - 0.5f) * 0.35f, 0.35f, 1.35f))); float raceHeight = umaData.umaRecipe.raceData.raceHeight; float raceRadius = umaData.umaRecipe.raceData.raceRadius; float raceMass = umaData.umaRecipe.raceData.raceMass; umaData.characterHeight = raceHeight * overallScale * (0.425f + 0.6f * lowerBackScale) + ((umaDna.feetSize - 0.5f) * 0.25f); umaData.characterRadius = raceRadius + ((umaDna.height - 0.5f) * 0.35f) + Mathf.Clamp01((umaDna.upperMuscle - 0.5f) * 0.19f); umaData.characterMass = raceMass * overallScale + 26f * umaDna.upperWeight + 26f * umaDna.lowerWeight; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq.Expressions; using System.Xml.Serialization; namespace DBTM.Domain.Entities { public class SqlStatementCollection : ISqlStatementCollection { private readonly IList<SqlStatement> _internalCollection = new List<SqlStatement>(); private bool _isSaved = true; public virtual void Add(SqlStatement item) { item.PropertyChanged+=SqlStatementPropertyChanged; _internalCollection.Add(item); SetCanMoveUpDownOnAllStatements(); FireCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); } public virtual void Clear() { _internalCollection.ForEach(i => i.PropertyChanged -= SqlStatementPropertyChanged); _internalCollection.Clear(); FireCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public virtual void Remove(SqlStatement item) { var index = _internalCollection.IndexOf(item); var removed = _internalCollection.Remove(item); SetCanMoveUpDownOnAllStatements(); FireCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); item.PropertyChanged -= SqlStatementPropertyChanged; } public virtual void MoveItemUp(SqlStatement item) { int oldIndex = _internalCollection.IndexOf(item); int newIndex = oldIndex - 1; SqlStatement affectedItem = _internalCollection[newIndex]; _internalCollection[newIndex] = item; _internalCollection[oldIndex] = affectedItem; SetCanMoveUpDownOnAllStatements(); FireCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, item, newIndex, oldIndex)); } public virtual void MoveItemDown(SqlStatement item) { int oldIndex = _internalCollection.IndexOf(item); int newIndex = oldIndex + 1; SqlStatement affectedItem = _internalCollection[newIndex]; _internalCollection[newIndex] = item; _internalCollection[oldIndex] = affectedItem; SetCanMoveUpDownOnAllStatements(); FireCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, item, newIndex, oldIndex)); } public virtual void SetCanMoveUpDownOnAllStatements() { foreach (var statement in _internalCollection) { statement.CanMoveDown = CanMoveDown(statement); statement.CanMoveUp = CanMoveUp(statement); } } [XmlIgnore] public int Count { get { return _internalCollection.Count; } } [XmlIgnore] public bool IsSaved { get { return _isSaved; } private set { if (_isSaved != value) { _isSaved = value; FirePropertyChangedEvent(x => x.IsSaved); } } } public void MarkAsSaved() { IsSaved = true; _internalCollection.ForEach(s => s.MarkAsSaved()); } public int IndexOf(SqlStatement item) { return _internalCollection.IndexOf(item); } public virtual bool CanMoveUp(SqlStatement item) { if (!item.IsEditable) { return false; } if (Count == 0 || item is EmptySqlStatement) { return false; } if (_internalCollection.IndexOf(item) == 0) { return false; } if (_internalCollection.IndexOf(item) == Count - 1) { return true; } return true; } public virtual bool CanMoveDown(SqlStatement item) { if (!item.IsEditable) { return false; } if (Count == 0 || item is EmptySqlStatement) { return false; } if (_internalCollection.IndexOf(item) == 0 && _internalCollection.IndexOf(item) != Count - 1) { return true; } if (_internalCollection.IndexOf(item) == Count - 1) { return false; } return true; } public virtual bool CanRemove(SqlStatement item) { if (!item.IsEditable) { return false; } if (Count == 0 || item is EmptySqlStatement) { return false; } return true; } public IEnumerator<SqlStatement> GetEnumerator() { return _internalCollection.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public event NotifyCollectionChangedEventHandler CollectionChanged; private void FireCollectionChanged(NotifyCollectionChangedEventArgs e) { IsSaved = false; if (CollectionChanged != null) { CollectionChanged(this, e); } } private void SqlStatementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == GetIsSavedPropertyName() && !((SqlStatement)sender).IsSaved) { IsSaved = false; } } private string GetIsSavedPropertyName() { return ((Expression<Func<SqlStatementCollection, object>>)(x => x.IsSaved)).GetMemberName(); } public event PropertyChangedEventHandler PropertyChanged; private void FirePropertyChangedEvent(Expression<Func<SqlStatementCollection, object>> propertyNameFunc) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyNameFunc.GetMemberName())); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_ProhibitDTD", Desc = "")] public class TC_SchemaSet_ProhibitDTD : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_ProhibitDTD(ITestOutputHelper output) { _output = output; } public bool bWarningCallback; public bool bErrorCallback; public int errorCount; public int warningCount; private void Initialize() { bWarningCallback = bErrorCallback = false; errorCount = warningCount = 0; } //hook up validaton callback private void ValidationCallback(object sender, ValidationEventArgs args) { switch (args.Severity) { case XmlSeverityType.Warning: _output.WriteLine("WARNING: "); bWarningCallback = true; warningCount++; break; case XmlSeverityType.Error: _output.WriteLine("ERROR: "); bErrorCallback = true; errorCount++; break; } _output.WriteLine("Exception Message:" + args.Exception.Message + "\n"); if (args.Exception.InnerException != null) { _output.WriteLine("InnerException Message:" + args.Exception.InnerException.Message + "\n"); } else { _output.WriteLine("Inner Exception is NULL\n"); } } private XmlReaderSettings GetSettings(bool prohibitDtd) { return new XmlReaderSettings { #pragma warning disable 0618 ProhibitDtd = prohibitDtd, #pragma warning restore 0618 XmlResolver = new XmlUrlResolver() }; } private XmlReader CreateReader(string xmlFile, bool prohibitDtd) { return XmlReader.Create(xmlFile, GetSettings(prohibitDtd)); } private XmlReader CreateReader(string xmlFile) { return XmlReader.Create(xmlFile); } private XmlReader CreateReader(XmlReader reader, bool prohibitDtd) { return XmlReader.Create(reader, GetSettings(prohibitDtd)); } private XmlReader CreateReader(string xmlFile, XmlSchemaSet ss, bool prohibitDTD) { var settings = GetSettings(prohibitDTD); settings.Schemas = new XmlSchemaSet(); settings.Schemas.XmlResolver = new XmlUrlResolver(); settings.Schemas.ValidationEventHandler += ValidationCallback; settings.Schemas.Add(ss); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += ValidationCallback; return XmlReader.Create(xmlFile, settings); } private XmlReader CreateReader(XmlReader reader, XmlSchemaSet ss, bool prohibitDTD) { var settings = GetSettings(prohibitDTD); settings.Schemas = new XmlSchemaSet(); settings.Schemas.XmlResolver = new XmlUrlResolver(); settings.Schemas.ValidationEventHandler += ValidationCallback; settings.Schemas.Add(ss); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += ValidationCallback; return XmlReader.Create(reader, settings); } //TEST DEFAULT VALUE FOR SCHEMA COMPILATION //[Variation(Desc = "v1- Test Default value of ProhibitDTD for Add(URL) of schema with DTD", Priority = 1)] [Fact] public void v1() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; try { xss.Add(null, Path.Combine(TestData._Root, "bug356711_a.xsd")); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v2- Test Default value of ProhibitDTD for Add(XmlReader) of schema with DTD", Priority = 1)] [Fact] public void v2() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, "bug356711_a.xsd")); try { xss.Add(null, r); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v3- Test Default value of ProhibitDTD for Add(URL) containing xs:import for schema with DTD", Priority = 1)] [Fact] public void v3() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; try { xss.Add(null, Path.Combine(TestData._Root, "bug356711.xsd")); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, 1, "Warning Count mismatch"); return; } //[Variation(Desc = "v4- Test Default value of ProhibitDTD for Add(XmlReader) containing xs:import for scehma with DTD", Priority = 1)] [Fact] public void v4() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, "bug356711.xsd")); try { xss.Add(null, r); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, 1, "Warning Count mismatch"); return; } [Theory] [ActiveIssue(39106)] //[Variation(Desc = "v5.2- Test Default value of ProhibitDTD for Add(TextReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd", 0 })] [InlineData("bug356711_a.xsd", 0)] //[Variation(Desc = "v5.1- Test Default value of ProhibitDTD for Add(TextReader) with an xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd", 0 })] [InlineData("bug356711.xsd", 0)] public void v5(object param0, object param1) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlSchema schema = XmlSchema.Read(new StreamReader(new FileStream(Path.Combine(TestData._Root, param0.ToString()), FileMode.Open, FileAccess.Read)), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback, new XmlUrlResolver()); #pragma warning restore 0618 try { xss.Add(schema); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, (int)param1, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Error Count mismatch"); } [Theory] [ActiveIssue(39106)] //[Variation(Desc = "v6.2- Test Default value of ProhibitDTD for Add(XmlTextReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] //[Variation(Desc = "v6.1- Test Default value of ProhibitDTD for Add(XmlTextReader) with an xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] public void v6(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; var reader = new XmlTextReader(Path.Combine(TestData._Root, param0.ToString())); reader.XmlResolver = new XmlUrlResolver(); XmlSchema schema = XmlSchema.Read(reader, ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 xss.Add(schema); // expect a validation warning for unresolvable schema location CError.Compare(warningCount, 0, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Error Count mismatch"); } //[Variation(Desc = "v7- Test Default value of ProhibitDTD for Add(XmlReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] [Theory] public void v7(object param0) { Initialize(); try { XmlSchema schema = XmlSchema.Read(CreateReader(Path.Combine(TestData._Root, param0.ToString())), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v8- Test Default value of ProhibitDTD for Add(XmlReader) with xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] [Theory] public void v8(object param0) { Initialize(); try { XmlSchema schema = XmlSchema.Read(CreateReader(Path.Combine(TestData._Root, param0.ToString())), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, 0, "Warning Count mismatch"); return; } //TEST CUSTOM VALUE FOR SCHEMA COMPILATION //[Variation(Desc = "v10.1- Test Custom value of ProhibitDTD for SchemaSet.Add(XmlReader) with xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] //[Variation(Desc = "v10.2- Test Custom value of ProhibitDTD for SchemaSet.Add(XmlReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] [Theory] public void v10(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, param0.ToString()), false); try { xss.Add(null, r); } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 0, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Warning Count mismatch"); return; } //[Variation(Desc = "v11.2- Test Custom value of ProhibitDTD for XmlSchema.Add(XmlReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] //[Variation(Desc = "v11.1- Test Custom value of ProhibitDTD for XmlSchema.Add(XmlReader) with an xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] [Theory] public void v11(object param0) { Initialize(); try { XmlSchema schema = XmlSchema.Read(CreateReader(Path.Combine(TestData._Root, param0.ToString()), false), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 0, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Warning Count mismatch"); return; } //[Variation(Desc = "v12- Test with underlying reader with ProhibitDTD=true, and new Setting with True for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] [Theory] public void v12(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, param0.ToString()), false); XmlReader r2 = CreateReader(r, true); try { xss.Add(null, r2); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v13- Test with underlying reader with ProhibitDTD=true, and new Setting with True for a schema with xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] [Theory] public void v13(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, param0.ToString()), false); XmlReader r2 = CreateReader(r, true); try { xss.Add(null, r2); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } _output.WriteLine("Count: " + xss.Count); CError.Compare(warningCount, 1, "Warning Count mismatch"); return; } //[Variation(Desc = "v14 - SchemaSet.Add(XmlReader) with pDTD False ,then a SchemaSet.Add(URL) for schema with DTD", Priority = 1)] [Fact] public void v14() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, "bug356711.xsd"), false); try { xss.Add(null, r); CError.Compare(xss.Count, 2, "SchemaSet count mismatch!"); xss.Add(null, Path.Combine(TestData._Root, "bug356711_b.xsd")); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v15 - SchemaSet.Add(XmlReader) with pDTD True ,then a SchemaSet.Add(XmlReader) with pDTD False with DTD", Priority = 1)] [Fact] public void v15() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; XmlReader r1 = CreateReader(Path.Combine(TestData._Root, "bug356711_a.xsd")); XmlReader r2 = CreateReader(Path.Combine(TestData._Root, "bug356711_b.xsd"), false); try { xss.Add(null, r1); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); CError.Compare(xss.Count, 0, "SchemaSet count mismatch!"); } try { xss.Add(null, r2); } catch (Exception) { Assert.True(false); } CError.Compare(xss.Count, 1, "SchemaSet count mismatch!"); return; } //TEST DEFAULT VALUE FOR INSTANCE VALIDATION //[Variation(Desc = "v20.1- Test Default value of ProhibitDTD for XML containing noNamespaceSchemaLocation for schema which contains xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711_1.xml" })] [InlineData("bug356711_1.xml")] //[Variation(Desc = "v20.2- Test Default value of ProhibitDTD for XML containing schemaLocation for schema with DTD", Priority = 1, Params = new object[] { "bug356711_2.xml" })] [InlineData("bug356711_2.xml")] //[Variation(Desc = "v20.3- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema with DTD", Priority = 1, Params = new object[] { "bug356711_3.xml" })] [InlineData("bug356711_3.xml")] //[Variation(Desc = "v20.4- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema which has a xs:import of schema with DTD", Priority = 1, Params = new object[] { "bug356711_4.xml" })] [InlineData("bug356711_4.xml")] [Theory] public void v20(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { XmlReader reader = CreateReader(Path.Combine(TestData._Root, param0.ToString()), xss, true); while (reader.Read()) ; } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 2, "ProhibitDTD did not work with schemaLocation"); return; } //[Variation(Desc = "v21- Underlying XmlReader with ProhibitDTD=False and Create new Reader with ProhibitDTD=True", Priority = 1)] [Fact] public void v21() { Initialize(); var xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { using (var r1 = CreateReader(Path.Combine(TestData._Root, "bug356711_1.xml"), false)) using (var r2 = CreateReader(r1, xss, true)) { while (r2.Read()) { } } } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 2, "ProhibitDTD did not work with schemaLocation"); return; } //TEST CUSTOM VALUE FOR INSTANCE VALIDATION //[Variation(Desc = "v22.1- Test Default value of ProhibitDTD for XML containing noNamespaceSchemaLocation for schema which contains xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711_1.xml" })] [InlineData("bug356711_1.xml")] //[Variation(Desc = "v22.2- Test Default value of ProhibitDTD for XML containing schemaLocation for schema with DTD", Priority = 1, Params = new object[] { "bug356711_2.xml" })] [InlineData("bug356711_2.xml")] //[Variation(Desc = "v22.3- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema with DTD", Priority = 1, Params = new object[] { "bug356711_3.xml" })] [InlineData("bug356711_3.xml")] //[Variation(Desc = "v22.4- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema which has a xs:import of schema with DTD", Priority = 1, Params = new object[] { "bug356711_4.xml" })] [InlineData("bug356711_4.xml")] [Theory] public void v22(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { XmlReader reader = CreateReader(Path.Combine(TestData._Root, param0.ToString()), xss, false); while (reader.Read()) ; } catch (XmlException) { Assert.True(false); } CError.Compare(errorCount, 0, "ProhibitDTD did not work with schemaLocation"); return; } //[Variation(Desc = "v23- Underlying XmlReader with ProhibitDTD=True and Create new Reader with ProhibitDTD=False", Priority = 1)] [Fact] public void v23() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { XmlReader r1 = CreateReader(Path.Combine(TestData._Root, "bug356711_1.xml"), true); XmlReader r2 = CreateReader(r1, xss, false); while (r2.Read()) ; } catch (XmlException) { Assert.True(false); } CError.Compare(errorCount, 0, "ProhibitDTD did not work with schemaLocation"); return; } } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Antlr.Runtime { using System.Collections.Generic; using InvalidOperationException = System.InvalidOperationException; using StringBuilder = System.Text.StringBuilder; /** <summary> * The most common stream of tokens is one where every token is buffered up * and tokens are prefiltered for a certain channel (the parser will only * see these tokens and cannot change the filter channel number during the * parse). * </summary> * * <remarks>TODO: how to access the full token stream? How to track all tokens matched per rule?</remarks> */ [System.Serializable] public class LegacyCommonTokenStream : ITokenStream { [System.NonSerialized] ITokenSource _tokenSource; /** <summary> * Record every single token pulled from the source so we can reproduce * chunks of it later. * </summary> */ protected List<IToken> tokens; /** <summary>Map<tokentype, channel> to override some Tokens' channel numbers</summary> */ protected IDictionary<int, int> channelOverrideMap; /** <summary>Set<tokentype>; discard any tokens with this type</summary> */ protected List<int> discardSet; /** <summary>Skip tokens on any channel but this one; this is how we skip whitespace...</summary> */ protected int channel = TokenChannels.Default; /** <summary>By default, track all incoming tokens</summary> */ protected bool discardOffChannelTokens = false; /** <summary>Track the last mark() call result value for use in rewind().</summary> */ protected int lastMarker; /** <summary> * The index into the tokens list of the current token (next token * to consume). p==-1 indicates that the tokens list is empty * </summary> */ protected int p = -1; public LegacyCommonTokenStream() { tokens = new List<IToken>( 500 ); } public LegacyCommonTokenStream(ITokenSource tokenSource) : this() { this._tokenSource = tokenSource; } public LegacyCommonTokenStream( ITokenSource tokenSource, int channel ) : this( tokenSource ) { this.channel = channel; } public virtual int Index { get { return p; } } /// <summary> /// How deep have we gone? /// </summary> public virtual int Range { get; protected set; } /** <summary>Reset this token stream by setting its token source.</summary> */ public virtual void SetTokenSource( ITokenSource tokenSource ) { this._tokenSource = tokenSource; tokens.Clear(); p = -1; channel = TokenChannels.Default; } /** <summary> * Load all tokens from the token source and put in tokens. * This is done upon first LT request because you might want to * set some token type / channel overrides before filling buffer. * </summary> */ public virtual void FillBuffer() { // fast return if the buffer is already full if ( p != -1 ) return; int index = 0; IToken t = _tokenSource.NextToken(); while ( t != null && t.Type != CharStreamConstants.EndOfFile ) { bool discard = false; // is there a channel override for token type? int channelI; if ( channelOverrideMap != null && channelOverrideMap.TryGetValue( t.Type, out channelI ) ) t.Channel = channelI; //if ( channelOverrideMap != null && channelOverrideMap.ContainsKey( t.getType() ) ) //{ // object channelI = channelOverrideMap.get( t.getType() ); // if ( channelI != null ) // { // t.setChannel( (int)channelI ); // } //} if ( discardSet != null && discardSet.Contains( t.Type ) ) { discard = true; } else if ( discardOffChannelTokens && t.Channel != this.channel ) { discard = true; } if ( !discard ) { t.TokenIndex = index; tokens.Add( t ); index++; } t = _tokenSource.NextToken(); } // leave p pointing at first token on channel p = 0; p = SkipOffTokenChannels( p ); } /** <summary> * Move the input pointer to the next incoming token. The stream * must become active with LT(1) available. consume() simply * moves the input pointer so that LT(1) points at the next * input symbol. Consume at least one token. * </summary> * * <remarks> * Walk past any token not on the channel the parser is listening to. * </remarks> */ public virtual void Consume() { if ( p < tokens.Count ) { p++; p = SkipOffTokenChannels( p ); // leave p on valid token } } /** <summary>Given a starting index, return the index of the first on-channel token.</summary> */ protected virtual int SkipOffTokenChannels( int i ) { int n = tokens.Count; while ( i < n && ( (IToken)tokens[i] ).Channel != channel ) { i++; } return i; } protected virtual int SkipOffTokenChannelsReverse( int i ) { while ( i >= 0 && ( (IToken)tokens[i] ).Channel != channel ) { i--; } return i; } /** <summary> * A simple filter mechanism whereby you can tell this token stream * to force all tokens of type ttype to be on channel. For example, * when interpreting, we cannot exec actions so we need to tell * the stream to force all WS and NEWLINE to be a different, ignored * channel. * </summary> */ public virtual void SetTokenTypeChannel( int ttype, int channel ) { if ( channelOverrideMap == null ) { channelOverrideMap = new Dictionary<int, int>(); } channelOverrideMap[ttype] = channel; } public virtual void DiscardTokenType( int ttype ) { if ( discardSet == null ) { discardSet = new List<int>(); } discardSet.Add( ttype ); } public virtual void SetDiscardOffChannelTokens( bool discardOffChannelTokens ) { this.discardOffChannelTokens = discardOffChannelTokens; } public virtual IList<IToken> GetTokens() { if ( p == -1 ) { FillBuffer(); } return tokens; } public virtual IList<IToken> GetTokens( int start, int stop ) { return GetTokens( start, stop, (BitSet)null ); } /** <summary> * Given a start and stop index, return a List of all tokens in * the token type BitSet. Return null if no tokens were found. This * method looks at both on and off channel tokens. * </summary> */ public virtual IList<IToken> GetTokens( int start, int stop, BitSet types ) { if ( p == -1 ) { FillBuffer(); } if ( stop >= tokens.Count ) { stop = tokens.Count - 1; } if ( start < 0 ) { start = 0; } if ( start > stop ) { return null; } // list = tokens[start:stop]:{Token t, t.getType() in types} IList<IToken> filteredTokens = new List<IToken>(); for ( int i = start; i <= stop; i++ ) { IToken t = tokens[i]; if ( types == null || types.Member( t.Type ) ) { filteredTokens.Add( t ); } } if ( filteredTokens.Count == 0 ) { filteredTokens = null; } return filteredTokens; } public virtual IList<IToken> GetTokens( int start, int stop, IList<int> types ) { return GetTokens( start, stop, new BitSet( types ) ); } public virtual IList<IToken> GetTokens( int start, int stop, int ttype ) { return GetTokens( start, stop, BitSet.Of( ttype ) ); } /** <summary> * Get the ith token from the current position 1..n where k=1 is the * first symbol of lookahead. * </summary> */ public virtual IToken LT( int k ) { if ( p == -1 ) { FillBuffer(); } if ( k == 0 ) { return null; } if ( k < 0 ) { return LB( -k ); } //System.out.print("LT(p="+p+","+k+")="); if ( ( p + k - 1 ) >= tokens.Count ) { return tokens[tokens.Count - 1]; } //System.out.println(tokens.get(p+k-1)); int i = p; int n = 1; // find k good tokens while ( n < k ) { // skip off-channel tokens i = SkipOffTokenChannels( i + 1 ); // leave p on valid token n++; } if ( i >= tokens.Count ) { return tokens[tokens.Count - 1]; } if (i > Range) Range = i; return (IToken)tokens[i]; } /** <summary>Look backwards k tokens on-channel tokens</summary> */ protected virtual IToken LB( int k ) { //System.out.print("LB(p="+p+","+k+") "); if ( p == -1 ) { FillBuffer(); } if ( k == 0 ) { return null; } if ( ( p - k ) < 0 ) { return null; } int i = p; int n = 1; // find k good tokens looking backwards while ( n <= k ) { // skip off-channel tokens i = SkipOffTokenChannelsReverse( i - 1 ); // leave p on valid token n++; } if ( i < 0 ) { return null; } return (IToken)tokens[i]; } /** <summary> * Return absolute token i; ignore which channel the tokens are on; * that is, count all tokens not just on-channel tokens. * </summary> */ public virtual IToken Get( int i ) { return (IToken)tokens[i]; } #if false /** Get all tokens from start..stop inclusively */ public virtual List<IToken> Get(int start, int count) { if (start < 0) throw new ArgumentOutOfRangeException("start"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (p == -1) FillBuffer(); return new List<IToken>(tokens.Skip(start).Take(count)); } #endif public virtual int LA( int i ) { return LT( i ).Type; } public virtual int Mark() { if ( p == -1 ) { FillBuffer(); } lastMarker = Index; return lastMarker; } public virtual void Release( int marker ) { // no resources to release } public virtual int Count { get { return tokens.Count; } } public virtual void Rewind( int marker ) { Seek( marker ); } public virtual void Rewind() { Seek( lastMarker ); } public virtual void Reset() { p = 0; lastMarker = 0; } public virtual void Seek( int index ) { p = index; } public virtual ITokenSource TokenSource { get { return _tokenSource; } } public virtual string SourceName { get { return TokenSource.SourceName; } } public override string ToString() { if ( p == -1 ) { throw new InvalidOperationException( "Buffer is not yet filled." ); } return ToString( 0, tokens.Count - 1 ); } public virtual string ToString( int start, int stop ) { if ( start < 0 || stop < 0 ) { return null; } if ( p == -1 ) { throw new InvalidOperationException( "Buffer is not yet filled." ); } if ( stop >= tokens.Count ) { stop = tokens.Count - 1; } StringBuilder buf = new StringBuilder(); for ( int i = start; i <= stop; i++ ) { IToken t = tokens[i]; buf.Append( t.Text ); } return buf.ToString(); } public virtual string ToString( IToken start, IToken stop ) { if ( start != null && stop != null ) { return ToString( start.TokenIndex, stop.TokenIndex ); } return null; } } }
using Lucene.Net.Documents; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections; namespace Lucene.Net.Search { using Lucene.Net.Randomized.Generators; using NUnit.Framework; using AtomicReader = Lucene.Net.Index.AtomicReader; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Bits = Lucene.Net.Util.Bits; using Directory = Lucene.Net.Store.Directory; using DocIdBitSet = Lucene.Net.Util.DocIdBitSet; using DocsEnum = Lucene.Net.Index.DocsEnum; using Document = Documents.Document; using Field = Field; using FilterStrategy = Lucene.Net.Search.FilteredQuery.FilterStrategy; using IndexReader = Lucene.Net.Index.IndexReader; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using Occur = Lucene.Net.Search.BooleanClause.Occur; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// FilteredQuery JUnit tests. /// /// <p>Created: Apr 21, 2004 1:21:46 PM /// /// /// @since 1.4 /// </summary> [TestFixture] public class TestFilteredQuery : LuceneTestCase { private IndexSearcher Searcher; private IndexReader Reader; private Directory Directory; private Query Query; private Filter Filter; [SetUp] public override void SetUp() { base.SetUp(); Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy())); Document doc = new Document(); doc.Add(NewTextField("field", "one two three four five", Field.Store.YES)); doc.Add(NewTextField("sorter", "b", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "one two three four", Field.Store.YES)); doc.Add(NewTextField("sorter", "d", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "one two three y", Field.Store.YES)); doc.Add(NewTextField("sorter", "a", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "one two x", Field.Store.YES)); doc.Add(NewTextField("sorter", "c", Field.Store.YES)); writer.AddDocument(doc); // tests here require single segment (eg try seed // 8239472272678419952L), because SingleDocTestFilter(x) // blindly accepts that docID in any sub-segment writer.ForceMerge(1); Reader = writer.Reader; writer.Dispose(); Searcher = NewSearcher(Reader); Query = new TermQuery(new Term("field", "three")); Filter = NewStaticFilterB(); } // must be static for serialization tests private static Filter NewStaticFilterB() { return new FilterAnonymousInnerClassHelper(); } private class FilterAnonymousInnerClassHelper : Filter { public FilterAnonymousInnerClassHelper() { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs) { if (acceptDocs == null) { acceptDocs = new Bits_MatchAllBits(5); } BitArray bitset = new BitArray(5); if (acceptDocs.Get(1)) { bitset.SafeSet(1, true); } if (acceptDocs.Get(3)) { bitset.SafeSet(3, true); } return new DocIdBitSet(bitset); } } [TearDown] public override void TearDown() { Reader.Dispose(); Directory.Dispose(); base.TearDown(); } [Test] public virtual void TestFilteredQuery_Mem() { // force the filter to be executed as bits TFilteredQuery(true); // force the filter to be executed as iterator TFilteredQuery(false); } private void TFilteredQuery(bool useRandomAccess) { Query filteredquery = new FilteredQuery(Query, Filter, RandomFilterStrategy(Random(), useRandomAccess)); ScoreDoc[] hits = Searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(1, hits[0].Doc); QueryUtils.Check(Random(), filteredquery, Searcher); hits = Searcher.Search(filteredquery, null, 1000, new Sort(new SortField("sorter", SortField.Type_e.STRING))).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(1, hits[0].Doc); filteredquery = new FilteredQuery(new TermQuery(new Term("field", "one")), Filter, RandomFilterStrategy(Random(), useRandomAccess)); hits = Searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check(Random(), filteredquery, Searcher); filteredquery = new FilteredQuery(new MatchAllDocsQuery(), Filter, RandomFilterStrategy(Random(), useRandomAccess)); hits = Searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check(Random(), filteredquery, Searcher); filteredquery = new FilteredQuery(new TermQuery(new Term("field", "x")), Filter, RandomFilterStrategy(Random(), useRandomAccess)); hits = Searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(3, hits[0].Doc); QueryUtils.Check(Random(), filteredquery, Searcher); filteredquery = new FilteredQuery(new TermQuery(new Term("field", "y")), Filter, RandomFilterStrategy(Random(), useRandomAccess)); hits = Searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); QueryUtils.Check(Random(), filteredquery, Searcher); // test boost Filter f = NewStaticFilterA(); float boost = 2.5f; BooleanQuery bq1 = new BooleanQuery(); TermQuery tq = new TermQuery(new Term("field", "one")); tq.Boost = boost; bq1.Add(tq, Occur.MUST); bq1.Add(new TermQuery(new Term("field", "five")), Occur.MUST); BooleanQuery bq2 = new BooleanQuery(); tq = new TermQuery(new Term("field", "one")); filteredquery = new FilteredQuery(tq, f, RandomFilterStrategy(Random(), useRandomAccess)); filteredquery.Boost = boost; bq2.Add(filteredquery, Occur.MUST); bq2.Add(new TermQuery(new Term("field", "five")), Occur.MUST); AssertScoreEquals(bq1, bq2); Assert.AreEqual(boost, filteredquery.Boost, 0); Assert.AreEqual(1.0f, tq.Boost, 0); // the boost value of the underlying query shouldn't have changed } // must be static for serialization tests private static Filter NewStaticFilterA() { return new FilterAnonymousInnerClassHelper2(); } private class FilterAnonymousInnerClassHelper2 : Filter { public FilterAnonymousInnerClassHelper2() { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs) { Assert.IsNull(acceptDocs, "acceptDocs should be null, as we have an index without deletions"); BitArray bitset = new BitArray(5, true); return new DocIdBitSet(bitset); } } /// <summary> /// Tests whether the scores of the two queries are the same. /// </summary> public virtual void AssertScoreEquals(Query q1, Query q2) { ScoreDoc[] hits1 = Searcher.Search(q1, null, 1000).ScoreDocs; ScoreDoc[] hits2 = Searcher.Search(q2, null, 1000).ScoreDocs; Assert.AreEqual(hits1.Length, hits2.Length); for (int i = 0; i < hits1.Length; i++) { Assert.AreEqual(hits1[i].Score, hits2[i].Score, 0.000001f); } } /// <summary> /// this tests FilteredQuery's rewrite correctness /// </summary> [Test] public virtual void TestRangeQuery() { // force the filter to be executed as bits TRangeQuery(true); TRangeQuery(false); } private void TRangeQuery(bool useRandomAccess) { TermRangeQuery rq = TermRangeQuery.NewStringRange("sorter", "b", "d", true, true); Query filteredquery = new FilteredQuery(rq, Filter, RandomFilterStrategy(Random(), useRandomAccess)); ScoreDoc[] hits = Searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check(Random(), filteredquery, Searcher); } [Test] public virtual void TestBooleanMUST() { // force the filter to be executed as bits TBooleanMUST(true); // force the filter to be executed as iterator TBooleanMUST(false); } private void TBooleanMUST(bool useRandomAccess) { BooleanQuery bq = new BooleanQuery(); Query query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(0), RandomFilterStrategy(Random(), useRandomAccess)); bq.Add(query, BooleanClause.Occur.MUST); query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(1), RandomFilterStrategy(Random(), useRandomAccess)); bq.Add(query, BooleanClause.Occur.MUST); ScoreDoc[] hits = Searcher.Search(bq, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); QueryUtils.Check(Random(), query, Searcher); } [Test] public virtual void TestBooleanSHOULD() { // force the filter to be executed as bits TBooleanSHOULD(true); // force the filter to be executed as iterator TBooleanSHOULD(false); } private void TBooleanSHOULD(bool useRandomAccess) { BooleanQuery bq = new BooleanQuery(); Query query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(0), RandomFilterStrategy(Random(), useRandomAccess)); bq.Add(query, BooleanClause.Occur.SHOULD); query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(1), RandomFilterStrategy(Random(), useRandomAccess)); bq.Add(query, BooleanClause.Occur.SHOULD); ScoreDoc[] hits = Searcher.Search(bq, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check(Random(), query, Searcher); } // Make sure BooleanQuery, which does out-of-order // scoring, inside FilteredQuery, works [Test] public virtual void TestBoolean2() { // force the filter to be executed as bits TBoolean2(true); // force the filter to be executed as iterator TBoolean2(false); } private void TBoolean2(bool useRandomAccess) { BooleanQuery bq = new BooleanQuery(); Query query = new FilteredQuery(bq, new SingleDocTestFilter(0), RandomFilterStrategy(Random(), useRandomAccess)); bq.Add(new TermQuery(new Term("field", "one")), BooleanClause.Occur.SHOULD); bq.Add(new TermQuery(new Term("field", "two")), BooleanClause.Occur.SHOULD); ScoreDoc[] hits = Searcher.Search(query, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); QueryUtils.Check(Random(), query, Searcher); } [Test] public virtual void TestChainedFilters() { // force the filter to be executed as bits TChainedFilters(true); // force the filter to be executed as iterator TChainedFilters(false); } private void TChainedFilters(bool useRandomAccess) { Query query = new FilteredQuery(new FilteredQuery(new MatchAllDocsQuery(), new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "three")))), RandomFilterStrategy(Random(), useRandomAccess)), new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "four")))), RandomFilterStrategy(Random(), useRandomAccess)); ScoreDoc[] hits = Searcher.Search(query, 10).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check(Random(), query, Searcher); // one more: query = new FilteredQuery(query, new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "five")))), RandomFilterStrategy(Random(), useRandomAccess)); hits = Searcher.Search(query, 10).ScoreDocs; Assert.AreEqual(1, hits.Length); QueryUtils.Check(Random(), query, Searcher); } [Test] public virtual void TestEqualsHashcode() { // some tests before, if the used queries and filters work: Assert.AreEqual(new PrefixFilter(new Term("field", "o")), new PrefixFilter(new Term("field", "o"))); Assert.IsFalse((new PrefixFilter(new Term("field", "a"))).Equals(new PrefixFilter(new Term("field", "o")))); QueryUtils.CheckHashEquals(new TermQuery(new Term("field", "one"))); QueryUtils.CheckUnequal(new TermQuery(new Term("field", "one")), new TermQuery(new Term("field", "two")) ); // now test FilteredQuery equals/hashcode: QueryUtils.CheckHashEquals(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")))); QueryUtils.CheckUnequal(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o"))), new FilteredQuery(new TermQuery(new Term("field", "two")), new PrefixFilter(new Term("field", "o"))) ); QueryUtils.CheckUnequal(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "a"))), new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o"))) ); } [Test] public virtual void TestInvalidArguments() { try { new FilteredQuery(null, null); Assert.Fail("Should throw IllegalArgumentException"); } catch (System.ArgumentException iae) { // pass } try { new FilteredQuery(new TermQuery(new Term("field", "one")), null); Assert.Fail("Should throw IllegalArgumentException"); } catch (System.ArgumentException iae) { // pass } try { new FilteredQuery(null, new PrefixFilter(new Term("field", "o"))); Assert.Fail("Should throw IllegalArgumentException"); } catch (System.ArgumentException iae) { // pass } } private FilterStrategy RandomFilterStrategy() { return RandomFilterStrategy(Random(), true); } private void AssertRewrite(FilteredQuery fq, Type clazz) { // assign crazy boost to FQ float boost = (float)Random().NextDouble() * 100.0f; fq.Boost = boost; // assign crazy boost to inner float innerBoost = (float)Random().NextDouble() * 100.0f; fq.Query.Boost = innerBoost; // check the class and boosts of rewritten query Query rewritten = Searcher.Rewrite(fq); Assert.IsTrue(clazz.IsInstanceOfType(rewritten), "is not instance of " + clazz.Name); if (rewritten is FilteredQuery) { Assert.AreEqual(boost, rewritten.Boost, 1E-5f); Assert.AreEqual(innerBoost, ((FilteredQuery)rewritten).Query.Boost, 1E-5f); Assert.AreEqual(fq.Strategy, ((FilteredQuery)rewritten).Strategy); } else { Assert.AreEqual(boost * innerBoost, rewritten.Boost, 1E-5f); } // check that the original query was not modified Assert.AreEqual(boost, fq.Boost, 1E-5f); Assert.AreEqual(innerBoost, fq.Query.Boost, 1E-5f); } [Test] public virtual void TestRewrite() { AssertRewrite(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")), RandomFilterStrategy()), typeof(FilteredQuery)); AssertRewrite(new FilteredQuery(new PrefixQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")), RandomFilterStrategy()), typeof(FilteredQuery)); } [Test] public virtual void TestGetFilterStrategy() { FilterStrategy randomFilterStrategy = RandomFilterStrategy(); FilteredQuery filteredQuery = new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")), randomFilterStrategy); Assert.AreSame(randomFilterStrategy, filteredQuery.Strategy); } private static FilteredQuery.FilterStrategy RandomFilterStrategy(Random random, bool useRandomAccess) { if (useRandomAccess) { return new RandomAccessFilterStrategyAnonymousInnerClassHelper(); } return TestUtil.RandomFilterStrategy(random); } private class RandomAccessFilterStrategyAnonymousInnerClassHelper : FilteredQuery.RandomAccessFilterStrategy { public RandomAccessFilterStrategyAnonymousInnerClassHelper() { } protected override bool UseRandomAccess(Bits bits, int firstFilterDoc) { return true; } } /* * Test if the QueryFirst strategy calls the bits only if the document has * been matched by the query and not otherwise */ [Test] public virtual void TestQueryFirstFilterStrategy() { Directory directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); int numDocs = AtLeast(50); int totalDocsWithZero = 0; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); int num = Random().Next(5); if (num == 0) { totalDocsWithZero++; } doc.Add(NewTextField("field", "" + num, Field.Store.YES)); writer.AddDocument(doc); } IndexReader reader = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(reader); Query query = new FilteredQuery(new TermQuery(new Term("field", "0")), new FilterAnonymousInnerClassHelper3(this, reader), FilteredQuery.QUERY_FIRST_FILTER_STRATEGY); TopDocs search = searcher.Search(query, 10); Assert.AreEqual(totalDocsWithZero, search.TotalHits); IOUtils.Close(reader, writer, directory); } private class FilterAnonymousInnerClassHelper3 : Filter { private readonly TestFilteredQuery OuterInstance; private IndexReader Reader; public FilterAnonymousInnerClassHelper3(TestFilteredQuery outerInstance, IndexReader reader) { this.OuterInstance = outerInstance; this.Reader = reader; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs) { bool nullBitset = Random().Next(10) == 5; AtomicReader reader = context.AtomicReader; DocsEnum termDocsEnum = reader.TermDocsEnum(new Term("field", "0")); if (termDocsEnum == null) { return null; // no docs -- return null } BitArray bitSet = new BitArray(reader.MaxDoc); int d; while ((d = termDocsEnum.NextDoc()) != DocsEnum.NO_MORE_DOCS) { bitSet.SafeSet(d, true); } return new DocIdSetAnonymousInnerClassHelper(this, nullBitset, reader, bitSet); } private class DocIdSetAnonymousInnerClassHelper : DocIdSet { private readonly FilterAnonymousInnerClassHelper3 OuterInstance; private bool NullBitset; private AtomicReader Reader; private BitArray BitSet; public DocIdSetAnonymousInnerClassHelper(FilterAnonymousInnerClassHelper3 outerInstance, bool nullBitset, AtomicReader reader, BitArray bitSet) { this.OuterInstance = outerInstance; this.NullBitset = nullBitset; this.Reader = reader; this.BitSet = bitSet; } public override Bits GetBits() { if (NullBitset) { return null; } return new BitsAnonymousInnerClassHelper(this); } private class BitsAnonymousInnerClassHelper : Bits { private readonly DocIdSetAnonymousInnerClassHelper OuterInstance; public BitsAnonymousInnerClassHelper(DocIdSetAnonymousInnerClassHelper outerInstance) { this.OuterInstance = outerInstance; } public bool Get(int index) { Assert.IsTrue(OuterInstance.BitSet.SafeGet(index), "filter was called for a non-matching doc"); return OuterInstance.BitSet.SafeGet(index); } public int Length() { return OuterInstance.BitSet.Length; } } public override DocIdSetIterator GetIterator() { Assert.IsTrue(NullBitset, "iterator should not be called if bitset is present"); return Reader.TermDocsEnum(new Term("field", "0")); } } } /* * Test if the leapfrog strategy works correctly in terms * of advancing / next the right thing first */ [Test] public virtual void TestLeapFrogStrategy() { Directory directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); int numDocs = AtLeast(50); int totalDocsWithZero = 0; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); int num = Random().Next(10); if (num == 0) { totalDocsWithZero++; } doc.Add(NewTextField("field", "" + num, Field.Store.YES)); writer.AddDocument(doc); } IndexReader reader = writer.Reader; writer.Dispose(); bool queryFirst = Random().NextBoolean(); IndexSearcher searcher = NewSearcher(reader); Query query = new FilteredQuery(new TermQuery(new Term("field", "0")), new FilterAnonymousInnerClassHelper4(this, queryFirst), queryFirst ? FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY : Random() .NextBoolean() ? FilteredQuery.RANDOM_ACCESS_FILTER_STRATEGY : FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY); // if filterFirst, we can use random here since bits are null TopDocs search = searcher.Search(query, 10); Assert.AreEqual(totalDocsWithZero, search.TotalHits); IOUtils.Close(reader, writer, directory); } private class FilterAnonymousInnerClassHelper4 : Filter { private readonly TestFilteredQuery OuterInstance; private bool QueryFirst; public FilterAnonymousInnerClassHelper4(TestFilteredQuery outerInstance, bool queryFirst) { this.OuterInstance = outerInstance; this.QueryFirst = queryFirst; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs) { return new DocIdSetAnonymousInnerClassHelper2(this, context); } private class DocIdSetAnonymousInnerClassHelper2 : DocIdSet { private readonly FilterAnonymousInnerClassHelper4 OuterInstance; private AtomicReaderContext Context; public DocIdSetAnonymousInnerClassHelper2(FilterAnonymousInnerClassHelper4 outerInstance, AtomicReaderContext context) { this.OuterInstance = outerInstance; this.Context = context; } public override Bits GetBits() { return null; } public override DocIdSetIterator GetIterator() { DocsEnum termDocsEnum = ((AtomicReader)Context.Reader).TermDocsEnum(new Term("field", "0")); if (termDocsEnum == null) { return null; } return new DocIdSetIteratorAnonymousInnerClassHelper(this, termDocsEnum); } private class DocIdSetIteratorAnonymousInnerClassHelper : DocIdSetIterator { private readonly DocIdSetAnonymousInnerClassHelper2 OuterInstance; private DocsEnum TermDocsEnum; public DocIdSetIteratorAnonymousInnerClassHelper(DocIdSetAnonymousInnerClassHelper2 outerInstance, DocsEnum termDocsEnum) { this.OuterInstance = outerInstance; this.TermDocsEnum = termDocsEnum; } internal bool nextCalled; internal bool advanceCalled; public override int NextDoc() { Assert.IsTrue(nextCalled || advanceCalled ^ !OuterInstance.OuterInstance.QueryFirst, "queryFirst: " + OuterInstance.OuterInstance.QueryFirst + " advanced: " + advanceCalled + " next: " + nextCalled); nextCalled = true; return TermDocsEnum.NextDoc(); } public override int DocID() { return TermDocsEnum.DocID(); } public override int Advance(int target) { Assert.IsTrue(advanceCalled || nextCalled ^ OuterInstance.OuterInstance.QueryFirst, "queryFirst: " + OuterInstance.OuterInstance.QueryFirst + " advanced: " + advanceCalled + " next: " + nextCalled); advanceCalled = true; return TermDocsEnum.Advance(target); } public override long Cost() { return TermDocsEnum.Cost(); } } } } } }
//----------------------------------------------------------------------- // <copyright file="MethodCaller.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Provides methods to dynamically find and call methods.</summary> //----------------------------------------------------------------------- using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using Csla.Properties; using Csla.Server; using Csla; using System.Globalization; using System.Threading.Tasks; namespace Csla.Reflection { /// <summary> /// Provides methods to dynamically find and call methods. /// </summary> public static class MethodCaller { private const BindingFlags allLevelFlags = BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ; private const BindingFlags oneLevelFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ; private const BindingFlags ctorFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ; private const BindingFlags factoryFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy; private const BindingFlags privateMethodFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy; #region Dynamic Method Cache private static Dictionary<MethodCacheKey, DynamicMethodHandle> _methodCache = new Dictionary<MethodCacheKey, DynamicMethodHandle>(); private static DynamicMethodHandle GetCachedMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters) { var key = new MethodCacheKey(obj.GetType().FullName, info.Name, GetParameterTypes(parameters)); DynamicMethodHandle mh = null; var found = false; try { found = _methodCache.TryGetValue(key, out mh); } catch { /* failure will drop into !found block */ } if (!found) { lock (_methodCache) { if (!_methodCache.TryGetValue(key, out mh)) { mh = new DynamicMethodHandle(info, parameters); _methodCache.Add(key, mh); } } } return mh; } private static DynamicMethodHandle GetCachedMethod(object obj, string method) { return GetCachedMethod(obj, method, false, null); } private static DynamicMethodHandle GetCachedMethod(object obj, string method, params object[] parameters) { return GetCachedMethod(obj, method, true, parameters); } private static DynamicMethodHandle GetCachedMethod(object obj, string method, bool hasParameters, params object[] parameters) { var key = new MethodCacheKey(obj.GetType().FullName, method, GetParameterTypes(hasParameters, parameters)); DynamicMethodHandle mh = null; if (!_methodCache.TryGetValue(key, out mh)) { lock (_methodCache) { if (!_methodCache.TryGetValue(key, out mh)) { var info = GetMethod(obj.GetType(), method, hasParameters, parameters); mh = new DynamicMethodHandle(info, parameters); _methodCache.Add(key, mh); } } } return mh; } #endregion #region Dynamic Constructor Cache private static Dictionary<Type, DynamicCtorDelegate> _ctorCache = new Dictionary<Type, DynamicCtorDelegate>(); private static DynamicCtorDelegate GetCachedConstructor(Type objectType) { if (objectType == null) throw new ArgumentNullException(nameof(objectType)); DynamicCtorDelegate result = null; var found = false; try { found = _ctorCache.TryGetValue(objectType, out result); } catch { /* failure will drop into !found block */ } if (!found) { lock (_ctorCache) { if (!_ctorCache.TryGetValue(objectType, out result)) { #if NETFX_CORE ConstructorInfo info = objectType.GetConstructor(ctorFlags, null, new Type[] { }, null); #else ConstructorInfo info = objectType.GetConstructor(ctorFlags, null, Type.EmptyTypes, null); #endif if (info == null) throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, "Cannot create instance of Type '{0}'. No public parameterless constructor found.", objectType)); result = DynamicMethodHandlerFactory.CreateConstructor(info); _ctorCache.Add(objectType, result); } } } return result; } #endregion #region GetType /// <summary> /// Gets a Type object based on the type name. /// </summary> /// <param name="typeName">Type name including assembly name.</param> /// <param name="throwOnError">true to throw an exception if the type can't be found.</param> /// <param name="ignoreCase">true for a case-insensitive comparison of the type name.</param> public static Type GetType(string typeName, bool throwOnError, bool ignoreCase) { string fullTypeName; #if NETFX_CORE if (typeName.Contains("Version=")) fullTypeName = typeName; else fullTypeName = typeName + ", Version=..., Culture=neutral, PublicKeyToken=null"; #else fullTypeName = typeName; #endif #if NETFX_CORE if (throwOnError) return Type.GetType(fullTypeName); else try { return Type.GetType(fullTypeName); } catch { return null; } #else return Type.GetType(fullTypeName, throwOnError, ignoreCase); #endif } /// <summary> /// Gets a Type object based on the type name. /// </summary> /// <param name="typeName">Type name including assembly name.</param> /// <param name="throwOnError">true to throw an exception if the type can't be found.</param> public static Type GetType(string typeName, bool throwOnError) { return GetType(typeName, throwOnError, false); } /// <summary> /// Gets a Type object based on the type name. /// </summary> /// <param name="typeName">Type name including assembly name.</param> public static Type GetType(string typeName) { return GetType(typeName, true, false); } #endregion #region Create Instance /// <summary> /// Uses reflection to create an object using its /// default constructor. /// </summary> /// <param name="objectType">Type of object to create.</param> public static object CreateInstance(Type objectType) { var ctor = GetCachedConstructor(objectType); if (ctor == null) throw new NotImplementedException(objectType.Name + " " + Resources.DefaultConstructor + Resources.MethodNotImplemented); return ctor.Invoke(); } /// <summary> /// Creates an instance of a generic type /// using its default constructor. /// </summary> /// <param name="type">Generic type to create</param> /// <param name="paramTypes">Type parameters</param> /// <returns></returns> public static object CreateGenericInstance(Type type, params Type[] paramTypes) { var genericType = type.GetGenericTypeDefinition(); var gt = genericType.MakeGenericType(paramTypes); return Activator.CreateInstance(gt); } #endregion private const BindingFlags propertyFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; private const BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; private static readonly Dictionary<MethodCacheKey, DynamicMemberHandle> _memberCache = new Dictionary<MethodCacheKey, DynamicMemberHandle>(); internal static DynamicMemberHandle GetCachedProperty(Type objectType, string propertyName) { var key = new MethodCacheKey(objectType.FullName, propertyName, GetParameterTypes(null)); DynamicMemberHandle mh = null; if (!_memberCache.TryGetValue(key, out mh)) { lock (_memberCache) { if (!_memberCache.TryGetValue(key, out mh)) { PropertyInfo info = objectType.GetProperty(propertyName, propertyFlags); if (info == null) throw new InvalidOperationException( string.Format(Resources.MemberNotFoundException, propertyName)); mh = new DynamicMemberHandle(info); _memberCache.Add(key, mh); } } } return mh; } internal static DynamicMemberHandle GetCachedField(Type objectType, string fieldName) { var key = new MethodCacheKey(objectType.FullName, fieldName, GetParameterTypes(null)); DynamicMemberHandle mh = null; if (!_memberCache.TryGetValue(key, out mh)) { lock (_memberCache) { if (!_memberCache.TryGetValue(key, out mh)) { FieldInfo info = objectType.GetField(fieldName, fieldFlags); if (info == null) throw new InvalidOperationException( string.Format(Resources.MemberNotFoundException, fieldName)); mh = new DynamicMemberHandle(info); _memberCache.Add(key, mh); } } } return mh; } /// <summary> /// Invokes a property getter using dynamic /// method invocation. /// </summary> /// <param name="obj">Target object.</param> /// <param name="property">Property to invoke.</param> /// <returns></returns> public static object CallPropertyGetter(object obj, string property) { if (ApplicationContext.UseReflectionFallback) { #if NET40 throw new NotSupportedException("CallPropertyGetter + UseReflectionFallback"); #else var propertyInfo = obj.GetType().GetProperty(property); return propertyInfo.GetValue(obj); #endif } else { if (obj == null) throw new ArgumentNullException("obj"); if (string.IsNullOrEmpty(property)) throw new ArgumentException("Argument is null or empty.", "property"); var mh = GetCachedProperty(obj.GetType(), property); if (mh.DynamicMemberGet == null) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, "The property '{0}' on Type '{1}' does not have a public getter.", property, obj.GetType())); } return mh.DynamicMemberGet(obj); } } /// <summary> /// Invokes a property setter using dynamic /// method invocation. /// </summary> /// <param name="obj">Target object.</param> /// <param name="property">Property to invoke.</param> /// <param name="value">New value for property.</param> public static void CallPropertySetter(object obj, string property, object value) { if (obj == null) throw new ArgumentNullException("obj"); if (string.IsNullOrEmpty(property)) throw new ArgumentException("Argument is null or empty.", "property"); if (ApplicationContext.UseReflectionFallback) { #if NET40 throw new NotSupportedException("CallPropertySetter + UseReflectionFallback"); #else var propertyInfo = obj.GetType().GetProperty(property); propertyInfo.SetValue(obj, value); #endif } else { var mh = GetCachedProperty(obj.GetType(), property); if (mh.DynamicMemberSet == null) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, "The property '{0}' on Type '{1}' does not have a public setter.", property, obj.GetType())); } mh.DynamicMemberSet(obj, value); } } #region Call Method /// <summary> /// Uses reflection to dynamically invoke a method /// if that method is implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> public static object CallMethodIfImplemented(object obj, string method) { return CallMethodIfImplemented(obj, method, false, null); } /// <summary> /// Uses reflection to dynamically invoke a method /// if that method is implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static object CallMethodIfImplemented(object obj, string method, params object[] parameters) { return CallMethodIfImplemented(obj, method, true, parameters); } private static object CallMethodIfImplemented(object obj, string method, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { var found = (FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)) != null); if (found) return CallMethod(obj, method, parameters); else return null; } else { var mh = GetCachedMethod(obj, method, parameters); if (mh == null || mh.DynamicMethod == null) return null; return CallMethod(obj, mh, hasParameters, parameters); } } /// <summary> /// Detects if a method matching the name and parameters is implemented on the provided object. /// </summary> /// <param name="obj">The object implementing the method.</param> /// <param name="method">The name of the method to find.</param> /// <param name="parameters">The parameters matching the parameters types of the method to match.</param> /// <returns>True obj implements a matching method.</returns> public static bool IsMethodImplemented(object obj, string method, params object[] parameters) { var mh = GetCachedMethod(obj, method, parameters); return mh != null && mh.DynamicMethod != null; } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> public static object CallMethod(object obj, string method) { return CallMethod(obj, method, false, null); } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static object CallMethod(object obj, string method, params object[] parameters) { return CallMethod(obj, method, true, parameters); } private static object CallMethod(object obj, string method, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { System.Reflection.MethodInfo info = GetMethod(obj.GetType(), method, hasParameters, parameters); if (info == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); return CallMethod(obj, info, hasParameters, parameters); } else { var mh = GetCachedMethod(obj, method, hasParameters, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); return CallMethod(obj, mh, hasParameters, parameters); } } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="info"> /// System.Reflection.MethodInfo for the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static object CallMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters) { return CallMethod(obj, info, true, parameters); } private static object CallMethod(object obj, System.Reflection.MethodInfo info, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { #if PCL46 || PCL259 throw new NotSupportedException("CallMethod + UseReflectionFallback"); #else var infoParams = info.GetParameters(); var infoParamsCount = infoParams.Length; bool hasParamArray = infoParamsCount > 0 && infoParams[infoParamsCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0; bool specialParamArray = false; if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(string[]))) specialParamArray = true; if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(object[]))) specialParamArray = true; object[] par = null; if (infoParamsCount == 1 && specialParamArray) { par = new object[] { parameters }; } else if (infoParamsCount > 1 && hasParamArray && specialParamArray) { par = new object[infoParamsCount]; for (int i = 0; i < infoParamsCount - 1; i++) par[i] = parameters[i]; par[infoParamsCount - 1] = parameters[infoParamsCount - 1]; } else { par = parameters; } object result = null; try { result = info.Invoke(obj, par); } catch (Exception e) { Exception inner = null; if (e.InnerException == null) inner = e; else inner = e.InnerException; throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner); } return result; #endif } else { var mh = GetCachedMethod(obj, info, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodNotImplemented); return CallMethod(obj, mh, hasParameters, parameters); } } private static object CallMethod(object obj, DynamicMethodHandle methodHandle, bool hasParameters, params object[] parameters) { object result = null; var method = methodHandle.DynamicMethod; object[] inParams = null; if (parameters == null) inParams = new object[] { null }; else inParams = parameters; if (methodHandle.HasFinalArrayParam) { // last param is a param array or only param is an array var pCount = methodHandle.MethodParamsLength; var inCount = inParams.Length; if (inCount == pCount - 1) { // no paramter was supplied for the param array // copy items into new array with last entry null object[] paramList = new object[pCount]; for (var pos = 0; pos <= pCount - 2; pos++) paramList[pos] = parameters[pos]; paramList[paramList.Length - 1] = hasParameters && inParams.Length == 0 ? inParams : null; // use new array inParams = paramList; } else if ((inCount == pCount && inParams[inCount - 1] != null && !inParams[inCount - 1].GetType().IsArray) || inCount > pCount) { // 1 or more params go in the param array // copy extras into an array var extras = inParams.Length - (pCount - 1); object[] extraArray = GetExtrasArray(extras, methodHandle.FinalArrayElementType); Array.Copy(inParams, pCount - 1, extraArray, 0, extras); // copy items into new array object[] paramList = new object[pCount]; for (var pos = 0; pos <= pCount - 2; pos++) paramList[pos] = parameters[pos]; paramList[paramList.Length - 1] = extraArray; // use new array inParams = paramList; } } try { result = methodHandle.DynamicMethod(obj, inParams); } catch (Exception ex) { throw new CallMethodException(obj.GetType().Name + "." + methodHandle.MethodName + " " + Resources.MethodCallFailed, ex); } return result; } private static object[] GetExtrasArray(int count, Type arrayType) { return (object[])(System.Array.CreateInstance(arrayType.GetElementType(), count)); } #endregion #region Get/Find Method /// <summary> /// Uses reflection to locate a matching method /// on the target object. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> public static System.Reflection.MethodInfo GetMethod(Type objectType, string method) { return GetMethod(objectType, method, true, false, null); } /// <summary> /// Uses reflection to locate a matching method /// on the target object. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static System.Reflection.MethodInfo GetMethod(Type objectType, string method, params object[] parameters) { return GetMethod(objectType, method, true, parameters); } private static System.Reflection.MethodInfo GetMethod(Type objectType, string method, bool hasParameters, params object[] parameters) { System.Reflection.MethodInfo result = null; object[] inParams = null; if (!hasParameters) inParams = new object[] { }; else if (parameters == null) inParams = new object[] { null }; else inParams = parameters; // try to find a strongly typed match // first see if there's a matching method // where all params match types result = FindMethod(objectType, method, GetParameterTypes(hasParameters, inParams)); if (result == null) { // no match found - so look for any method // with the right number of parameters try { result = FindMethod(objectType, method, inParams.Length); } catch (AmbiguousMatchException) { // we have multiple methods matching by name and parameter count result = FindMethodUsingFuzzyMatching(objectType, method, inParams); } } // no strongly typed match found, get default based on name only if (result == null) { result = objectType.GetMethod(method, allLevelFlags); } return result; } private static System.Reflection.MethodInfo FindMethodUsingFuzzyMatching(Type objectType, string method, object[] parameters) { System.Reflection.MethodInfo result = null; Type currentType = objectType; do { System.Reflection.MethodInfo[] methods = currentType.GetMethods(oneLevelFlags); int parameterCount = parameters.Length; // Match based on name and parameter types and parameter arrays foreach (System.Reflection.MethodInfo m in methods) { if (m.Name == method) { var infoParams = m.GetParameters(); var pCount = infoParams.Length; if (pCount > 0) { if (pCount == 1 && infoParams[0].ParameterType.IsArray) { // only param is an array if (parameters.GetType().Equals(infoParams[0].ParameterType)) { // got a match so use it result = m; break; } } #if NETFX_CORE if (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0) #else if (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0) #endif { // last param is a param array if (parameterCount == pCount && parameters[pCount - 1].GetType().Equals(infoParams[pCount - 1].ParameterType)) { // got a match so use it result = m; break; } } } } } if (result == null) { // match based on parameter name and number of parameters foreach (System.Reflection.MethodInfo m in methods) { if (m.Name == method && m.GetParameters().Length == parameterCount) { result = m; break; } } } if (result != null) break; #if NETFX_CORE currentType = currentType.BaseType(); #else currentType = currentType.BaseType; #endif } while (currentType != null); return result; } /// <summary> /// Returns information about the specified /// method, even if the parameter types are /// generic and are located in an abstract /// generic base class. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="types"> /// Parameter types to pass to method. /// </param> public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, Type[] types) { System.Reflection.MethodInfo info = null; do { // find for a strongly typed match info = objectType.GetMethod(method, oneLevelFlags, null, types, null); if (info != null) { break; // match found } #if NETFX_CORE objectType = objectType.BaseType(); #else objectType = objectType.BaseType; #endif } while (objectType != null); return info; } /// <summary> /// Returns information about the specified /// method, finding the method based purely /// on the method name and number of parameters. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameterCount"> /// Number of parameters to pass to method. /// </param> public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, int parameterCount) { // walk up the inheritance hierarchy looking // for a method with the right number of // parameters System.Reflection.MethodInfo result = null; Type currentType = objectType; do { System.Reflection.MethodInfo info = currentType.GetMethod(method, oneLevelFlags); if (info != null) { var infoParams = info.GetParameters(); var pCount = infoParams.Length; if (pCount > 0 && ((pCount == 1 && infoParams[0].ParameterType.IsArray) || #if NETFX_CORE (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0))) #else (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0))) #endif { // last param is a param array or only param is an array if (parameterCount >= pCount - 1) { // got a match so use it result = info; break; } } else if (pCount == parameterCount) { // got a match so use it result = info; break; } } #if NETFX_CORE currentType = currentType.BaseType(); #else currentType = currentType.BaseType; #endif } while (currentType != null); return result; } #endregion /// <summary> /// Returns an array of Type objects corresponding /// to the type of parameters provided. /// </summary> public static Type[] GetParameterTypes() { return GetParameterTypes(false, null); } /// <summary> /// Returns an array of Type objects corresponding /// to the type of parameters provided. /// </summary> /// <param name="parameters"> /// Parameter values. /// </param> public static Type[] GetParameterTypes(object[] parameters) { return GetParameterTypes(true, parameters); } private static Type[] GetParameterTypes(bool hasParameters, object[] parameters) { if (!hasParameters) return new Type[] { }; List<Type> result = new List<Type>(); if (parameters == null) { result.Add(typeof(object)); } else { foreach (object item in parameters) { if (item == null) { result.Add(typeof(object)); } else { result.Add(item.GetType()); } } } return result.ToArray(); } #if !NETFX_CORE /// <summary> /// Gets a property type descriptor by name. /// </summary> /// <param name="t">Type of object containing the property.</param> /// <param name="propertyName">Name of the property.</param> public static PropertyDescriptor GetPropertyDescriptor(Type t, string propertyName) { var propertyDescriptors = TypeDescriptor.GetProperties(t); PropertyDescriptor result = null; foreach (PropertyDescriptor desc in propertyDescriptors) if (desc.Name == propertyName) { result = desc; break; } return result; } #endif /// <summary> /// Gets information about a property. /// </summary> /// <param name="objectType">Object containing the property.</param> /// <param name="propertyName">Name of the property.</param> public static PropertyInfo GetProperty(Type objectType, string propertyName) { return objectType.GetProperty(propertyName, propertyFlags); } /// <summary> /// Gets a property value. /// </summary> /// <param name="obj">Object containing the property.</param> /// <param name="info">Property info object for the property.</param> /// <returns>The value of the property.</returns> public static object GetPropertyValue(object obj, PropertyInfo info) { object result = null; try { result = info.GetValue(obj, null); } catch (Exception e) { Exception inner = null; if (e.InnerException == null) inner = e; else inner = e.InnerException; throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner); } return result; } /// <summary> /// Invokes an instance method on an object. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="info">Method info object.</param> /// <returns>Any value returned from the method.</returns> public static object CallMethod(object obj, System.Reflection.MethodInfo info) { object result = null; try { result = info.Invoke(obj, null); } catch (Exception e) { Exception inner = null; if (e.InnerException == null) inner = e; else inner = e.InnerException; throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner); } return result; } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method, params object[] parameters) { return await CallMethodTryAsync(obj, method, true, parameters); } /// <summary> /// Invokes an instance method on an object. If the method /// is async returning Task of object it will be invoked using an await statement. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="method"> /// Name of the method. /// </param> public async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method) { return await CallMethodTryAsync(obj, method, false, null); } private async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method, bool hasParameters, params object[] parameters) { try { if (ApplicationContext.UseReflectionFallback) { #if PCL46 || PCL259 throw new NotSupportedException("CallMethod + UseReflectionFallback"); #else var info = FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)); if (info == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); var isAsyncTask = (info.ReturnType == typeof(System.Threading.Tasks.Task)); var isAsyncTaskObject = (info.ReturnType.IsGenericType && (info.ReturnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>))); if (isAsyncTask) { await (System.Threading.Tasks.Task)CallMethod(obj, method, hasParameters, parameters); return null; } else if (isAsyncTaskObject) { return await (System.Threading.Tasks.Task<object>)CallMethod(obj, method, hasParameters, parameters); } else { return CallMethod(obj, method, hasParameters, parameters); } #endif } else { var mh = GetCachedMethod(obj, method, hasParameters, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); if (mh.IsAsyncTask) { await (System.Threading.Tasks.Task)CallMethod(obj, mh, hasParameters, parameters); return null; } else if (mh.IsAsyncTaskObject) { return await (System.Threading.Tasks.Task<object>)CallMethod(obj, mh, hasParameters, parameters); } else { return CallMethod(obj, mh, hasParameters, parameters); } } } catch (InvalidCastException ex) { throw new NotSupportedException( string.Format(Resources.TaskOfObjectException, obj.GetType().Name + "." + method), ex); } } /// <summary> /// Returns true if the method provided is an async method returning a Task object. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="method">Name of the method.</param> public static bool IsAsyncMethod(object obj, string method) { return IsAsyncMethod(obj, method, false, null); } /// <summary> /// Returns true if the method provided is an async method returning a Task object. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="method">Name of the method.</param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static bool IsAsyncMethod(object obj, string method, params object[] parameters) { return IsAsyncMethod(obj, method, true, parameters); } private static bool IsAsyncMethod(object obj, string method, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { #if PCL46 || PCL259 throw new NotSupportedException("CallMethod + UseReflectionFallback"); #else var info = FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)); if (info == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); var isAsyncTask = (info.ReturnType == typeof(System.Threading.Tasks.Task)); var isAsyncTaskObject = (info.ReturnType.IsGenericType && (info.ReturnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>))); return isAsyncTask || isAsyncTaskObject; #endif } else { var mh = GetCachedMethod(obj, method, hasParameters, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); return mh.IsAsyncTask || mh.IsAsyncTaskObject; } } #if !NETFX_CORE /// <summary> /// Invokes a generic async static method by name /// </summary> /// <param name="objectType">Class containing static method</param> /// <param name="method">Method to invoke</param> /// <param name="typeParams">Type parameters for method</param> /// <param name="hasParameters">Flag indicating whether method accepts parameters</param> /// <param name="parameters">Parameters for method</param> /// <returns></returns> public static Task<object> CallGenericStaticMethodAsync(Type objectType, string method, Type[] typeParams, bool hasParameters, params object[] parameters) { var tcs = new TaskCompletionSource<object>(); try { Task task = null; if (hasParameters) { var pTypes = GetParameterTypes(parameters); var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, pTypes, null); if (methodReference == null) methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public); if (methodReference == null) throw new InvalidOperationException(objectType.Name + "." + method); var gr = methodReference.MakeGenericMethod(typeParams); task = (Task)gr.Invoke(null, parameters); } else { var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, System.Type.EmptyTypes, null); var gr = methodReference.MakeGenericMethod(typeParams); task = (Task)gr.Invoke(null, null); } task.Wait(); if (task.Exception != null) tcs.SetException(task.Exception); else tcs.SetResult(Csla.Reflection.MethodCaller.CallPropertyGetter(task, "Result")); } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; } #endif /// <summary> /// Invokes a generic method by name /// </summary> /// <param name="target">Object containing method to invoke</param> /// <param name="method">Method to invoke</param> /// <param name="typeParams">Type parameters for method</param> /// <param name="hasParameters">Flag indicating whether method accepts parameters</param> /// <param name="parameters">Parameters for method</param> /// <returns></returns> public static object CallGenericMethod(object target, string method, Type[] typeParams, bool hasParameters, params object[] parameters) { var objectType = target.GetType(); object result = null; if (hasParameters) { var pTypes = GetParameterTypes(parameters); #if NETFX_CORE var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, pTypes, null); #else var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.Any, pTypes, null); #endif if (methodReference == null) methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public); if (methodReference == null) throw new InvalidOperationException(objectType.Name + "." + method); var gr = methodReference.MakeGenericMethod(typeParams); result = gr.Invoke(target, parameters); } else { #if PCL46 || PCL259 var emptyTypes = new Type[] { }; var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, emptyTypes, null); #elif NETFX_CORE var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, System.Type.EmptyTypes, null); #else var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, System.Type.EmptyTypes, null); #endif if (methodReference == null) throw new InvalidOperationException(objectType.Name + "." + method); var gr = methodReference.MakeGenericMethod(typeParams); result = gr.Invoke(target, null); } return result; } /// <summary> /// Invokes a static factory method. /// </summary> /// <param name="objectType">Business class where the factory is defined.</param> /// <param name="method">Name of the factory method</param> /// <param name="parameters">Parameters passed to factory method.</param> /// <returns>Result of the factory method invocation.</returns> public static object CallFactoryMethod(Type objectType, string method, params object[] parameters) { object returnValue; System.Reflection.MethodInfo factory = objectType.GetMethod( method, factoryFlags, null, MethodCaller.GetParameterTypes(parameters), null); if (factory == null) { // strongly typed factory couldn't be found // so find one with the correct number of // parameters int parameterCount = parameters.Length; System.Reflection.MethodInfo[] methods = objectType.GetMethods(factoryFlags); foreach (System.Reflection.MethodInfo oneMethod in methods) if (oneMethod.Name == method && oneMethod.GetParameters().Length == parameterCount) { factory = oneMethod; break; } } if (factory == null) { // no matching factory could be found // so throw exception throw new InvalidOperationException( string.Format(Resources.NoSuchFactoryMethod, method)); } try { returnValue = factory.Invoke(null, parameters); } catch (Exception ex) { Exception inner = null; if (ex.InnerException == null) inner = ex; else inner = ex.InnerException; throw new CallMethodException(objectType.Name + "." + factory.Name + " " + Resources.MethodCallFailed, inner); } return returnValue; } /// <summary> /// Gets a System.Reflection.MethodInfo object corresponding to a /// non-public method. /// </summary> /// <param name="objectType">Object containing the method.</param> /// <param name="method">Name of the method.</param> public static System.Reflection.MethodInfo GetNonPublicMethod(Type objectType, string method) { System.Reflection.MethodInfo result = null; result = FindMethod(objectType, method, privateMethodFlags); return result; } #if !NETFX_CORE /// <summary> /// Returns information about the specified /// method. /// </summary> /// <param name="objType">Type of object.</param> /// <param name="method">Name of the method.</param> /// <param name="flags">Flag values.</param> public static System.Reflection.MethodInfo FindMethod(Type objType, string method, BindingFlags flags) { System.Reflection.MethodInfo info = null; do { // find for a strongly typed match info = objType.GetMethod(method, flags); if (info != null) break; // match found objType = objType.BaseType; } while (objType != null); return info; } #else /// <summary> /// Returns information about the specified /// method. /// </summary> /// <param name="objType">Type of object.</param> /// <param name="method">Name of the method.</param> /// <param name="flags">Flag values.</param> public static System.Reflection.MethodInfo FindMethod(Type objType, string method, BindingFlags flags) { var info = objType.GetMethod(method); return info; } #endif } }
#nullable disable using System; namespace WWT.Imaging { // Summary: // Describes a custom vertex format structure that contains position and one // set of texture coordinates. // Summary: // Describes and manipulates a vector in three-dimensional (3-D) space. [Serializable] public struct Vector3d { // Summary: // Retrieves or sets the x component of a 3-D vector. public double X; // // Summary: // Retrieves or sets the y component of a 3-D vector. public double Y; // // Summary: // Retrieves or sets the z component of a 3-D vector. public double Z; // // Summary: // Initializes a new instance of the Microsoft.DirectX.Vector3d class. // // Parameters: // valueX: // Initial Microsoft.DirectX.Vector3d.X value. // // valueY: // Initial Microsoft.DirectX.Vector3d.Y value. // // valueZ: // Initial Microsoft.DirectX.Vector3d.Z value. public Vector3d(double valueX, double valueY, double valueZ) { X = valueX; Y = valueY; Z = valueZ; } public Vector3d(Vector3d value) { X = value.X; Y = value.Y; Z = value.Z; } // Summary: // Negates the vector. // // Parameters: // vec: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // The Microsoft.DirectX.Vector3d structure that is the result of the operation. public static Vector3d operator -(Vector3d vec) { Vector3d result; result.X = -vec.X; result.Y = -vec.Y; result.Z = -vec.Z; return result; } // // Summary: // Subtracts two 3-D vectors. // // Parameters: // left: // The Microsoft.DirectX.Vector3d structure to the left of the subtraction operator. // // right: // The Microsoft.DirectX.Vector3d structure to the right of the subtraction operator. // // Returns: // Resulting Microsoft.DirectX.Vector3d structure. public static Vector3d operator -(Vector3d left, Vector3d right) { return new Vector3d(left.X - right.X, left.Y - right.Y, left.Z - left.Z); } // // Summary: // Compares the current instance of a class to another instance to determine // whether they are different. // // Parameters: // left: // The Microsoft.DirectX.Vector3d structure to the left of the inequality operator. // // right: // The Microsoft.DirectX.Vector3d structure to the right of the inequality operator. // // Returns: // Value that is true if the objects are different, or false if they are the // same. public static bool operator !=(Vector3d left, Vector3d right) { return (left.X != right.X || left.Y != right.Y || left.Z != right.Z); } // // Summary: // Determines the product of a single value and a 3-D vector. // // Parameters: // right: // Source System.Single structure. // // left: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the product of the Microsoft.DirectX.Vector3d.op_Multiply() // and Microsoft.DirectX.Vector3d.op_Multiply() parameters. //public static Vector3d operator *(double right, Vector3d left); // // Summary: // Determines the product of a single value and a 3-D vector. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure. // // right: // Source System.Single structure. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the product of the Microsoft.DirectX.Vector3d.op_Multiply() // and Microsoft.DirectX.Vector3d.op_Multiply() parameters. //public static Vector3d operator *(Vector3d left, double right); // // Summary: // Adds two vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure. // // right: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A Microsoft.DirectX.Vector3d structure that contains the sum of the parameters. //public static Vector3d operator +(Vector3d left, Vector3d right); // // Summary: // Compares the current instance of a class to another instance to determine // whether they are the same. // // Parameters: // left: // The Microsoft.DirectX.Vector3d structure to the left of the equality operator. // // right: // The Microsoft.DirectX.Vector3d structure to the right of the equality operator. // // Returns: // Value that is true if the objects are the same, or false if they are different. public static bool operator ==(Vector3d left, Vector3d right) { return (left.X == right.X || left.Y == right.Y || left.Z == right.Z); } public static Vector3d MidPoint(Vector3d left, Vector3d right) { Vector3d result = new Vector3d((left.X + right.X) / 2, (left.Y + right.Y) / 2, (left.Z + right.Z) / 2); result.Normalize(); return result; } // Summary: // Retrieves an empty 3-D vector. public static Vector3d Empty { get { return new Vector3d(0, 0, 0); } } // Summary: // Adds two 3-D vectors. // // Parameters: // source: public void Add(Vector3d source) { X += source.X; Y += source.Y; Z += source.Z; } // // Summary: // Adds two 3-D vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d. // // right: // Source Microsoft.DirectX.Vector3d. // // Returns: // Sum of the two Microsoft.DirectX.Vector3d structures. public static Vector3d Add(Vector3d left, Vector3d right) { return new Vector3d(left.X + right.X, left.Y + right.Y, left.Z + right.Z); } // // Summary: // Returns a point in barycentric coordinates, using specified 3-D vectors. // // Parameters: // v1: // Source Microsoft.DirectX.Vector3d structure. // // v2: // Source Microsoft.DirectX.Vector3d structure. // // v3: // Source Microsoft.DirectX.Vector3d structure. // // f: // Weighting factor. See Remarks. // // g: // Weighting factor. See Remarks. // // Returns: // A Microsoft.DirectX.Vector3d structure in barycentric coordinates. //public static Vector3d BaryCentric(Vector3d v1, Vector3d v2, Vector3d v3, double f, double g); // // Summary: // Performs a Catmull-Rom interpolation using specified 3-D vectors. // // Parameters: // position1: // Source Microsoft.DirectX.Vector3d structure that is a position vector. // // position2: // Source Microsoft.DirectX.Vector3d structure that is a position vector. // // position3: // Source Microsoft.DirectX.Vector3d structure that is a position vector. // // position4: // Source Microsoft.DirectX.Vector3d structure that is a position vector. // // weightingFactor: // Weighting factor. See Remarks. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the result of the Catmull-Rom // interpolation. //public static Vector3d CatmullRom(Vector3d position1, Vector3d position2, Vector3d position3, Vector3d position4, double weightingFactor) //{ //} // // Summary: // Determines the cross product of two 3-D vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure. // // right: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the cross product of two 3-D // vectors. public static Vector3d Cross(Vector3d left, Vector3d right) { return new Vector3d( left.Y * right.Z - left.Z * right.Y, left.Z * right.X - left.X * right.Z, left.X * right.Y - left.Y * right.X); } // // Summary: // Determines the dot product of two 3-D vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure. // // right: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A System.Single value that is the dot product. public static double Dot(Vector3d left, Vector3d right) { return left.X * right.X + left.Y * right.Y + left.Z * right.Z; } // // Summary: // Returns a value that indicates whether the current instance is equal to a // specified object. // // Parameters: // compare: // Object with which to make the comparison. // // Returns: // Value that is true if the current instance is equal to the specified object, // or false if it is not. public override bool Equals(object compare) { Vector3d comp = (Vector3d)compare; return this.X == comp.X && this.Y == comp.Y && this.Z == comp.Z; } // // Summary: // Returns the hash code for the current instance. // // Returns: // Hash code for the instance. public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); } // // Summary: // Performs a Hermite spline interpolation using the specified 3-D vectors. // // Parameters: // position: // Source Microsoft.DirectX.Vector3d structure that is a position vector. // // tangent: // Source Microsoft.DirectX.Vector3d structure that is a tangent vector. // // position2: // Source Microsoft.DirectX.Vector3d structure that is a position vector. // // tangent2: // Source Microsoft.DirectX.Vector3d structure that is a tangent vector. // // weightingFactor: // Weighting factor. See Remarks. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the result of the Hermite spline // interpolation. //public static Vector3d Hermite(Vector3d position, Vector3d tangent, Vector3d position2, Vector3d tangent2, double weightingFactor); // // Summary: // Returns the length of a 3-D vector. // // Returns: // A System.Single value that contains the vector's length. public double Length() { return System.Math.Sqrt(X * X + Y * Y + Z * Z); } // // Summary: // Returns the length of a 3-D vector. // // Parameters: // source: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A System.Single value that contains the vector's length. public static double Length(Vector3d source) { return System.Math.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z); } // // Summary: // Returns the square of the length of a 3-D vector. // // Returns: // A System.Single value that contains the vector's squared length. public double LengthSq() { return X * X + Y * Y + Z * Z; } // // Summary: // Returns the square of the length of a 3-D vector. // // Parameters: // source: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A System.Single value that contains the vector's squared length. public static double LengthSq(Vector3d source) { return source.X * source.X + source.Y * source.Y + source.Z * source.Z; } // // Summary: // Performs a linear interpolation between two 3-D vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure. // // right: // Source Microsoft.DirectX.Vector3d structure. // // interpolater: // Parameter that linearly interpolates between the vectors. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the result of the linear interpolation. public static Vector3d Lerp(Vector3d left, Vector3d right, double interpolater) { return new Vector3d( left.X * (1.0 - interpolater) + right.X * interpolater, left.Y * (1.0 - interpolater) + right.Y * interpolater, left.Z * (1.0 - interpolater) + right.Z * interpolater); } // // Summary: // Returns a 3-D vector that is made up of the largest components of two 3-D // vectors. // // Parameters: // source: // Source Microsoft.DirectX.Vector3d structure. //public void Maximize(Vector3d source); // // Summary: // Returns a 3-D vector that is made up of the largest components of two 3-D // vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure. // // right: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A Microsoft.DirectX.Vector3d structure that is made up of the largest components // of the two vectors. //public static Vector3d Maximize(Vector3d left, Vector3d right); // // Summary: // Returns a 3-D vector that is made up of the smallest components of two 3-D // vectors. // // Parameters: // source: // Source Microsoft.DirectX.Vector3d structure. //public void Minimize(Vector3d source); // // Summary: // Returns a 3-D vector that is made up of the smallest components of two 3-D // vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure. // // right: // Source Microsoft.DirectX.Vector3d structure. // // Returns: // A Microsoft.DirectX.Vector3d structure that is made up of the smallest components // of the two vectors. //public static Vector3d Minimize(Vector3d left, Vector3d right); // // Summary: // Multiplies a 3-D vector by a System.Single value. // // Parameters: // s: // Source System.Single value used as a multiplier. public void Multiply(double s) { X *= s; Y *= s; Z *= s; } // // Summary: // Multiplies a 3-D vector by a System.Single value. // // Parameters: // source: // Source Microsoft.DirectX.Vector3d structure. // // f: // Source System.Single value used as a multiplier. // // Returns: // A Microsoft.DirectX.Vector3d structure that is multiplied by the System.Single // value. public static Vector3d Multiply(Vector3d source, double f) { Vector3d result = new Vector3d(source); result.Multiply(f); return result; } // // Summary: // Returns the normalized version of a 3-D vector. public void Normalize() { // Vector3.Length property is under length section double length = this.Length(); if (length != 0) { X /= length; Y /= length; Z /= length; } } // // Summary: // Scales a 3-D vector. // // Parameters: // source: // Source Microsoft.DirectX.Vector3d structure. // // scalingFactor: // Scaling value. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the scaled vector. public static Vector3d Scale(Vector3d source, double scalingFactor) { Vector3d result = source; result.Multiply(scalingFactor); return result; } // // Summary: // Subtracts two 3-D vectors. // // Parameters: // source: // Source Microsoft.DirectX.Vector3d structure to subtract from the current instance. public void Subtract(Vector3d source) { this.X -= source.X; this.Y -= source.Y; this.Z -= source.Z; } // // Summary: // Subtracts two 3-D vectors. // // Parameters: // left: // Source Microsoft.DirectX.Vector3d structure to the left of the subtraction // operator. // // right: // Source Microsoft.DirectX.Vector3d structure to the right of the subtraction // operator. // // Returns: // A Microsoft.DirectX.Vector3d structure that is the result of the operation. public static Vector3d Subtract(Vector3d left, Vector3d right) { Vector3d result = left; result.Subtract(right); return result; } // // Summary: // Obtains a string representation of the current instance. // // Returns: // String that represents the object. public override string ToString() { return String.Format("{0}, {1}, {2}", X, Y, Z); } public Vector2d ToSpherical() { double ascention; double declination; double radius = Math.Sqrt(X * X + Y * Y + Z * Z); double XZ = Math.Sqrt(X * X + Z * Z); declination = Math.Asin(Y / radius); if (XZ == 0) { ascention = 0; } else if (0 <= X) { ascention = Math.Asin(Z / XZ); } else { ascention = Math.PI - Math.Asin(Z / XZ); } //if (vector.Z < 0) //{ // ascention = ascention - Math.PI; //} // 0 -1.0 return new Vector2d((((ascention + Math.PI) / (2.0 * Math.PI)) % 1.0f), ((declination + (Math.PI / 2.0)) / (Math.PI))); return new Vector2d((((ascention + Math.PI) % (2.0 * Math.PI))), ((declination + (Math.PI / 2.0)))); } public Vector2d ToRaDec(bool edge) { Vector2d point = ToSpherical(); point.X = point.X / Math.PI * 180; if (edge && point.X == 0) { point.X = 360; } point.Y = (point.Y / Math.PI * 180) - 90; return point; } public Vector2d ToRaDec() { Vector2d vectord = ToSpherical(); vectord.X = vectord.X / Math.PI * 180.0; vectord.Y = vectord.Y / Math.PI * 180.0 - 90.0; return vectord; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; namespace System.Management.Automation.ComInterop { /// <summary> /// If a managed user type (as opposed to a primitive type or a COM object) is passed as an argument to a COM call, we need /// to determine the VarEnum type we will marshal it as. We have the following options: /// 1.Raise an exception. Languages with their own version of primitive types would not be able to call /// COM methods using the language's types (for eg. strings in IronRuby are not System.String). An explicit /// cast would be needed. /// 2.We could marshal it as VT_DISPATCH. Then COM code will be able to access all the APIs in a late-bound manner, /// but old COM components will probably malfunction if they expect a primitive type. /// 3.We could guess which primitive type is the closest match. This will make COM components be as easily /// accessible as .NET methods. /// 4.We could use the type library to check what the expected type is. However, the type library may not be available. /// /// VarEnumSelector implements option # 3. /// </summary> internal class VarEnumSelector { private static readonly Dictionary<VarEnum, Type> s_comToManagedPrimitiveTypes = CreateComToManagedPrimitiveTypes(); private static readonly IList<IList<VarEnum>> s_comPrimitiveTypeFamilies = CreateComPrimitiveTypeFamilies(); internal VarEnumSelector(Type[] explicitArgTypes) { VariantBuilders = new VariantBuilder[explicitArgTypes.Length]; for (int i = 0; i < explicitArgTypes.Length; i++) { VariantBuilders[i] = GetVariantBuilder(explicitArgTypes[i]); } } internal VariantBuilder[] VariantBuilders { get; } internal static Type GetTypeForVarEnum(VarEnum vt) { Type type; switch (vt) { // VarEnums which can be used in VARIANTs, but which cannot occur in a TYPEDESC case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: case VarEnum.VT_RECORD: type = typeof(void); break; // VarEnums which are not used in VARIANTs, but which can occur in a TYPEDESC case VarEnum.VT_VOID: type = typeof(void); break; case VarEnum.VT_HRESULT: type = typeof(int); break; case ((VarEnum)37): // VT_INT_PTR: type = typeof(IntPtr); break; case ((VarEnum)38): // VT_UINT_PTR: type = typeof(UIntPtr); break; case VarEnum.VT_SAFEARRAY: case VarEnum.VT_CARRAY: type = typeof(Array); break; case VarEnum.VT_LPSTR: case VarEnum.VT_LPWSTR: type = typeof(string); break; case VarEnum.VT_PTR: case VarEnum.VT_USERDEFINED: type = typeof(object); break; // For VarEnums that can be used in VARIANTs and well as TYPEDESCs, just use VarEnumSelector default: type = VarEnumSelector.GetManagedMarshalType(vt); break; } return type; } /// <summary> /// Gets the managed type that an object needs to be coverted to in order for it to be able /// to be represented as a Variant. /// /// In general, there is a many-to-many mapping between Type and VarEnum. However, this method /// returns a simple mapping that is needed for the current implementation. The reason for the /// many-to-many relation is: /// 1. Int32 maps to VT_I4 as well as VT_ERROR, and Decimal maps to VT_DECIMAL and VT_CY. However, /// this changes if you throw the wrapper types into the mix. /// 2. There is no Type to represent COM types. __ComObject is a private type, and Object is too /// general. /// </summary> internal static Type GetManagedMarshalType(VarEnum varEnum) { Debug.Assert((varEnum & VarEnum.VT_BYREF) == 0); if (varEnum == VarEnum.VT_CY) { return typeof(CurrencyWrapper); } if (Variant.IsPrimitiveType(varEnum)) { return s_comToManagedPrimitiveTypes[varEnum]; } switch (varEnum) { case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: case VarEnum.VT_UNKNOWN: case VarEnum.VT_DISPATCH: case VarEnum.VT_VARIANT: return typeof(Object); case VarEnum.VT_ERROR: return typeof(ErrorWrapper); default: throw Error.UnexpectedVarEnum(varEnum); } } private static Dictionary<VarEnum, Type> CreateComToManagedPrimitiveTypes() { Dictionary<VarEnum, Type> dict = new Dictionary<VarEnum, Type>(); #region Generated Outer ComToManagedPrimitiveTypes // *** BEGIN GENERATED CODE *** // generated by function: gen_ComToManagedPrimitiveTypes from: generate_comdispatch.py dict[VarEnum.VT_I1] = typeof(SByte); dict[VarEnum.VT_I2] = typeof(Int16); dict[VarEnum.VT_I4] = typeof(Int32); dict[VarEnum.VT_I8] = typeof(Int64); dict[VarEnum.VT_UI1] = typeof(Byte); dict[VarEnum.VT_UI2] = typeof(UInt16); dict[VarEnum.VT_UI4] = typeof(UInt32); dict[VarEnum.VT_UI8] = typeof(UInt64); dict[VarEnum.VT_INT] = typeof(Int32); dict[VarEnum.VT_UINT] = typeof(UInt32); dict[VarEnum.VT_PTR] = typeof(IntPtr); dict[VarEnum.VT_BOOL] = typeof(Boolean); dict[VarEnum.VT_R4] = typeof(Single); dict[VarEnum.VT_R8] = typeof(Double); dict[VarEnum.VT_DECIMAL] = typeof(Decimal); dict[VarEnum.VT_DATE] = typeof(DateTime); dict[VarEnum.VT_BSTR] = typeof(String); dict[VarEnum.VT_CLSID] = typeof(Guid); // *** END GENERATED CODE *** #endregion dict[VarEnum.VT_CY] = typeof(CurrencyWrapper); dict[VarEnum.VT_ERROR] = typeof(ErrorWrapper); return dict; } #region Primitive COM types /// <summary> /// Creates a family of COM types such that within each family, there is a completely non-lossy /// conversion from a type to an earlier type in the family. /// </summary> private static IList<IList<VarEnum>> CreateComPrimitiveTypeFamilies() { VarEnum[][] typeFamilies = new VarEnum[][] { new VarEnum[] { VarEnum.VT_I8, VarEnum.VT_I4, VarEnum.VT_I2, VarEnum.VT_I1 }, new VarEnum[] { VarEnum.VT_UI8, VarEnum.VT_UI4, VarEnum.VT_UI2, VarEnum.VT_UI1 }, new VarEnum[] { VarEnum.VT_INT }, new VarEnum[] { VarEnum.VT_UINT }, new VarEnum[] { VarEnum.VT_BOOL }, new VarEnum[] { VarEnum.VT_DATE }, new VarEnum[] { VarEnum.VT_R8, VarEnum.VT_R4 }, new VarEnum[] { VarEnum.VT_DECIMAL }, new VarEnum[] { VarEnum.VT_BSTR }, // wrappers new VarEnum[] { VarEnum.VT_CY }, new VarEnum[] { VarEnum.VT_ERROR }, }; return typeFamilies; } /// <summary> /// Get the (one representative type for each) primitive type families that the argument can be converted to. /// </summary> private static List<VarEnum> GetConversionsToComPrimitiveTypeFamilies(Type argumentType) { List<VarEnum> compatibleComTypes = new List<VarEnum>(); foreach (IList<VarEnum> typeFamily in s_comPrimitiveTypeFamilies) { foreach (VarEnum candidateType in typeFamily) { Type candidateManagedType = s_comToManagedPrimitiveTypes[candidateType]; if (TypeUtils.IsImplicitlyConvertible(argumentType, candidateManagedType, true)) { compatibleComTypes.Add(candidateType); // Move on to the next type family. We need atmost one type from each family break; } } } return compatibleComTypes; } /// <summary> /// If there is more than one type family that the argument can be converted to, we will throw a /// AmbiguousMatchException instead of randomly picking a winner. /// </summary> private static void CheckForAmbiguousMatch(Type argumentType, List<VarEnum> compatibleComTypes) { if (compatibleComTypes.Count <= 1) { return; } string typeNames = string.Empty; for (int i = 0; i < compatibleComTypes.Count; i++) { string typeName = s_comToManagedPrimitiveTypes[compatibleComTypes[i]].Name; if (i == (compatibleComTypes.Count - 1)) { typeNames += " and "; } else if (i != 0) { typeNames += ", "; } typeNames += typeName; } throw Error.AmbiguousConversion(argumentType.Name, typeNames); } private static bool TryGetPrimitiveComType(Type argumentType, out VarEnum primitiveVarEnum) { #region Generated Outer Managed To COM Primitive Type Map // *** BEGIN GENERATED CODE *** // generated by function: gen_ManagedToComPrimitiveTypes from: generate_comdispatch.py switch (Type.GetTypeCode(argumentType)) { case TypeCode.Boolean: primitiveVarEnum = VarEnum.VT_BOOL; return true; case TypeCode.Char: primitiveVarEnum = VarEnum.VT_UI2; return true; case TypeCode.SByte: primitiveVarEnum = VarEnum.VT_I1; return true; case TypeCode.Byte: primitiveVarEnum = VarEnum.VT_UI1; return true; case TypeCode.Int16: primitiveVarEnum = VarEnum.VT_I2; return true; case TypeCode.UInt16: primitiveVarEnum = VarEnum.VT_UI2; return true; case TypeCode.Int32: primitiveVarEnum = VarEnum.VT_I4; return true; case TypeCode.UInt32: primitiveVarEnum = VarEnum.VT_UI4; return true; case TypeCode.Int64: primitiveVarEnum = VarEnum.VT_I8; return true; case TypeCode.UInt64: primitiveVarEnum = VarEnum.VT_UI8; return true; case TypeCode.Single: primitiveVarEnum = VarEnum.VT_R4; return true; case TypeCode.Double: primitiveVarEnum = VarEnum.VT_R8; return true; case TypeCode.Decimal: primitiveVarEnum = VarEnum.VT_DECIMAL; return true; case TypeCode.DateTime: primitiveVarEnum = VarEnum.VT_DATE; return true; case TypeCode.String: primitiveVarEnum = VarEnum.VT_BSTR; return true; } if (argumentType == typeof(CurrencyWrapper)) { primitiveVarEnum = VarEnum.VT_CY; return true; } if (argumentType == typeof(ErrorWrapper)) { primitiveVarEnum = VarEnum.VT_ERROR; return true; } if (argumentType == typeof(IntPtr)) { primitiveVarEnum = VarEnum.VT_PTR; return true; } if (argumentType == typeof(UIntPtr)) { primitiveVarEnum = VarEnum.VT_PTR; return true; } // *** END GENERATED CODE *** #endregion primitiveVarEnum = VarEnum.VT_VOID; // error return false; } /// <summary> /// Is there a unique primitive type that has the best conversion for the argument. /// </summary> private static bool TryGetPrimitiveComTypeViaConversion(Type argumentType, out VarEnum primitiveVarEnum) { // Look for a unique type family that the argument can be converted to. List<VarEnum> compatibleComTypes = GetConversionsToComPrimitiveTypeFamilies(argumentType); CheckForAmbiguousMatch(argumentType, compatibleComTypes); if (compatibleComTypes.Count == 1) { primitiveVarEnum = compatibleComTypes[0]; return true; } primitiveVarEnum = VarEnum.VT_VOID; // error return false; } #endregion // Type.InvokeMember tries to marshal objects as VT_DISPATCH, and falls back to VT_UNKNOWN // VT_RECORD here just indicates that we have user defined type. // We will try VT_DISPATCH and then call GetNativeVariantForObject. private const VarEnum VT_DEFAULT = VarEnum.VT_RECORD; private VarEnum GetComType(ref Type argumentType) { if (argumentType == typeof(Missing)) { // actual variant type will be VT_ERROR | E_PARAMNOTFOUND return VarEnum.VT_RECORD; } if (argumentType.IsArray) { // actual variant type will be VT_ARRAY | VT_<ELEMENT_TYPE> return VarEnum.VT_ARRAY; } if (argumentType == typeof(UnknownWrapper)) { return VarEnum.VT_UNKNOWN; } else if (argumentType == typeof(DispatchWrapper)) { return VarEnum.VT_DISPATCH; } else if (argumentType == typeof(VariantWrapper)) { return VarEnum.VT_VARIANT; } else if (argumentType == typeof(BStrWrapper)) { return VarEnum.VT_BSTR; } else if (argumentType == typeof(ErrorWrapper)) { return VarEnum.VT_ERROR; } else if (argumentType == typeof(CurrencyWrapper)) { return VarEnum.VT_CY; } // Many languages require an explicit cast for an enum to be used as the underlying type. // However, we want to allow this conversion for COM without requiring an explicit cast // so that enums from interop assemblies can be used as arguments. if (argumentType.IsEnum) { argumentType = Enum.GetUnderlyingType(argumentType); return GetComType(ref argumentType); } // COM cannot express valuetype nulls so we will convert to underlying type // it will throw if there is no value if (TypeUtils.IsNullableType(argumentType)) { argumentType = TypeUtils.GetNonNullableType(argumentType); return GetComType(ref argumentType); } // generic types cannot be exposed to COM so they do not implement COM interfaces. if (argumentType.IsGenericType) { return VarEnum.VT_UNKNOWN; } VarEnum primitiveVarEnum; if (TryGetPrimitiveComType(argumentType, out primitiveVarEnum)) { return primitiveVarEnum; } // We could not find a way to marshal the type as a specific COM type return VT_DEFAULT; } /// <summary> /// Get the COM Variant type that argument should be marshaled as for a call to COM. /// </summary> private VariantBuilder GetVariantBuilder(Type argumentType) { // argumentType is coming from MarshalType, null means the dynamic object holds // a null value and not byref if (argumentType == null) { return new VariantBuilder(VarEnum.VT_EMPTY, new NullArgBuilder()); } if (argumentType == typeof(DBNull)) { return new VariantBuilder(VarEnum.VT_NULL, new NullArgBuilder()); } ArgBuilder argBuilder; if (argumentType.IsByRef) { Type elementType = argumentType.GetElementType(); VarEnum elementVarEnum; if (elementType == typeof(object) || elementType == typeof(DBNull)) { // no meaningful value to pass ByRef. // perhaps the calee will replace it with something. // need to pass as a variant reference elementVarEnum = VarEnum.VT_VARIANT; } else { elementVarEnum = GetComType(ref elementType); } argBuilder = GetSimpleArgBuilder(elementType, elementVarEnum); return new VariantBuilder(elementVarEnum | VarEnum.VT_BYREF, argBuilder); } VarEnum varEnum = GetComType(ref argumentType); argBuilder = GetByValArgBuilder(argumentType, ref varEnum); return new VariantBuilder(varEnum, argBuilder); } // This helper is called when we are looking for a ByVal marshalling // In a ByVal case we can take into account conversions or IConvertible if all other // attempts to find marshalling type failed private static ArgBuilder GetByValArgBuilder(Type elementType, ref VarEnum elementVarEnum) { // if VT indicates that marshalling type is unknown if (elementVarEnum == VT_DEFAULT) { // trying to find a conversion. VarEnum convertibleTo; if (TryGetPrimitiveComTypeViaConversion(elementType, out convertibleTo)) { elementVarEnum = convertibleTo; Type marshalType = GetManagedMarshalType(elementVarEnum); return new ConversionArgBuilder(elementType, GetSimpleArgBuilder(marshalType, elementVarEnum)); } // checking for IConvertible. if (typeof(IConvertible).IsAssignableFrom(elementType)) { return new ConvertibleArgBuilder(); } } return GetSimpleArgBuilder(elementType, elementVarEnum); } // This helper can produce a builder for types that are directly supported by Variant. private static SimpleArgBuilder GetSimpleArgBuilder(Type elementType, VarEnum elementVarEnum) { SimpleArgBuilder argBuilder; switch (elementVarEnum) { case VarEnum.VT_BSTR: argBuilder = new StringArgBuilder(elementType); break; case VarEnum.VT_BOOL: argBuilder = new BoolArgBuilder(elementType); break; case VarEnum.VT_DATE: argBuilder = new DateTimeArgBuilder(elementType); break; case VarEnum.VT_CY: argBuilder = new CurrencyArgBuilder(elementType); break; case VarEnum.VT_DISPATCH: argBuilder = new DispatchArgBuilder(elementType); break; case VarEnum.VT_UNKNOWN: argBuilder = new UnknownArgBuilder(elementType); break; case VarEnum.VT_VARIANT: case VarEnum.VT_ARRAY: case VarEnum.VT_RECORD: argBuilder = new VariantArgBuilder(elementType); break; case VarEnum.VT_ERROR: argBuilder = new ErrorArgBuilder(elementType); break; default: var marshalType = GetManagedMarshalType(elementVarEnum); if (elementType == marshalType) { argBuilder = new SimpleArgBuilder(elementType); } else { argBuilder = new ConvertArgBuilder(elementType, marshalType); } break; } return argBuilder; } } } #endif
using System; using System.Collections; using System.Data.SqlClient; using System.Web; using System.Web.UI.WebControls; using Rainbow.Framework; using Rainbow.Framework.Content.Data; using Rainbow.Framework.Web.UI; using ImageButton=Rainbow.Framework.Web.UI.WebControls.ImageButton; namespace Rainbow.Content.Web.Modules { [History("jminond", "2005/3/12", "Changes for moving Tab to Page")] [History("Mario Endara", "2004/6/1", "Added EsperantusKeys for Localization")] public partial class BlogView : ViewItemPage { protected Localize OnLabel; protected Localize CreatedLabel; protected HyperLink deleteLink; protected ImageButton btnDelete; public bool IsDeleteable = false; /// <summary> /// Author: Joe Audette /// Created: 1/18/2004 /// Last Modified: 2/8/2004 /// /// The Page_Load server event handler on this page is used /// to obtain the Blogs list, and to then display /// the message contents. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack && ModuleID > 0 && ItemID > 0) { if (Context.User.Identity.IsAuthenticated) { char[] separator = {';'}; string[] deleteRoles = Module.AuthorizedDeleteRoles.Split(separator); foreach (string role in deleteRoles) { if (role.Length > 0) { if (Context.User.IsInRole(role)) { IsDeleteable = true; } } } } lnkRSS.HRef = HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Blog/RSS.aspx", PageID, "&mID=" + ModuleID); imgRSS.Src = HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Blog/xml.gif"); lblCopyright.Text = moduleSettings["Copyright"].ToString(); BindData(); } } /// <summary> /// Set the module guids with free access to this page /// </summary> protected override ArrayList AllowedModules { get { ArrayList al = new ArrayList(); al.Add("55EF407B-C9D6-47e3-B627-EFA6A5EEF4B2"); return al; } } protected void btnDelete_Click(object sender, EventArgs e) { // Redirect back to the blog page RedirectBackToReferringPage(); } protected void dlComments_ItemCommand(object source, DataListCommandEventArgs e) { if (e.CommandName == "DeleteComment") { BlogDB blogDB = new BlogDB(); blogDB.DeleteBlogComment(int.Parse(e.CommandArgument.ToString())); Response.Clear(); Response.Redirect(Request.Url.ToString()); } } protected void btnPostComment_Click(object sender, EventArgs e) { if (IsValidComment()) { if (chkRememberMe.Checked) { SetCookies(); } BlogDB blogDB = new BlogDB(); blogDB.AddBlogComment(ModuleID, ItemID, txtName.Text, txtTitle.Text, txtURL.Text, txtComments.Text); Response.Redirect(Request.Url.ToString()); } } private bool IsValidComment() { bool result = true; //TODO do we need validation? return result; } private void SetCookies() { HttpCookie blogUserCookie = new HttpCookie("blogUser", txtName.Text); HttpCookie blogUrlCookie = new HttpCookie("blogUrl", txtURL.Text); blogUserCookie.Expires = DateTime.Now.AddMonths(1); blogUrlCookie.Expires = DateTime.Now.AddMonths(1); Response.Cookies.Add(blogUserCookie); Response.Cookies.Add(blogUrlCookie); } /// <summary> /// The BindData method is used to obtain details of a message /// from the Blogs table, and update the page with /// the message content. /// </summary> private void BindData() { // Obtain the selected item from the Blogs table BlogDB blogDB = new BlogDB(); SqlDataReader dataReader = blogDB.GetSingleBlog(ItemID); try { // Load first row from database if (dataReader.Read()) { // Update labels with message contents Title.Text = (string) dataReader["Title"].ToString(); txtTitle.Text = "re: " + (string) dataReader["Title"].ToString(); StartDate.Text = ((DateTime) dataReader["StartDate"]).ToString("dddd MMMM d yyyy hh:mm tt"); Description.Text = Server.HtmlDecode((string) dataReader["Description"].ToString()); } } finally { dataReader.Close(); } dlComments.DataSource = blogDB.GetBlogComments(ModuleID, ItemID); dlComments.DataBind(); if (Request.Params.Get("blogUser") != null) { txtName.Text = Request.Params.Get("blogUser"); } if (Request.Params.Get("blogUrl") != null) { txtURL.Text = Request.Params.Get("blogUrl"); } dlArchive.DataSource = blogDB.GetBlogMonthArchive(ModuleID); dlArchive.DataBind(); dataReader = blogDB.GetBlogStats(ModuleID); try { if (dataReader.Read()) { lblEntryCount.Text = General.GetString("BLOG_ENTRIES", "Entries", null) + " (" + (string) dataReader["EntryCount"].ToString() + ")"; lblCommentCount.Text = General.GetString("BLOG_COMMENTS", "Comments", null) + " (" + (string) dataReader["CommentCount"].ToString() + ")"; } } finally { dataReader.Close(); } } #region Web Form Designer generated code /// <summary> /// Raises OnInitEvent /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { InitializeComponent(); // - jminond // View item pages in general have no need for viewstate // Especailly big texts. this.Page.EnableViewState = false; 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.dlComments.ItemCommand += new DataListCommandEventHandler(this.dlComments_ItemCommand); this.btnPostComment.Click += new EventHandler(this.btnPostComment_Click); this.Load += new EventHandler(this.Page_Load); if (!this.IsCssFileRegistered("Mod_Blogs")) this.RegisterCssFile("Mod_Blogs"); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using restlicsharpdata.restlidata; // DO NOT EDIT - THIS FILE IS GENERATED BY restli-csharp // Generated from com\linkedin\restli\common\ErrorResponse.pdsc namespace com.linkedin.restli.common { /// <summary> /// A generic ErrorResponse /// </summary> public class ErrorResponse : RecordTemplate { // The HTTP status code public int status { get; } public bool hasStatus { get; } // An service-specific error code (documented in prose) public int serviceErrorCode { get; } public bool hasServiceErrorCode { get; } // A human-readable explanation of the error public string message { get; } public bool hasMessage { get; } // The FQCN of the exception thrown by the server (included the case of a server fault) public string exceptionClass { get; } public bool hasExceptionClass { get; } // The full (??) stack trace (included the case of a server fault) public string stackTrace { get; } public bool hasStackTrace { get; } public ErrorDetails errorDetails { get; } public bool hasErrorDetails { get; } public ErrorResponse(Dictionary<string, object> data) { object value; // Retrieve data for status if (data.TryGetValue("status", out value)) { status = Convert.ToInt32(value); hasStatus = true; } else { hasStatus = false; } // Retrieve data for serviceErrorCode if (data.TryGetValue("serviceErrorCode", out value)) { serviceErrorCode = Convert.ToInt32(value); hasServiceErrorCode = true; } else { hasServiceErrorCode = false; } // Retrieve data for message if (data.TryGetValue("message", out value)) { message = (string)value; hasMessage = true; } else { hasMessage = false; } // Retrieve data for exceptionClass if (data.TryGetValue("exceptionClass", out value)) { exceptionClass = (string)value; hasExceptionClass = true; } else { hasExceptionClass = false; } // Retrieve data for stackTrace if (data.TryGetValue("stackTrace", out value)) { stackTrace = (string)value; hasStackTrace = true; } else { hasStackTrace = false; } // Retrieve data for errorDetails if (data.TryGetValue("errorDetails", out value)) { errorDetails = new ErrorDetails((Dictionary<string, object>)value); hasErrorDetails = true; } else { hasErrorDetails = false; } } public ErrorResponse(ErrorResponseBuilder builder) { // Retrieve data for status if (builder.status != null) { status = (int)builder.status; hasStatus = true; } else { hasStatus = false; } // Retrieve data for serviceErrorCode if (builder.serviceErrorCode != null) { serviceErrorCode = (int)builder.serviceErrorCode; hasServiceErrorCode = true; } else { hasServiceErrorCode = false; } // Retrieve data for message if (builder.message != null) { message = builder.message; hasMessage = true; } else { hasMessage = false; } // Retrieve data for exceptionClass if (builder.exceptionClass != null) { exceptionClass = builder.exceptionClass; hasExceptionClass = true; } else { hasExceptionClass = false; } // Retrieve data for stackTrace if (builder.stackTrace != null) { stackTrace = builder.stackTrace; hasStackTrace = true; } else { hasStackTrace = false; } // Retrieve data for errorDetails if (builder.errorDetails != null) { errorDetails = builder.errorDetails; hasErrorDetails = true; } else { hasErrorDetails = false; } } public override Dictionary<string, object> Data() { Dictionary<string, object> dataMap = new Dictionary<string, object>(); if (hasStatus) dataMap.Add("status", status); if (hasServiceErrorCode) dataMap.Add("serviceErrorCode", serviceErrorCode); if (hasMessage) dataMap.Add("message", message); if (hasExceptionClass) dataMap.Add("exceptionClass", exceptionClass); if (hasStackTrace) dataMap.Add("stackTrace", stackTrace); if (hasErrorDetails) dataMap.Add("errorDetails", errorDetails.Data()); return dataMap; } } public class ErrorResponseBuilder { public int? status { get; set; } public int? serviceErrorCode { get; set; } public string message { get; set; } public string exceptionClass { get; set; } public string stackTrace { get; set; } public ErrorDetails errorDetails { get; set; } public ErrorResponse Build() { return new ErrorResponse(this); } } }
// // X509CertificateDatabase.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Data; using System.Collections; using System.Collections.Generic; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Security; using Org.BouncyCastle.Asn1.BC; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.X509.Store; namespace MimeKit.Cryptography { /// <summary> /// An X.509 certificate database. /// </summary> /// <remarks> /// An X.509 certificate database is used for storing certificates, metdata related to the certificates /// (such as encryption algorithms supported by the associated client), certificate revocation lists (CRLs), /// and private keys. /// </remarks> public abstract class X509CertificateDatabase : IX509CertificateDatabase { const X509CertificateRecordFields PrivateKeyFields = X509CertificateRecordFields.Certificate | X509CertificateRecordFields.PrivateKey; static readonly DerObjectIdentifier DefaultEncryptionAlgorithm = BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc; const int DefaultMinIterations = 1024; const int DefaultSaltSize = 20; readonly char[] passwd; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.X509CertificateDatabase"/> class. /// </summary> /// <remarks> /// The password is used to encrypt and decrypt private keys in the database and cannot be null. /// </remarks> /// <param name="password">The password used for encrypting and decrypting the private keys.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="password"/> is <c>null</c>. /// </exception> protected X509CertificateDatabase (string password) { if (password == null) throw new ArgumentNullException ("password"); EncryptionAlgorithm = DefaultEncryptionAlgorithm; MinIterations = DefaultMinIterations; SaltSize = DefaultSaltSize; passwd = password.ToCharArray (); } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="MimeKit.Cryptography.X509CertificateDatabase"/> is reclaimed by garbage collection. /// </summary> /// <remarks> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="MimeKit.Cryptography.X509CertificateDatabase"/> is reclaimed by garbage collection. /// </remarks> ~X509CertificateDatabase () { Dispose (false); } /// <summary> /// Gets or sets the algorithm used for encrypting the private keys. /// </summary> /// <remarks> /// <para>The encryption algorithm should be one of the PBE (password-based encryption) algorithms /// supported by Bouncy Castle.</para> /// <para>The default algorithm is SHA-256 + AES256.</para> /// </remarks> /// <value>The encryption algorithm.</value> protected DerObjectIdentifier EncryptionAlgorithm { get; set; } /// <summary> /// Gets or sets the minimum iterations. /// </summary> /// <remarks> /// The default minimum number of iterations is <c>1024</c>. /// </remarks> /// <value>The minimum iterations.</value> protected int MinIterations { get; set; } /// <summary> /// Gets or sets the size of the salt. /// </summary> /// <remarks> /// The default salt size is <c>20</c>. /// </remarks> /// <value>The size of the salt.</value> protected int SaltSize { get; set; } static int ReadBinaryBlob (IDataRecord reader, int column, ref byte[] buffer) { long nread; // first, get the length of the buffer needed if ((nread = reader.GetBytes (column, 0, null, 0, buffer.Length)) > buffer.Length) Array.Resize (ref buffer, (int) nread); // read the certificate data return (int) reader.GetBytes (column, 0, buffer, 0, (int) nread); } static X509Certificate DecodeCertificate (IDataRecord reader, X509CertificateParser parser, int column, ref byte[] buffer) { int nread = ReadBinaryBlob (reader, column, ref buffer); using (var memory = new MemoryStream (buffer, 0, nread, false)) { return parser.ReadCertificate (memory); } } static X509Crl DecodeX509Crl (IDataRecord reader, X509CrlParser parser, int column, ref byte[] buffer) { int nread = ReadBinaryBlob (reader, column, ref buffer); using (var memory = new MemoryStream (buffer, 0, nread, false)) { return parser.ReadCrl (memory); } } byte[] EncryptAsymmetricKeyParameter (AsymmetricKeyParameter key) { var cipher = PbeUtilities.CreateEngine (EncryptionAlgorithm.Id) as IBufferedCipher; var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo (key); var random = new SecureRandom (); var salt = new byte[SaltSize]; if (cipher == null) throw new Exception ("Unknown encryption algorithm: " + EncryptionAlgorithm.Id); random.NextBytes (salt); var pbeParameters = PbeUtilities.GenerateAlgorithmParameters (EncryptionAlgorithm.Id, salt, MinIterations); var algorithm = new AlgorithmIdentifier (EncryptionAlgorithm, pbeParameters); var cipherParameters = PbeUtilities.GenerateCipherParameters (algorithm, passwd); cipher.Init (true, cipherParameters); var encoded = cipher.DoFinal (keyInfo.GetEncoded ()); var encrypted = new EncryptedPrivateKeyInfo (algorithm, encoded); return encrypted.GetEncoded (); } AsymmetricKeyParameter DecryptAsymmetricKeyParameter (byte[] buffer, int length) { using (var memory = new MemoryStream (buffer, 0, length, false)) { using (var asn1 = new Asn1InputStream (memory)) { var sequence = asn1.ReadObject () as Asn1Sequence; if (sequence == null) return null; var encrypted = EncryptedPrivateKeyInfo.GetInstance (sequence); var algorithm = encrypted.EncryptionAlgorithm; var encoded = encrypted.GetEncryptedData (); var cipher = PbeUtilities.CreateEngine (algorithm) as IBufferedCipher; if (cipher == null) return null; var cipherParameters = PbeUtilities.GenerateCipherParameters (algorithm, passwd); cipher.Init (false, cipherParameters); var decrypted = cipher.DoFinal (encoded); var keyInfo = PrivateKeyInfo.GetInstance (decrypted); return PrivateKeyFactory.CreateKey (keyInfo); } } } AsymmetricKeyParameter DecodePrivateKey (IDataRecord reader, int column, ref byte[] buffer) { if (reader.IsDBNull (column)) return null; int nread = ReadBinaryBlob (reader, column, ref buffer); return DecryptAsymmetricKeyParameter (buffer, nread); } byte[] EncodePrivateKey (AsymmetricKeyParameter key) { return key != null ? EncryptAsymmetricKeyParameter (key) : null; } static EncryptionAlgorithm[] DecodeEncryptionAlgorithms (IDataRecord reader, int column) { if (reader.IsDBNull (column)) return null; var algorithms = new List<EncryptionAlgorithm> (); var values = reader.GetString (column); foreach (var token in values.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { EncryptionAlgorithm algorithm; #if NET_3_5 try { algorithm = (EncryptionAlgorithm) Enum.Parse (typeof (EncryptionAlgorithm), token.Trim (), true); algorithms.Add (algorithm); } catch (ArgumentException) { } catch (OverflowException) { } #else if (Enum.TryParse (token.Trim (), true, out algorithm)) algorithms.Add (algorithm); #endif } return algorithms.ToArray (); } static string EncodeEncryptionAlgorithms (EncryptionAlgorithm[] algorithms) { if (algorithms == null) return null; var tokens = new string[algorithms.Length]; for (int i = 0; i < algorithms.Length; i++) tokens[i] = algorithms[i].ToString (); return string.Join (",", tokens); } X509CertificateRecord LoadCertificateRecord (IDataRecord reader, X509CertificateParser parser, ref byte[] buffer) { var record = new X509CertificateRecord (); for (int i = 0; i < reader.FieldCount; i++) { switch (reader.GetName (i).ToUpperInvariant ()) { case "CERTIFICATE": record.Certificate = DecodeCertificate (reader, parser, i, ref buffer); break; case "PRIVATEKEY": record.PrivateKey = DecodePrivateKey (reader, i, ref buffer); break; case "ALGORITHMS": record.Algorithms = DecodeEncryptionAlgorithms (reader, i); break; case "ALGORITHMSUPDATED": record.AlgorithmsUpdated = reader.GetDateTime (i); break; case "TRUSTED": record.IsTrusted = reader.GetBoolean (i); break; case "ID": record.Id = reader.GetInt32 (i); break; } } return record; } X509CrlRecord LoadCrlRecord (IDataRecord reader, X509CrlParser parser, ref byte[] buffer) { var record = new X509CrlRecord (); for (int i = 0; i < reader.FieldCount; i++) { switch (reader.GetName (i).ToUpperInvariant ()) { case "CRL": record.Crl = DecodeX509Crl (reader, parser, i, ref buffer); break; case "THISUPDATE": record.ThisUpdate = reader.GetDateTime (i); break; case "NEXTUPDATE": record.NextUpdate = reader.GetDateTime (i); break; case "DELTA": record.IsDelta = reader.GetBoolean (i); break; case "ID": record.Id = reader.GetInt32 (i); break; } } return record; } /// <summary> /// Gets the column names for the specified fields. /// </summary> /// <remarks> /// Gets the column names for the specified fields. /// </remarks> /// <returns>The column names.</returns> /// <param name="fields">The fields.</param> protected static string[] GetColumnNames (X509CertificateRecordFields fields) { var columns = new List<string> (); if ((fields & X509CertificateRecordFields.Id) != 0) columns.Add ("ID"); if ((fields & X509CertificateRecordFields.Trusted) != 0) columns.Add ("TRUSTED"); if ((fields & X509CertificateRecordFields.Algorithms) != 0) columns.Add ("ALGORITHMS"); if ((fields & X509CertificateRecordFields.AlgorithmsUpdated) != 0) columns.Add ("ALGORITHMSUPDATED"); if ((fields & X509CertificateRecordFields.Certificate) != 0) columns.Add ("CERTIFICATE"); if ((fields & X509CertificateRecordFields.PrivateKey) != 0) columns.Add ("PRIVATEKEY"); return columns.ToArray (); } /// <summary> /// Gets the database command to select the record matching the specified certificate. /// </summary> /// <remarks> /// Gets the database command to select the record matching the specified certificate. /// </remarks> /// <returns>The database command.</returns> /// <param name="certificate">The certificate.</param> /// <param name="fields">The fields to return.</param> protected abstract IDbCommand GetSelectCommand (X509Certificate certificate, X509CertificateRecordFields fields); /// <summary> /// Gets the database command to select the certificate records for the specified mailbox. /// </summary> /// <remarks> /// Gets the database command to select the certificate records for the specified mailbox. /// </remarks> /// <returns>The database command.</returns> /// <param name="mailbox">The mailbox.</param> /// <param name="now">The date and time for which the certificate should be valid.</param> /// <param name="requirePrivateKey"><c>true</c> if the certificate must have a private key.</param> /// <param name="fields">The fields to return.</param> protected abstract IDbCommand GetSelectCommand (MailboxAddress mailbox, DateTime now, bool requirePrivateKey, X509CertificateRecordFields fields); /// <summary> /// Gets the database command to select certificate records matching the specified selector. /// </summary> /// <remarks> /// Gets the database command to select certificate records matching the specified selector. /// </remarks> /// <returns>The database command.</returns> /// <param name="selector">Selector.</param> /// <param name="trustedOnly"><c>true</c> if only trusted certificates should be matched.</param> /// <param name="requirePrivateKey"><c>true</c> if the certificate must have a private key.</param> /// <param name="fields">The fields to return.</param> protected abstract IDbCommand GetSelectCommand (IX509Selector selector, bool trustedOnly, bool requirePrivateKey, X509CertificateRecordFields fields); /// <summary> /// Gets the column names for the specified fields. /// </summary> /// <remarks> /// Gets the column names for the specified fields. /// </remarks> /// <returns>The column names.</returns> /// <param name="fields">The fields.</param> protected static string[] GetColumnNames (X509CrlRecordFields fields) { const X509CrlRecordFields all = X509CrlRecordFields.Id | X509CrlRecordFields.IsDelta | X509CrlRecordFields.IssuerName | X509CrlRecordFields.ThisUpdate | X509CrlRecordFields.NextUpdate | X509CrlRecordFields.Crl; if (fields == all) return new [] { "*" }; var columns = new List<string> (); if ((fields & X509CrlRecordFields.Id) != 0) columns.Add ("ID"); if ((fields & X509CrlRecordFields.IsDelta) != 0) columns.Add ("DELTA"); if ((fields & X509CrlRecordFields.IssuerName) != 0) columns.Add ("ISSUERNAME"); if ((fields & X509CrlRecordFields.ThisUpdate) != 0) columns.Add ("THISUPDATE"); if ((fields & X509CrlRecordFields.NextUpdate) != 0) columns.Add ("NEXTUPDATE"); if ((fields & X509CrlRecordFields.Crl) != 0) columns.Add ("CRL"); return columns.ToArray (); } /// <summary> /// Gets the database command to select the CRL records matching the specified issuer. /// </summary> /// <remarks> /// Gets the database command to select the CRL records matching the specified issuer. /// </remarks> /// <returns>The database command.</returns> /// <param name="issuer">The issuer.</param> /// <param name="fields">The fields to return.</param> protected abstract IDbCommand GetSelectCommand (X509Name issuer, X509CrlRecordFields fields); /// <summary> /// Gets the database command to select the record for the specified CRL. /// </summary> /// <remarks> /// Gets the database command to select the record for the specified CRL. /// </remarks> /// <returns>The database command.</returns> /// <param name="crl">The X.509 CRL.</param> /// <param name="fields">The fields to return.</param> protected abstract IDbCommand GetSelectCommand (X509Crl crl, X509CrlRecordFields fields); /// <summary> /// Gets the database command to select all CRLs in the table. /// </summary> /// <remarks> /// Gets the database command to select all CRLs in the table. /// </remarks> /// <returns>The database command.</returns> protected abstract IDbCommand GetSelectAllCrlsCommand (); /// <summary> /// Gets the database command to delete the specified certificate record. /// </summary> /// <remarks> /// Gets the database command to delete the specified certificate record. /// </remarks> /// <returns>The database command.</returns> /// <param name="record">The certificate record.</param> protected abstract IDbCommand GetDeleteCommand (X509CertificateRecord record); /// <summary> /// Gets the database command to delete the specified CRL record. /// </summary> /// <remarks> /// Gets the database command to delete the specified CRL record. /// </remarks> /// <returns>The database command.</returns> /// <param name="record">The record.</param> protected abstract IDbCommand GetDeleteCommand (X509CrlRecord record); /// <summary> /// Gets the value for the specified column. /// </summary> /// <remarks> /// Gets the value for the specified column. /// </remarks> /// <returns>The value.</returns> /// <param name="record">The certificate record.</param> /// <param name="columnName">The column name.</param> /// <exception cref="System.ArgumentException"> /// <paramref name="columnName"/> is not a known column name. /// </exception> protected object GetValue (X509CertificateRecord record, string columnName) { switch (columnName) { case "ID": return record.Id; case "BASICCONSTRAINTS": return record.BasicConstraints; case "TRUSTED": return record.IsTrusted; case "KEYUSAGE": return (int) record.KeyUsage; case "NOTBEFORE": return record.NotBefore; case "NOTAFTER": return record.NotAfter; case "ISSUERNAME": return record.IssuerName; case "SERIALNUMBER": return record.SerialNumber; case "SUBJECTEMAIL": return record.SubjectEmail != null ? record.SubjectEmail.ToLowerInvariant () : string.Empty; case "FINGERPRINT": return record.Fingerprint.ToLowerInvariant (); case "ALGORITHMS": return EncodeEncryptionAlgorithms (record.Algorithms); case "ALGORITHMSUPDATED": return record.AlgorithmsUpdated; case "CERTIFICATE": return record.Certificate.GetEncoded (); case "PRIVATEKEY": return EncodePrivateKey (record.PrivateKey); default: throw new ArgumentException (string.Format ("Unknown column name: {0}", columnName), "columnName"); } } /// <summary> /// Gets the value for the specified column. /// </summary> /// <remarks> /// Gets the value for the specified column. /// </remarks> /// <returns>The value.</returns> /// <param name="record">The CRL record.</param> /// <param name="columnName">The column name.</param> /// <exception cref="System.ArgumentException"> /// <paramref name="columnName"/> is not a known column name. /// </exception> protected static object GetValue (X509CrlRecord record, string columnName) { switch (columnName) { case "ID": return record.Id; case "DELTA": return record.IsDelta; case "ISSUERNAME": return record.IssuerName; case "THISUPDATE": return record.ThisUpdate; case "NEXTUPDATE": return record.NextUpdate; case "CRL": return record.Crl.GetEncoded (); default: throw new ArgumentException (string.Format ("Unknown column name: {0}", columnName), "columnName"); } } /// <summary> /// Gets the database command to insert the specified certificate record. /// </summary> /// <remarks> /// Gets the database command to insert the specified certificate record. /// </remarks> /// <returns>The database command.</returns> /// <param name="record">The certificate record.</param> protected abstract IDbCommand GetInsertCommand (X509CertificateRecord record); /// <summary> /// Gets the database command to insert the specified CRL record. /// </summary> /// <remarks> /// Gets the database command to insert the specified CRL record. /// </remarks> /// <returns>The database command.</returns> /// <param name="record">The CRL record.</param> protected abstract IDbCommand GetInsertCommand (X509CrlRecord record); /// <summary> /// Gets the database command to update the specified record. /// </summary> /// <remarks> /// Gets the database command to update the specified record. /// </remarks> /// <returns>The database command.</returns> /// <param name="record">The certificate record.</param> /// <param name="fields">The fields to update.</param> protected abstract IDbCommand GetUpdateCommand (X509CertificateRecord record, X509CertificateRecordFields fields); /// <summary> /// Gets the database command to update the specified CRL record. /// </summary> /// <remarks> /// Gets the database command to update the specified CRL record. /// </remarks> /// <returns>The database command.</returns> /// <param name="record">The CRL record.</param> protected abstract IDbCommand GetUpdateCommand (X509CrlRecord record); /// <summary> /// Find the specified certificate. /// </summary> /// <remarks> /// Searches the database for the specified certificate, returning the matching /// record with the desired fields populated. /// </remarks> /// <returns>The matching record if found; otherwise <c>null</c>.</returns> /// <param name="certificate">The certificate.</param> /// <param name="fields">The desired fields.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public X509CertificateRecord Find (X509Certificate certificate, X509CertificateRecordFields fields) { if (certificate == null) throw new ArgumentNullException ("certificate"); using (var command = GetSelectCommand (certificate, fields)) { var reader = command.ExecuteReader (); try { if (reader.Read ()) { var parser = new X509CertificateParser (); var buffer = new byte[4096]; return LoadCertificateRecord (reader, parser, ref buffer); } } finally { reader.Close (); } } return null; } /// <summary> /// Finds the certificates matching the specified selector. /// </summary> /// <remarks> /// Searches the database for certificates matching the selector, returning all /// matching certificates. /// </remarks> /// <returns>The matching certificates.</returns> /// <param name="selector">The match selector or <c>null</c> to return all certificates.</param> public IEnumerable<X509Certificate> FindCertificates (IX509Selector selector) { using (var command = GetSelectCommand (selector, false, false, X509CertificateRecordFields.Certificate)) { var reader = command.ExecuteReader (); try { var parser = new X509CertificateParser (); var buffer = new byte[4096]; while (reader.Read ()) { var record = LoadCertificateRecord (reader, parser, ref buffer); if (selector == null || selector.Match (record.Certificate)) yield return record.Certificate; } } finally { reader.Close (); } } yield break; } /// <summary> /// Finds the private keys matching the specified selector. /// </summary> /// <remarks> /// Searches the database for certificate records matching the selector, returning the /// private keys for each matching record. /// </remarks> /// <returns>The matching certificates.</returns> /// <param name="selector">The match selector or <c>null</c> to return all private keys.</param> public IEnumerable<AsymmetricKeyParameter> FindPrivateKeys (IX509Selector selector) { using (var command = GetSelectCommand (selector, false, true, PrivateKeyFields)) { var reader = command.ExecuteReader (); try { var parser = new X509CertificateParser (); var buffer = new byte[4096]; while (reader.Read ()) { var record = LoadCertificateRecord (reader, parser, ref buffer); if (selector == null || selector.Match (record.Certificate)) yield return record.PrivateKey; } } finally { reader.Close (); } } yield break; } /// <summary> /// Finds the certificate records for the specified mailbox. /// </summary> /// <remarks> /// Searches the database for certificates matching the specified mailbox that are valid /// for the date and time specified, returning all matching records populated with the /// desired fields. /// </remarks> /// <returns>The matching certificate records populated with the desired fields.</returns> /// <param name="mailbox">The mailbox.</param> /// <param name="now">The date and time.</param> /// <param name="requirePrivateKey"><c>true</c> if a private key is required.</param> /// <param name="fields">The desired fields.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="mailbox"/> is <c>null</c>. /// </exception> public IEnumerable<X509CertificateRecord> Find (MailboxAddress mailbox, DateTime now, bool requirePrivateKey, X509CertificateRecordFields fields) { if (mailbox == null) throw new ArgumentNullException ("mailbox"); using (var command = GetSelectCommand (mailbox, now, requirePrivateKey, fields)) { var reader = command.ExecuteReader (); try { var parser = new X509CertificateParser (); var buffer = new byte[4096]; while (reader.Read ()) { yield return LoadCertificateRecord (reader, parser, ref buffer); } } finally { reader.Close (); } } yield break; } /// <summary> /// Finds the certificate records matching the specified selector. /// </summary> /// <remarks> /// Searches the database for certificate records matching the selector, returning all /// of the matching records populated with the desired fields. /// </remarks> /// <returns>The matching certificate records populated with the desired fields.</returns> /// <param name="selector">The match selector or <c>null</c> to match all certificates.</param> /// <param name="trustedOnly"><c>true</c> if only trusted certificates should be returned.</param> /// <param name="fields">The desired fields.</param> public IEnumerable<X509CertificateRecord> Find (IX509Selector selector, bool trustedOnly, X509CertificateRecordFields fields) { using (var command = GetSelectCommand (selector, trustedOnly, false, fields | X509CertificateRecordFields.Certificate)) { var reader = command.ExecuteReader (); try { var parser = new X509CertificateParser (); var buffer = new byte[4096]; while (reader.Read ()) { var record = LoadCertificateRecord (reader, parser, ref buffer); if (selector == null || selector.Match (record.Certificate)) yield return record; } } finally { reader.Close (); } } yield break; } /// <summary> /// Add the specified certificate record. /// </summary> /// <remarks> /// Adds the specified certificate record to the database. /// </remarks> /// <param name="record">The certificate record.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="record"/> is <c>null</c>. /// </exception> public void Add (X509CertificateRecord record) { if (record == null) throw new ArgumentNullException ("record"); using (var command = GetInsertCommand (record)) { command.ExecuteNonQuery (); } } /// <summary> /// Remove the specified certificate record. /// </summary> /// <remarks> /// Removes the specified certificate record from the database. /// </remarks> /// <param name="record">The certificate record.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="record"/> is <c>null</c>. /// </exception> public void Remove (X509CertificateRecord record) { if (record == null) throw new ArgumentNullException ("record"); using (var command = GetDeleteCommand (record)) { command.ExecuteNonQuery (); } } /// <summary> /// Update the specified certificate record. /// </summary> /// <remarks> /// Updates the specified fields of the record in the database. /// </remarks> /// <param name="record">The certificate record.</param> /// <param name="fields">The fields to update.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="record"/> is <c>null</c>. /// </exception> public void Update (X509CertificateRecord record, X509CertificateRecordFields fields) { if (record == null) throw new ArgumentNullException ("record"); using (var command = GetUpdateCommand (record, fields)) { command.ExecuteNonQuery (); } } /// <summary> /// Finds the CRL records for the specified issuer. /// </summary> /// <remarks> /// Searches the database for CRL records matching the specified issuer, returning /// all matching records populated with the desired fields. /// </remarks> /// <returns>The matching CRL records populated with the desired fields.</returns> /// <param name="issuer">The issuer.</param> /// <param name="fields">The desired fields.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="issuer"/> is <c>null</c>. /// </exception> public IEnumerable<X509CrlRecord> Find (X509Name issuer, X509CrlRecordFields fields) { if (issuer == null) throw new ArgumentNullException ("issuer"); using (var command = GetSelectCommand (issuer, fields)) { var reader = command.ExecuteReader (); try { var parser = new X509CrlParser (); var buffer = new byte[4096]; while (reader.Read ()) { yield return LoadCrlRecord (reader, parser, ref buffer); } } finally { reader.Close (); } } yield break; } /// <summary> /// Finds the specified certificate revocation list. /// </summary> /// <remarks> /// Searches the database for the specified CRL, returning the matching record with /// the desired fields populated. /// </remarks> /// <returns>The matching record if found; otherwise <c>null</c>.</returns> /// <param name="crl">The certificate revocation list.</param> /// <param name="fields">The desired fields.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="crl"/> is <c>null</c>. /// </exception> public X509CrlRecord Find (X509Crl crl, X509CrlRecordFields fields) { if (crl == null) throw new ArgumentNullException ("crl"); using (var command = GetSelectCommand (crl, fields)) { var reader = command.ExecuteReader (); try { if (reader.Read ()) { var parser = new X509CrlParser (); var buffer = new byte[4096]; return LoadCrlRecord (reader, parser, ref buffer); } } finally { reader.Close (); } } return null; } /// <summary> /// Add the specified CRL record. /// </summary> /// <remarks> /// Adds the specified CRL record to the database. /// </remarks> /// <param name="record">The CRL record.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="record"/> is <c>null</c>. /// </exception> public void Add (X509CrlRecord record) { if (record == null) throw new ArgumentNullException ("record"); using (var command = GetInsertCommand (record)) { command.ExecuteNonQuery (); } } /// <summary> /// Remove the specified CRL record. /// </summary> /// <remarks> /// Removes the specified CRL record from the database. /// </remarks> /// <param name="record">The CRL record.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="record"/> is <c>null</c>. /// </exception> public void Remove (X509CrlRecord record) { if (record == null) throw new ArgumentNullException ("record"); using (var command = GetDeleteCommand (record)) { command.ExecuteNonQuery (); } } /// <summary> /// Update the specified CRL record. /// </summary> /// <remarks> /// Updates the specified fields of the record in the database. /// </remarks> /// <param name="record">The CRL record.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="record"/> is <c>null</c>. /// </exception> public void Update (X509CrlRecord record) { if (record == null) throw new ArgumentNullException ("record"); using (var command = GetUpdateCommand (record)) { command.ExecuteNonQuery (); } } /// <summary> /// Gets a certificate revocation list store. /// </summary> /// <remarks> /// Gets a certificate revocation list store. /// </remarks> /// <returns>A certificate recovation list store.</returns> public IX509Store GetCrlStore () { var crls = new List<X509Crl> (); using (var command = GetSelectAllCrlsCommand ()) { var reader = command.ExecuteReader (); try { var parser = new X509CrlParser (); var buffer = new byte[4096]; while (reader.Read ()) { var record = LoadCrlRecord (reader, parser, ref buffer); crls.Add (record.Crl); } } finally { reader.Close (); } } return X509StoreFactory.Create ("Crl/Collection", new X509CollectionStoreParameters (crls)); } #region IX509Store implementation /// <summary> /// Gets a collection of matching certificates matching the specified selector. /// </summary> /// <remarks> /// Gets a collection of matching certificates matching the specified selector. /// </remarks> /// <returns>The matching certificates.</returns> /// <param name="selector">The match criteria.</param> ICollection IX509Store.GetMatches (IX509Selector selector) { return new List<X509Certificate> (FindCertificates (selector)); } #endregion #region IDisposable implementation /// <summary> /// Releases the unmanaged resources used by the <see cref="X509CertificateDatabase"/> and /// optionally releases the managed resources. /// </summary> /// <remarks> /// Releases the unmanaged resources used by the <see cref="X509CertificateDatabase"/> and /// optionally releases the managed resources. /// </remarks> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; /// <c>false</c> to release only the unmanaged resources.</param> protected virtual void Dispose (bool disposing) { for (int i = 0; i < passwd.Length; i++) passwd[i] = '\0'; } /// <summary> /// Releases all resource used by the <see cref="MimeKit.Cryptography.X509CertificateDatabase"/> object. /// </summary> /// <remarks>Call <see cref="Dispose()"/> when you are finished using the /// <see cref="MimeKit.Cryptography.X509CertificateDatabase"/>. The <see cref="Dispose()"/> method leaves the /// <see cref="MimeKit.Cryptography.X509CertificateDatabase"/> in an unusable state. After calling /// <see cref="Dispose()"/>, you must release all references to the /// <see cref="MimeKit.Cryptography.X509CertificateDatabase"/> so the garbage collector can reclaim the memory that /// the <see cref="MimeKit.Cryptography.X509CertificateDatabase"/> was occupying.</remarks> public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } #endregion } }
using System; namespace DDay.Update.ConfigurationTool.Forms { partial class OptionsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.cbEnableUpdateLogging = new System.Windows.Forms.CheckBox(); this.cbDebugLog = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.tbNumVersions = new System.Windows.Forms.TextBox(); this.rbDeleteAfter = new System.Windows.Forms.RadioButton(); this.rbKeepAll = new System.Windows.Forms.RadioButton(); this.cbKeepPrevVersions = new System.Windows.Forms.CheckBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.tbPreserve = new System.Windows.Forms.TextBox(); this.lbPreserve = new System.Windows.Forms.ListBox(); this.btnPresRemove = new System.Windows.Forms.Button(); this.btnPresAdd = new System.Windows.Forms.Button(); this.cbPreserve = new System.Windows.Forms.CheckBox(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.cbAppFolder = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.cbUseSecurityFolder = new System.Windows.Forms.CheckBox(); this.cbAutoUpdate = new System.Windows.Forms.CheckBox(); this.tabPage4 = new System.Windows.Forms.TabPage(); this.gbCredentials = new System.Windows.Forms.GroupBox(); this.label5 = new System.Windows.Forms.Label(); this.txtDomain = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.txtPassword = new System.Windows.Forms.TextBox(); this.txtUsername = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.cbUseCredentials = new System.Windows.Forms.CheckBox(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.tbRemove = new System.Windows.Forms.TextBox(); this.lbRemove = new System.Windows.Forms.ListBox(); this.btnRemoveRemove = new System.Windows.Forms.Button(); this.btnRemoveAdd = new System.Windows.Forms.Button(); this.cbRemove = new System.Windows.Forms.CheckBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.listBox1 = new System.Windows.Forms.ListBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.groupBox5.SuspendLayout(); this.tabPage4.SuspendLayout(); this.gbCredentials.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.SuspendLayout(); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.Location = new System.Drawing.Point(222, 369); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(75, 23); this.btnOK.TabIndex = 0; this.btnOK.Text = "&OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(141, 369); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 1; this.btnCancel.Text = "&Cancel"; this.btnCancel.UseVisualStyleBackColor = true; // // cbEnableUpdateLogging // this.cbEnableUpdateLogging.AutoSize = true; this.cbEnableUpdateLogging.Location = new System.Drawing.Point(6, 19); this.cbEnableUpdateLogging.Name = "cbEnableUpdateLogging"; this.cbEnableUpdateLogging.Size = new System.Drawing.Size(151, 18); this.cbEnableUpdateLogging.TabIndex = 2; this.cbEnableUpdateLogging.Text = "Enable Update &Logging"; this.cbEnableUpdateLogging.UseVisualStyleBackColor = true; // // cbDebugLog // this.cbDebugLog.AutoSize = true; this.cbDebugLog.Enabled = false; this.cbDebugLog.Location = new System.Drawing.Point(6, 43); this.cbDebugLog.Name = "cbDebugLog"; this.cbDebugLog.Size = new System.Drawing.Size(130, 18); this.cbDebugLog.TabIndex = 3; this.cbDebugLog.Text = "Include Debug Info"; this.cbDebugLog.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.cbEnableUpdateLogging); this.groupBox1.Controls.Add(this.cbDebugLog); this.groupBox1.Location = new System.Drawing.Point(6, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(287, 65); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "Update Logging"; // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.tbNumVersions); this.groupBox2.Controls.Add(this.rbDeleteAfter); this.groupBox2.Controls.Add(this.rbKeepAll); this.groupBox2.Controls.Add(this.cbKeepPrevVersions); this.groupBox2.Location = new System.Drawing.Point(6, 79); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(287, 92); this.groupBox2.TabIndex = 5; this.groupBox2.TabStop = false; this.groupBox2.Text = "Previous Versions"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(177, 69); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(105, 14); this.label1.TabIndex = 4; this.label1.Text = "previous versions"; // // tbNumVersions // this.tbNumVersions.Location = new System.Drawing.Point(132, 66); this.tbNumVersions.Name = "tbNumVersions"; this.tbNumVersions.Size = new System.Drawing.Size(43, 20); this.tbNumVersions.TabIndex = 3; this.tbNumVersions.TextChanged += new System.EventHandler(this.tbNumVersions_TextChanged); // // rbDeleteAfter // this.rbDeleteAfter.AutoSize = true; this.rbDeleteAfter.Location = new System.Drawing.Point(38, 67); this.rbDeleteAfter.Name = "rbDeleteAfter"; this.rbDeleteAfter.Size = new System.Drawing.Size(95, 18); this.rbDeleteAfter.TabIndex = 2; this.rbDeleteAfter.TabStop = true; this.rbDeleteAfter.Text = "Keep at most"; this.rbDeleteAfter.UseVisualStyleBackColor = true; // // rbKeepAll // this.rbKeepAll.AutoSize = true; this.rbKeepAll.Location = new System.Drawing.Point(38, 43); this.rbKeepAll.Name = "rbKeepAll"; this.rbKeepAll.Size = new System.Drawing.Size(118, 18); this.rbKeepAll.TabIndex = 1; this.rbKeepAll.TabStop = true; this.rbKeepAll.Text = "Keep all versions"; this.rbKeepAll.UseVisualStyleBackColor = true; // // cbKeepPrevVersions // this.cbKeepPrevVersions.AutoSize = true; this.cbKeepPrevVersions.Checked = true; this.cbKeepPrevVersions.CheckState = System.Windows.Forms.CheckState.Checked; this.cbKeepPrevVersions.Location = new System.Drawing.Point(6, 19); this.cbKeepPrevVersions.Name = "cbKeepPrevVersions"; this.cbKeepPrevVersions.Size = new System.Drawing.Size(154, 18); this.cbKeepPrevVersions.TabIndex = 0; this.cbKeepPrevVersions.Text = "Keep Previous Versions"; this.cbKeepPrevVersions.UseVisualStyleBackColor = true; this.cbKeepPrevVersions.CheckedChanged += new System.EventHandler(this.cbKeepPrevVersions_CheckedChanged); // // groupBox3 // this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox3.Controls.Add(this.tbPreserve); this.groupBox3.Controls.Add(this.lbPreserve); this.groupBox3.Controls.Add(this.btnPresRemove); this.groupBox3.Controls.Add(this.btnPresAdd); this.groupBox3.Controls.Add(this.cbPreserve); this.groupBox3.Location = new System.Drawing.Point(7, 6); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(286, 324); this.groupBox3.TabIndex = 6; this.groupBox3.TabStop = false; this.groupBox3.Text = "Preserve Files"; // // tbPreserve // this.tbPreserve.Location = new System.Drawing.Point(6, 71); this.tbPreserve.Name = "tbPreserve"; this.tbPreserve.Size = new System.Drawing.Size(192, 20); this.tbPreserve.TabIndex = 8; // // lbPreserve // this.lbPreserve.FormattingEnabled = true; this.lbPreserve.ItemHeight = 14; this.lbPreserve.Location = new System.Drawing.Point(6, 98); this.lbPreserve.Name = "lbPreserve"; this.lbPreserve.Size = new System.Drawing.Size(192, 214); this.lbPreserve.TabIndex = 7; // // btnPresRemove // this.btnPresRemove.Location = new System.Drawing.Point(204, 97); this.btnPresRemove.Name = "btnPresRemove"; this.btnPresRemove.Size = new System.Drawing.Size(75, 23); this.btnPresRemove.TabIndex = 2; this.btnPresRemove.Text = "&Remove"; this.btnPresRemove.UseVisualStyleBackColor = true; this.btnPresRemove.Click += new System.EventHandler(this.btnPresRemove_Click); // // btnPresAdd // this.btnPresAdd.Location = new System.Drawing.Point(204, 68); this.btnPresAdd.Name = "btnPresAdd"; this.btnPresAdd.Size = new System.Drawing.Size(75, 23); this.btnPresAdd.TabIndex = 1; this.btnPresAdd.Text = "&Add"; this.btnPresAdd.UseVisualStyleBackColor = true; this.btnPresAdd.Click += new System.EventHandler(this.btnPresAdd_Click); // // cbPreserve // this.cbPreserve.Location = new System.Drawing.Point(6, 19); this.cbPreserve.Name = "cbPreserve"; this.cbPreserve.Size = new System.Drawing.Size(273, 46); this.cbPreserve.TabIndex = 0; this.cbPreserve.Text = "Preserve (don\'t overwrite) files that match the following pattern(s). These file" + "s will not receive updates!"; this.cbPreserve.UseVisualStyleBackColor = true; this.cbPreserve.CheckedChanged += new System.EventHandler(this.cbPreserve_CheckedChanged); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage4); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Top; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(309, 363); this.tabControl1.TabIndex = 7; // // tabPage1 // this.tabPage1.Controls.Add(this.groupBox5); this.tabPage1.Controls.Add(this.groupBox1); this.tabPage1.Controls.Add(this.groupBox2); this.tabPage1.Location = new System.Drawing.Point(4, 23); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(301, 336); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "General"; this.tabPage1.UseVisualStyleBackColor = true; // // groupBox5 // this.groupBox5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox5.Controls.Add(this.cbAppFolder); this.groupBox5.Controls.Add(this.label6); this.groupBox5.Controls.Add(this.cbUseSecurityFolder); this.groupBox5.Controls.Add(this.cbAutoUpdate); this.groupBox5.Location = new System.Drawing.Point(6, 177); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(287, 99); this.groupBox5.TabIndex = 6; this.groupBox5.TabStop = false; this.groupBox5.Text = "Updates"; // // cbAppFolder // this.cbAppFolder.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbAppFolder.FormattingEnabled = true; this.cbAppFolder.Items.AddRange(new object[] { "User\'s", "Public"}); this.cbAppFolder.Location = new System.Drawing.Point(118, 39); this.cbAppFolder.Name = "cbAppFolder"; this.cbAppFolder.Size = new System.Drawing.Size(91, 22); this.cbAppFolder.TabIndex = 3; // // label6 // this.label6.Location = new System.Drawing.Point(22, 61); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(234, 32); this.label6.TabIndex = 2; this.label6.Text = "application folder (Helps to avoid some permission-based problems)."; // // cbUseSecurityFolder // this.cbUseSecurityFolder.AutoSize = true; this.cbUseSecurityFolder.CheckAlign = System.Drawing.ContentAlignment.TopLeft; this.cbUseSecurityFolder.Checked = true; this.cbUseSecurityFolder.CheckState = System.Windows.Forms.CheckState.Checked; this.cbUseSecurityFolder.Location = new System.Drawing.Point(6, 43); this.cbUseSecurityFolder.Name = "cbUseSecurityFolder"; this.cbUseSecurityFolder.Size = new System.Drawing.Size(115, 18); this.cbUseSecurityFolder.TabIndex = 1; this.cbUseSecurityFolder.Text = "Store updates in"; this.cbUseSecurityFolder.UseVisualStyleBackColor = true; // // cbAutoUpdate // this.cbAutoUpdate.AutoSize = true; this.cbAutoUpdate.Checked = true; this.cbAutoUpdate.CheckState = System.Windows.Forms.CheckState.Checked; this.cbAutoUpdate.Location = new System.Drawing.Point(6, 19); this.cbAutoUpdate.Name = "cbAutoUpdate"; this.cbAutoUpdate.Size = new System.Drawing.Size(203, 18); this.cbAutoUpdate.TabIndex = 0; this.cbAutoUpdate.Text = "Automatically update application"; this.cbAutoUpdate.UseVisualStyleBackColor = true; // // tabPage4 // this.tabPage4.Controls.Add(this.gbCredentials); this.tabPage4.Controls.Add(this.cbUseCredentials); this.tabPage4.Location = new System.Drawing.Point(4, 23); this.tabPage4.Name = "tabPage4"; this.tabPage4.Padding = new System.Windows.Forms.Padding(3); this.tabPage4.Size = new System.Drawing.Size(301, 336); this.tabPage4.TabIndex = 3; this.tabPage4.Text = "Security"; this.tabPage4.UseVisualStyleBackColor = true; // // gbCredentials // this.gbCredentials.Controls.Add(this.label5); this.gbCredentials.Controls.Add(this.txtDomain); this.gbCredentials.Controls.Add(this.label4); this.gbCredentials.Controls.Add(this.txtPassword); this.gbCredentials.Controls.Add(this.txtUsername); this.gbCredentials.Controls.Add(this.label3); this.gbCredentials.Controls.Add(this.label2); this.gbCredentials.Enabled = false; this.gbCredentials.Location = new System.Drawing.Point(31, 39); this.gbCredentials.Name = "gbCredentials"; this.gbCredentials.Size = new System.Drawing.Size(233, 116); this.gbCredentials.TabIndex = 1; this.gbCredentials.TabStop = false; this.gbCredentials.Text = "Credentials"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(8, 92); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(79, 14); this.label5.TabIndex = 9; this.label5.Text = "(if applicable)"; // // txtDomain // this.txtDomain.Location = new System.Drawing.Point(93, 72); this.txtDomain.Name = "txtDomain"; this.txtDomain.Size = new System.Drawing.Size(126, 20); this.txtDomain.TabIndex = 4; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(40, 75); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(47, 14); this.label4.TabIndex = 4; this.label4.Text = "Domain"; // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(93, 46); this.txtPassword.Name = "txtPassword"; this.txtPassword.PasswordChar = '*'; this.txtPassword.Size = new System.Drawing.Size(126, 20); this.txtPassword.TabIndex = 3; // // txtUsername // this.txtUsername.Location = new System.Drawing.Point(93, 22); this.txtUsername.Name = "txtUsername"; this.txtUsername.Size = new System.Drawing.Size(126, 20); this.txtUsername.TabIndex = 2; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(29, 49); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(58, 14); this.label3.TabIndex = 1; this.label3.Text = "Password"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(26, 25); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(61, 14); this.label2.TabIndex = 0; this.label2.Text = "Username"; // // cbUseCredentials // this.cbUseCredentials.Location = new System.Drawing.Point(7, 7); this.cbUseCredentials.Margin = new System.Windows.Forms.Padding(7); this.cbUseCredentials.Name = "cbUseCredentials"; this.cbUseCredentials.Size = new System.Drawing.Size(286, 32); this.cbUseCredentials.TabIndex = 0; this.cbUseCredentials.Text = "Use security credentials to access updates."; this.cbUseCredentials.UseVisualStyleBackColor = true; this.cbUseCredentials.CheckedChanged += new System.EventHandler(this.cbUseCredentials_CheckedChanged); // // tabPage2 // this.tabPage2.Controls.Add(this.groupBox3); this.tabPage2.Location = new System.Drawing.Point(4, 23); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(301, 336); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Preserve"; this.tabPage2.UseVisualStyleBackColor = true; // // tabPage3 // this.tabPage3.Controls.Add(this.groupBox4); this.tabPage3.Location = new System.Drawing.Point(4, 23); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(301, 336); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Remove"; this.tabPage3.UseVisualStyleBackColor = true; // // groupBox4 // this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox4.Controls.Add(this.tbRemove); this.groupBox4.Controls.Add(this.lbRemove); this.groupBox4.Controls.Add(this.btnRemoveRemove); this.groupBox4.Controls.Add(this.btnRemoveAdd); this.groupBox4.Controls.Add(this.cbRemove); this.groupBox4.Location = new System.Drawing.Point(7, 6); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(286, 324); this.groupBox4.TabIndex = 7; this.groupBox4.TabStop = false; this.groupBox4.Text = "Remove Files"; // // tbRemove // this.tbRemove.Location = new System.Drawing.Point(6, 58); this.tbRemove.Name = "tbRemove"; this.tbRemove.Size = new System.Drawing.Size(192, 20); this.tbRemove.TabIndex = 8; // // lbRemove // this.lbRemove.FormattingEnabled = true; this.lbRemove.ItemHeight = 14; this.lbRemove.Location = new System.Drawing.Point(6, 84); this.lbRemove.Name = "lbRemove"; this.lbRemove.Size = new System.Drawing.Size(192, 228); this.lbRemove.TabIndex = 7; // // btnRemoveRemove // this.btnRemoveRemove.Location = new System.Drawing.Point(204, 84); this.btnRemoveRemove.Name = "btnRemoveRemove"; this.btnRemoveRemove.Size = new System.Drawing.Size(75, 23); this.btnRemoveRemove.TabIndex = 2; this.btnRemoveRemove.Text = "&Remove"; this.btnRemoveRemove.UseVisualStyleBackColor = true; this.btnRemoveRemove.Click += new System.EventHandler(this.btnRemoveRemove_Click); // // btnRemoveAdd // this.btnRemoveAdd.Location = new System.Drawing.Point(204, 55); this.btnRemoveAdd.Name = "btnRemoveAdd"; this.btnRemoveAdd.Size = new System.Drawing.Size(75, 23); this.btnRemoveAdd.TabIndex = 1; this.btnRemoveAdd.Text = "&Add"; this.btnRemoveAdd.UseVisualStyleBackColor = true; this.btnRemoveAdd.Click += new System.EventHandler(this.btnRemoveAdd_Click); // // cbRemove // this.cbRemove.Location = new System.Drawing.Point(6, 19); this.cbRemove.Name = "cbRemove"; this.cbRemove.Size = new System.Drawing.Size(273, 41); this.cbRemove.TabIndex = 0; this.cbRemove.Text = "Remove files that match the following pattern(s)"; this.cbRemove.UseVisualStyleBackColor = true; this.cbRemove.CheckedChanged += new System.EventHandler(this.cbRemove_CheckedChanged); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(6, 58); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(192, 20); this.textBox1.TabIndex = 8; // // listBox1 // this.listBox1.FormattingEnabled = true; this.listBox1.Location = new System.Drawing.Point(6, 84); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(192, 225); this.listBox1.TabIndex = 7; // // button1 // this.button1.Location = new System.Drawing.Point(204, 84); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 2; this.button1.Text = "&Remove"; this.button1.UseVisualStyleBackColor = true; // // button2 // this.button2.Location = new System.Drawing.Point(204, 55); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 1; this.button2.Text = "&Add"; this.button2.UseVisualStyleBackColor = true; // // checkBox1 // this.checkBox1.Checked = true; this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox1.Location = new System.Drawing.Point(6, 19); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(273, 41); this.checkBox1.TabIndex = 0; this.checkBox1.Text = "Preserve (don\'t overwrite) files that match the following pattern(s)"; this.checkBox1.UseVisualStyleBackColor = true; // // OptionsForm // this.AcceptButton = this.btnOK; this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(309, 404); this.Controls.Add(this.tabControl1); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Font = new System.Drawing.Font("Lucida Sans", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "OptionsForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = " Options"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.tabPage4.ResumeLayout(false); this.gbCredentials.ResumeLayout(false); this.gbCredentials.PerformLayout(); this.tabPage2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.CheckBox cbEnableUpdateLogging; private System.Windows.Forms.CheckBox cbDebugLog; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.CheckBox cbKeepPrevVersions; private System.Windows.Forms.RadioButton rbKeepAll; private System.Windows.Forms.RadioButton rbDeleteAfter; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbNumVersions; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.ListBox lbPreserve; private System.Windows.Forms.Button btnPresRemove; private System.Windows.Forms.Button btnPresAdd; private System.Windows.Forms.CheckBox cbPreserve; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.TextBox tbPreserve; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.TextBox tbRemove; private System.Windows.Forms.ListBox lbRemove; private System.Windows.Forms.Button btnRemoveRemove; private System.Windows.Forms.Button btnRemoveAdd; private System.Windows.Forms.CheckBox cbRemove; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.CheckBox checkBox1; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.CheckBox cbAutoUpdate; private System.Windows.Forms.CheckBox cbUseSecurityFolder; private System.Windows.Forms.TabPage tabPage4; private System.Windows.Forms.GroupBox gbCredentials; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.TextBox txtUsername; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.CheckBox cbUseCredentials; private System.Windows.Forms.TextBox txtDomain; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cbAppFolder; private System.Windows.Forms.Label label6; } }
namespace PrimWorkshop { partial class frmPrimWorkshop { /// <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)) { glControl.DestroyContexts(); components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menu = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.opToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openPrimXMLToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.textureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.savePrimXMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveTextureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.importToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.worldBrowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.oBJToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.wireframeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.splitContainer = new System.Windows.Forms.SplitContainer(); this.glControl = new Tao.Platform.Windows.SimpleOpenGlControl(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.panel2 = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.cboFace = new System.Windows.Forms.ComboBox(); this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.cboPrim = new System.Windows.Forms.ComboBox(); this.scrollRoll = new System.Windows.Forms.HScrollBar(); this.scrollPitch = new System.Windows.Forms.HScrollBar(); this.scrollYaw = new System.Windows.Forms.HScrollBar(); this.picTexture = new System.Windows.Forms.PictureBox(); this.scrollZoom = new System.Windows.Forms.HScrollBar(); this.menu.SuspendLayout(); this.splitContainer.Panel1.SuspendLayout(); this.splitContainer.Panel2.SuspendLayout(); this.splitContainer.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.panel2.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picTexture)).BeginInit(); this.SuspendLayout(); // // menu // this.menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.viewToolStripMenuItem, this.helpToolStripMenuItem}); this.menu.Location = new System.Drawing.Point(0, 0); this.menu.Name = "menu"; this.menu.Size = new System.Drawing.Size(996, 24); this.menu.TabIndex = 0; this.menu.Text = "menu"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.opToolStripMenuItem, this.toolStripMenuItem2, this.savePrimXMLToolStripMenuItem, this.saveTextureToolStripMenuItem, this.importToolStripMenuItem, this.exportToolStripMenuItem, this.toolStripMenuItem1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "File"; // // opToolStripMenuItem // this.opToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openPrimXMLToolStripMenuItem1, this.textureToolStripMenuItem}); this.opToolStripMenuItem.Name = "opToolStripMenuItem"; this.opToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.opToolStripMenuItem.Text = "Open"; // // openPrimXMLToolStripMenuItem1 // this.openPrimXMLToolStripMenuItem1.Name = "openPrimXMLToolStripMenuItem1"; this.openPrimXMLToolStripMenuItem1.Size = new System.Drawing.Size(127, 22); this.openPrimXMLToolStripMenuItem1.Text = "Prim XML"; this.openPrimXMLToolStripMenuItem1.Click += new System.EventHandler(this.openPrimXMLToolStripMenuItem1_Click); // // textureToolStripMenuItem // this.textureToolStripMenuItem.Name = "textureToolStripMenuItem"; this.textureToolStripMenuItem.Size = new System.Drawing.Size(127, 22); this.textureToolStripMenuItem.Text = "Texture"; this.textureToolStripMenuItem.Click += new System.EventHandler(this.textureToolStripMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(151, 6); // // savePrimXMLToolStripMenuItem // this.savePrimXMLToolStripMenuItem.Name = "savePrimXMLToolStripMenuItem"; this.savePrimXMLToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.savePrimXMLToolStripMenuItem.Text = "Save Prim XML"; this.savePrimXMLToolStripMenuItem.Click += new System.EventHandler(this.savePrimXMLToolStripMenuItem_Click); // // saveTextureToolStripMenuItem // this.saveTextureToolStripMenuItem.Name = "saveTextureToolStripMenuItem"; this.saveTextureToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.saveTextureToolStripMenuItem.Text = "Save Texture"; this.saveTextureToolStripMenuItem.Click += new System.EventHandler(this.saveTextureToolStripMenuItem_Click); // // importToolStripMenuItem // this.importToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.worldBrowserToolStripMenuItem}); this.importToolStripMenuItem.Name = "importToolStripMenuItem"; this.importToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.importToolStripMenuItem.Text = "Import"; // // worldBrowserToolStripMenuItem // this.worldBrowserToolStripMenuItem.Name = "worldBrowserToolStripMenuItem"; this.worldBrowserToolStripMenuItem.Size = new System.Drawing.Size(155, 22); this.worldBrowserToolStripMenuItem.Text = "World Browser"; this.worldBrowserToolStripMenuItem.Click += new System.EventHandler(this.worldBrowserToolStripMenuItem_Click); // // exportToolStripMenuItem // this.exportToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.oBJToolStripMenuItem}); this.exportToolStripMenuItem.Name = "exportToolStripMenuItem"; this.exportToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.exportToolStripMenuItem.Text = "Export"; // // oBJToolStripMenuItem // this.oBJToolStripMenuItem.Name = "oBJToolStripMenuItem"; this.oBJToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.oBJToolStripMenuItem.Text = "OBJ Format"; this.oBJToolStripMenuItem.Click += new System.EventHandler(this.oBJToolStripMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(151, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.wireframeToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(41, 20); this.viewToolStripMenuItem.Text = "View"; // // wireframeToolStripMenuItem // this.wireframeToolStripMenuItem.Checked = true; this.wireframeToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.wireframeToolStripMenuItem.Name = "wireframeToolStripMenuItem"; this.wireframeToolStripMenuItem.Size = new System.Drawing.Size(135, 22); this.wireframeToolStripMenuItem.Text = "Wireframe"; this.wireframeToolStripMenuItem.Click += new System.EventHandler(this.wireframeToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "Help"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(114, 22); this.aboutToolStripMenuItem.Text = "About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // splitContainer // this.splitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer.Location = new System.Drawing.Point(0, 24); this.splitContainer.Name = "splitContainer"; // // splitContainer.Panel1 // this.splitContainer.Panel1.Controls.Add(this.glControl); // // splitContainer.Panel2 // this.splitContainer.Panel2.Controls.Add(this.tableLayoutPanel1); this.splitContainer.Size = new System.Drawing.Size(996, 512); this.splitContainer.SplitterDistance = 550; this.splitContainer.TabIndex = 6; // // glControl // this.glControl.AccumBits = ((byte)(0)); this.glControl.AutoCheckErrors = false; this.glControl.AutoFinish = false; this.glControl.AutoMakeCurrent = true; this.glControl.AutoSwapBuffers = true; this.glControl.BackColor = System.Drawing.Color.Black; this.glControl.ColorBits = ((byte)(32)); this.glControl.DepthBits = ((byte)(16)); this.glControl.Dock = System.Windows.Forms.DockStyle.Fill; this.glControl.Location = new System.Drawing.Point(0, 0); this.glControl.Name = "glControl"; this.glControl.Size = new System.Drawing.Size(550, 512); this.glControl.StencilBits = ((byte)(0)); this.glControl.TabIndex = 5; this.glControl.Paint += new System.Windows.Forms.PaintEventHandler(this.glControl_Paint); this.glControl.Resize += new System.EventHandler(this.glControl_Resize); // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.panel2, 0, 5); this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 4); this.tableLayoutPanel1.Controls.Add(this.scrollRoll, 0, 0); this.tableLayoutPanel1.Controls.Add(this.scrollPitch, 0, 1); this.tableLayoutPanel1.Controls.Add(this.scrollYaw, 0, 2); this.tableLayoutPanel1.Controls.Add(this.picTexture, 0, 6); this.tableLayoutPanel1.Controls.Add(this.scrollZoom, 0, 3); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 7; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 24F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(442, 512); this.tableLayoutPanel1.TabIndex = 9; // // panel2 // this.panel2.Controls.Add(this.label2); this.panel2.Controls.Add(this.cboFace); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(3, 117); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(436, 24); this.panel2.TabIndex = 16; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(4, 5); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(34, 13); this.label2.TabIndex = 16; this.label2.Text = "Face:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // cboFace // this.cboFace.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboFace.FormattingEnabled = true; this.cboFace.Location = new System.Drawing.Point(40, 2); this.cboFace.Name = "cboFace"; this.cboFace.Size = new System.Drawing.Size(174, 21); this.cboFace.TabIndex = 15; this.cboFace.SelectedIndexChanged += new System.EventHandler(this.cboFace_SelectedIndexChanged); // // panel1 // this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.cboPrim); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(3, 87); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(436, 24); this.panel1.TabIndex = 15; // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(4, 5); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(30, 13); this.label1.TabIndex = 16; this.label1.Text = "Prim:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // cboPrim // this.cboPrim.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboPrim.FormattingEnabled = true; this.cboPrim.Location = new System.Drawing.Point(40, 2); this.cboPrim.Name = "cboPrim"; this.cboPrim.Size = new System.Drawing.Size(174, 21); this.cboPrim.TabIndex = 15; this.cboPrim.SelectedIndexChanged += new System.EventHandler(this.cboPrim_SelectedIndexChanged); // // scrollRoll // this.scrollRoll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.scrollRoll.Location = new System.Drawing.Point(0, 2); this.scrollRoll.Maximum = 360; this.scrollRoll.Name = "scrollRoll"; this.scrollRoll.Size = new System.Drawing.Size(442, 16); this.scrollRoll.TabIndex = 9; this.scrollRoll.ValueChanged += new System.EventHandler(this.scroll_ValueChanged); // // scrollPitch // this.scrollPitch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.scrollPitch.Location = new System.Drawing.Point(0, 22); this.scrollPitch.Maximum = 360; this.scrollPitch.Name = "scrollPitch"; this.scrollPitch.Size = new System.Drawing.Size(442, 16); this.scrollPitch.TabIndex = 10; this.scrollPitch.ValueChanged += new System.EventHandler(this.scroll_ValueChanged); // // scrollYaw // this.scrollYaw.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.scrollYaw.Location = new System.Drawing.Point(0, 42); this.scrollYaw.Maximum = 360; this.scrollYaw.Name = "scrollYaw"; this.scrollYaw.Size = new System.Drawing.Size(442, 16); this.scrollYaw.TabIndex = 11; this.scrollYaw.ValueChanged += new System.EventHandler(this.scroll_ValueChanged); // // picTexture // this.picTexture.BackColor = System.Drawing.Color.Black; this.picTexture.Dock = System.Windows.Forms.DockStyle.Fill; this.picTexture.Location = new System.Drawing.Point(3, 147); this.picTexture.Name = "picTexture"; this.picTexture.Size = new System.Drawing.Size(436, 362); this.picTexture.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picTexture.TabIndex = 17; this.picTexture.TabStop = false; this.picTexture.MouseLeave += new System.EventHandler(this.picTexture_MouseLeave); this.picTexture.MouseMove += new System.Windows.Forms.MouseEventHandler(this.picTexture_MouseMove); this.picTexture.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picTexture_MouseDown); this.picTexture.Paint += new System.Windows.Forms.PaintEventHandler(this.picTexture_Paint); this.picTexture.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picTexture_MouseUp); // // scrollZoom // this.scrollZoom.Dock = System.Windows.Forms.DockStyle.Fill; this.scrollZoom.LargeChange = 1; this.scrollZoom.Location = new System.Drawing.Point(0, 60); this.scrollZoom.Maximum = 0; this.scrollZoom.Minimum = -200; this.scrollZoom.Name = "scrollZoom"; this.scrollZoom.Size = new System.Drawing.Size(442, 24); this.scrollZoom.TabIndex = 19; this.scrollZoom.Value = -50; this.scrollZoom.ValueChanged += new System.EventHandler(this.scrollZoom_ValueChanged); // // frmPrimWorkshop // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(996, 536); this.Controls.Add(this.splitContainer); this.Controls.Add(this.menu); this.MainMenuStrip = this.menu; this.Name = "frmPrimWorkshop"; this.Text = "Prim Workshop"; this.Shown += new System.EventHandler(this.frmPrimWorkshop_Shown); this.menu.ResumeLayout(false); this.menu.PerformLayout(); this.splitContainer.Panel1.ResumeLayout(false); this.splitContainer.Panel2.ResumeLayout(false); this.splitContainer.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picTexture)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menu; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.SplitContainer splitContainer; private Tao.Platform.Windows.SimpleOpenGlControl glControl; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.HScrollBar scrollRoll; private System.Windows.Forms.HScrollBar scrollPitch; private System.Windows.Forms.HScrollBar scrollYaw; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cboFace; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cboPrim; private System.Windows.Forms.PictureBox picTexture; private System.Windows.Forms.ToolStripMenuItem savePrimXMLToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem saveTextureToolStripMenuItem; private System.Windows.Forms.HScrollBar scrollZoom; private System.Windows.Forms.ToolStripMenuItem exportToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem oBJToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem wireframeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem importToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem worldBrowserToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem opToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openPrimXMLToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem textureToolStripMenuItem; } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Syndication { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; using System.Runtime.CompilerServices; [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] [XmlRoot(ElementName = Rss20Constants.ItemTag, Namespace = Rss20Constants.Rss20Namespace)] public class Rss20ItemFormatter : SyndicationItemFormatter, IXmlSerializable { Rss20FeedFormatter feedSerializer; Type itemType; bool preserveAttributeExtensions; bool preserveElementExtensions; bool serializeExtensionsAsAtom; public Rss20ItemFormatter() : this(typeof(SyndicationItem)) { } public Rss20ItemFormatter(Type itemTypeToCreate) : base() { if (itemTypeToCreate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("itemTypeToCreate"); } if (!typeof(SyndicationItem).IsAssignableFrom(itemTypeToCreate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("itemTypeToCreate", SR.GetString(SR.InvalidObjectTypePassed, "itemTypeToCreate", "SyndicationItem")); } this.feedSerializer = new Rss20FeedFormatter(); this.feedSerializer.PreserveAttributeExtensions = this.preserveAttributeExtensions = true; this.feedSerializer.PreserveElementExtensions = this.preserveElementExtensions = true; this.feedSerializer.SerializeExtensionsAsAtom = this.serializeExtensionsAsAtom = true; this.itemType = itemTypeToCreate; } public Rss20ItemFormatter(SyndicationItem itemToWrite) : this(itemToWrite, true) { } public Rss20ItemFormatter(SyndicationItem itemToWrite, bool serializeExtensionsAsAtom) : base(itemToWrite) { // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class this.feedSerializer = new Rss20FeedFormatter(); this.feedSerializer.PreserveAttributeExtensions = this.preserveAttributeExtensions = true; this.feedSerializer.PreserveElementExtensions = this.preserveElementExtensions = true; this.feedSerializer.SerializeExtensionsAsAtom = this.serializeExtensionsAsAtom = serializeExtensionsAsAtom; this.itemType = itemToWrite.GetType(); } public bool PreserveAttributeExtensions { get { return this.preserveAttributeExtensions; } set { this.preserveAttributeExtensions = value; this.feedSerializer.PreserveAttributeExtensions = value; } } public bool PreserveElementExtensions { get { return this.preserveElementExtensions; } set { this.preserveElementExtensions = value; this.feedSerializer.PreserveElementExtensions = value; } } public bool SerializeExtensionsAsAtom { get { return this.serializeExtensionsAsAtom; } set { this.serializeExtensionsAsAtom = value; this.feedSerializer.SerializeExtensionsAsAtom = value; } } public override string Version { get { return SyndicationVersions.Rss20; } } protected Type ItemType { get { return this.itemType; } } public override bool CanRead(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } return reader.IsStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] XmlSchema IXmlSerializable.GetSchema() { return null; } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.ReadXml(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } SyndicationFeedFormatter.TraceItemReadBegin(); ReadItem(reader); SyndicationFeedFormatter.TraceItemReadEnd(); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.WriteXml(XmlWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } SyndicationFeedFormatter.TraceItemWriteBegin(); WriteItem(writer); SyndicationFeedFormatter.TraceItemWriteEnd(); } public override void ReadFrom(XmlReader reader) { SyndicationFeedFormatter.TraceItemReadBegin(); if (!CanRead(reader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.UnknownItemXml, reader.LocalName, reader.NamespaceURI))); } ReadItem(reader); SyndicationFeedFormatter.TraceItemReadEnd(); } public override void WriteTo(XmlWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } SyndicationFeedFormatter.TraceItemWriteBegin(); writer.WriteStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace); WriteItem(writer); writer.WriteEndElement(); SyndicationFeedFormatter.TraceItemWriteEnd(); } protected override SyndicationItem CreateItemInstance() { return SyndicationItemFormatter.CreateItemInstance(this.itemType); } void ReadItem(XmlReader reader) { SetItem(CreateItemInstance()); feedSerializer.ReadItemFrom(XmlDictionaryReader.CreateDictionaryReader(reader), this.Item); } void WriteItem(XmlWriter writer) { if (this.Item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ItemFormatterDoesNotHaveItem))); } XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(writer); feedSerializer.WriteItemContents(w, this.Item); } } [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] [XmlRoot(ElementName = Rss20Constants.ItemTag, Namespace = Rss20Constants.Rss20Namespace)] public class Rss20ItemFormatter<TSyndicationItem> : Rss20ItemFormatter, IXmlSerializable where TSyndicationItem : SyndicationItem, new () { public Rss20ItemFormatter() : base(typeof(TSyndicationItem)) { } public Rss20ItemFormatter(TSyndicationItem itemToWrite) : base(itemToWrite) { } public Rss20ItemFormatter(TSyndicationItem itemToWrite, bool serializeExtensionsAsAtom) : base(itemToWrite, serializeExtensionsAsAtom) { } protected override SyndicationItem CreateItemInstance() { return new TSyndicationItem(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Avalonia.Platform; namespace Avalonia.Threading { /// <summary> /// A main loop in a <see cref="Dispatcher"/>. /// </summary> internal class JobRunner { private IPlatformThreadingInterface _platform; private readonly Queue<IJob>[] _queues = Enumerable.Range(0, (int) DispatcherPriority.MaxValue + 1) .Select(_ => new Queue<IJob>()).ToArray(); public JobRunner(IPlatformThreadingInterface platform) { _platform = platform; } /// <summary> /// Runs continuations pushed on the loop. /// </summary> /// <param name="priority">Priority to execute jobs for. Pass null if platform doesn't have internal priority system</param> public void RunJobs(DispatcherPriority? priority) { var minimumPriority = priority ?? DispatcherPriority.MinValue; while (true) { var job = GetNextJob(minimumPriority); if (job == null) return; job.Run(); } } /// <summary> /// Invokes a method on the main loop. /// </summary> /// <param name="action">The method.</param> /// <param name="priority">The priority with which to invoke the method.</param> /// <returns>A task that can be used to track the method's execution.</returns> public Task InvokeAsync(Action action, DispatcherPriority priority) { var job = new Job(action, priority, false); AddJob(job); return job.Task; } /// <summary> /// Invokes a method on the main loop. /// </summary> /// <param name="function">The method.</param> /// <param name="priority">The priority with which to invoke the method.</param> /// <returns>A task that can be used to track the method's execution.</returns> public Task<TResult> InvokeAsync<TResult>(Func<TResult> function, DispatcherPriority priority) { var job = new Job<TResult>(function, priority); AddJob(job); return job.Task; } /// <summary> /// Post action that will be invoked on main thread /// </summary> /// <param name="action">The method.</param> /// /// <param name="priority">The priority with which to invoke the method.</param> internal void Post(Action action, DispatcherPriority priority) { AddJob(new Job(action, priority, true)); } /// <summary> /// Allows unit tests to change the platform threading interface. /// </summary> internal void UpdateServices() { _platform = AvaloniaLocator.Current.GetService<IPlatformThreadingInterface>(); } private void AddJob(IJob job) { bool needWake; var queue = _queues[(int) job.Priority]; lock (queue) { needWake = queue.Count == 0; queue.Enqueue(job); } if (needWake) _platform?.Signal(job.Priority); } private IJob GetNextJob(DispatcherPriority minimumPriority) { for (int c = (int) DispatcherPriority.MaxValue; c >= (int) minimumPriority; c--) { var q = _queues[c]; lock (q) { if (q.Count > 0) return q.Dequeue(); } } return null; } private interface IJob { /// <summary> /// Gets the job priority. /// </summary> DispatcherPriority Priority { get; } /// <summary> /// Runs the job. /// </summary> void Run(); } /// <summary> /// A job to run. /// </summary> private sealed class Job : IJob { /// <summary> /// The method to call. /// </summary> private readonly Action _action; /// <summary> /// The task completion source. /// </summary> private readonly TaskCompletionSource<object> _taskCompletionSource; /// <summary> /// Initializes a new instance of the <see cref="Job"/> class. /// </summary> /// <param name="action">The method to call.</param> /// <param name="priority">The job priority.</param> /// <param name="throwOnUiThread">Do not wrap exception in TaskCompletionSource</param> public Job(Action action, DispatcherPriority priority, bool throwOnUiThread) { _action = action; Priority = priority; _taskCompletionSource = throwOnUiThread ? null : new TaskCompletionSource<object>(); } /// <inheritdoc/> public DispatcherPriority Priority { get; } /// <summary> /// The task. /// </summary> public Task Task => _taskCompletionSource?.Task; /// <inheritdoc/> void IJob.Run() { if (_taskCompletionSource == null) { _action(); return; } try { _action(); _taskCompletionSource.SetResult(null); } catch (Exception e) { _taskCompletionSource.SetException(e); } } } /// <summary> /// A job to run. /// </summary> private sealed class Job<TResult> : IJob { private readonly Func<TResult> _function; private readonly TaskCompletionSource<TResult> _taskCompletionSource; /// <summary> /// Initializes a new instance of the <see cref="Job"/> class. /// </summary> /// <param name="function">The method to call.</param> /// <param name="priority">The job priority.</param> public Job(Func<TResult> function, DispatcherPriority priority) { _function = function; Priority = priority; _taskCompletionSource = new TaskCompletionSource<TResult>(); } /// <inheritdoc/> public DispatcherPriority Priority { get; } /// <summary> /// The task. /// </summary> public Task<TResult> Task => _taskCompletionSource.Task; /// <inheritdoc/> void IJob.Run() { try { var result = _function(); _taskCompletionSource.SetResult(result); } catch (Exception e) { _taskCompletionSource.SetException(e); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal static partial class ProcessManager { public static IntPtr GetMainWindowHandle(int processId) { MainWindowFinder finder = new MainWindowFinder(); return finder.FindMainWindow(processId); } } internal sealed class MainWindowFinder { private const int GW_OWNER = 4; private IntPtr _bestHandle; private int _processId; public IntPtr FindMainWindow(int processId) { _bestHandle = (IntPtr)0; _processId = processId; Interop.User32.EnumThreadWindowsCallback callback = new Interop.User32.EnumThreadWindowsCallback(EnumWindowsCallback); Interop.User32.EnumWindows(callback, IntPtr.Zero); GC.KeepAlive(callback); return _bestHandle; } private bool IsMainWindow(IntPtr handle) { if (Interop.User32.GetWindow(handle, GW_OWNER) != (IntPtr)0 || !Interop.User32.IsWindowVisible(handle)) return false; return true; } private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter) { int processId; Interop.User32.GetWindowThreadProcessId(handle, out processId); if (processId == _processId) { if (IsMainWindow(handle)) { _bestHandle = handle; return false; } } return true; } } internal static partial class NtProcessManager { private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (;;) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount); char[] chars = new char[1024]; for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } } IntPtr moduleHandle = moduleHandles[i]; Interop.Kernel32.NtModuleInfo ntModuleInfo; if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo)) { HandleError(); continue; } var module = new ProcessModule() { ModuleMemorySize = ntModuleInfo.SizeOfImage, EntryPointAddress = ntModuleInfo.EntryPoint, BaseAddress = ntModuleInfo.BaseOfDll }; int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.ModuleName = new string(chars, 0, length); length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ? new string(chars, 4, length - 4) : new string(chars, 0, length); modules.Add(module); } return modules; } finally { if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } } internal static class NtProcessInfoHelper { // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif internal static ProcessInfo[] GetProcessInfos(Predicate<int> processIdFilter = null) { int requiredSize = 0; int status; ProcessInfo[] processInfos; // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } unsafe { fixed (long* bufferPtr = buffer) { status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferPtr, bufferSize, out requiredSize); } } if (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(MemoryMarshal.AsBytes<long>(buffer), processIdFilter); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); } return processInfos; } private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } private static unsafe ProcessInfo[] GetProcessInfos(ReadOnlySpan<byte> data, Predicate<int> processIdFilter) { // Use a dictionary to avoid duplicate entries if any // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); int processInformationOffset = 0; while (true) { ref readonly SystemProcessInformation pi = ref MemoryMarshal.AsRef<SystemProcessInformation>(data.Slice(processInformationOffset)); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. int processInfoProcessId = pi.UniqueProcessId.ToInt32(); if (processIdFilter == null || processIdFilter(processInfoProcessId)) { // get information for a process ProcessInfo processInfo = new ProcessInfo(); processInfo.ProcessId = processInfoProcessId; processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; processInfo.HandleCount = (int)pi.HandleCount; if (pi.ImageName.Buffer == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.ImageName.Buffer, pi.ImageName.Length / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; int threadInformationOffset = processInformationOffset + sizeof(SystemProcessInformation); for (int i = 0; i < pi.NumberOfThreads; i++) { ref readonly SystemThreadInformation ti = ref MemoryMarshal.AsRef<SystemThreadInformation>(data.Slice(threadInformationOffset)); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.ClientId.UniqueProcess; threadInfo._threadId = (ulong)ti.ClientId.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); threadInformationOffset += sizeof(SystemThreadInformation); } } if (pi.NextEntryOffset == 0) { break; } processInformationOffset += (int)pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(string name) { if (string.IsNullOrEmpty(name)) { return string.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) ReadOnlySpan<char> extension = name.AsSpan(period); if (extension.Equals(".exe", StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private fixed byte Reserved1[48]; internal Interop.UNICODE_STRING ImageName; internal int BasePriority; internal IntPtr UniqueProcessId; private UIntPtr Reserved2; internal uint HandleCount; internal uint SessionId; private UIntPtr Reserved3; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; private uint Reserved4; internal UIntPtr PeakWorkingSetSize; // SIZE_T internal UIntPtr WorkingSetSize; // SIZE_T private UIntPtr Reserved5; internal UIntPtr QuotaPagedPoolUsage; // SIZE_T private UIntPtr Reserved6; internal UIntPtr QuotaNonPagedPoolUsage; // SIZE_T internal UIntPtr PagefileUsage; // SIZE_T internal UIntPtr PeakPagefileUsage; // SIZE_T internal UIntPtr PrivatePageCount; // SIZE_T private fixed long Reserved7[6]; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct SystemThreadInformation { private fixed long Reserved1[3]; private uint Reserved2; internal IntPtr StartAddress; internal CLIENT_ID ClientId; internal int Priority; internal int BasePriority; private uint Reserved3; internal uint ThreadState; internal uint WaitReason; } [StructLayout(LayoutKind.Sequential)] internal struct CLIENT_ID { internal IntPtr UniqueProcess; internal IntPtr UniqueThread; } } }
/* [nwazet Open Source Software & Open Source Hardware Authors: Fabien Royer Software License Agreement (BSD License) Copyright (c) 2010-2012, Nwazet, LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nwazet, LLC. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * The names '[nwazet', 'nwazet', the ASCII hazelnut in the [nwazet logo and the color of the logo are Trademarks of nwazet, LLC. and cannot be used to endorse or promote products derived from this software or any hardware designs without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Threading; using System.Collections; using Nwazet.Go.Helpers; using Nwazet.Go.Display.TouchScreen; using Nwazet.BmpImage; using GoBus; using Microsoft.SPOT.Hardware; namespace Nwazet.Go.Imaging { public class VirtualCanvas : GoModule { protected enum Command { DrawTestPattern = 'A', DrawPixel = 'B', DrawFill = 'C', DrawLine = 'D', DrawLineDotted = 'E', DrawCircle = 'F', DrawCircleFilled = 'G', DrawCornerFilled = 'H', DrawArrow = 'I', DrawRectangle = 'J', DrawRectangleFilled = 'K', DrawRectangleRounded = 'L', DrawTriangle = 'M', DrawTriangleFilled = 'N', DrawProgressBar = 'O', DrawButton = 'P', DrawIcon16 = 'Q', DrawString = 'R', DrawImageInitialize = 'S', DrawImageData = 'T', SetOrientation = 'U', Synchronicity = 'V', TouchscreenCalibration = 'W', TouchscreenShowDialog = 'X', TouchscreenWaitForEvent = 'Y', Reboot = 'Z', TouchscreenGetCalibrationMatrix = 'a', TouchscreenSetCalibrationMatrix = 'b' } protected enum TouchScreenDataType { String, TouchEvent, CalibrationMatrix } public int Width { get; set; } public int Height { get; set; } public const int MaxSpiTxBufferSize = 1024 * 8; public const int SpiTxBufferHighWatermark = MaxSpiTxBufferSize - 64; public const int MaxSpiRxBufferSize = 1024 * 8; protected BasicTypeSerializerContext SendContext; protected BasicTypeDeSerializerContext ReceiveContext; protected SPI Spi; protected InterruptPort GoBusIrqPort; protected ManualResetEvent GoBusIrqEvent; private byte[] _spiRxBuffer; private bool _moduleReady; public ArrayList RegisteredWidgets; public event TouchEventHandler Touch; public event WidgetClickedHandler WidgetClicked; public VirtualCanvas() : this(null, null) {} public VirtualCanvas(TouchEventHandler touchEventHandler, WidgetClickedHandler widgetClickedHandler) { TrackOrientation(Orientation.Portrait); _spiRxBuffer = new byte[MaxSpiRxBufferSize]; SendContext = new BasicTypeSerializerContext(MaxSpiTxBufferSize, SpiTxBufferHighWatermark, OnCanvasBufferNearlyFull); ReceiveContext = new BasicTypeDeSerializerContext(); GoBusIrqEvent = new ManualResetEvent(false); RegisteredWidgets = new ArrayList(); if (widgetClickedHandler != null) { WidgetClicked += widgetClickedHandler; } if (touchEventHandler != null) { Touch += touchEventHandler; } } ~VirtualCanvas() { Dispose(true); } public void Initialize(GoSocket socket, uint speedKHz = 25000) { if (speedKHz < 5000 || speedKHz > 40000) throw new ArgumentException("speedKHz"); if (socket == null) throw new ArgumentNullException("socket"); SPI.SPI_module displaySpi; Cpu.Pin displayChipSelect; Cpu.Pin displayGPIO; socket.GetPhysicalResources(out displayGPIO, out displaySpi, out displayChipSelect); if (!BindSocket(socket)) throw new InvalidOperationException("socket already bound"); SetSocketPowerState(false); Thread.Sleep(2000); SetSocketPowerState(true); Thread.Sleep(250); Spi = new SPI(new SPI.Configuration( SPI_mod: displaySpi, ChipSelect_Port: displayChipSelect, ChipSelect_ActiveState: false, ChipSelect_SetupTime: 0, ChipSelect_HoldTime: 0, Clock_IdleState: false, Clock_Edge: false, Clock_RateKHz: speedKHz)); GoBusIrqPort = new InterruptPort(displayGPIO, false, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLow); GoBusIrqPort.OnInterrupt += OnGoBusIrq; WaitUntilModuleIsInitialized(); } protected void OnCanvasBufferNearlyFull() { Execute(); } public void RegisterWidget(Widget widget) { if (RegisteredWidgets.Contains(widget)) return; RegisteredWidgets.Add(widget); } public void UnRegisterWidget(Widget widget) { if (!RegisteredWidgets.Contains(widget)) return; RegisteredWidgets.Remove(widget); } public void UnRegisterAllWidgets() { RegisteredWidgets.Clear(); } public void RenderWidgets(Render renderOption = Render.Dirty) { if (renderOption == Render.All) { foreach (Widget widget in RegisteredWidgets) { widget.Dirty = true; widget.Draw(this); } } else { foreach (Widget widget in RegisteredWidgets) { widget.Draw(this); } } } public void ActivateWidgets(bool active) { foreach (Widget widget in RegisteredWidgets) { widget.Active = active; } } protected override void Dispose(bool disposing) { Spi.Dispose(); GoBusIrqPort.Dispose(); SendContext.Dispose(); ReceiveContext.Dispose(); _spiRxBuffer = null; WidgetClicked = null; Touch = null; RegisteredWidgets = null; GoBusIrqEvent = null; SetSocketPowerState(false); base.Dispose(disposing); } private void OnGoBusIrq(UInt32 data1, UInt32 data2, DateTime timestamp) { GoBusIrqPort.ClearInterrupt(); GoBusIrqEvent.Set(); } public void Execute(Synchronicity sync = Synchronicity.Synchronous) { SetSynchronicity(sync); int contentSize; var spiTxBuffer = SendContext.GetBuffer(out contentSize); if (contentSize >= MaxSpiTxBufferSize) { throw new ApplicationException("contentSize"); } GoBusIrqEvent.Reset(); Spi.WriteRead(spiTxBuffer, 0, MaxSpiTxBufferSize, _spiRxBuffer, 0, MaxSpiRxBufferSize, 0); if (sync == Synchronicity.Synchronous) { WaitUntilGoBusIrqIsAsserted(); } } private void Receive() { Execute(); ReceiveContext.Bind(_spiRxBuffer, BasicTypeDeSerializerContext.BufferStartOffsetDefault); } public void WaitUntilGoBusIrqIsAsserted() { GoBusIrqEvent.WaitOne(); } private const byte _identifier8bitCrc = 54; public void WaitUntilModuleIsInitialized() { while (!_moduleReady) { Execute(Synchronicity.Asynchronous); if (_spiRxBuffer[0] == 0x80 && _spiRxBuffer[1] == '[' && _spiRxBuffer[2] == 'n' && _spiRxBuffer[3] == 'w' && _spiRxBuffer[4] == 'a' && _spiRxBuffer[5] == 'z' && _spiRxBuffer[6] == 'e' && _spiRxBuffer[7] == 't' && _spiRxBuffer[8] == '.' && _spiRxBuffer[9] == 'd' && _spiRxBuffer[10] == 'i' && _spiRxBuffer[11] == 's' && _spiRxBuffer[12] == 'p') { if (_spiRxBuffer[17] != _identifier8bitCrc) throw new ApplicationException("SPI data corruption"); _moduleReady = true; return; } Thread.Sleep(200); } } public void DrawTestPattern() { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawTestPattern); SendContext.CheckHighWatermark(); } public void DrawPixel(int x, int y, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawPixel); BasicTypeSerializer.Put(SendContext,(ushort)x); BasicTypeSerializer.Put(SendContext,(ushort)y); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawFill(ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawFill); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawLine(int x0, int y0, int x1, int y1, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawLine); BasicTypeSerializer.Put(SendContext,(ushort)x0); BasicTypeSerializer.Put(SendContext,(ushort)y0); BasicTypeSerializer.Put(SendContext,(ushort)x1); BasicTypeSerializer.Put(SendContext,(ushort)y1); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawLineDotted(int x0, int y0, int x1, int y1, int empty, int solid, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawLineDotted); BasicTypeSerializer.Put(SendContext,(ushort)x0); BasicTypeSerializer.Put(SendContext,(ushort)y0); BasicTypeSerializer.Put(SendContext,(ushort)x1); BasicTypeSerializer.Put(SendContext,(ushort)y1); BasicTypeSerializer.Put(SendContext,(ushort)empty); BasicTypeSerializer.Put(SendContext,(ushort)solid); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawCircle(int xCenter, int yCenter, int radius, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawCircle); BasicTypeSerializer.Put(SendContext,(ushort)xCenter); BasicTypeSerializer.Put(SendContext,(ushort)yCenter); BasicTypeSerializer.Put(SendContext,(ushort)radius); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawCircleFilled(int xCenter, int yCenter, int radius, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawCircleFilled); BasicTypeSerializer.Put(SendContext,(ushort)xCenter); BasicTypeSerializer.Put(SendContext,(ushort)yCenter); BasicTypeSerializer.Put(SendContext,(ushort)radius); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawCornerFilled(int xCenter, int yCenter, int radius, CornerPosition position, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawCornerFilled); BasicTypeSerializer.Put(SendContext,(ushort)xCenter); BasicTypeSerializer.Put(SendContext,(ushort)yCenter); BasicTypeSerializer.Put(SendContext,(ushort)radius); BasicTypeSerializer.Put(SendContext,(ushort)position); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawArrow(int x, int y, int size, DrawingDirection direction, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawArrow); BasicTypeSerializer.Put(SendContext,(ushort)x); BasicTypeSerializer.Put(SendContext,(ushort)y); BasicTypeSerializer.Put(SendContext,(ushort)size); BasicTypeSerializer.Put(SendContext,(ushort)direction); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawRectangle(int x0, int y0, int x1, int y1, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawRectangle); BasicTypeSerializer.Put(SendContext,(ushort)x0); BasicTypeSerializer.Put(SendContext,(ushort)y0); BasicTypeSerializer.Put(SendContext,(ushort)x1); BasicTypeSerializer.Put(SendContext,(ushort)y1); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawRectangleFilled(int x0, int y0, int x1, int y1, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawRectangleFilled); BasicTypeSerializer.Put(SendContext,(ushort)x0); BasicTypeSerializer.Put(SendContext,(ushort)y0); BasicTypeSerializer.Put(SendContext,(ushort)x1); BasicTypeSerializer.Put(SendContext,(ushort)y1); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawRectangleRounded(int x0, int y0, int x1, int y1, ushort color, int radius, RoundedCornerStyle corners) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawRectangleRounded); BasicTypeSerializer.Put(SendContext,(ushort)x0); BasicTypeSerializer.Put(SendContext,(ushort)y0); BasicTypeSerializer.Put(SendContext,(ushort)x1); BasicTypeSerializer.Put(SendContext,(ushort)y1); BasicTypeSerializer.Put(SendContext,(ushort)color); BasicTypeSerializer.Put(SendContext,(ushort)radius); BasicTypeSerializer.Put(SendContext,(ushort)corners); SendContext.CheckHighWatermark(); } public void DrawTriangle(int x0, int y0, int x1, int y1, int x2, int y2, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawTriangle); BasicTypeSerializer.Put(SendContext,(ushort)x0); BasicTypeSerializer.Put(SendContext,(ushort)y0); BasicTypeSerializer.Put(SendContext,(ushort)x1); BasicTypeSerializer.Put(SendContext,(ushort)y1); BasicTypeSerializer.Put(SendContext,(ushort)x2); BasicTypeSerializer.Put(SendContext,(ushort)y2); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawTriangleFilled(int x0, int y0, int x1, int y1, int x2, int y2, ushort color) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawTriangleFilled); BasicTypeSerializer.Put(SendContext,(ushort)x0); BasicTypeSerializer.Put(SendContext,(ushort)y0); BasicTypeSerializer.Put(SendContext,(ushort)x1); BasicTypeSerializer.Put(SendContext,(ushort)y1); BasicTypeSerializer.Put(SendContext,(ushort)x2); BasicTypeSerializer.Put(SendContext,(ushort)y2); BasicTypeSerializer.Put(SendContext,(ushort)color); SendContext.CheckHighWatermark(); } public void DrawProgressBar( int x, int y, int width, int height, RoundedCornerStyle borderCorners, RoundedCornerStyle progressCorners, ushort borderColor, ushort borderFillColor, ushort progressBorderColor, ushort progressFillColor, int progress) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawProgressBar); BasicTypeSerializer.Put(SendContext,(ushort)x); BasicTypeSerializer.Put(SendContext,(ushort)y); BasicTypeSerializer.Put(SendContext,(ushort)width); BasicTypeSerializer.Put(SendContext,(ushort)height); BasicTypeSerializer.Put(SendContext,(ushort)borderCorners); BasicTypeSerializer.Put(SendContext,(ushort)progressCorners); BasicTypeSerializer.Put(SendContext,(ushort)borderColor); BasicTypeSerializer.Put(SendContext,(ushort)borderFillColor); BasicTypeSerializer.Put(SendContext,(ushort)progressBorderColor); BasicTypeSerializer.Put(SendContext,(ushort)progressFillColor); BasicTypeSerializer.Put(SendContext,(ushort)progress); SendContext.CheckHighWatermark(); } public void DrawButton( int x, int y, int width, int height, ushort fontID, int fontHeight, ushort borderColor, ushort fillColor, ushort fontColor, string text, RoundedCornerStyle cornerStyle = RoundedCornerStyle.All) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawButton); BasicTypeSerializer.Put(SendContext,(ushort)x); BasicTypeSerializer.Put(SendContext,(ushort)y); BasicTypeSerializer.Put(SendContext,(ushort)width); BasicTypeSerializer.Put(SendContext,(ushort)height); BasicTypeSerializer.Put(SendContext,(ushort)fontID); BasicTypeSerializer.Put(SendContext,(ushort)fontHeight); BasicTypeSerializer.Put(SendContext,(ushort)borderColor); BasicTypeSerializer.Put(SendContext,(ushort)fillColor); BasicTypeSerializer.Put(SendContext,(ushort)fontColor); BasicTypeSerializer.Put(SendContext,text, true); BasicTypeSerializer.Put(SendContext,(ushort)cornerStyle); SendContext.CheckHighWatermark(); } public void DrawIcon16(int x, int y, ushort color, ushort[] icon) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawIcon16); BasicTypeSerializer.Put(SendContext,(ushort)x); BasicTypeSerializer.Put(SendContext,(ushort)y); BasicTypeSerializer.Put(SendContext,(ushort)color); BasicTypeSerializer.Put(SendContext,icon); SendContext.CheckHighWatermark(); } public void DrawString(int x, int y, ushort color, ushort fontID, string text) { BasicTypeSerializer.Put(SendContext,(byte)Command.DrawString); BasicTypeSerializer.Put(SendContext,(ushort)x); BasicTypeSerializer.Put(SendContext,(ushort)y); BasicTypeSerializer.Put(SendContext,(ushort)color); BasicTypeSerializer.Put(SendContext,(ushort)fontID); BasicTypeSerializer.Put(SendContext,text, true); SendContext.CheckHighWatermark(); } private const int _maxImageChunkSize = MaxSpiTxBufferSize - 128; protected enum BytesPerPixel { Two = 2, Three = 3 } public void DrawBitmapImage(int x, int y, string filename) { using (var bmpStream = new FileStream(filename, FileMode.Open)) { var bmpImageInfo = BmpImageHeaderReader.Read(bmpStream); if (bmpImageInfo.Width > Width || bmpImageInfo.Height > Height) throw new ArgumentOutOfRangeException("Dimensions"); var imageChunk = new byte[_maxImageChunkSize]; DrawImageInitialize(x, y, bmpImageInfo.Width, bmpImageInfo.Height, BytesPerPixel.Three); var offset = bmpStream.Length; var bytesLeft = (long)bmpImageInfo.ImageSizeInBytes; var bmpImageRowLengthInBytes = bmpImageInfo.Width * (int)BytesPerPixel.Three; var maxBmpImageChunkSize = (_maxImageChunkSize / bmpImageRowLengthInBytes) * bmpImageRowLengthInBytes; while (bytesLeft != 0) { var bytesInChunk = (int)Math.Min(bytesLeft, maxBmpImageChunkSize); offset -= bytesInChunk; bytesLeft -= bytesInChunk; bmpStream.Seek(offset, SeekOrigin.Begin); var bytesRead = bmpStream.Read(imageChunk, 0, bytesInChunk); TransferImage(imageChunk, bytesRead); } } } public void DrawBitmapImageRaw(int x, int y, int width, int height, byte[] bytes) { DrawImageInitialize(x, y, width, height, BytesPerPixel.Two); TransferImage(bytes, bytes.Length); } protected void TransferImage(byte[] bytes, int imageSize) { ushort offset = 0; var maxImageChunkSize = _maxImageChunkSize; while (offset < imageSize) { var count = (ushort)Math.Min(maxImageChunkSize, imageSize - offset); DrawImageData(bytes, offset, count); Execute(); offset += count; } } protected void DrawImageInitialize(int x, int y, int width, int height, BytesPerPixel bytesPerPixel) { BasicTypeSerializer.Put(SendContext, (byte)Command.DrawImageInitialize); BasicTypeSerializer.Put(SendContext, (ushort)x); BasicTypeSerializer.Put(SendContext, (ushort)y); BasicTypeSerializer.Put(SendContext, (ushort)width); BasicTypeSerializer.Put(SendContext, (ushort)height); BasicTypeSerializer.Put(SendContext, (ushort)bytesPerPixel); } protected void DrawImageData(byte[] bytes, ushort offset, ushort count) { BasicTypeSerializer.Put(SendContext, (byte)Command.DrawImageData); BasicTypeSerializer.Put(SendContext, bytes, offset, count); } public void SetOrientation(Orientation orientation) { BasicTypeSerializer.Put(SendContext,(byte)Command.SetOrientation); BasicTypeSerializer.Put(SendContext,(ushort)orientation); SendContext.CheckHighWatermark(); TrackOrientation(orientation); } private void TrackOrientation(Orientation orientation) { if (orientation == Orientation.Portrait) { Width = 240; Height = 320; } else { Height = 240; Width = 320; } } protected void SetSynchronicity(Synchronicity sync) { BasicTypeSerializer.Put(SendContext, (byte)Command.Synchronicity); BasicTypeSerializer.Put(SendContext, (byte)sync); } public void TouchscreenCalibration() { BasicTypeSerializer.Put(SendContext, (byte)Command.TouchscreenCalibration); Execute(); } public string TouchscreenShowDialog(DialogType dialogType) { BasicTypeSerializer.Put(SendContext, (byte)Command.TouchscreenShowDialog); BasicTypeSerializer.Put(SendContext, (ushort)dialogType); Execute(); Receive(); TouchScreenDataType eventType = (TouchScreenDataType) BasicTypeDeSerializer.Get(ReceiveContext); if (eventType != TouchScreenDataType.String) { throw new ApplicationException("eventType"); } return BasicTypeDeSerializer.Get(ReceiveContext, ""); } public void TouchscreenWaitForEvent(TouchScreenEventMode mode = TouchScreenEventMode.Blocking) { BasicTypeSerializer.Put(SendContext, (byte)Command.TouchscreenWaitForEvent); BasicTypeSerializer.Put(SendContext, (byte)mode); Execute(); Receive(); TouchScreenDataType eventType = (TouchScreenDataType)BasicTypeDeSerializer.Get(ReceiveContext); if (eventType != TouchScreenDataType.TouchEvent) { throw new ApplicationException("eventType"); } var touchEvent = new TouchEvent(); touchEvent.X = BasicTypeDeSerializer.Get(ReceiveContext, touchEvent.X); touchEvent.Y = BasicTypeDeSerializer.Get(ReceiveContext, touchEvent.Y); touchEvent.Pressure = BasicTypeDeSerializer.Get(ReceiveContext, touchEvent.Pressure); touchEvent.IsValid = BasicTypeDeSerializer.Get(ReceiveContext); OnTouch(touchEvent); if (WidgetClicked != null && touchEvent.IsValid != 0) { foreach (Widget widget in RegisteredWidgets) { widget.OnClickEvent(touchEvent); if (widget.Clicked) { WidgetClicked(this, widget, touchEvent); } } } } protected void OnWidgetClicked(Widget widget, TouchEvent touchEvent) { if (WidgetClicked != null) { WidgetClicked(this, widget, touchEvent); } } protected void OnTouch(TouchEvent touchEvent) { if (Touch != null) { Touch(this, touchEvent); } } public void Reboot() { BasicTypeSerializer.Put(SendContext, (byte)Command.Reboot); Execute(Synchronicity.Asynchronous); } public CalibrationMatrix GetTouchscreenCalibrationMatrix() { BasicTypeSerializer.Put(SendContext, (byte)Command.TouchscreenGetCalibrationMatrix); Execute(); Receive(); TouchScreenDataType eventType = (TouchScreenDataType)BasicTypeDeSerializer.Get(ReceiveContext); if (eventType != TouchScreenDataType.CalibrationMatrix) { throw new ApplicationException("eventType"); } var matrix = new CalibrationMatrix(); matrix.Get(ReceiveContext); return matrix; } public void SetTouchscreenCalibrationMatrix(CalibrationMatrix matrix) { BasicTypeSerializer.Put(SendContext, (byte)Command.TouchscreenSetCalibrationMatrix); matrix.Put(SendContext); Execute(); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 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; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Configuration; using Orleans.Runtime.Scheduler; using Orleans.Runtime.ConsistentRing; namespace Orleans.Runtime.ReminderService { internal class LocalReminderService : SystemTarget, IReminderService, IRingRangeListener { private enum ReminderServiceStatus { Booting = 0, Started, Stopped, } private readonly Dictionary<ReminderIdentity, LocalReminderData> localReminders; private readonly IConsistentRingProvider ring; private readonly IReminderTable reminderTable; private readonly OrleansTaskScheduler scheduler; private ReminderServiceStatus status; private IRingRange myRange; private long localTableSequence; private GrainTimer listRefresher; // timer that refreshes our list of reminders to reflect global reminder table private readonly TaskCompletionSource<bool> startedTask; private readonly AverageTimeSpanStatistic tardinessStat; private readonly CounterStatistic ticksDeliveredStat; private readonly TraceLogger logger; private readonly GlobalConfiguration config; private readonly TimeSpan initTimeout; internal LocalReminderService( SiloAddress addr, GrainId id, IConsistentRingProvider ring, OrleansTaskScheduler localScheduler, IReminderTable reminderTable, GlobalConfiguration config, TimeSpan initTimeout) : base(id, addr) { logger = TraceLogger.GetLogger("ReminderService", TraceLogger.LoggerType.Runtime); localReminders = new Dictionary<ReminderIdentity, LocalReminderData>(); this.ring = ring; scheduler = localScheduler; this.reminderTable = reminderTable; this.config = config; this.initTimeout = initTimeout; status = ReminderServiceStatus.Booting; myRange = null; localTableSequence = 0; tardinessStat = AverageTimeSpanStatistic.FindOrCreate(StatisticNames.REMINDERS_AVERAGE_TARDINESS_SECONDS); IntValueStatistic.FindOrCreate(StatisticNames.REMINDERS_NUMBER_ACTIVE_REMINDERS, () => localReminders.Count); ticksDeliveredStat = CounterStatistic.FindOrCreate(StatisticNames.REMINDERS_COUNTERS_TICKS_DELIVERED); startedTask = new TaskCompletionSource<bool>(); } #region Public methods /// <summary> /// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance) /// </summary> /// <returns></returns> public async Task Start() { myRange = ring.GetMyRange(); logger.Info(ErrorCode.RS_ServiceStarting, "Starting reminder system target on: {0} x{1,8:X8}, with range {2}", Silo, Silo.GetConsistentHashCode(), myRange); await reminderTable.Init(config.ServiceId, config.DeploymentId, config.DataConnectionString).WithTimeout(initTimeout); await ReadAndUpdateReminders(); logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", Silo, Silo.GetConsistentHashCode(), myRange); status = ReminderServiceStatus.Started; startedTask.TrySetResult(true); var random = new SafeRandom(); var dueTime = random.NextTimeSpan(Constants.RefreshReminderList); listRefresher = GrainTimer.FromTaskCallback( _ => ReadAndUpdateReminders(), null, dueTime, Constants.RefreshReminderList, name: "ReminderService.ReminderListRefresher"); listRefresher.Start(); ring.SubscribeToRangeChangeEvents(this); } public Task Stop() { logger.Info(ErrorCode.RS_ServiceStopping, "Stopping reminder system target"); status = ReminderServiceStatus.Stopped; ring.UnSubscribeFromRangeChangeEvents(this); if (listRefresher != null) { listRefresher.Dispose(); listRefresher = null; } foreach (LocalReminderData r in localReminders.Values) r.StopReminder(logger); // for a graceful shutdown, also handover reminder responsibilities to new owner, and update the ReminderTable // currently, this is taken care of by periodically reading the reminder table return TaskDone.Done; } public async Task<IGrainReminder> RegisterOrUpdateReminder(GrainReference grainRef, string reminderName, TimeSpan dueTime, TimeSpan period) { var entry = new ReminderEntry { GrainRef = grainRef, ReminderName = reminderName, StartAt = DateTime.UtcNow.Add(dueTime), Period = period, }; if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_RegisterOrUpdate, "RegisterOrUpdateReminder: {0}", entry.ToString()); await DoResponsibilitySanityCheck(grainRef, "RegisterReminder"); var newEtag = await reminderTable.UpsertRow(entry); if (newEtag != null) { if (logger.IsVerbose) logger.Verbose("Registered reminder {0} in table, assigned localSequence {1}", entry, localTableSequence); entry.ETag = newEtag; StartAndAddTimer(entry); if (logger.IsVerbose3) PrintReminders(); return new ReminderData(grainRef, reminderName, newEtag) as IGrainReminder; } var msg = string.Format("Could not register reminder {0} to reminder table due to a race. Please try again later.", entry); logger.Error(ErrorCode.RS_Register_TableError, msg); throw new ReminderException(msg); } /// <summary> /// Stop the reminder locally, and remove it from the external storage system /// </summary> /// <param name="reminder"></param> /// <returns></returns> public async Task UnregisterReminder(IGrainReminder reminder) { var remData = (ReminderData)reminder; if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_Unregister, "UnregisterReminder: {0}, LocalTableSequence: {1}", remData, localTableSequence); GrainReference grainRef = remData.GrainRef; string reminderName = remData.ReminderName; string eTag = remData.ETag; await DoResponsibilitySanityCheck(grainRef, "RemoveReminder"); // it may happen that we dont have this reminder locally ... even then, we attempt to remove the reminder from the reminder // table ... the periodic mechanism will stop this reminder at any silo's LocalReminderService that might have this reminder locally // remove from persistent/memory store var success = await reminderTable.RemoveRow(grainRef, reminderName, eTag); if (success) { bool removed = TryStopPreviousTimer(grainRef, reminderName); if (removed) { if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_Stop, "Stopped reminder {0}", reminder); if (logger.IsVerbose3) PrintReminders(string.Format("After removing {0}.", reminder)); } else { // no-op if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_RemoveFromTable, "Removed reminder from table which I didn't have locally: {0}.", reminder); } } else { var msg = string.Format("Could not unregister reminder {0} from the reminder table, due to tag mismatch. You can retry.", reminder); logger.Error(ErrorCode.RS_Unregister_TableError, msg); throw new ReminderException(msg); } } public async Task<IGrainReminder> GetReminder(GrainReference grainRef, string reminderName) { if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_GetReminder,"GetReminder: GrainReference={0} ReminderName={1}", grainRef.ToDetailedString(), reminderName); var entry = await reminderTable.ReadRow(grainRef, reminderName); return entry.ToIGrainReminder(); } public async Task<List<IGrainReminder>> GetReminders(GrainReference grainRef) { if (logger.IsVerbose) logger.Verbose(ErrorCode.RS_GetReminders, "GetReminders: GrainReference={0}", grainRef.ToDetailedString()); var tableData = await reminderTable.ReadRows(grainRef); return tableData.Reminders.Select(entry => entry.ToIGrainReminder()).ToList(); } #endregion /// <summary> /// Attempt to retrieve reminders from the global reminder table /// </summary> private async Task ReadAndUpdateReminders() { // try to retrieve reminder from all my subranges myRange = ring.GetMyRange(); if (logger.IsVerbose2) logger.Verbose2("My range= {0}", myRange); var acks = new List<Task>(); foreach (SingleRange range in RangeFactory.GetSubRanges(myRange)) { if (logger.IsVerbose2) logger.Verbose2("Reading rows for range {0}", range); acks.Add(ReadTableAndStartTimers(range)); } await Task.WhenAll(acks); if (logger.IsVerbose3) PrintReminders(); } #region Change in membership, e.g., failure of predecessor /// <summary> /// Actions to take when the range of this silo changes on the ring due to a failure or a join /// </summary> /// <param name="old">my previous responsibility range</param> /// <param name="now">my new/current responsibility range</param> /// <param name="increased">True: my responsibility increased, false otherwise</param> public void RangeChangeNotification(IRingRange old, IRingRange now, bool increased) { // run on my own turn & context scheduler.QueueTask(() => OnRangeChange(old, now, increased), this.SchedulingContext).Ignore(); } private async Task OnRangeChange(IRingRange oldRange, IRingRange newRange, bool increased) { logger.Info(ErrorCode.RS_RangeChanged, "My range changed from {0} to {1} increased = {2}", oldRange, newRange, increased); myRange = newRange; if (status == ReminderServiceStatus.Started) await ReadAndUpdateReminders(); else if (logger.IsVerbose) logger.Verbose("Ignoring range change until ReminderService is Started -- Current status = {0}", status); } #endregion #region Internal implementation methods private async Task ReadTableAndStartTimers(IRingRange range) { if (logger.IsVerbose) logger.Verbose("Reading rows from {0}", range.ToString()); localTableSequence++; long cachedSequence = localTableSequence; try { var srange = (SingleRange)range; ReminderTableData table = await reminderTable.ReadRows(srange.Begin, srange.End); // get all reminders, even the ones we already have // if null is a valid value, it means that there's nothing to do. if (null == table && reminderTable is MockReminderTable) return; var remindersNotInTable = new Dictionary<ReminderIdentity, LocalReminderData>(localReminders); // shallow copy if (logger.IsVerbose) logger.Verbose("For range {0}, I read in {1} reminders from table. LocalTableSequence {2}, CachedSequence {3}", range.ToString(), table.Reminders.Count, localTableSequence, cachedSequence); foreach (ReminderEntry entry in table.Reminders) { var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName); LocalReminderData localRem; if (localReminders.TryGetValue(key, out localRem)) { if (cachedSequence > localRem.LocalSequenceNumber) // info read from table is same or newer than local info { if (localRem.Timer != null) // if ticking { if (logger.IsVerbose2) logger.Verbose2("In table, In local, Old, & Ticking {0}", localRem); // it might happen that our local reminder is different than the one in the table, i.e., eTag is different // if so, stop the local timer for the old reminder, and start again with new info if (!localRem.ETag.Equals(entry.ETag)) // this reminder needs a restart { if (logger.IsVerbose2) logger.Verbose2("{0} Needs a restart", localRem); localRem.StopReminder(logger); localReminders.Remove(localRem.Identity); if (ring.GetMyRange().InRange(entry.GrainRef)) // if its not my responsibility, I shouldn't start it locally { StartAndAddTimer(entry); } } } else // if not ticking { // no-op if (logger.IsVerbose2) logger.Verbose2("In table, In local, Old, & Not Ticking {0}", localRem); } } else // cachedSequence < localRem.LocalSequenceNumber ... // info read from table is older than local info { if (localRem.Timer != null) // if ticking { // no-op if (logger.IsVerbose2) logger.Verbose2("In table, In local, Newer, & Ticking {0}", localRem); } else // if not ticking { // no-op if (logger.IsVerbose2) logger.Verbose2("In table, In local, Newer, & Not Ticking {0}", localRem); } } } else // exists in table, but not locally { if (logger.IsVerbose2) logger.Verbose2("In table, Not in local, {0}", entry); // create and start the reminder if (ring.GetMyRange().InRange(entry.GrainRef)) // if its not my responsibility, I shouldn't start it locally StartAndAddTimer(entry); } // keep a track of extra reminders ... this 'reminder' is useful, so remove it from extra list remindersNotInTable.Remove(new ReminderIdentity(entry.GrainRef, entry.ReminderName)); } // foreach reminder read from table // foreach reminder that is not in global table, but exists locally foreach (var reminder in remindersNotInTable.Values) { if (cachedSequence < reminder.LocalSequenceNumber) { // no-op if (logger.IsVerbose2) logger.Verbose2("Not in table, In local, Newer, {0}", reminder); } else // cachedSequence > reminder.LocalSequenceNumber { if (logger.IsVerbose2) logger.Verbose2("Not in table, In local, Old, so removing. {0}", reminder); // remove locally reminder.StopReminder(logger); localReminders.Remove(reminder.Identity); } } } catch (Exception exc) { logger.Error(ErrorCode.RS_FailedToReadTableAndStartTimer, "Failed to read rows from table.", exc); throw; } } private void StartAndAddTimer(ReminderEntry entry) { // it might happen that we already have a local reminder with a different eTag // if so, stop the local timer for the old reminder, and start again with new info // Note: it can happen here that we restart a reminder that has the same eTag as what we just registered ... its a rare case, and restarting it doesn't hurt, so we don't check for it var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName); LocalReminderData prevReminder; if (localReminders.TryGetValue(key, out prevReminder)) // if found locally { if (logger.IsVerbose) logger.Verbose(ErrorCode.RS_LocalStop, "Localy stopping reminder {0} as it is different than newly registered reminder {1}", prevReminder, entry); prevReminder.StopReminder(logger); localReminders.Remove(prevReminder.Identity); } var newReminder = new LocalReminderData(entry); localTableSequence++; newReminder.LocalSequenceNumber = localTableSequence; localReminders.Add(newReminder.Identity, newReminder); newReminder.StartTimer(AsyncTimerCallback, logger); if (logger.IsVerbose) logger.Verbose(ErrorCode.RS_Started, "Started reminder {0}.", entry.ToString()); } // stop without removing it. will remove later. private bool TryStopPreviousTimer(GrainReference grainRef, string reminderName) { // we stop the locally running timer for this reminder var key = new ReminderIdentity(grainRef, reminderName); LocalReminderData localRem; if (!localReminders.TryGetValue(key, out localRem)) return false; // if we have it locally localTableSequence++; // move to next sequence localRem.LocalSequenceNumber = localTableSequence; localRem.StopReminder(logger); return true; } #endregion /// <summary> /// Local timer expired ... notify it as a 'tick' to the grain who registered this reminder /// </summary> /// <param name="rem">Reminder that this timeout represents</param> private async Task AsyncTimerCallback(object rem) { var reminder = (LocalReminderData)rem; if (!localReminders.ContainsKey(reminder.Identity) // we have already stopped this timer || reminder.Timer == null) // this timer was unregistered, and is waiting to be gc-ied return; ticksDeliveredStat.Increment(); await reminder.OnTimerTick(tardinessStat, logger); } #region Utility (less useful) methods private async Task DoResponsibilitySanityCheck(GrainReference grainRef, string debugInfo) { if (status != ReminderServiceStatus.Started) await startedTask.Task; if (!myRange.InRange(grainRef)) { logger.Warn(ErrorCode.RS_NotResponsible, "I shouldn't have received request '{0}' for {1}. It is not in my responsibility range: {2}", debugInfo, grainRef.ToDetailedString(), myRange); // For now, we still let the caller proceed without throwing an exception... the periodical mechanism will take care of reminders being registered at the wrong silo // otherwise, we can either reject the request, or re-route the request } } // Note: The list of reminders can be huge in production! private void PrintReminders(string msg = null) { if (!logger.IsVerbose3) return; var str = String.Format("{0}{1}{2}", (msg ?? "Current list of reminders:"), Environment.NewLine, Utils.EnumerableToString(localReminders, null, Environment.NewLine)); logger.Verbose3(str); } #endregion private class LocalReminderData { private readonly IRemindable remindable; private Stopwatch stopwatch; private readonly DateTime firstTickTime; // time for the first tick of this reminder private readonly TimeSpan period; private GrainReference GrainRef { get { return Identity.GrainRef; } } private string ReminderName { get { return Identity.ReminderName; } } internal ReminderIdentity Identity { get; private set; } internal string ETag; internal GrainTimer Timer; internal long LocalSequenceNumber; // locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests internal LocalReminderData(ReminderEntry entry) { Identity = new ReminderIdentity(entry.GrainRef, entry.ReminderName); firstTickTime = entry.StartAt; period = entry.Period; remindable = entry.GrainRef.Cast<IRemindable>(); ETag = entry.ETag; LocalSequenceNumber = -1; } public void StartTimer(Func<object, Task> asyncCallback, TraceLogger logger) { StopReminder(logger); // just to make sure. var dueTimeSpan = CalculateDueTime(); Timer = GrainTimer.FromTaskCallback(asyncCallback, this, dueTimeSpan, period, name: ReminderName); if (logger.IsVerbose) logger.Verbose("Reminder {0}, Due time{1}", this, dueTimeSpan); Timer.Start(); } public void StopReminder(TraceLogger logger) { if (Timer != null) Timer.Dispose(); Timer = null; } private TimeSpan CalculateDueTime() { TimeSpan dueTimeSpan; var now = DateTime.UtcNow; if (now < firstTickTime) // if the time for first tick hasn't passed yet { dueTimeSpan = firstTickTime.Subtract(now); // then duetime is duration between now and the first tick time } else // the first tick happened in the past ... compute duetime based on the first tick time, and period { // formula used: // due = period - 'time passed since last tick (==sinceLast)' // due = period - ((Now - FirstTickTime) % period) // explanation of formula: // (Now - FirstTickTime) => gives amount of time since first tick happened // (Now - FirstTickTime) % period => gives amount of time passed since the last tick should have triggered var sinceFirstTick = now.Subtract(firstTickTime); var sinceLastTick = TimeSpan.FromTicks(sinceFirstTick.Ticks % period.Ticks); dueTimeSpan = period.Subtract(sinceLastTick); // in corner cases, dueTime can be equal to period ... so, take another mod dueTimeSpan = TimeSpan.FromTicks(dueTimeSpan.Ticks % period.Ticks); } return dueTimeSpan; } public async Task OnTimerTick(AverageTimeSpanStatistic tardinessStat, TraceLogger logger) { var before = DateTime.UtcNow; var status = TickStatus.NewStruct(firstTickTime, period, before); if (logger.IsVerbose2) logger.Verbose2("Triggering tick for {0}, status {1}, now {2}", this.ToString(), status, before); try { if (null != stopwatch) { stopwatch.Stop(); var tardiness = stopwatch.Elapsed - period; tardinessStat.AddSample(Math.Max(0, tardiness.Ticks)); } await remindable.ReceiveReminder(ReminderName, status); if (null == stopwatch) stopwatch = new Stopwatch(); stopwatch.Restart(); var after = DateTime.UtcNow; if (logger.IsVerbose2) logger.Verbose2("Tick triggered for {0}, dt {1} sec, next@~ {2}", this.ToString(), (after - before).TotalSeconds, // the next tick isn't actually scheduled until we return control to // AsyncSafeTimer but we can approximate it by adding the period of the reminder // to the after time. after + period); } catch (Exception exc) { var after = DateTime.UtcNow; logger.Error( ErrorCode.RS_Tick_Delivery_Error, String.Format("Could not deliver reminder tick for {0}, next {1}.", this.ToString(), after + period), exc); // What to do with repeated failures to deliver a reminder's ticks? } } public override string ToString() { return string.Format("[{0}, {1}, {2}, {3}, {4}, {5}, {6}]", ReminderName, GrainRef.ToDetailedString(), period, TraceLogger.PrintDate(firstTickTime), ETag, LocalSequenceNumber, Timer == null ? "Not_ticking" : "Ticking"); } } private struct ReminderIdentity : IEquatable<ReminderIdentity> { private readonly GrainReference grainRef; private readonly string reminderName; public GrainReference GrainRef { get { return grainRef; } } public string ReminderName { get { return reminderName; } } public ReminderIdentity(GrainReference grainRef, string reminderName) { if (grainRef == null) throw new ArgumentNullException("grainRef"); if (string.IsNullOrWhiteSpace(reminderName)) throw new ArgumentException("The reminder name is either null or whitespace.", "reminderName"); this.grainRef = grainRef; this.reminderName = reminderName; } public bool Equals(ReminderIdentity other) { return grainRef.Equals(other.grainRef) && reminderName.Equals(other.reminderName); } public override bool Equals(object other) { return (other is ReminderIdentity) && Equals((ReminderIdentity)other); } public override int GetHashCode() { return unchecked((int)((uint)grainRef.GetHashCode() + (uint)reminderName.GetHashCode())); } } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using System; namespace Mosa.TestWorld.x86.Tests { public class ExceptionTest : KernelTest { public ExceptionTest() : base("Exception") { testMethods.AddLast(ExceptionTest1); testMethods.AddLast(ExceptionTest2); testMethods.AddLast(ExceptionTest3); testMethods.AddLast(ExceptionTest4); testMethods.AddLast(ExceptionTest5); testMethods.AddLast(ExceptionTest6); testMethods.AddLast(ExceptionTest7); testMethods.AddLast(ExceptionTest8); } public static bool ExceptionTest1() { int a = 10; try { a = a + 1; } finally { a = a + 3; } a = a + 7; return (a == 21); } public static bool ExceptionTest2() { int a = 10; int b = 13; try { a = a + 1; } finally { b = b + a; } b = b + 3; a = a + 3; int c = b + a; return (c == 41); } public static bool ExceptionTest3() { int a = 10; try { try { a = a + 1; } finally { a = a + 100; } } finally { a = a + 3; } a = a + 7; return (a == 121); } public static bool ExceptionTest4() { int a = 10; try { try { a = a + 1; } finally { a = a + 100; } } finally { a = a + 3; } a = a + 7; try { try { a = a + 1; } finally { a = a + 100; } } finally { a = a + 3; } a = a + 7; return (a == 232); } public static bool ExceptionTest5() { int a = 10; try { a = a + 2; //throw new System.Exception(); } catch { a = a + 50; } a = a + 7; return (a == 19); } public static bool ExceptionTest6() { int a = 10; try { a = a + 20; } catch { a = a + 30; } finally { a = a + 40; } a = a + 50; return (a == 120); } public static bool ExceptionTest7() { int a = 10; try { a = a + 15; try { a = a + 20; } catch { try { a = a + 30; } catch { a = a + 40; } a = a + 50; } a = a + 55; } catch { a = a + 40; } a = a + 60; return (a == 160); } public static bool ExceptionTest8() { int a = 10; try { a = a + 2; if (a > 0) throw new Exception(); a = a + 1000; } catch { a = a + 50; } a = a + 7; return (a == 69); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Dataflow.V1Beta3 { /// <summary>Settings for <see cref="FlexTemplatesServiceClient"/> instances.</summary> public sealed partial class FlexTemplatesServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FlexTemplatesServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FlexTemplatesServiceSettings"/>.</returns> public static FlexTemplatesServiceSettings GetDefault() => new FlexTemplatesServiceSettings(); /// <summary>Constructs a new <see cref="FlexTemplatesServiceSettings"/> object with default settings.</summary> public FlexTemplatesServiceSettings() { } private FlexTemplatesServiceSettings(FlexTemplatesServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); LaunchFlexTemplateSettings = existing.LaunchFlexTemplateSettings; OnCopy(existing); } partial void OnCopy(FlexTemplatesServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FlexTemplatesServiceClient.LaunchFlexTemplate</c> and /// <c>FlexTemplatesServiceClient.LaunchFlexTemplateAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings LaunchFlexTemplateSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FlexTemplatesServiceSettings"/> object.</returns> public FlexTemplatesServiceSettings Clone() => new FlexTemplatesServiceSettings(this); } /// <summary> /// Builder class for <see cref="FlexTemplatesServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class FlexTemplatesServiceClientBuilder : gaxgrpc::ClientBuilderBase<FlexTemplatesServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FlexTemplatesServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FlexTemplatesServiceClientBuilder() { UseJwtAccessWithScopes = FlexTemplatesServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FlexTemplatesServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FlexTemplatesServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FlexTemplatesServiceClient Build() { FlexTemplatesServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FlexTemplatesServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FlexTemplatesServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FlexTemplatesServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FlexTemplatesServiceClient.Create(callInvoker, Settings); } private async stt::Task<FlexTemplatesServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FlexTemplatesServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FlexTemplatesServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FlexTemplatesServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FlexTemplatesServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FlexTemplatesService client wrapper, for convenient use.</summary> /// <remarks> /// Provides a service for Flex templates. This feature is not ready yet. /// </remarks> public abstract partial class FlexTemplatesServiceClient { /// <summary> /// The default endpoint for the FlexTemplatesService service, which is a host of "dataflow.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "dataflow.googleapis.com:443"; /// <summary>The default FlexTemplatesService scopes.</summary> /// <remarks> /// The default FlexTemplatesService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// <item><description>https://www.googleapis.com/auth/compute</description></item> /// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item> /// <item><description>https://www.googleapis.com/auth/userinfo.email</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/userinfo.email", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FlexTemplatesServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="FlexTemplatesServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FlexTemplatesServiceClient"/>.</returns> public static stt::Task<FlexTemplatesServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FlexTemplatesServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FlexTemplatesServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="FlexTemplatesServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FlexTemplatesServiceClient"/>.</returns> public static FlexTemplatesServiceClient Create() => new FlexTemplatesServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FlexTemplatesServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FlexTemplatesServiceSettings"/>.</param> /// <returns>The created <see cref="FlexTemplatesServiceClient"/>.</returns> internal static FlexTemplatesServiceClient Create(grpccore::CallInvoker callInvoker, FlexTemplatesServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FlexTemplatesService.FlexTemplatesServiceClient grpcClient = new FlexTemplatesService.FlexTemplatesServiceClient(callInvoker); return new FlexTemplatesServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FlexTemplatesService client</summary> public virtual FlexTemplatesService.FlexTemplatesServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Launch a job with a FlexTemplate. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual LaunchFlexTemplateResponse LaunchFlexTemplate(LaunchFlexTemplateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Launch a job with a FlexTemplate. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<LaunchFlexTemplateResponse> LaunchFlexTemplateAsync(LaunchFlexTemplateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Launch a job with a FlexTemplate. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<LaunchFlexTemplateResponse> LaunchFlexTemplateAsync(LaunchFlexTemplateRequest request, st::CancellationToken cancellationToken) => LaunchFlexTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>FlexTemplatesService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Provides a service for Flex templates. This feature is not ready yet. /// </remarks> public sealed partial class FlexTemplatesServiceClientImpl : FlexTemplatesServiceClient { private readonly gaxgrpc::ApiCall<LaunchFlexTemplateRequest, LaunchFlexTemplateResponse> _callLaunchFlexTemplate; /// <summary> /// Constructs a client wrapper for the FlexTemplatesService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="FlexTemplatesServiceSettings"/> used within this client.</param> public FlexTemplatesServiceClientImpl(FlexTemplatesService.FlexTemplatesServiceClient grpcClient, FlexTemplatesServiceSettings settings) { GrpcClient = grpcClient; FlexTemplatesServiceSettings effectiveSettings = settings ?? FlexTemplatesServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callLaunchFlexTemplate = clientHelper.BuildApiCall<LaunchFlexTemplateRequest, LaunchFlexTemplateResponse>(grpcClient.LaunchFlexTemplateAsync, grpcClient.LaunchFlexTemplate, effectiveSettings.LaunchFlexTemplateSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location); Modify_ApiCall(ref _callLaunchFlexTemplate); Modify_LaunchFlexTemplateApiCall(ref _callLaunchFlexTemplate); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_LaunchFlexTemplateApiCall(ref gaxgrpc::ApiCall<LaunchFlexTemplateRequest, LaunchFlexTemplateResponse> call); partial void OnConstruction(FlexTemplatesService.FlexTemplatesServiceClient grpcClient, FlexTemplatesServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FlexTemplatesService client</summary> public override FlexTemplatesService.FlexTemplatesServiceClient GrpcClient { get; } partial void Modify_LaunchFlexTemplateRequest(ref LaunchFlexTemplateRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Launch a job with a FlexTemplate. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override LaunchFlexTemplateResponse LaunchFlexTemplate(LaunchFlexTemplateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_LaunchFlexTemplateRequest(ref request, ref callSettings); return _callLaunchFlexTemplate.Sync(request, callSettings); } /// <summary> /// Launch a job with a FlexTemplate. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<LaunchFlexTemplateResponse> LaunchFlexTemplateAsync(LaunchFlexTemplateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_LaunchFlexTemplateRequest(ref request, ref callSettings); return _callLaunchFlexTemplate.Async(request, callSettings); } } }
#region License, Terms and Author(s) // // Gurtle - IBugTraqProvider for Google Code // Copyright (c) 2008, 2009 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.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 namespace Gurtle { #region Imports using Gurtle.Providers; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using IssueListViewItem = ListViewItem<Issue>; #endregion internal sealed partial class IssueBrowserDialog : Form { private IProvider _project; private readonly string _titleFormat; private readonly string _foundFormat; private Action _aborter; private long _totalBytesDownloaded; private ReadOnlyCollection<int> _selectedIssues; private ReadOnlyCollection<Issue> _roSelectedIssueObjects; private readonly List<Issue> _selectedIssueObjects; private string _userNamePattern; private string _statusPattern; private bool _closed; private WebClient _updateClient; private Func<IWin32Window, DialogResult> _upgrade; private readonly ObservableCollection<IssueListViewItem> _issues; private readonly ListViewSorter<IssueListViewItem, Issue> _sorter; private readonly Font _deadFont; public IssueBrowserDialog(IProvider project) { InitializeComponent(); _project = project; _titleFormat = Text; _foundFormat = foundLabel.Text; var issues = _issues = new ObservableCollection<IssueListViewItem>(); issues.ItemAdded += (sender, args) => ListIssues(Enumerable.Repeat(args.Item, 1)); issues.ItemsAdded += (sender, args) => ListIssues(args.Items); issues.ItemRemoved += (sender, args) => issueListView.Items.Remove(args.Item); issues.Cleared += delegate { issueListView.Items.Clear(); }; _selectedIssueObjects = new List<Issue>(); _deadFont = new Font(issueListView.Font, FontStyle.Strikeout); _project.SetupListView(issueListView); _sorter = _project.GenerateListViewSorter(issueListView); _sorter.AutoHandle(); _sorter.SortByColumn(0); var searchSourceItems = searchFieldBox.Items; _project.FillSearchItems(searchSourceItems); searchFieldBox.SelectedIndex = 0; searchBox.EnableShortcutToSelectAllText(); _updateClient = new WebClient(); includeClosedCheckBox.DataBindings.Add("Enabled", refreshButton, "Enabled"); UpdateControlStates(); UpdateTitle(); } public string ProjectName { get { return Project != null ? Project.ProjectName : string.Empty; } } internal IProvider Project { get { return _project; } } public string UserNamePattern { get { return _userNamePattern ?? string.Empty; } set { _userNamePattern = value; } } public string StatusPattern { get { return _statusPattern ?? string.Empty; } set { _statusPattern = value; } } public bool UpdateCheckEnabled { get; set; } public IList<int> SelectedIssues { get { if (_selectedIssues == null) _selectedIssues = new ReadOnlyCollection<int>(SelectedIssueObjects.Select(issue => issue.Id).ToList()); return _selectedIssues; } } internal IList<Issue> SelectedIssueObjects { get { if (_roSelectedIssueObjects == null) _roSelectedIssueObjects = new ReadOnlyCollection<Issue>(_selectedIssueObjects); return _roSelectedIssueObjects; } } protected override void OnLoad(EventArgs e) { if (ProjectName.Length > 0) { DownloadIssues(); Project.Load(); } /* if (UpdateCheckEnabled) { var updateClient = new WebClient(); updateClient.DownloadStringCompleted += (sender, args) => { _updateClient = null; if (_closed || args.Cancelled || args.Error != null) return; var updateAction = _upgrade = OnVersionDataDownloaded(args.Result); if (updateAction == null) return; updateNotifyIcon.Visible = true; updateNotifyIcon.ShowBalloonTip(15 * 1000); }; updateClient.DownloadStringAsync(new Uri("http://gurtle.googlecode.com/svn/www/update.txt")); _updateClient = updateClient; } base.OnLoad(e); */ } /* private static Func<IWin32Window, DialogResult> OnVersionDataDownloaded(string data) { Debug.Assert(data != null); var separators = new[] { ':', '=' }; var headers = ( from line in new StringReader(data).ReadLines() where line.Length > 0 && line[0] != '#' let parts = line.Split(separators, 2) where parts.Length == 2 let key = parts[0].Trim() let value = parts[1].Trim() where key.Length > 0 && value.Length > 0 let pair = new KeyValuePair<string, string>(key, value) group pair by pair.Key into g select g ) .ToDictionary(g => g.Key, p => p.Last().Value, StringComparer.OrdinalIgnoreCase); Version version; try { version = new Version(headers.Find("version")); // // Zero out build and revision if not supplied in the string // format, e.g. 2.0 -> 2.0.0.0. // version = new Version(version.Major, version.Minor, Math.Max(version.Build, 0), Math.Max(0, version.Revision)); } catch (ArgumentException) { return null; } catch (FormatException) { return null; } catch (OverflowException) { return null; } var href = headers.Find("href").MaskNull(); if (href.Length == 0 || !Uri.IsWellFormedUriString(href, UriKind.Absolute)) href = new GoogleCodeProject("gurtle").DownloadsListUrl().ToString(); var thisVersion = typeof(Plugin).Assembly.GetName().Version; if (version <= thisVersion) return null; return owner => { var message = new StringBuilder() .AppendLine("There is a new version of Gurtle available. Would you like to update now?") .AppendLine() .Append("Your version: ").Append(thisVersion).AppendLine() .Append("New version: ").Append(version).AppendLine() .ToString(); var reply = MessageBox.Show(owner, message, "Update Notice", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (reply == DialogResult.Yes) Process.Start(href); return reply; }; } */ private void UpdateNotifyIcon_Click(object sender, EventArgs e) { Debug.Assert(_upgrade != null); var reply = _upgrade(this); if (reply == DialogResult.Cancel) return; updateNotifyIcon.Visible = false; if (reply == DialogResult.Yes) Close(); } private void DownloadIssues() { Debug.Assert(_aborter == null); refreshButton.Enabled = false; workStatus.Visible = true; statusLabel.Text = "Downloading\x2026"; _aborter = _project.DownloadIssues(ProjectName, 0, includeClosedCheckBox.Checked, OnIssuesDownloaded, OnUpdateProgress, OnDownloadComplete); } private void OnDownloadComplete(bool cancelled, Exception e) { if (_closed) return; // orphaned notification _aborter = null; refreshButton.Enabled = true; workStatus.Visible = false; if (cancelled) { statusLabel.Text = "Download aborted"; return; } if (e != null) { statusLabel.Text = "Error downloading"; MessageBox.Show(this, e.Message, "Download Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } statusLabel.Text = string.Format("{0} issue(s) downloaded", _issues.Count.ToString("N0")); UpdateTitle(); } private void OnUpdateProgress(DownloadProgressChangedEventArgs args) { if (_closed) return; // orphaned notification _totalBytesDownloaded += args.BytesReceived; statusLabel.Text = string.Format("Downloading\x2026 {0} transferred", ByteSizeFormatter.StrFormatByteSize(_totalBytesDownloaded)); UpdateTitle(); } private void UpdateTitle() { Text = string.Format(_titleFormat, ProjectName, _issues.Count.ToString("N0")); } private IEnumerable<Issue> GetSelectedIssuesFromListView() { return GetSelectedIssuesFromListView(null); } private IEnumerable<Issue> GetSelectedIssuesFromListView(Func<ListView, IEnumerable> itemsSelector) { return from IssueListViewItem item in (itemsSelector != null ? itemsSelector(issueListView) : issueListView.CheckedItems) select item.Tag; } private void IssueListView_DoubleClick(object sender, EventArgs e) { AcceptButton.PerformClick(); } private void DetailButton_Click(object sender, EventArgs e) { var issue = GetSelectedIssuesFromListView(lv => lv.SelectedItems).FirstOrDefault(); if (issue != null) ShowIssueDetails(issue); } private void ShowIssueDetails(Issue issue) { Debug.Assert(issue != null); Process.Start(Project.IssueDetailUrl(issue.Id).ToString()); } private void IssueListView_ItemChecked(object sender, ItemCheckedEventArgs e) { UpdateControlStates(); } private void IssueListView_SelectedIndexChanged(object sender, EventArgs e) { UpdateControlStates(); } private void SearchBox_TextChanged(object sender, EventArgs e) { issueListView.Items.Clear(); ListIssues(_issues); } private void SearchFieldBox_SelectedIndexChanged(object sender, EventArgs e) { var provider = (ISearchSourceStringProvider<Issue>)searchFieldBox.SelectedItem; if (provider == null) return; var definitions = searchBox.Items; definitions.Clear(); var isPredefined = SearchableStringSourceCharacteristics.Predefined == ( provider.SourceCharacteristics & SearchableStringSourceCharacteristics.Predefined); if (!isPredefined) return; // TODO: Update definitions if issues are still being downloaded definitions.AddRange(_issues .Select(lvi => provider.ToSearchableString(lvi.Tag)) .Distinct(StringComparer.CurrentCultureIgnoreCase).ToArray()); // update search after changing field SearchBox_TextChanged(null, null); } private void UpdateControlStates() { detailButton.Enabled = issueListView.SelectedItems.Count == 1; okButton.Enabled = issueListView.CheckedItems.Count > 0; } protected override void OnClosed(EventArgs e) { Debug.Assert(!_closed); Release(ref _aborter, a => a()); Release(ref _updateClient, wc => wc.CancelAsync()); if (Project != null) Project.CancelLoad(); _closed = true; base.OnClosed(e); } private static void Release<T>(ref T member, Action<T> free) where T : class { Debug.Assert(free != null); var local = member; if (local == null) return; member = null; free(local); } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); if (DialogResult != DialogResult.OK || e.Cancel) return; var selectedIssues = _issues.Where(lvi => lvi.Checked) .Select(lvi => lvi.Tag) .ToArray(); // // If the user has selected unowned or closed issues then // provide a warning and confirm the intention. // var warnIssues = selectedIssues.Where(issue => !issue.HasOwner || Project.IsClosedStatus(issue.Status)); if (warnIssues.Any()) { var message = string.Format( "You selected one or more unowned or closed issues ({0}). " + "Normally you should only select open issues with owners assigned. " + "Proceed anyway?", string.Join(", ", warnIssues.OrderBy(issue => issue.Id) .Select(issue => "#" + issue.Id).ToArray())); var reply = MessageBox.Show(this, message, "Unowned/Closed Issues Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, /* no */ MessageBoxDefaultButton.Button2); if (reply == DialogResult.No) { e.Cancel = true; return; } } _selectedIssueObjects.AddRange(selectedIssues); } private void RefreshButton_Click(object sender, EventArgs e) { _issues.Clear(); OnIssuesDownloaded(Enumerable.Empty<Issue>()); UpdateTitle(); DownloadIssues(); } private bool OnIssuesDownloaded(IEnumerable<Issue> issues) { Debug.Assert(issues != null); if (_closed) return false; // orphaned notification /*if (UserNamePattern.Length > 0) issues = issues.Where(issue => Regex.IsMatch(issue.Owner, UserNamePattern));*/ if (StatusPattern.Length > 0) issues = issues.Where(issue => Regex.IsMatch(issue.Status, StatusPattern)); var items = issues.Select(issue => { var id = issue.Id.ToString(CultureInfo.InvariantCulture); var item = new IssueListViewItem(id) { Tag = issue, UseItemStyleForSubItems = true }; if (Project.IsClosedStatus(issue.Status)) { item.ForeColor = SystemColors.GrayText; item.Font = _deadFont; } else if (!issue.HasOwner) { item.ForeColor = SystemColors.GrayText; } _project.GeneratorSubItems(item, issue); return item; }) .ToArray(); _issues.AddRange(items); return items.Length > 0; } private void ListIssues(IEnumerable<IssueListViewItem> items) { Debug.Assert(items != null); var searchWords = searchBox.Text.Split().Where(s => s.Length > 0); if (searchWords.Any()) { var provider = (ISearchSourceStringProvider<Issue>) searchFieldBox.SelectedItem; items = from item in items let issue = item.Tag where searchWords.All(word => provider.ToSearchableString(issue).IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0) select item; } // // We need to stop listening to the ItemChecked event because it // is raised for each item added and this has visually noticable // performance implications for the user on large lists. // ItemCheckedEventHandler onItemChecked = IssueListView_ItemChecked; issueListView.ItemChecked -= onItemChecked; issueListView.Items.AddRange(items.ToArray()); // // Update control states once and start listening to the // ItemChecked event once more. // UpdateControlStates(); issueListView.ItemChecked += onItemChecked; foundLabel.Text = string.Format(_foundFormat, issueListView.Items.Count.ToString("N0")); foundLabel.Visible = searchWords.Any(); } [ Serializable, Flags ] internal enum SearchableStringSourceCharacteristics { None, Predefined } /// <summary> /// Represents a provider that yields the string for an object that /// can be used in text-based searches and indexing. /// </summary> private interface ISearchSourceStringProvider<T> { SearchableStringSourceCharacteristics SourceCharacteristics { get; } string ToSearchableString(T item); } /// <summary> /// Base class for transforming an <see cref="Issue"/> into a /// searchable string. /// </summary> internal abstract class IssueSearchSource : ISearchSourceStringProvider<Issue> { private readonly string _label; protected IssueSearchSource(string label, SearchableStringSourceCharacteristics sourceCharacteristics) { Debug.Assert(label != null); Debug.Assert(label.Length > 0); _label = label; SourceCharacteristics = sourceCharacteristics; } public SearchableStringSourceCharacteristics SourceCharacteristics { get; private set; } public abstract string ToSearchableString(Issue issue); public override string ToString() { return _label; } } /// <summary> /// An <see cref="IssueSearchSource"/> implementation that uses a /// property of an <see cref="Issue"/> as the searchable string. /// </summary> internal sealed class SingleFieldIssueSearchSource : IssueSearchSource { private readonly IProperty<Issue> _property; public SingleFieldIssueSearchSource(string label, IProperty<Issue> property) : this(label, property, SearchableStringSourceCharacteristics.None) {} public SingleFieldIssueSearchSource(string label, IProperty<Issue> property, SearchableStringSourceCharacteristics sourceCharacteristics) : base(label, sourceCharacteristics) { Debug.Assert(property != null); _property = property; } public override string ToSearchableString(Issue issue) { Debug.Assert(issue != null); return _property.GetValue(issue).ToString(); } } /// <summary> /// An <see cref="IssueSearchSource"/> implementation that uses /// concatenates multiple properties of an <see cref="Issue"/> as /// the searchable string. /// </summary> internal sealed class MultiFieldIssueSearchSource : IssueSearchSource { private readonly IProperty<Issue>[] _properties; public MultiFieldIssueSearchSource(string label, IEnumerable<IProperty<Issue>> properties) : base(label, SearchableStringSourceCharacteristics.None) { Debug.Assert(properties != null); _properties = properties.Where(p => p != null).ToArray(); } public override string ToSearchableString(Issue issue) { Debug.Assert(issue != null); return _properties.Aggregate(new StringBuilder(), (sb, p) => sb.Append(p.GetValue(issue)).Append(' ')).ToString(); } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.S3.Model { /// <summary> /// The parameters to request upload of a part in a multipart upload operation. /// </summary> /// <remarks> /// <para> /// If PartSize is not specified then the rest of the content from the file /// or stream will be sent to Amazon S3. /// </para> /// <para> /// You must set either the FilePath or InputStream. If FilePath is set then the FilePosition /// property must be set. /// </para> /// </remarks> public partial class UploadPartRequest : AmazonWebServiceRequest { private Stream inputStream; private string bucketName; private string key; private int? partNumber; private string uploadId; private long? partSize; private string md5Digest; private ServerSideEncryptionCustomerMethod serverSideCustomerEncryption; private string serverSideEncryptionCustomerProvidedKey; private string serverSideEncryptionCustomerProvidedKeyMD5; private string filePath; private long? filePosition; private bool lastPart; internal int IVSize { get; set; } /// <summary> /// Caller needs to set this to true when uploading the last part. This property only needs to be set /// when using the AmazonS3EncryptionClient. /// </summary> public bool IsLastPart { get { return this.lastPart; } set { this.lastPart = value; } } /// <summary> /// Input stream for the request; content for the request will be read from the stream. /// </summary> public Stream InputStream { get { return this.inputStream; } set { this.inputStream = value; } } // Check to see if Body property is set internal bool IsSetInputStream() { return this.inputStream != null; } /// <summary> /// The name of the bucket containing the object to receive the part. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } // Check to see if Bucket property is set internal bool IsSetBucketName() { return this.bucketName != null; } /// <summary> /// The key of the object. /// </summary> public string Key { get { return this.key; } set { this.key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this.key != null; } /// <summary> /// Part number of part being uploaded. /// /// </summary> public int PartNumber { get { return this.partNumber.GetValueOrDefault(); } set { this.partNumber = value; } } // Check to see if PartNumber property is set internal bool IsSetPartNumber() { return this.partNumber.HasValue; } /// <summary> /// The size of the part to be uploaded. /// </summary> public long PartSize { get { return this.partSize.GetValueOrDefault(); } set { this.partSize = value; } } /// <summary> /// Checks if PartSize property is set. /// </summary> /// <returns>true if PartSize property is set.</returns> internal bool IsSetPartSize() { return this.partSize.HasValue; } /// <summary> /// Upload ID identifying the multipart upload whose part is being uploaded. /// /// </summary> public string UploadId { get { return this.uploadId; } set { this.uploadId = value; } } // Check to see if UploadId property is set internal bool IsSetUploadId() { return this.uploadId != null; } /// <summary> /// An MD5 digest for the part. /// </summary> public string MD5Digest { get { return this.md5Digest; } set { this.md5Digest = value; } } /// <summary> /// The Server-side encryption algorithm to be used with the customer provided key. /// /// </summary> public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod { get { return this.serverSideCustomerEncryption; } set { this.serverSideCustomerEncryption = value; } } // Check to see if ServerSideEncryptionCustomerMethod property is set internal bool IsSetServerSideEncryptionCustomerMethod() { return this.serverSideCustomerEncryption != null && this.serverSideCustomerEncryption != ServerSideEncryptionCustomerMethod.None; } /// <summary> /// The base64-encoded encryption key for Amazon S3 to use to encrypt the object /// <para> /// Using the encryption key you provide as part of your request Amazon S3 manages both the encryption, as it writes /// to disks, and decryption, when you access your objects. Therefore, you don't need to maintain any data encryption code. The only /// thing you do is manage the encryption keys you provide. /// </para> /// <para> /// When you retrieve an object, you must provide the same encryption key as part of your request. Amazon S3 first verifies /// the encryption key you provided matches, and then decrypts the object before returning the object data to you. /// </para> /// <para> /// Important: Amazon S3 does not store the encryption key you provide. /// </para> /// </summary> public string ServerSideEncryptionCustomerProvidedKey { get { return this.serverSideEncryptionCustomerProvidedKey; } set { this.serverSideEncryptionCustomerProvidedKey = value; } } /// <summary> /// Checks if ServerSideEncryptionCustomerProvidedKey property is set. /// </summary> /// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns> internal bool IsSetServerSideEncryptionCustomerProvidedKey() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKey); } /// <summary> /// The MD5 of the customer encryption key specified in the ServerSideEncryptionCustomerProvidedKey property. The MD5 is /// base 64 encoded. This field is optional, the SDK will calculate the MD5 if this is not set. /// </summary> public string ServerSideEncryptionCustomerProvidedKeyMD5 { get { return this.serverSideEncryptionCustomerProvidedKeyMD5; } set { this.serverSideEncryptionCustomerProvidedKeyMD5 = value; } } /// <summary> /// Checks if ServerSideEncryptionCustomerProvidedKeyMD5 property is set. /// </summary> /// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns> internal bool IsSetServerSideEncryptionCustomerProvidedKeyMD5() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKeyMD5); } /// <summary> /// <para> /// Full path and name of a file from which the content for the part is retrieved. /// </para> /// <para> /// For WinRT and Windows Phone this property must be in the form of "ms-appdata:///local/file.txt". /// </para> /// </summary> public string FilePath { get { return this.filePath; } set { this.filePath = value; } } /// <summary> /// Checks if the FilePath property is set. /// </summary> /// <returns>true if FilePath property is set.</returns> internal bool IsSetFilePath() { return !string.IsNullOrEmpty(this.filePath); } /// <summary> /// Position in the file specified by FilePath from which to retrieve the content of the part. /// This field is required when a file path is specified. It is ignored when using the InputStream property. /// </summary> public long FilePosition { get { return this.filePosition.GetValueOrDefault(); } set { this.filePosition = value; } } /// <summary> /// Checks if the FilePosition property is set. /// </summary> /// <returns>true if FilePosition property is set.</returns> internal bool IsSetFilePosition() { return this.filePosition.HasValue; } /// <summary> /// Checks if the MD5Digest property is set. /// </summary> /// <returns>true if Md5Digest property is set.</returns> internal bool IsSetMD5Digest() { return !string.IsNullOrEmpty(this.md5Digest); } /// <summary> /// Attach a callback that will be called as data is being sent to the AWS Service. /// </summary> public EventHandler<Amazon.Runtime.StreamTransferProgressArgs> StreamTransferProgress { get { return this.StreamUploadProgressCallback; } set { this.StreamUploadProgressCallback = value; } } internal override bool IncludeSHA256Header { get { return false; } } internal override bool Expect100Continue { get { return true; } } } }
//------------------------------------------------------------------------------ // <copyright file="Transfer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Blob; /// <summary> /// Base class for transfer operation. /// </summary> #if !BINARY_SERIALIZATION [DataContract] [KnownType(typeof(AzureBlobDirectoryLocation))] [KnownType(typeof(AzureBlobLocation))] [KnownType(typeof(AzureFileDirectoryLocation))] [KnownType(typeof(AzureFileLocation))] [KnownType(typeof(DirectoryLocation))] [KnownType(typeof(FileLocation))] // StreamLocation intentionally omitted because it is not serializable [KnownType(typeof(UriLocation))] [KnownType(typeof(SingleObjectTransfer))] [KnownType(typeof(MultipleObjectsTransfer))] [KnownType(typeof(DirectoryTransfer))] #endif internal abstract class Transfer : JournalItem, IDisposable #if BINARY_SERIALIZATION , ISerializable #endif // BINARY_SERIALIZATION { private const string FormatVersionName = "Version"; private const string SourceName = "Source"; private const string DestName = "Dest"; private const string TransferMethodName = "TransferMethod"; private const string TransferProgressName = "Progress"; // Currently, we have two ways to persist the transfer instance: // 1. User can persist a TransferCheckpoint instance with all transfer instances in it. // 2. User can input a stream to TransferCheckpoint that DMLib will persistant ongoing transfer instances to the stream. // 2# solution is used to transfer large amount of files without occupying too much memory. // With this solution, // a. when persisting a DirectoryTransfer, we don't save its subtransfers with it, instead we'll allocate a new // transfer chunk for each subtransfer. // b. We don't persist its TransferProgressTracker with Transfer instance, intead we save the TransferProgressTracker to a separate place. // Please referece to explaination in StreamJournal for details. #if !BINARY_SERIALIZATION [DataMember] private TransferProgressTracker progressTracker; #endif /// <summary> /// Initializes a new instance of the <see cref="Transfer"/> class. /// </summary> /// <param name="source">Transfer source.</param> /// <param name="dest">Transfer destination.</param> /// <param name="transferMethod">Transfer method, see <see cref="TransferMethod"/> for detail available methods.</param> public Transfer(TransferLocation source, TransferLocation dest, TransferMethod transferMethod) { this.Source = source; this.Destination = dest; this.TransferMethod = transferMethod; this.ProgressTracker = new TransferProgressTracker(); this.OriginalFormatVersion = Constants.FormatVersion; } #if BINARY_SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="Transfer"/> class. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected Transfer(SerializationInfo info, StreamingContext context) { if (info == null) { throw new System.ArgumentNullException("info"); } string version = info.GetString(FormatVersionName); if (!string.Equals(Constants.FormatVersion, version, StringComparison.Ordinal)) { throw new System.InvalidOperationException( string.Format( CultureInfo.CurrentCulture, Resources.DeserializationVersionNotMatchException, "TransferJob", version, Constants.FormatVersion)); } var serializableSourceLocation = (SerializableTransferLocation)info.GetValue(SourceName, typeof(SerializableTransferLocation)); var serializableDestLocation = (SerializableTransferLocation)info.GetValue(DestName, typeof(SerializableTransferLocation)); this.Source = serializableSourceLocation.Location; this.Destination = serializableDestLocation.Location; this.TransferMethod = (TransferMethod)info.GetValue(TransferMethodName, typeof(TransferMethod)); if (null == context.Context || !(context.Context is StreamJournal)) { this.ProgressTracker = (TransferProgressTracker)info.GetValue(TransferProgressName, typeof(TransferProgressTracker)); } else { this.ProgressTracker = new TransferProgressTracker(); } } #endif // BINARY_SERIALIZATION #if !BINARY_SERIALIZATION [OnSerializing] private void OnSerializingCallback(StreamingContext context) { if (!IsStreamJournal) { this.progressTracker = this.ProgressTracker; } } [OnDeserialized] private void OnDeserializedCallback(StreamingContext context) { if (!string.Equals(Constants.FormatVersion, OriginalFormatVersion, StringComparison.Ordinal)) { throw new System.InvalidOperationException( string.Format( CultureInfo.CurrentCulture, Resources.DeserializationVersionNotMatchException, "TransferJob", OriginalFormatVersion, Constants.FormatVersion)); } if (!IsStreamJournal) { this.ProgressTracker = this.progressTracker; } else { this.ProgressTracker = new TransferProgressTracker(); } } #endif /// <summary> /// Initializes a new instance of the <see cref="Transfer"/> class. /// </summary> protected Transfer(Transfer other) { this.Source = other.Source; this.Destination = other.Destination; this.TransferMethod = other.TransferMethod; this.OriginalFormatVersion = other.OriginalFormatVersion; } /// Used to ensure that deserialized transfers are only used /// in scenarios with the same format version they were serialized with. #if !BINARY_SERIALIZATION [DataMember] #endif private string OriginalFormatVersion { get; set; } /// <summary> /// Gets source location for this transfer. /// </summary> #if !BINARY_SERIALIZATION [DataMember] #endif public TransferLocation Source { get; private set; } /// <summary> /// Gets destination location for this transfer. /// </summary> #if !BINARY_SERIALIZATION [DataMember] #endif public TransferLocation Destination { get; private set; } /// <summary> /// Gets the transfer method used in this transfer. /// </summary> #if !BINARY_SERIALIZATION [DataMember] #endif public TransferMethod TransferMethod { get; private set; } #if !BINARY_SERIALIZATION /// <summary> /// Gets or sets a variable to indicate whether the transfer will be saved to a streamed journal. /// </summary> [DataMember] public bool IsStreamJournal { get; set; } #endif /// <summary> /// Gets or sets the transfer context of this transfer. /// </summary> public virtual TransferContext Context { get; set; } /// <summary> /// Gets or sets blob type of destination blob. /// </summary> public BlobType BlobType { get; set; } /// <summary> /// Gets the progress tracker for this transfer. /// </summary> public TransferProgressTracker ProgressTracker { get; protected set; } #if BINARY_SERIALIZATION /// <summary> /// Serializes the object. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue(FormatVersionName, Constants.FormatVersion, typeof(string)); SerializableTransferLocation serializableSourceLocation = new SerializableTransferLocation(this.Source); SerializableTransferLocation serializableDestLocation = new SerializableTransferLocation(this.Destination); info.AddValue(SourceName, serializableSourceLocation, typeof(SerializableTransferLocation)); info.AddValue(DestName, serializableDestLocation, typeof(SerializableTransferLocation)); info.AddValue(TransferMethodName, this.TransferMethod); if (null == context.Context || !(context.Context is StreamJournal)) { info.AddValue(TransferProgressName, this.ProgressTracker); } } #endif // BINARY_SERIALIZATION /// <summary> /// Execute the transfer asynchronously. /// </summary> /// <param name="scheduler">Transfer scheduler</param> /// <param name="cancellationToken">Token that can be used to cancel the transfer.</param> /// <returns>A task representing the transfer operation.</returns> public abstract Task ExecuteAsync(TransferScheduler scheduler, CancellationToken cancellationToken); public void UpdateTransferJobStatus(TransferJob transferJob, TransferJobStatus targetStatus) { lock (this.ProgressTracker) { switch (targetStatus) { case TransferJobStatus.Transfer: case TransferJobStatus.Monitor: if (transferJob.Status == TransferJobStatus.Failed) { UpdateProgress(transferJob, () => this.ProgressTracker.AddNumberOfFilesFailed(-1)); } break; case TransferJobStatus.Skipped: UpdateProgress(transferJob, () => this.ProgressTracker.AddNumberOfFilesSkipped(1)); break; case TransferJobStatus.Finished: UpdateProgress(transferJob, () => this.ProgressTracker.AddNumberOfFilesTransferred(1)); break; case TransferJobStatus.Failed: UpdateProgress(transferJob, () => this.ProgressTracker.AddNumberOfFilesFailed(1)); break; case TransferJobStatus.NotStarted: default: break; } transferJob.Status = targetStatus; } transferJob.Transfer.UpdateJournal(); } public abstract Transfer Copy(); public void UpdateJournal() { this.Journal?.UpdateJournalItem(this); } private static void UpdateProgress(TransferJob job, Action updateAction) { try { job.ProgressUpdateLock?.EnterReadLock(); updateAction(); } finally { job.ProgressUpdateLock?.ExitReadLock(); } } /// <summary> /// Public dispose method to release all resources owned. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Nothing to dispose } } }
// #region Using directives using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.DebugHelpers; //#endregion namespace Microsoft.Msagl.Core.Geometry.Curves { /// <summary> /// Cubic Bezier Segment /// </summary> #if TEST_MSAGL [Serializable] #endif public class CubicBezierSegment : ICurve { /// <summary> /// left derivative at t /// </summary> /// <param name="t">the parameter where the derivative is calculated</param> /// <returns></returns> public Point LeftDerivative(double t) { return Derivative(t); } /// <summary> /// right derivative at t /// </summary> /// <param name="t">the parameter where the derivative is calculated</param> /// <returns></returns> public Point RightDerivative(double t) { return Derivative(t); } /// <summary> /// control points /// </summary> Point[] b = new Point[4]; /// <summary> /// coefficients /// </summary> Point l, e, c; /// <summary> /// get a control point /// </summary> /// <param name="controlPointIndex"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "B")] public Point B(int controlPointIndex) { return b[controlPointIndex]; } /// <summary> /// ToString /// </summary> /// <returns></returns> override public string ToString() { return String.Format(CultureInfo.InvariantCulture, "(Bezie{0},{1},{2},{3})", b[0], b[1], b[2], b[3]); } ParallelogramNodeOverICurve pBoxNode; /// <summary> /// A tree of ParallelogramNodes covering the curve. /// This tree is used in curve intersections routines. /// </summary> /// <value></value> public ParallelogramNodeOverICurve ParallelogramNodeOverICurve { get { #if PPC lock(this){ #endif if (pBoxNode != null) return pBoxNode; return pBoxNode = ParallelogramNodeOverICurve.CreateParallelogramNodeForCurveSegment(this); #if PPC } #endif } } /// <summary> /// Returns the point on the curve corresponding to parameter t /// </summary> /// <param name="t"></param> /// <returns></returns> public Point this[double t] { get { double t2 = t * t; double t3 = t2 * t; return l * t3 + e * t2 + c * t + b[0]; } } static void AdjustParamTo01(ref double u) { if (u > 1) u = 1; else if (u < 0) u = 0; } //throw away the segments [0,u] and [v,1] of the segment /// <summary> /// Returns the trimmed curve /// </summary> /// <param name="u"></param> /// <param name="v"></param> /// <returns></returns> public ICurve Trim(double u, double v) { AdjustParamTo01(ref u); AdjustParamTo01(ref v); if (u > v) return Trim(v, u); if (u > 1.0 - ApproximateComparer.Tolerance) return new CubicBezierSegment(b[3], b[3], b[3], b[3]); Point[] b1 = new Point[3]; Point[] b2 = new Point[2]; Point pv = Casteljau(u, b1, b2); //this will be the trim to [v,1] CubicBezierSegment trimByU = new CubicBezierSegment(pv, b2[1], b1[2], b[3]); //1-v is not zero here because we have handled already the case v=1 Point pu = trimByU.Casteljau((v - u) / (1.0 - u), b1, b2); return new CubicBezierSegment(trimByU.b[0], b1[0], b2[0], pu); } /// <summary> /// Not Implemented: Returns the trimmed curve, wrapping around the end if start is greater than end. /// </summary> /// <param name="start">The starting parameter</param> /// <param name="end">The ending parameter</param> /// <returns>The trimmed curve</returns> public ICurve TrimWithWrap(double start, double end) { throw new NotImplementedException(); } //array for Casteljau method internal Point Casteljau(double t, Point[] b1, Point[] b2) { double f = 1.0 - t; for (int i = 0; i < 3; i++) b1[i] = b[i] * f + b[i + 1] * t; for (int i = 0; i < 2; i++) b2[i] = b1[i] * f + b1[i + 1] * t; return b2[0] * f + b2[1] * t; } /// <summary> /// first derivative /// </summary> /// <param name="t"></param> /// <returns></returns> public Point Derivative(double t) { return 3 * l * t * t + 2 * e * t + c; } /// <summary> /// second derivative /// </summary> /// <param name="t"></param> /// <returns></returns> public Point SecondDerivative(double t) { return 6 * l * t + 2 * e; } /// <summary> /// third derivative /// </summary> /// <param name="t"></param> /// <returns></returns> public Point ThirdDerivative(double t) { return 6 * l; } /// <summary> /// the constructor /// </summary> /// <param name="b0"></param> /// <param name="b1"></param> /// <param name="b2"></param> /// <param name="b3"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b")] public CubicBezierSegment(Point b0, Point b1, Point b2, Point b3) { this.b[0] = b0; this.b[1] = b1; this.b[2] = b2; this.b[3] = b3; c = 3 * (b[1] - b[0]); e = 3 * (b[2] - b[1]) - c; l = b[3] - b[0] - c - e; } /// <summary> /// this[ParStart] /// </summary> public Point Start { get { return b[0]; } } /// <summary> /// this[ParEnd] /// </summary> public Point End { get { return b[3]; } } double parStart; /// <summary> /// the start of the parameter domain /// </summary> public double ParStart { get { return parStart; } set { parStart = value; } } double parEnd = 1; /// <summary> /// the end of the parameter domain /// </summary> public double ParEnd { get { return parEnd; } set { parEnd = value; } } /// <summary> /// this[Reverse[t]]=this[ParEnd+ParStart-t] /// </summary> /// <returns></returns> public ICurve Reverse() { return new CubicBezierSegment(b[3], b[2], b[1], b[0]); } /// <summary> /// Returns the curved moved by delta /// </summary> public void Translate(Point delta) { this.b[0] += delta; this.b[1] += delta; this.b[2] += delta; this.b[3] += delta; c = 3 * (b[1] - b[0]); e = 3 * (b[2] - b[1]) - c; l = b[3] - b[0] - c - e; pBoxNode = null; } /// <summary> /// Returns the curved scaled by x and y /// </summary> /// <param name="xScale"></param> /// <param name="yScale"></param> /// <returns></returns> public ICurve ScaleFromOrigin(double xScale, double yScale) { return new CubicBezierSegment(Point.Scale(xScale, yScale, b[0]), Point.Scale(xScale, yScale, b[1]), Point.Scale(xScale, yScale, b[2]), Point.Scale(xScale, yScale, b[3])); } /// <summary> /// Offsets the curve in the direction of dir /// </summary> /// <param name="offset"></param> /// <param name="dir"></param> /// <returns></returns> public ICurve OffsetCurve(double offset, Point dir) { return null; } /// <summary> /// return length of the curve segment [start,end] /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public double LengthPartial(double start, double end) { return Trim(start, end).Length; } /// <summary> /// Get the length of the curve /// </summary> public double Length { get { return LengthOnControlPolygon(b[0],b[1],b[2],b[3]); } } /// <summary> /// /// </summary> /// <param name="b0"></param> /// <param name="b1"></param> /// <param name="b2"></param> /// <param name="b3"></param> /// <returns></returns> static double LengthOnControlPolygon(Point b0, Point b1, Point b2, Point b3) { var innerCordLength = (b3- b0).Length; var controlPointPolygonLength = (b1 - b0).Length + (b2 - b1).Length + (b3 - b2).Length; if (controlPointPolygonLength - innerCordLength > Curve.LineSegmentThreshold) { var mb0 = (b0 + b1)/2; var mb1 = (b1 + b2)/2; var mb2=(b2 + b3)/2; var mmb0 = (mb0 + mb1)/2; var mmb1 = (mb2 + mb1)/2; var mmmb0 = (mmb0 + mmb1)/2; // LayoutAlgorithmSettings.ShowDebugCurves(new DebugCurve(100, 2, "blue", new CubicBezierSegment(b0, b1, b2, b3)), new DebugCurve(100, 1, "red", new CubicBezierSegment(b0, mb0, mmb0, mmmb0)), new DebugCurve(100, 1, "green", new CubicBezierSegment(mmmb0, mmb1, mb2, b3))); return LengthOnControlPolygon(b0, mb0, mmb0, mmmb0) + LengthOnControlPolygon(mmmb0, mmb1, mb2, b3); } return (controlPointPolygonLength + innerCordLength) / 2; } /// <summary> /// the segment bounding box /// </summary> public Rectangle BoundingBox { get { var ret = new Rectangle(this.b[0], this.b[1]); ret.Add(b[2]); ret.Add(b[3]); return ret; } } /// <summary> /// Return the transformed curve /// </summary> /// <param name="transformation"></param> /// <returns>the transformed curve</returns> public ICurve Transform(PlaneTransformation transformation) { return new CubicBezierSegment(transformation * b[0], transformation * b[1], transformation * b[2], transformation * b[3]); } /// <summary> /// returns a parameter t such that the distance between curve[t] and targetPoint is minimal /// and t belongs to the closed segment [low,high] /// </summary> /// <param name="targetPoint">the point to find the closest point</param> /// <param name="high">the upper bound of the parameter</param> /// <param name="low">the low bound of the parameter</param> /// <returns></returns> public double ClosestParameterWithinBounds(Point targetPoint, double low, double high) { System.Diagnostics.Debug.Assert(high <= 1 && low >= 0); System.Diagnostics.Debug.Assert(low <= high); double t = (high-low) / 8; double closest = 0; double minDist = Double.MaxValue; for (int i = 0; i < 9; i++) { Point p = targetPoint - this[i * t + low]; double d = p * p; if (d < minDist) { minDist = d; closest = i * t + low; } } return ClosestPointOnCurve.ClosestPoint(this, targetPoint, closest, low, high); } /// <summary> /// clones the curve. /// </summary> /// <returns>the cloned curve</returns> public ICurve Clone() { return new CubicBezierSegment(this.b[0], this.b[1], this.b[2], this.b[3]); } /// <summary> /// the signed curvature of the segment at t /// </summary> /// <param name="t"></param> /// <returns></returns> public double Curvature(double t) { System.Diagnostics.Debug.Assert(t >= ParStart && t <= ParEnd); double den = G(t); System.Diagnostics.Debug.Assert(Math.Abs(den) > 0.00001); return F(t) / den; } double F(double t) { return Xp(t) * Ypp(t) - Yp(t) * Xpp(t); } /// <summary> /// G(t) is the denomenator of the curvature /// </summary> /// <param name="t"></param> /// <returns></returns> double G(double t) { double xp = Xp(t); double yp = Yp(t); double den = (xp * xp + yp * yp); return Math.Sqrt(den * den * den); } /// <summary> /// the first derivative of x-coord /// </summary> /// <param name="t"></param> /// <returns></returns> double Xp(double t) { return 3 * l.X * t * t + 2 * e.X * t + c.X; } /// <summary> /// the second derivativ of y-coordinate /// </summary> /// <param name="t"></param> /// <returns></returns> double Ypp(double t) { return 6 * l.Y * t + 2 * e.Y; } /// <summary> /// the first derivative of y-coord /// </summary> /// <param name="t"></param> /// <returns></returns> double Yp(double t) { return 3 * l.Y * t * t + 2 * e.Y * t + c.Y; } /// <summary> /// the seconde derivative of x coord /// </summary> /// <param name="t"></param> /// <returns></returns> double Xpp(double t) { return 6 * l.X * t + 2 * e.X; } /// <summary> /// the third derivative of x coordinate /// </summary> /// <param name="t"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "t")] double Xppp(double t) { return 6 * l.X; } /// <summary> /// the third derivative of y coordinate /// </summary> /// <param name="t"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "t")] double Yppp(double t) { return 6 * l.Y; } /// <summary> /// the derivative of the curvature at t /// </summary> /// <param name="t"></param> /// <returns></returns> public double CurvatureDerivative(double t) { // we need to calculate the derivative of f/g where f=xp* ypp-yp*xpp and g=(xp*xp+yp*yp)^(3/2) double h = G(t); return (Fp(t) * h - Gp(t) * F(t)) / (h * h); } double Fp(double t) { return Xp(t) * Yppp(t) - Yp(t) * Xppp(t); } double Fpp(double t) { return Xpp(t) * Yppp(t) // + Xp(t) * Ypppp(t)=0 - Ypp(t) * Xppp(t);//- Yp(t) * Xpppp(t)=0 } /// <summary> /// returns a parameter t such that the distance between curve[t] and a is minimal /// </summary> /// <param name="targetPoint"></param> /// <returns></returns> public double ClosestParameter(Point targetPoint) { double t = 1.0 / 8; double closest = 0; double minDist = Double.MaxValue; for (int i = 0; i < 9; i++) { Point p = targetPoint - this[i * t]; double d = p * p; if (d < minDist) { minDist = d; closest = i * t; } } return ClosestPointOnCurve.ClosestPoint(this, targetPoint, closest, 0, 1); } /// <summary> /// /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public IEnumerable<Tuple<double, double>> MaximalCurvaturePoints { get { List<Tuple<double, double>> maxCurveCandidates = new List<Tuple<double, double>>(); int n = 8; double d = 1.0 / n; double prev = -1;//out of the domain for (int i = 0; i < n; i++) { double start = i * d; double end = start + d; double x; if (RootFinder.TryToFindRoot(new CurvatureDerivative(this, start, end), start, end, (start + end) / 2, out x)) { if (x != prev) { prev = x; maxCurveCandidates.Add(new Tuple<double, double>(x, Curvature(x))); } } } maxCurveCandidates.Add(new Tuple<double, double>(ParStart, Curvature(ParStart))); maxCurveCandidates.Add(new Tuple<double, double>(ParEnd, Curvature(ParEnd))); var maxCur = maxCurveCandidates.Max(l => Math.Abs(l.Item2)); return from v in maxCurveCandidates where Math.Abs(v.Item2) == maxCur select v; } } #region ICurve Members /// <summary> /// /// </summary> /// <param name="t"></param> /// <returns></returns> public double CurvatureSecondDerivative(double t) { double g = G(t); return (Qp(t) * g - 2 * Q(t) * Gp(t)) / (g * g * g); } double Q(double t) { return Fp(t) * G(t) - Gp(t) * F(t); } double Qp(double t) { return Fpp(t) * G(t) - Gpp(t) * F(t); } double Gpp(double t) { var xp = Xp(t); var yp = Yp(t); var xpp = Xpp(t); var ypp = Ypp(t); var xppp = Xppp(t); var yppp = Yppp(t); var u = Math.Sqrt(xp * xp + yp * yp); var v = xp * xpp + yp * ypp; return 3 * ((v * v) / u + u * (xpp * xpp + xp * xppp + ypp * ypp + yp * yppp)); } double Gp(double t) { var xp = Xp(t); var yp = Yp(t); var xpp = Xpp(t); var ypp = Ypp(t); return 3 * Math.Sqrt(xp * xp + yp * yp) * (xp * xpp + yp * ypp); } #endregion /// <summary> /// /// </summary> /// <param name="length"></param> /// <returns></returns> public double GetParameterAtLength(double length) { double low = 0; double upper = 1; while (upper - low > ApproximateComparer.Tolerance) { var middle = (upper + low)/2; int err = EvaluateError(length, middle); if (err > 0) upper = middle; else if (err < 0) low = middle; else return middle; } return (low + upper)/2; } int EvaluateError(double length, double t) { //todo: this is a slow version! var f = 1 - t; var mb0 = f*b[0] + t*b[1]; var mb1 = f*b[1] + t*b[2]; var mb2 = f*b[2] + t*b[3]; var mmb0 = f * mb0 + t * mb1; var mmb1 = f * mb1 + t * mb2; var mmmb0 = f * mmb0 + t * mmb1; var lengthAtT = LengthOnControlPolygon(b[0], mb0, mmb0, mmmb0); if (lengthAtT > length + ApproximateComparer.DistanceEpsilon) return 1; if (lengthAtT < length - ApproximateComparer.DistanceEpsilon) return -1; return 0; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.IO; namespace Avro { public class CodeGen { /// <summary> /// Object that contains all the generated types /// </summary> public CodeCompileUnit CompileUnit { get; private set; } /// <summary> /// List of schemas to generate code for /// </summary> public IList<Schema> Schemas { get; private set; } /// <summary> /// List of protocols to generate code for /// </summary> public IList<Protocol> Protocols { get; private set; } /// <summary> /// List of generated namespaces /// </summary> protected Dictionary<string, CodeNamespace> namespaceLookup = new Dictionary<string, CodeNamespace>(StringComparer.Ordinal); /// <summary> /// Default constructor /// </summary> public CodeGen() { this.Schemas = new List<Schema>(); this.Protocols = new List<Protocol>(); } /// <summary> /// Adds a protocol object to generate code for /// </summary> /// <param name="protocol">protocol object</param> public virtual void AddProtocol(Protocol protocol) { Protocols.Add(protocol); } /// <summary> /// Adds a schema object to generate code for /// </summary> /// <param name="schema">schema object</param> public virtual void AddSchema(Schema schema) { Schemas.Add(schema); } /// <summary> /// Adds a namespace object for the given name into the dictionary if it doesn't exist yet /// </summary> /// <param name="name">name of namespace</param> /// <returns></returns> protected virtual CodeNamespace addNamespace(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name", "name cannot be null."); CodeNamespace ns = null; if (!namespaceLookup.TryGetValue(name, out ns)) { ns = new CodeNamespace(CodeGenUtil.Instance.Mangle(name)); foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports) ns.Imports.Add(nci); CompileUnit.Namespaces.Add(ns); namespaceLookup.Add(name, ns); } return ns; } /// <summary> /// Generates code for the given protocol and schema objects /// </summary> /// <returns>CodeCompileUnit object</returns> public virtual CodeCompileUnit GenerateCode() { CompileUnit = new CodeCompileUnit(); processSchemas(); processProtocols(); return CompileUnit; } /// <summary> /// Generates code for the schema objects /// </summary> protected virtual void processSchemas() { foreach (Schema schema in this.Schemas) { SchemaNames names = generateNames(schema); foreach (KeyValuePair<SchemaName, NamedSchema> sn in names) { switch (sn.Value.Tag) { case Schema.Type.Enumeration: processEnum(sn.Value); break; case Schema.Type.Fixed: processFixed(sn.Value); break; case Schema.Type.Record: processRecord(sn.Value); break; case Schema.Type.Error: processRecord(sn.Value); break; default: throw new CodeGenException("Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag); } } } } /// <summary> /// Generates code for the protocol objects /// </summary> protected virtual void processProtocols() { foreach (Protocol protocol in Protocols) { SchemaNames names = generateNames(protocol); foreach (KeyValuePair<SchemaName, NamedSchema> sn in names) { switch (sn.Value.Tag) { case Schema.Type.Enumeration: processEnum(sn.Value); break; case Schema.Type.Fixed: processFixed(sn.Value); break; case Schema.Type.Record: processRecord(sn.Value); break; case Schema.Type.Error: processRecord(sn.Value); break; default: throw new CodeGenException("Names in protocol should only be of type NamedSchema, type found " + sn.Value.Tag); } } } } /// <summary> /// Generate list of named schemas from given protocol /// </summary> /// <param name="protocol">protocol to process</param> /// <returns></returns> protected virtual SchemaNames generateNames(Protocol protocol) { var names = new SchemaNames(); foreach (Schema schema in protocol.Types) addName(schema, names); return names; } /// <summary> /// Generate list of named schemas from given schema /// </summary> /// <param name="schema">schema to process</param> /// <returns></returns> protected virtual SchemaNames generateNames(Schema schema) { var names = new SchemaNames(); addName(schema, names); return names; } /// <summary> /// Recursively search the given schema for named schemas and adds them to the given container /// </summary> /// <param name="schema">schema object to search</param> /// <param name="names">list of named schemas</param> protected virtual void addName(Schema schema, SchemaNames names) { NamedSchema ns = schema as NamedSchema; if (null != ns) if (names.Contains(ns.SchemaName)) return; switch (schema.Tag) { case Schema.Type.Null: case Schema.Type.Boolean: case Schema.Type.Int: case Schema.Type.Long: case Schema.Type.Float: case Schema.Type.Double: case Schema.Type.Bytes: case Schema.Type.String: break; case Schema.Type.Enumeration: case Schema.Type.Fixed: names.Add(ns); break; case Schema.Type.Record: case Schema.Type.Error: var rs = schema as RecordSchema; names.Add(rs); foreach (Field field in rs.Fields) addName(field.Schema, names); break; case Schema.Type.Array: var asc = schema as ArraySchema; addName(asc.ItemSchema, names); break; case Schema.Type.Map: var ms = schema as MapSchema; addName(ms.ValueSchema, names); break; case Schema.Type.Union: var us = schema as UnionSchema; foreach (Schema usc in us.Schemas) addName(usc, names); break; default: throw new CodeGenException("Unable to add name for " + schema.Name + " type " + schema.Tag); } } /// <summary> /// Creates a class declaration for fixed schema /// </summary> /// <param name="schema">fixed schema</param> /// <param name="ns">namespace object</param> protected virtual void processFixed(Schema schema) { FixedSchema fixedSchema = schema as FixedSchema; if (null == fixedSchema) throw new CodeGenException("Unable to cast schema into a fixed"); CodeTypeDeclaration ctd = new CodeTypeDeclaration(); ctd.Name = CodeGenUtil.Instance.Mangle(fixedSchema.Name); ctd.IsClass = true; ctd.IsPartial = true; ctd.Attributes = MemberAttributes.Public; ctd.BaseTypes.Add("SpecificFixed"); // create static schema field createSchemaField(schema, ctd, true); // Add Size field string sizefname = "fixedSize"; var ctrfield = new CodeTypeReference(typeof(uint)); var codeField = new CodeMemberField(ctrfield, sizefname); codeField.Attributes = MemberAttributes.Private | MemberAttributes.Static; codeField.InitExpression = new CodePrimitiveExpression(fixedSchema.Size); ctd.Members.Add(codeField); // Add Size property var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), sizefname); var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Static; property.Name = "FixedSize"; property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(schema.Name + "." + sizefname))); ctd.Members.Add(property); // create constructor to initiate base class SpecificFixed CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public; cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(sizefname)); ctd.Members.Add(cc); string nspace = fixedSchema.Namespace; if (string.IsNullOrEmpty(nspace)) throw new CodeGenException("Namespace required for enum schema " + fixedSchema.Name); CodeNamespace codens = addNamespace(nspace); codens.Types.Add(ctd); } /// <summary> /// Creates an enum declaration /// </summary> /// <param name="schema">enum schema</param> /// <param name="ns">namespace</param> protected virtual void processEnum(Schema schema) { EnumSchema enumschema = schema as EnumSchema; if (null == enumschema) throw new CodeGenException("Unable to cast schema into an enum"); CodeTypeDeclaration ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(enumschema.Name)); ctd.IsEnum = true; ctd.Attributes = MemberAttributes.Public; foreach (string symbol in enumschema.Symbols) { if (CodeGenUtil.Instance.ReservedKeywords.Contains(symbol)) throw new CodeGenException("Enum symbol " + symbol + " is a C# reserved keyword"); CodeMemberField field = new CodeMemberField(typeof(int), symbol); ctd.Members.Add(field); } string nspace = enumschema.Namespace; if (string.IsNullOrEmpty(nspace)) throw new CodeGenException("Namespace required for enum schema " + enumschema.Name); CodeNamespace codens = addNamespace(nspace); codens.Types.Add(ctd); } /// <summary> /// Creates a class declaration /// </summary> /// <param name="schema">record schema</param> /// <param name="ns">namespace</param> /// <returns></returns> protected virtual CodeTypeDeclaration processRecord(Schema schema) { RecordSchema recordSchema = schema as RecordSchema; if (null == recordSchema) throw new CodeGenException("Unable to cast schema into a record"); // declare the class var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name)); ctd.BaseTypes.Add("ISpecificRecord"); ctd.Attributes = MemberAttributes.Public; ctd.IsClass = true; ctd.IsPartial = true; createSchemaField(schema, ctd, false); // declare Get() to be used by the Writer classes var cmmGet = new CodeMemberMethod(); cmmGet.Name = "Get"; cmmGet.Attributes = MemberAttributes.Public; cmmGet.ReturnType = new CodeTypeReference("System.Object"); cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); // declare Put() to be used by the Reader classes var cmmPut = new CodeMemberMethod(); cmmPut.Name = "Put"; cmmPut.Attributes = MemberAttributes.Public; cmmPut.ReturnType = new CodeTypeReference(typeof(void)); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue")); var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); foreach (Field field in recordSchema.Fields) { // Determine type of field bool nullibleEnum = false; string baseType = getType(field.Schema, false, ref nullibleEnum); var ctrfield = new CodeTypeReference(baseType); // Create field string privFieldName = string.Concat("_", field.Name); var codeField = new CodeMemberField(ctrfield, privFieldName); codeField.Attributes = MemberAttributes.Private; // Process field documentation if it exist and add to the field CodeCommentStatement propertyComment = null; if (!string.IsNullOrEmpty(field.Documentation)) { propertyComment = createDocComment(field.Documentation); if (null != propertyComment) codeField.Comments.Add(propertyComment); } // Add field to class ctd.Members.Add(codeField); // Create reference to the field - this.fieldname var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName); var mangledName = CodeGenUtil.Instance.Mangle(field.Name); // Create field property with get and set methods var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = mangledName; property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression())); if (null != propertyComment) property.Comments.Add(propertyComment); // Add field property to class ctd.Members.Add(property); // add to Get() getFieldStmt.Append("\t\t\tcase "); getFieldStmt.Append(field.Pos); getFieldStmt.Append(": return this."); getFieldStmt.Append(mangledName); getFieldStmt.Append(";\n"); // add to Put() putFieldStmt.Append("\t\t\tcase "); putFieldStmt.Append(field.Pos); putFieldStmt.Append(": this."); putFieldStmt.Append(mangledName); if (nullibleEnum) { putFieldStmt.Append(" = fieldValue == null ? ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")null : ("); string type = baseType.Remove(0, 16); // remove System.Nullable< type = type.Remove(type.Length - 1); // remove > putFieldStmt.Append(type); putFieldStmt.Append(")fieldValue; break;\n"); } else { putFieldStmt.Append(" = ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")fieldValue; break;\n"); } } // end switch block for Get() getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}"); var cseGet = new CodeSnippetExpression(getFieldStmt.ToString()); cmmGet.Statements.Add(cseGet); ctd.Members.Add(cmmGet); // end switch block for Put() putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}"); var csePut = new CodeSnippetExpression(putFieldStmt.ToString()); cmmPut.Statements.Add(csePut); ctd.Members.Add(cmmPut); string nspace = recordSchema.Namespace; if (string.IsNullOrEmpty(nspace)) throw new CodeGenException("Namespace required for record schema " + recordSchema.Name); CodeNamespace codens = addNamespace(nspace); codens.Types.Add(ctd); return ctd; } /// <summary> /// Gets the string representation of the schema's data type /// </summary> /// <param name="schema">schema</param> /// <param name="nullible">flag to indicate union with null</param> /// <returns></returns> internal static string getType(Schema schema, bool nullible, ref bool nullibleEnum) { switch (schema.Tag) { case Schema.Type.Null: return "System.Object"; case Schema.Type.Boolean: if (nullible) return "System.Nullable<bool>"; else return typeof(bool).ToString(); case Schema.Type.Int: if (nullible) return "System.Nullable<int>"; else return typeof(int).ToString(); case Schema.Type.Long: if (nullible) return "System.Nullable<long>"; else return typeof(long).ToString(); case Schema.Type.Float: if (nullible) return "System.Nullable<float>"; else return typeof(float).ToString(); case Schema.Type.Double: if (nullible) return "System.Nullable<double>"; else return typeof(double).ToString(); case Schema.Type.Bytes: return typeof(byte[]).ToString(); case Schema.Type.String: return typeof(string).ToString(); case Schema.Type.Enumeration: var namedSchema = schema as NamedSchema; if (null == namedSchema) throw new CodeGenException("Unable to cast schema into a named schema"); if (nullible) { nullibleEnum = true; return "System.Nullable<" + CodeGenUtil.Instance.Mangle(namedSchema.Fullname) + ">"; } else return CodeGenUtil.Instance.Mangle(namedSchema.Fullname); case Schema.Type.Fixed: case Schema.Type.Record: case Schema.Type.Error: namedSchema = schema as NamedSchema; if (null == namedSchema) throw new CodeGenException("Unable to cast schema into a named schema"); return CodeGenUtil.Instance.Mangle(namedSchema.Fullname); case Schema.Type.Array: var arraySchema = schema as ArraySchema; if (null == arraySchema) throw new CodeGenException("Unable to cast schema into an array schema"); return "IList<" + getType(arraySchema.ItemSchema, false, ref nullibleEnum) + ">"; case Schema.Type.Map: var mapSchema = schema as MapSchema; if (null == mapSchema) throw new CodeGenException("Unable to cast schema into a map schema"); return "IDictionary<string," + getType(mapSchema.ValueSchema, false, ref nullibleEnum) + ">"; case Schema.Type.Union: var unionSchema = schema as UnionSchema; if (null == unionSchema) throw new CodeGenException("Unable to cast schema into a union schema"); Schema nullibleType = getNullableType(unionSchema); if (null == nullibleType) return CodeGenUtil.Object; else return getType(nullibleType, true, ref nullibleEnum); } throw new CodeGenException("Unable to generate CodeTypeReference for " + schema.Name + " type " + schema.Tag); } /// <summary> /// Gets the schema of a union with null /// </summary> /// <param name="schema">union schema</param> /// <returns>schema that is nullible</returns> public static Schema getNullableType(UnionSchema schema) { Schema ret = null; if (schema.Count == 2) { bool nullable = false; foreach (Schema childSchema in schema.Schemas) { if (childSchema.Tag == Schema.Type.Null) nullable = true; else ret = childSchema; } if (!nullable) ret = null; } return ret; } /// <summary> /// Creates the static schema field for class types /// </summary> /// <param name="schema">schema</param> /// <param name="ctd">CodeTypeDeclaration for the class</param> protected virtual void createSchemaField(Schema schema, CodeTypeDeclaration ctd, bool overrideFlag) { // create schema field var ctrfield = new CodeTypeReference("Schema"); string schemaFname = "_SCHEMA"; var codeField = new CodeMemberField(ctrfield, schemaFname); codeField.Attributes = MemberAttributes.Public | MemberAttributes.Static; // create function call Schema.Parse(json) var cpe = new CodePrimitiveExpression(schema.ToString()); var cmie = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Schema)), "Parse"), new CodeExpression[] { cpe }); codeField.InitExpression = cmie; ctd.Members.Add(codeField); // create property to get static schema field var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public; if (overrideFlag) property.Attributes |= MemberAttributes.Override; property.Name = "Schema"; property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(ctd.Name + "." + schemaFname))); ctd.Members.Add(property); } /// <summary> /// Creates an XML documentation for the given comment /// </summary> /// <param name="comment">comment</param> /// <returns>CodeCommentStatement object</returns> protected virtual CodeCommentStatement createDocComment(string comment) { string text = string.Format("<summary>\r\n {0}\r\n </summary>", comment); return new CodeCommentStatement(text, true); } /// <summary> /// Writes the generated compile unit into one file /// </summary> /// <param name="outputFile">name of output file to write to</param> public virtual void WriteCompileUnit(string outputFile) { var cscp = new CSharpCodeProvider(); var opts = new CodeGeneratorOptions(); opts.BracingStyle = "C"; opts.IndentString = "\t"; opts.BlankLinesBetweenMembers = false; using (var outfile = new StreamWriter(outputFile)) { cscp.GenerateCodeFromCompileUnit(CompileUnit, outfile, opts); } } /// <summary> /// Writes each types in each namespaces into individual files /// </summary> /// <param name="outputdir">name of directory to write to</param> public virtual void WriteTypes(string outputdir) { var cscp = new CSharpCodeProvider(); var opts = new CodeGeneratorOptions(); opts.BracingStyle = "C"; opts.IndentString = "\t"; opts.BlankLinesBetweenMembers = false; CodeNamespaceCollection nsc = CompileUnit.Namespaces; for (int i = 0; i < nsc.Count; i++) { var ns = nsc[i]; string dir = outputdir + "\\" + CodeGenUtil.Instance.UnMangle(ns.Name).Replace('.', '\\'); Directory.CreateDirectory(dir); var new_ns = new CodeNamespace(ns.Name); new_ns.Comments.Add(CodeGenUtil.Instance.FileComment); foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports) new_ns.Imports.Add(nci); var types = ns.Types; for (int j = 0; j < types.Count; j++) { var ctd = types[j]; string file = dir + "\\" + CodeGenUtil.Instance.UnMangle(ctd.Name) + ".cs"; using (var writer = new StreamWriter(file, false)) { new_ns.Types.Add(ctd); cscp.GenerateCodeFromNamespace(new_ns, writer, opts); new_ns.Types.Remove(ctd); } } } } } }
/* * 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.Reflection; using System.Threading; using System.Text; using System.Timers; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Mono.Addins; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")] public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}"; private Scene m_scene = null; private int m_savetime = 5; // seconds to wait before saving changed appearance private int m_sendtime = 2; // seconds to wait before sending changed appearance private bool m_reusetextures = false; private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates private System.Timers.Timer m_updateTimer = new System.Timers.Timer(); private Dictionary<UUID,long> m_savequeue = new Dictionary<UUID,long>(); private Dictionary<UUID,long> m_sendqueue = new Dictionary<UUID,long>(); private object m_setAppearanceLock = new object(); #region Region Module interface public void Initialise(IConfigSource config) { IConfig appearanceConfig = config.Configs["Appearance"]; if (appearanceConfig != null) { m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime))); m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime))); m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures",m_reusetextures); // m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime); } } public void AddRegion(Scene scene) { if (m_scene == null) m_scene = scene; scene.RegisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient += SubscribeToClientEvents; } public void RemoveRegion(Scene scene) { if (scene == m_scene) { scene.UnregisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient -= SubscribeToClientEvents; } m_scene = null; } public void RegionLoaded(Scene scene) { m_updateTimer.Enabled = false; m_updateTimer.AutoReset = true; m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer); } public void Close() { } public string Name { get { return "Default Avatar Factory"; } } public bool IsSharedModule { get { return false; } } public Type ReplaceableInterface { get { return null; } } private void SubscribeToClientEvents(IClientAPI client) { client.OnRequestWearables += Client_OnRequestWearables; client.OnSetAppearance += Client_OnSetAppearance; client.OnAvatarNowWearing += Client_OnAvatarNowWearing; client.OnCachedTextureRequest += Client_OnCachedTextureRequest; } #endregion #region IAvatarFactoryModule /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems) { SetAppearance(sp, appearance.Texture, appearance.VisualParams, cacheItems); } public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { float oldoff = sp.Appearance.AvatarFeetOffset; Vector3 oldbox = sp.Appearance.AvatarBoxSize; SetAppearance(sp, textureEntry, visualParams, cacheItems); sp.Appearance.SetSize(avSize); float off = sp.Appearance.AvatarFeetOffset; Vector3 box = sp.Appearance.AvatarBoxSize; if (oldoff != off || oldbox != box) ((ScenePresence)sp).SetSize(box, off); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems) { // m_log.DebugFormat( // "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}", // sp.Name, textureEntry, visualParams); // TODO: This is probably not necessary any longer, just assume the // textureEntry set implies that the appearance transaction is complete bool changed = false; // Process the texture entry transactionally, this doesn't guarantee that Appearance is // going to be handled correctly but it does serialize the updates to the appearance lock (m_setAppearanceLock) { // Process the visual params, this may change height as well if (visualParams != null) { changed = sp.Appearance.SetVisualParams(visualParams); } // Process the baked texture array if (textureEntry != null) { m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID); // WriteBakedTexturesReport(sp, m_log.DebugFormat); changed = sp.Appearance.SetTextureEntries(textureEntry) || changed; // WriteBakedTexturesReport(sp, m_log.DebugFormat); UpdateBakedTextureCache(sp, cacheItems); // This appears to be set only in the final stage of the appearance // update transaction. In theory, we should be able to do an immediate // appearance send and save here. } // NPC should send to clients immediately and skip saving appearance if (((ScenePresence)sp).PresenceType == PresenceType.Npc) { SendAppearance((ScenePresence)sp); return; } // save only if there were changes, send no matter what (doesn't hurt to send twice) if (changed) QueueAppearanceSave(sp.ControllingClient.AgentId); QueueAppearanceSend(sp.ControllingClient.AgentId); } // m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString()); } private void SendAppearance(ScenePresence sp) { // Send the appearance to everyone in the scene sp.SendAppearanceToAllOtherAgents(); // Send animations back to the avatar as well sp.Animator.SendAnimPack(); } public bool SendAppearance(UUID agentId) { // m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId); ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) { // This is expected if the user has gone away. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId); return false; } SendAppearance(sp); return true; } public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); return GetBakedTextureFaces(sp); } public WearableCacheItem[] GetCachedItems(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); WearableCacheItem[] items = sp.Appearance.WearableCacheItems; //foreach (WearableCacheItem item in items) //{ //} return items; } public bool SaveBakedTextures(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return false; m_log.DebugFormat( "[AV FACTORY]: Permanently saving baked textures for {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp); if (bakedTextures.Count == 0) return false; IAssetCache cache = sp.Scene.RequestModuleInterface<IAssetCache>(); if(cache == null) return true; // no baked local caching so nothing to do foreach (BakeType bakeType in bakedTextures.Keys) { Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType]; if (bakedTextureFace == null) continue; AssetBase asset; cache.Get(bakedTextureFace.TextureID.ToString(), out asset); if (asset != null && asset.Local) { // cache does not update asset contents cache.Expire(bakedTextureFace.TextureID.ToString()); // Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars asset.ID = asset.FullID.ToString(); asset.Temporary = false; asset.Local = false; m_scene.AssetService.Store(asset); } if (asset == null) { m_log.WarnFormat( "[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently", bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName); } } return true; } /// <summary> /// Queue up a request to send appearance. /// </summary> /// <remarks> /// Makes it possible to accumulate changes without sending out each one separately. /// </remarks> /// <param name="agentId"></param> public void QueueAppearanceSend(UUID agentid) { // m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000); lock (m_sendqueue) { m_sendqueue[agentid] = timestamp; m_updateTimer.Start(); } } public void QueueAppearanceSave(UUID agentid) { // m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000); lock (m_savequeue) { m_savequeue[agentid] = timestamp; m_updateTimer.Start(); } } // called on textures update public bool UpdateBakedTextureCache(IScenePresence sp, WearableCacheItem[] cacheItems) { if(cacheItems == null) return false; // npcs dont have baked cache if (((ScenePresence)sp).IsNPC) return true; // uploaded baked textures will be in assets local cache IAssetService cache = m_scene.AssetService; IBakedTextureModule m_BakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); int validDirtyBakes = 0; int hits = 0; // our main cacheIDs mapper is p.Appearance.WearableCacheItems WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems; if (wearableCache == null) { wearableCache = WearableCacheItem.GetDefaultCacheItem(); } List<UUID> missing = new List<UUID>(); bool haveSkirt = (wearableCache[19].TextureAsset != null); bool haveNewSkirt = false; // Process received baked textures for (int i = 0; i < cacheItems.Length; i++) { int idx = (int)cacheItems[i].TextureIndex; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // No face if (face == null) { // for some reason viewer is cleaning this if(idx != 19) // skirt is optional { sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint) idx); sp.Appearance.Texture.FaceTextures[idx].TextureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE; } wearableCache[idx].CacheId = UUID.Zero; wearableCache[idx].TextureID = UUID.Zero; wearableCache[idx].TextureAsset = null; continue; } else { if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) { wearableCache[idx].CacheId = UUID.Zero; wearableCache[idx].TextureID = UUID.Zero; wearableCache[idx].TextureAsset = null; continue; } if(idx == 19) haveNewSkirt = true; /* if (face.TextureID == wearableCache[idx].TextureID && m_BakedTextureModule != null) { if (wearableCache[idx].CacheId != cacheItems[i].CacheId) { wearableCache[idx].CacheId = cacheItems[i].CacheId; validDirtyBakes++; //assuming this can only happen if asset is in cache } hits++; continue; } */ wearableCache[idx].TextureAsset = null; if (cache != null) wearableCache[idx].TextureAsset = cache.GetCached(face.TextureID.ToString()); if (wearableCache[idx].TextureAsset != null) { if ( wearableCache[idx].TextureID != face.TextureID || wearableCache[idx].CacheId != cacheItems[i].CacheId) validDirtyBakes++; wearableCache[idx].TextureID = face.TextureID; wearableCache[idx].CacheId = cacheItems[i].CacheId; hits++; } else { wearableCache[idx].CacheId = UUID.Zero; wearableCache[idx].TextureID = UUID.Zero; wearableCache[idx].TextureAsset = null; missing.Add(face.TextureID); continue; } } } // handle optional skirt case if(!haveNewSkirt && haveSkirt) { wearableCache[19].CacheId = UUID.Zero; wearableCache[19].TextureID = UUID.Zero; wearableCache[19].TextureAsset = null; validDirtyBakes++; } sp.Appearance.WearableCacheItems = wearableCache; if (missing.Count > 0) { foreach (UUID id in missing) sp.ControllingClient.SendRebakeAvatarTextures(id); } if (validDirtyBakes > 0 && hits == cacheItems.Length) { // if we got a full set of baked textures save all in BakedTextureModule if (m_BakedTextureModule != null) { m_log.Debug("[UpdateBakedCache] start async uploading to bakedModule cache"); m_BakedTextureModule.Store(sp.UUID, wearableCache); } } // debug m_log.Debug("[UpdateBakedCache] cache hits: " + hits.ToString() + " changed entries: " + validDirtyBakes.ToString() + " rebakes " + missing.Count); /* for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++) { int j = AvatarAppearance.BAKE_INDICES[iter]; m_log.Debug("[UpdateBCache] {" + iter + "/" + sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" + sp.Appearance.WearableCacheItems[j].CacheId + ", t-" + sp.Appearance.WearableCacheItems[j].TextureID); } */ return (hits == cacheItems.Length); } // called when we get a new root avatar public bool ValidateBakedTextureCache(IScenePresence sp) { int hits = 0; if (((ScenePresence)sp).IsNPC) return true; lock (m_setAppearanceLock) { IAssetService cache = m_scene.AssetService; IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); WearableCacheItem[] bakedModuleCache = null; if (cache == null) return false; WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems; // big debug m_log.DebugFormat("[AVFACTORY]: ValidateBakedTextureCache start for {0} {1}", sp.Name, sp.UUID); /* for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++) { int j = AvatarAppearance.BAKE_INDICES[iter]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[j]; if (wearableCache == null) { if (face != null) m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- " + face.TextureID); else m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- No texture"); } else { if (face != null) m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " ft- " + face.TextureID + "}: cc-" + wearableCache[j].CacheId + ", ct-" + wearableCache[j].TextureID ); else m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t - No texture" + "}: cc-" + wearableCache[j].CacheId + ", ct-" + wearableCache[j].TextureID ); } } */ bool wearableCacheValid = false; if (wearableCache == null) { wearableCache = WearableCacheItem.GetDefaultCacheItem(); } else { // we may have received a full cache // check same coerence and store wearableCacheValid = true; for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; if (face != null) { if (face.TextureID == wearableCache[idx].TextureID && face.TextureID != UUID.Zero) { if (wearableCache[idx].TextureAsset != null) { hits++; wearableCache[idx].TextureAsset.Temporary = true; wearableCache[idx].TextureAsset.Local = true; cache.Store(wearableCache[idx].TextureAsset); continue; } if (cache.GetCached((wearableCache[idx].TextureID).ToString()) != null) { hits++; continue; } } wearableCacheValid = false; } } wearableCacheValid = (wearableCacheValid && (hits >= AvatarAppearance.BAKE_INDICES.Length - 1)); if (wearableCacheValid) m_log.Debug("[ValidateBakedCache] have valid local cache"); else wearableCache[19].TextureAsset = null; // clear optional skirt } bool checkExternal = false; if (!wearableCacheValid) { hits = 0; // only use external bake module on login condition check // ScenePresence ssp = null; // if (sp is ScenePresence) { // ssp = (ScenePresence)sp; // checkExternal = (((uint)ssp.TeleportFlags & (uint)TeleportFlags.ViaLogin) != 0) && // bakedModule != null; // or do it anytime we dont have the cache checkExternal = bakedModule != null; } } if (checkExternal) { bool gotbacked = false; m_log.Debug("[ValidateBakedCache] local cache invalid, checking bakedModule"); try { bakedModuleCache = bakedModule.Get(sp.UUID); } catch (Exception e) { m_log.ErrorFormat(e.ToString()); bakedModuleCache = null; } if (bakedModuleCache != null) { m_log.Debug("[ValidateBakedCache] got bakedModule " + bakedModuleCache.Length + " cached textures"); for (int i = 0; i < bakedModuleCache.Length; i++) { int j = (int)bakedModuleCache[i].TextureIndex; if (bakedModuleCache[i].TextureAsset != null) { wearableCache[j].TextureID = bakedModuleCache[i].TextureID; wearableCache[j].CacheId = bakedModuleCache[i].CacheId; wearableCache[j].TextureAsset = bakedModuleCache[i].TextureAsset; bakedModuleCache[i].TextureAsset.Temporary = true; bakedModuleCache[i].TextureAsset.Local = true; cache.Store(bakedModuleCache[i].TextureAsset); } } gotbacked = true; } if (gotbacked) { // force the ones we got for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; if(wearableCache[idx].TextureAsset == null) { if(idx == 19) { sp.Appearance.Texture.FaceTextures[idx] = null; hits++; } continue; } Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; if (face == null) { face = sp.Appearance.Texture.CreateFace((uint)idx); sp.Appearance.Texture.FaceTextures[idx] = face; } face.TextureID = wearableCache[idx].TextureID; hits++; } } } sp.Appearance.WearableCacheItems = wearableCache; } // debug m_log.DebugFormat("[ValidateBakedCache]: Completed texture check for {0} {1} with {2} hits", sp.Name, sp.UUID, hits); /* for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++) { int j = AvatarAppearance.BAKE_INDICES[iter]; m_log.Debug("[ValidateBakedCache] {" + iter + "/" + sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" + sp.Appearance.WearableCacheItems[j].CacheId + ", t-" + sp.Appearance.WearableCacheItems[j].TextureID); } */ return (hits >= AvatarAppearance.BAKE_INDICES.Length - 1); // skirt is optional } public int RequestRebake(IScenePresence sp, bool missingTexturesOnly) { if (((ScenePresence)sp).IsNPC) return 0; int texturesRebaked = 0; // IAssetCache cache = m_scene.RequestModuleInterface<IAssetCache>(); for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // if there is no texture entry, skip it if (face == null) continue; if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue; if (missingTexturesOnly) { if (m_scene.AssetService.Get(face.TextureID.ToString()) != null) { continue; } else { // On inter-simulator teleports, this occurs if baked textures are not being stored by the // grid asset service (which means that they are not available to the new region and so have // to be re-requested from the client). // // The only available core OpenSimulator behaviour right now // is not to store these textures, temporarily or otherwise. m_log.DebugFormat( "[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.", face.TextureID, idx, sp.Name); } } else { m_log.DebugFormat( "[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.", face.TextureID, idx, sp.Name); } texturesRebaked++; sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID); } return texturesRebaked; } #endregion #region AvatarFactoryModule private methods private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp) { if (sp.IsChildAgent) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = new Dictionary<BakeType, Primitive.TextureEntryFace>(); AvatarAppearance appearance = sp.Appearance; Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures; foreach (int i in Enum.GetValues(typeof(BakeType))) { BakeType bakeType = (BakeType)i; if (bakeType == BakeType.Unknown) continue; // m_log.DebugFormat( // "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}", // acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]); int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType); Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture bakedTextures[bakeType] = texture; } return bakedTextures; } private void HandleAppearanceUpdateTimer(object sender, EventArgs ea) { long now = DateTime.Now.Ticks; lock (m_sendqueue) { Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue); foreach (KeyValuePair<UUID, long> kvp in sends) { // We have to load the key and value into local parameters to avoid a race condition if we loop // around and load kvp with a different value before FireAndForget has launched its thread. UUID avatarID = kvp.Key; long sendTime = kvp.Value; // m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now); if (sendTime < now) { Util.FireAndForget(o => SendAppearance(avatarID), null, "AvatarFactoryModule.SendAppearance"); m_sendqueue.Remove(avatarID); } } } lock (m_savequeue) { Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue); foreach (KeyValuePair<UUID, long> kvp in saves) { // We have to load the key and value into local parameters to avoid a race condition if we loop // around and load kvp with a different value before FireAndForget has launched its thread. UUID avatarID = kvp.Key; long sendTime = kvp.Value; if (sendTime < now) { Util.FireAndForget(o => SaveAppearance(avatarID), null, "AvatarFactoryModule.SaveAppearance"); m_savequeue.Remove(avatarID); } } // We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on // another thread inbetween the first count calls and m_updateTimer.Stop() on this thread. lock (m_sendqueue) if (m_savequeue.Count == 0 && m_sendqueue.Count == 0) m_updateTimer.Stop(); } } private void SaveAppearance(UUID agentid) { // We must set appearance parameters in the en_US culture in order to avoid issues where values are saved // in a culture where decimal points are commas and then reloaded in a culture which just treats them as // number seperators. Culture.SetCurrentCulture(); ScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) { // This is expected if the user has gone away. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid); return; } // m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid); // This could take awhile since it needs to pull inventory // We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape // assets and item asset id changes to complete. // I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids // multiple save requests. SetAppearanceAssets(sp.UUID, sp.Appearance); // List<AvatarAttachment> attachments = sp.Appearance.GetAttachments(); // foreach (AvatarAttachment att in attachments) // { // m_log.DebugFormat( // "[AVFACTORY]: For {0} saving attachment {1} at point {2}", // sp.Name, att.ItemID, att.AttachPoint); // } m_scene.AvatarService.SetAppearance(agentid, sp.Appearance); // Trigger this here because it's the final step in the set/queue/save process for appearance setting. // Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes). m_scene.EventManager.TriggerAvatarAppearanceChanged(sp); } /// <summary> /// For a given set of appearance items, check whether the items are valid and add their asset IDs to /// appearance data. /// </summary> /// <param name='userID'></param> /// <param name='appearance'></param> private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance) { IInventoryService invService = m_scene.InventoryService; if (invService.GetRootFolder(userID) != null) { for (int i = 0; i < appearance.Wearables.Length; i++) { for (int j = 0; j < appearance.Wearables[i].Count; j++) { if (appearance.Wearables[i][j].ItemID == UUID.Zero) { m_log.WarnFormat( "[AVFACTORY]: Wearable item {0}:{1} for user {2} unexpectedly UUID.Zero. Ignoring.", i, j, userID); continue; } // Ignore ruth's assets if (i < AvatarWearable.DefaultWearables.Length) { if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) continue; } InventoryItemBase baseItem = invService.GetItem(userID, appearance.Wearables[i][j].ItemID); if (baseItem != null) { appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); } else { m_log.WarnFormat( "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", appearance.Wearables[i][j].ItemID, (WearableType)i); appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID); } } } } else { m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); } // IInventoryService invService = m_scene.InventoryService; // bool resetwearable = false; // if (invService.GetRootFolder(userID) != null) // { // for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) // { // for (int j = 0; j < appearance.Wearables[i].Count; j++) // { // // Check if the default wearables are not set // if (appearance.Wearables[i][j].ItemID == UUID.Zero) // { // switch ((WearableType) i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // m_log.Warn("[AVFACTORY]: UUID.Zero Wearables, passing fake values."); // resetwearable = true; // break; // // } // continue; // } // // // Ignore ruth's assets except for the body parts! missing body parts fail avatar appearance on V1 // if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) // { // switch ((WearableType)i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // // m_log.WarnFormat("[AVFACTORY]: {0} Default Wearables, passing existing values.", (WearableType)i); // resetwearable = true; // break; // // } // continue; // } // // InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); // baseItem = invService.GetItem(baseItem); // // if (baseItem != null) // { // appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); // int unmodifiedWearableIndexForClosure = i; // m_scene.AssetService.Get(baseItem.AssetID.ToString(), this, // delegate(string x, object y, AssetBase z) // { // if (z == null) // { // TryAndRepairBrokenWearable( // (WearableType)unmodifiedWearableIndexForClosure, invService, // userID, appearance); // } // }); // } // else // { // m_log.ErrorFormat( // "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", // appearance.Wearables[i][j].ItemID, (WearableType)i); // // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // // } // } // } // // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int) WearableType.Eyes] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Eyes are Null, passing existing values.", (WearableType.Eyes)); // // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int) WearableType.Eyes][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Eyes are UUID.Zero are broken, {0} {1}", // appearance.Wearables[(int) WearableType.Eyes][0].ItemID, // appearance.Wearables[(int) WearableType.Eyes][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Shape] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} shape is Null, passing existing values.", (WearableType.Shape)); // // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Shape][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Shape is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Shape][0].ItemID, // appearance.Wearables[(int)WearableType.Shape][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Hair] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Hair is Null, passing existing values.", (WearableType.Hair)); // // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Hair][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Hair is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Hair][0].ItemID, // appearance.Wearables[(int)WearableType.Hair][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Skin] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Skin is Null, passing existing values.", (WearableType.Skin)); // // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Skin][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Skin is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Skin][0].ItemID, // appearance.Wearables[(int)WearableType.Skin][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // // } // // } // if (resetwearable) // { // ScenePresence presence = null; // if (m_scene.TryGetScenePresence(userID, out presence)) // { // presence.ControllingClient.SendWearables(presence.Appearance.Wearables, // presence.Appearance.Serial++); // } // } // // } // else // { // m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); // } } private void TryAndRepairBrokenWearable(WearableType type, IInventoryService invService, UUID userID,AvatarAppearance appearance) { UUID defaultwearable = GetDefaultItem(type); if (defaultwearable != UUID.Zero) { UUID newInvItem = UUID.Random(); InventoryItemBase itembase = new InventoryItemBase(newInvItem, userID) { AssetID = defaultwearable, AssetType = (int)FolderType.BodyPart, CreatorId = userID.ToString(), //InvType = (int)InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService.GetFolderForType(userID, FolderType.BodyPart).ID, Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type), BasePermissions = (uint) PermissionMask.Copy, CurrentPermissions = (uint) PermissionMask.Copy, EveryOnePermissions = (uint) PermissionMask.Copy, GroupPermissions = (uint) PermissionMask.Copy, NextPermissions = (uint) PermissionMask.Copy }; invService.AddItem(itembase); UUID LinkInvItem = UUID.Random(); itembase = new InventoryItemBase(LinkInvItem, userID) { AssetID = newInvItem, AssetType = (int)AssetType.Link, CreatorId = userID.ToString(), InvType = (int) InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService.GetFolderForType(userID, FolderType.CurrentOutfit).ID, Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type), BasePermissions = (uint) PermissionMask.Copy, CurrentPermissions = (uint) PermissionMask.Copy, EveryOnePermissions = (uint) PermissionMask.Copy, GroupPermissions = (uint) PermissionMask.Copy, NextPermissions = (uint) PermissionMask.Copy }; invService.AddItem(itembase); appearance.Wearables[(int)type] = new AvatarWearable(newInvItem, GetDefaultItem(type)); ScenePresence presence = null; if (m_scene.TryGetScenePresence(userID, out presence)) { m_scene.SendInventoryUpdate(presence.ControllingClient, invService.GetFolderForType(userID, FolderType.CurrentOutfit), false, true); } } } private UUID GetDefaultItem(WearableType wearable) { // These are ruth UUID ret = UUID.Zero; switch (wearable) { case WearableType.Eyes: ret = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7"); break; case WearableType.Hair: ret = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66"); break; case WearableType.Pants: ret = new UUID("00000000-38f9-1111-024e-222222111120"); break; case WearableType.Shape: ret = new UUID("66c41e39-38f9-f75a-024e-585989bfab73"); break; case WearableType.Shirt: ret = new UUID("00000000-38f9-1111-024e-222222111110"); break; case WearableType.Skin: ret = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb"); break; case WearableType.Undershirt: ret = new UUID("16499ebb-3208-ec27-2def-481881728f47"); break; case WearableType.Underpants: ret = new UUID("4ac2e9c7-3671-d229-316a-67717730841d"); break; } return ret; } #endregion #region Client Event Handlers /// <summary> /// Tell the client for this scene presence what items it should be wearing now /// </summary> /// <param name="client"></param> private void Client_OnRequestWearables(IClientAPI client) { Util.FireAndForget(delegate(object x) { Thread.Sleep(4000); // m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++); else m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId); }, null, "AvatarFactoryModule.OnClientRequestWearables"); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) received from a client /// </summary> /// <param name="client"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { // m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) SetAppearance(sp, textureEntry, visualParams,avSize, cacheItems); else m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId); } /// <summary> /// Update what the avatar is wearing using an item from their inventory. /// </summary> /// <param name="client"></param> /// <param name="e"></param> private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e) { // m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null) { m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId); return; } // we need to clean out the existing textures sp.Appearance.ResetAppearance(); // operate on a copy of the appearance so we don't have to lock anything yet AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false); foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) { // If the wearable type is larger than the current array, expand it if (avatAppearance.Wearables.Length <= wear.Type) { int currentLength = avatAppearance.Wearables.Length; AvatarWearable[] wears = avatAppearance.Wearables; Array.Resize(ref wears, wear.Type + 1); for (int i = currentLength ; i <= wear.Type ; i++) wears[i] = new AvatarWearable(); avatAppearance.Wearables = wears; } avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero); } avatAppearance.GetAssetsFrom(sp.Appearance); lock (m_setAppearanceLock) { // Update only those fields that we have changed. This is important because the viewer // often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing // shouldn't overwrite the changes made in SetAppearance. sp.Appearance.Wearables = avatAppearance.Wearables; sp.Appearance.Texture = avatAppearance.Texture; // We don't need to send the appearance here since the "iswearing" will trigger a new set // of visual param and baked texture changes. When those complete, the new appearance will be sent QueueAppearanceSave(client.AgentId); } } /// <summary> /// Respond to the cached textures request from the client /// </summary> /// <param name="client"></param> /// <param name="serial"></param> /// <param name="cachedTextureRequest"></param> private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest) { // m_log.WarnFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>(); foreach (CachedTextureRequestArg request in cachedTextureRequest) { UUID texture = UUID.Zero; int index = request.BakedTextureIndex; if (m_reusetextures) { // this is the most insanely dumb way to do this... however it seems to // actually work. if the appearance has been reset because wearables have // changed then the texture entries are zero'd out until the bakes are // uploaded. on login, if the textures exist in the cache (eg if you logged // into the simulator recently, then the appearance will pull those and send // them back in the packet and you won't have to rebake. if the textures aren't // in the cache then the intial makeroot() call in scenepresence will zero // them out. // // a better solution (though how much better is an open question) is to // store the hashes in the appearance and compare them. Thats's coming. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index]; if (face != null) texture = face.TextureID; // m_log.WarnFormat("[AVFACTORY]: reuse texture {0} for index {1}",texture,index); } CachedTextureResponseArg response = new CachedTextureResponseArg(); response.BakedTextureIndex = index; response.BakedTextureID = texture; response.HostName = null; cachedTextureResponse.Add(response); } // m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial); // The serial number appears to be used to match requests and responses // in the texture transaction. We just send back the serial number // that was provided in the request. The viewer bumps this for us. client.SendCachedTextureResponse(sp, serial, cachedTextureResponse); } #endregion public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction) { outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID"); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID); foreach (BakeType bt in bakedTextures.Keys) { string rawTextureID; if (bakedTextures[bt] == null) { rawTextureID = "not set"; } else { rawTextureID = bakedTextures[bt].TextureID.ToString(); if (m_scene.AssetService.Get(rawTextureID) == null) rawTextureID += " (not found)"; else rawTextureID += " (uploaded)"; } outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID); } bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp); outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete"); } } }
using Dapper; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using YesSql.Commands; using YesSql.Data; using YesSql.Indexes; using YesSql.Services; namespace YesSql { public class Session : ISession { private DbConnection _connection; private DbTransaction _transaction; internal List<IIndexCommand> _commands; private readonly Dictionary<string, SessionState> _collectionStates; private readonly SessionState _defaultState; private Dictionary<string, IEnumerable<IndexDescriptor>> _descriptors; internal readonly Store _store; private volatile bool _disposed; private bool _flushing; protected bool _cancel; protected bool _save; protected List<IIndexProvider> _indexes; protected string _tablePrefix; private readonly ISqlDialect _dialect; private readonly ILogger _logger; public Session(Store store) { _store = store; _tablePrefix = _store.Configuration.TablePrefix; _dialect = store.Dialect; _logger = store.Configuration.Logger; _defaultState = new SessionState(); _collectionStates = new Dictionary<string, SessionState>() { [""] = _defaultState }; } public ISession RegisterIndexes(IIndexProvider[] indexProviders, string collection = null) { foreach (var indexProvider in indexProviders) { if (indexProvider.CollectionName == null) { indexProvider.CollectionName = collection ?? ""; } } if (_indexes == null) { _indexes = new List<IIndexProvider>(); } _indexes.AddRange(indexProviders); return this; } private SessionState GetState(string collection) { if (String.IsNullOrEmpty(collection)) { return _defaultState; } if (!_collectionStates.TryGetValue(collection, out var state)) { state = new SessionState(); _collectionStates[collection] = state; } return state; } public void Save(object entity, bool checkConcurrency = false, string collection = null) { var state = GetState(collection); CheckDisposed(); // already being saved or updated or tracked? if (state.Saved.Contains(entity) || state.Updated.Contains(entity)) { return; } // remove from tracked entities if explicitly saved state.Tracked.Remove(entity); // is it a new object? if (state.IdentityMap.TryGetDocumentId(entity, out var id)) { state.Updated.Add(entity); // If this entity needs to be checked for concurrency, track its version if (checkConcurrency || _store.Configuration.ConcurrentTypes.Contains(entity.GetType())) { state.Concurrent.Add(id); } return; } // Does it have a valid identifier? var accessor = _store.GetIdAccessor(entity.GetType()); if (accessor != null) { id = accessor.Get(entity); if (id > 0) { state.IdentityMap.AddEntity(id, entity); state.Updated.Add(entity); // If this entity needs to be checked for concurrency, track its version if (checkConcurrency || _store.Configuration.ConcurrentTypes.Contains(entity.GetType())) { state.Concurrent.Add(id); } return; } } // It's a new entity id = _store.GetNextId(collection); state.IdentityMap.AddEntity(id, entity); // Then assign a new identifier if it has one if (accessor != null) { accessor.Set(entity, id); } state.Saved.Add(entity); } public bool Import(object entity, int id = 0, int version = 0, string collection = null) { CheckDisposed(); var state = GetState(collection); // already known? if (state.IdentityMap.HasEntity(entity)) { return false; } var doc = new Document { Type = Store.TypeNames[entity.GetType()], Content = Store.Configuration.ContentSerializer.Serialize(entity) }; // Import version if (version != 0) { doc.Version = version; } else { var versionAccessor = _store.GetVersionAccessor(entity.GetType()); if (versionAccessor != null) { doc.Version = versionAccessor.Get(entity); } } if (id != 0) { state.IdentityMap.AddEntity(id, entity); state.Updated.Add(entity); doc.Id = id; state.IdentityMap.AddDocument(doc); return true; } else { // Does it have a valid identifier? var accessor = _store.GetIdAccessor(entity.GetType()); if (accessor != null) { id = accessor.Get(entity); if (id > 0) { state.IdentityMap.AddEntity(id, entity); state.Updated.Add(entity); doc.Id = id; state.IdentityMap.AddDocument(doc); return true; } else { throw new InvalidOperationException($"Invalid 'Id' value: {id}"); } } else { throw new InvalidOperationException("Objects without an 'Id' property can't be imported if no 'id' argument is provided."); } } } public void Detach(object entity, string collection) { CheckDisposed(); var state = GetState(collection); state.Saved.Remove(entity); state.Updated.Remove(entity); state.Tracked.Remove(entity); state.Deleted.Remove(entity); if (state.IdentityMap.TryGetDocumentId(entity, out var id)) { state.IdentityMap.Remove(id, entity); } } private async Task SaveEntityAsync(object entity, string collection) { if (entity == null) { throw new ArgumentNullException("obj"); } if (entity is Document) { throw new ArgumentException("A document should not be saved explicitely"); } if (entity is IIndex) { throw new ArgumentException("An index should not be saved explicitely"); } var state = GetState(collection); var doc = new Document { Type = Store.TypeNames[entity.GetType()] }; if (!state.IdentityMap.TryGetDocumentId(entity, out var id)) { throw new InvalidOperationException("The object to save was not found in identity map."); } doc.Id = id; await CreateConnectionAsync(); var versionAccessor = _store.GetVersionAccessor(entity.GetType()); if (versionAccessor != null) { doc.Version = versionAccessor.Get(entity); } if (doc.Version == 0) { doc.Version = 1; } if (versionAccessor != null) { versionAccessor.Set(entity, (int) doc.Version); } doc.Content = Store.Configuration.ContentSerializer.Serialize(entity); _commands ??= new List<IIndexCommand>(); _commands.Add(new CreateDocumentCommand(doc, Store.Configuration.TableNameConvention, _tablePrefix, collection)); state.IdentityMap.AddDocument(doc); await MapNew(doc, entity, collection); } private async Task UpdateEntityAsync(object entity, bool tracked, string collection) { if (entity == null) { throw new ArgumentNullException("obj"); } var index = entity as IIndex; if (entity is Document) { throw new ArgumentException("A document should not be saved explicitely"); } if (index != null) { throw new ArgumentException("An index should not be saved explicitely"); } var state = GetState(collection); // Reload to get the old map if (!state.IdentityMap.TryGetDocumentId(entity, out var id)) { throw new InvalidOperationException("The object to update was not found in identity map."); } if (!state.IdentityMap.TryGetDocument(id, out var oldDoc)) { oldDoc = await GetDocumentByIdAsync(id, collection); if (oldDoc == null) { throw new InvalidOperationException("Incorrect attempt to update an object that doesn't exist. Ensure a new object was not saved with an identifier value."); } } var newContent = Store.Configuration.ContentSerializer.Serialize(entity); // if the document has already been updated or saved with this session (auto or intentional flush), ensure it has // been changed before doing another query if (tracked && String.Equals(newContent, oldDoc.Content)) { return; } long version = -1; if (state.Concurrent.Contains(id)) { version = oldDoc.Version; var versionAccessor = _store.GetVersionAccessor(entity.GetType()); if (versionAccessor != null) { var localVersion = versionAccessor.Get(entity); // if the version has been set, use it if (localVersion != 0) { version = localVersion; } } oldDoc.Version += 1; // apply the new version to the object if (versionAccessor != null) { versionAccessor.Set(entity, (int)oldDoc.Version); newContent = Store.Configuration.ContentSerializer.Serialize(entity); } } var oldObj = Store.Configuration.ContentSerializer.Deserialize(oldDoc.Content, entity.GetType()); // Update map index await MapDeleted(oldDoc, oldObj, collection); await MapNew(oldDoc, entity, collection); await CreateConnectionAsync(); oldDoc.Content = newContent; _commands ??= new List<IIndexCommand>(); _commands.Add(new UpdateDocumentCommand(oldDoc, Store, version, collection)); } private async Task<Document> GetDocumentByIdAsync(int id, string collection) { await CreateConnectionAsync(); var documentTable = Store.Configuration.TableNameConvention.GetDocumentTable(collection); var command = "select * from " + _dialect.QuoteForTableName(_tablePrefix + documentTable) + " where " + _dialect.QuoteForColumnName("Id") + " = @Id"; var key = new WorkerQueryKey(nameof(GetDocumentByIdAsync), new[] { id }); try { var result = await _store.ProduceAsync(key, (state) => { var logger = state.Store.Configuration.Logger; if (logger.IsEnabled(LogLevel.Trace)) { logger.LogTrace(state.Command); } return state.Connection.QueryAsync<Document>(state.Command, state.Parameters, state.Transaction); }, new { Store = _store, Connection = _connection, Transaction = _transaction, Command = command, Parameters = new { Id = id } }); return result.FirstOrDefault(); } catch { await CancelAsync(); throw; } } public void Delete(object obj, string collection = null) { CheckDisposed(); var state = GetState(collection); state.Deleted.Add(obj); } private async Task DeleteEntityAsync(object obj, string collection) { if (obj == null) { throw new ArgumentNullException("obj"); } else if (obj is IIndex) { throw new ArgumentException("Can't call DeleteEntity on an Index"); } else { var state = GetState(collection); if (!state.IdentityMap.TryGetDocumentId(obj, out var id)) { var accessor = _store.GetIdAccessor(obj.GetType()); if (accessor == null) { throw new InvalidOperationException("Could not delete object as it doesn't have an Id property"); } id = accessor.Get(obj); } var doc = await GetDocumentByIdAsync(id, collection); if (doc != null) { // Untrack the deleted object state.IdentityMap.Remove(id, obj); // Update impacted indexes await MapDeleted(doc, obj, collection); _commands ??= new List<IIndexCommand>(); // The command needs to come after any index deletion because of the database constraints _commands.Add(new DeleteDocumentCommand(doc, Store, collection)); } } } public async Task<IEnumerable<T>> GetAsync<T>(int[] ids, string collection = null) where T : class { if (ids == null || !ids.Any()) { return Enumerable.Empty<T>(); } CheckDisposed(); // Auto-flush await FlushAsync(); await CreateConnectionAsync(); var documentTable = Store.Configuration.TableNameConvention.GetDocumentTable(collection); var command = "select * from " + _dialect.QuoteForTableName(_tablePrefix + documentTable) + " where " + _dialect.QuoteForColumnName("Id") + " " + _dialect.InOperator("@Ids"); var key = new WorkerQueryKey(nameof(GetAsync), ids); try { var documents = await _store.ProduceAsync(key, (state) => { var logger = state.Store.Configuration.Logger; if (logger.IsEnabled(LogLevel.Trace)) { logger.LogTrace(state.Command); } return state.Connection.QueryAsync<Document>(state.Command, state.Parameters, state.Transaction); }, new { Store = _store, Connection = _connection, Transaction = _transaction, Command = command, Parameters = new { Ids = ids } }); return Get<T>(documents.OrderBy(d => Array.IndexOf(ids, d.Id)).ToArray(), collection); } catch { await CancelAsync(); throw; } } public IEnumerable<T> Get<T>(IList<Document> documents, string collection) where T : class { if (documents == null || !documents.Any()) { return Enumerable.Empty<T>(); } var result = new List<T>(); var defaultAccessor = _store.GetIdAccessor(typeof(T)); var typeName = Store.TypeNames[typeof(T)]; var state = GetState(collection); // Are all the objects already in cache? foreach (var d in documents) { if (state.IdentityMap.TryGetEntityById(d.Id, out var entity)) { result.Add((T)entity); } else { T item; IAccessor<int> accessor; // If the document type doesn't match the requested one, check it's a base type if (!String.Equals(typeName, d.Type, StringComparison.Ordinal)) { var itemType = Store.TypeNames[d.Type]; // Ignore the document if it can't be casted to the requested type if (!typeof(T).IsAssignableFrom(itemType)) { continue; } accessor = _store.GetIdAccessor(itemType); item = (T)Store.Configuration.ContentSerializer.Deserialize(d.Content, itemType); } else { item = (T)Store.Configuration.ContentSerializer.Deserialize(d.Content, typeof(T)); accessor = defaultAccessor; } if (accessor != null) { accessor.Set(item, d.Id); } // track the loaded object state.IdentityMap.AddEntity(d.Id, item); state.IdentityMap.AddDocument(d); result.Add(item); } }; return result; } public IQuery Query(string collection = null) { return new DefaultQuery(this, _tablePrefix, collection); } public IQuery<T> ExecuteQuery<T>(ICompiledQuery<T> compiledQuery, string collection = null) where T : class { if (compiledQuery == null) { throw new ArgumentNullException(nameof(compiledQuery)); } var compiledQueryType = compiledQuery.GetType(); var discriminator = NullableThumbprintFactory.GetNullableThumbprint(compiledQuery); if (!_store.CompiledQueries.TryGetValue(discriminator, out var queryState)) { lock (_store.CompiledQueries) { if (!_store.CompiledQueries.TryGetValue(discriminator, out queryState)) { var localQuery = ((IQuery)new DefaultQuery(this, _tablePrefix, collection)).For<T>(false); var defaultQuery = (DefaultQuery.Query<T>)compiledQuery.Query().Compile().Invoke(localQuery); queryState = defaultQuery._query._queryState; _store.CompiledQueries[discriminator] = queryState; } } } queryState = queryState.Clone(); IQuery newQuery = new DefaultQuery(this, queryState, compiledQuery); return newQuery.For<T>(false); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(Session)); } } ~Session() { // Ensure the session gets disposed if the user cannot wrap the session in a using block. // For instance in OrchardCore the session is disposed from a middleware, so if an exception // is thrown in a middleware, it might not get triggered. Dispose(false); } public void Dispose(bool disposing) { // Do nothing if Dispose() was already called if (!_disposed) { try { CommitOrRollbackTransaction(); } catch { _connection = null; _transaction = null; } } _disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public async Task FlushAsync() { if (!HasWork()) { return; } // prevent recursive calls in FlushAsync, // when autoflush is triggered from an IndexProvider // for instance. if (_flushing) { return; } _flushing = true; // we only check if the session is disposed if // there are no commands to commit. CheckDisposed(); try { // saving all tracked entities foreach (var collectionState in _collectionStates) { var state = collectionState.Value; var collection = collectionState.Key; foreach (var obj in state.Tracked) { if (!state.Deleted.Contains(obj)) { await UpdateEntityAsync(obj, true, collection); } } // saving all updated entities foreach (var obj in state.Updated) { if (!state.Deleted.Contains(obj)) { await UpdateEntityAsync(obj, false, collection); } } // saving all pending entities foreach (var obj in state.Saved) { await SaveEntityAsync(obj, collection); } // deleting all pending entities foreach (var obj in state.Deleted) { await DeleteEntityAsync(obj, collection); } } // compute all reduce indexes await ReduceAsync(); await BeginTransactionAsync(); BatchCommands(); if (_commands != null) { foreach (var command in _commands) { await command.ExecuteAsync(_connection, _transaction, _dialect, _logger); } } } catch { await CancelAsync(); throw; } finally { foreach (var state in _collectionStates.Values) { // Track all saved and updated entities in case they are modified before // CommitAsync is called foreach (var saved in state.Saved) { state.Tracked.Add(saved); } foreach (var updated in state.Updated) { state.Tracked.Add(updated); } state.Saved.Clear(); state.Updated.Clear(); state.Deleted.Clear(); state.Maps.Clear(); } _commands?.Clear(); _flushing = false; } } private void BatchCommands() { if (_commands != null && _commands.Count == 0) { return; } if (!_dialect.SupportsBatching || _store.Configuration.CommandsPageSize == 0) { return; } var batches = new List<IIndexCommand>(); // holds the queries, parameters and actions returned by an IIndexCommand, until we know we can // add it to a batch if it fits the limits (page size and parameters boundaries) var localDbCommand = _connection.CreateCommand(); var localQueries = new List<string>(); var localActions = new List<Action<DbDataReader>>(); var batch = new BatchCommand(_connection.CreateCommand()); var index = 0; foreach (var command in _commands.OrderBy(x => x.ExecutionOrder)) { index++; // Can the command be batched if (command.AddToBatch(_dialect, localQueries, localDbCommand, localActions, index)) { // Does it go over the page or parameters limits var tooManyQueries = batch.Queries.Count + localQueries.Count > _store.Configuration.CommandsPageSize; var tooManyCommands = batch.Command.Parameters.Count + localDbCommand.Parameters.Count > _store.Configuration.SqlDialect.MaxParametersPerCommand; if (tooManyQueries || tooManyCommands) { batches.Add(batch); // Then start a new batch batch = new BatchCommand(_connection.CreateCommand()); } // We can add the queries to the current batch batch.Queries.AddRange(localQueries); batch.Actions.AddRange(localActions); for (var i = localDbCommand.Parameters.Count - 1; i >= 0; i--) { // npgsql will prevent a parameter from being added to a collection // if it's already in another one var parameter = localDbCommand.Parameters[i]; localDbCommand.Parameters.RemoveAt(i); batch.Command.Parameters.Add(parameter); } } else { // The command can't be added to a batch, we leave it in the list of commands to execute individually // Finalize the current batch if (batch.Queries.Count > 0) { batches.Add(batch); // Then start a new batch batch = new BatchCommand(_connection.CreateCommand()); } batches.Add(command); } localQueries.Clear(); localDbCommand.Parameters.Clear(); localActions.Clear(); } // If the ongoing batch is not empty, add it if (batch.Queries.Count > 0) { batches.Add(batch); } _commands.Clear(); _commands.AddRange(batches); } public async Task SaveChangesAsync() { try { if (!_cancel) { await FlushAsync(); _save = true; } } finally { #if SUPPORTS_ASYNC_TRANSACTIONS await CommitOrRollbackTransactionAsync(); #else CommitOrRollbackTransaction(); #endif } } private void CommitOrRollbackTransaction() { // This method is still used in Dispose() when SUPPORTS_ASYNC_TRANSACTIONS is defined try { if (_cancel || !_save) { if (_transaction != null) { _transaction.Rollback(); } } else { if (_transaction != null) { _transaction.Commit(); } } } finally { ReleaseConnection(); } } #if SUPPORTS_ASYNC_TRANSACTIONS public async ValueTask DisposeAsync() { // Do nothing if Dispose() was already called if (_disposed) { return; } _disposed = true; try { await CommitOrRollbackTransactionAsync(); } catch { _transaction = null; _connection = null; } GC.SuppressFinalize(this); } private async Task CommitOrRollbackTransactionAsync() { try { if (!_cancel) { if (_transaction != null) { await _transaction.CommitAsync(); } } else { if (_transaction != null) { await _transaction.RollbackAsync(); } } } finally { await ReleaseConnectionAsync(); } } /// <summary> /// Clears all the resources associated to the transaction. /// </summary> private async Task ReleaseTransactionAsync() { foreach (var state in _collectionStates.Values) { // IndentityMap is cleared in ReleaseSession() state._concurrent?.Clear(); state._saved?.Clear(); state._updated?.Clear(); state._tracked?.Clear(); state._deleted?.Clear(); state._maps?.Clear(); } _commands?.Clear(); _commands = null; if (_transaction != null) { await _transaction.DisposeAsync(); _transaction = null; } } private async Task ReleaseConnectionAsync() { await ReleaseTransactionAsync(); if (_connection != null) { await _connection.CloseAsync(); await _connection.DisposeAsync(); _connection = null; } } #else public ValueTask DisposeAsync() { Dispose(); return default; } #endif /// <summary> /// Clears all the resources associated to the transaction. /// </summary> private void ReleaseTransaction() { foreach (var state in _collectionStates.Values) { // IndentityMap is cleared in ReleaseSession() state._concurrent?.Clear(); state._saved?.Clear(); state._updated?.Clear(); state._tracked?.Clear(); state._deleted?.Clear(); state._maps?.Clear(); } _commands?.Clear(); _commands = null; if (_transaction != null) { _transaction.Dispose(); _transaction = null; } } private void ReleaseConnection() { ReleaseTransaction(); if (_connection != null) { _connection.Close(); _connection.Dispose(); _connection = null; } } /// <summary> /// Whether the current session has data to flush or not. /// </summary> internal bool HasWork() { foreach (var state in _collectionStates.Values) { if ( state.Saved.Count + state.Updated.Count + state.Tracked.Count + state.Deleted.Count > 0 ) return true; } return false; } private async Task ReduceAsync() { foreach (var collectionState in _collectionStates) { var state = collectionState.Value; var collection = collectionState.Key; // loop over each Indexer used by new objects foreach (var descriptor in state.Maps.Keys) { // if the descriptor has no reduce behavior, ignore it if (descriptor.Reduce == null) { continue; } if (descriptor.GroupKey == null) { throw new InvalidOperationException( "A map/reduce index must declare at least one property with a GroupKey attribute: " + descriptor.Type.FullName); } // a groupping method for the current descriptor var descriptorGroup = GetGroupingMetod(descriptor); // list all available grouping keys in the current set var allKeysForDescriptor = state.Maps[descriptor].Select(x => x.Map).Select(descriptorGroup).Distinct().ToArray(); // reduce each group, will result in one Reduced index per group foreach (var currentKey in allKeysForDescriptor) { // group all mapped indexes var newMapsGroup = state.Maps[descriptor].Where(x => x.State == MapStates.New).Select(x => x.Map).Where( x => descriptorGroup(x).Equals(currentKey)).ToArray(); var deletedMapsGroup = state.Maps[descriptor].Where(x => x.State == MapStates.Delete).Select(x => x.Map).Where( x => descriptorGroup(x).Equals(currentKey)).ToArray(); var updatedMapsGroup = state.Maps[descriptor].Where(x => x.State == MapStates.Update).Select(x => x.Map).Where( x => descriptorGroup(x).Equals(currentKey)).ToArray(); // todo: if an updated object got his Key changed, then apply a New to the new value group // and a Delete to the old value group. Otherwise apply Update to the current value group IIndex index = null; if (newMapsGroup.Any()) { // reducing an already groupped set (technically the reduction should contain the grouping step, but by design ...) index = descriptor.Reduce(newMapsGroup.GroupBy(descriptorGroup).First()); if (index == null) { throw new InvalidOperationException( "The reduction on a grouped set should have resulted in a unique result" ); } } var dbIndex = await ReduceForAsync(descriptor, currentKey, collection); // if index present in db and new objects, reduce them if (dbIndex != null && index != null) { // reduce over the two objects var reductions = new[] { dbIndex, index }; var grouppedReductions = reductions.GroupBy(descriptorGroup).SingleOrDefault(); if (grouppedReductions == null) { throw new InvalidOperationException( "The grouping on the db and in memory set should have resulted in a unique result"); } index = descriptor.Reduce(grouppedReductions); if (index == null) { throw new InvalidOperationException( "The reduction on a grouped set should have resulted in a unique result"); } } else if (dbIndex != null) { index = dbIndex; } if (index != null) { // are there any deleted object for this descriptor/group ? if (deletedMapsGroup.Any()) { index = descriptor.Delete(index, deletedMapsGroup.GroupBy(descriptorGroup).First()); // At this point, index can be null if the reduction returned a null index from Delete handler } // are there any updated object for this descriptor/group ? if (updatedMapsGroup.Any()) { index = descriptor.Update(index, updatedMapsGroup.GroupBy(descriptorGroup).First()); } } var deletedDocumentIds = deletedMapsGroup.SelectMany(x => x.GetRemovedDocuments().Select(d => d.Id)).ToArray(); var addedDocumentIds = newMapsGroup.SelectMany(x => x.GetAddedDocuments().Select(d => d.Id)).ToArray(); _commands ??= new List<IIndexCommand>(); if (dbIndex != null) { if (index == null) { _commands.Add(new DeleteReduceIndexCommand(dbIndex, Store, collection)); } else { index.Id = dbIndex.Id; var common = addedDocumentIds.Intersect(deletedDocumentIds).ToArray(); addedDocumentIds = addedDocumentIds.Where(x => !common.Contains(x)).ToArray(); deletedDocumentIds = deletedDocumentIds.Where(x => !common.Contains(x)).ToArray(); // Update updated, new and deleted linked documents _commands.Add(new UpdateIndexCommand(index, addedDocumentIds, deletedDocumentIds, Store, collection)); } } else { if (index != null) { // The index is new _commands.Add(new CreateIndexCommand(index, addedDocumentIds, Store, collection)); } } } } } } private async Task<ReduceIndex> ReduceForAsync(IndexDescriptor descriptor, object currentKey, string collection) { await CreateConnectionAsync(); var name = _tablePrefix + _store.Configuration.TableNameConvention.GetIndexTable(descriptor.IndexType, collection); var sql = "select * from " + _dialect.QuoteForTableName(name) + " where " + _dialect.QuoteForColumnName(descriptor.GroupKey.Name) + " = @currentKey"; var index = await _connection.QueryAsync(descriptor.IndexType, sql, new { currentKey }, _transaction); return index.FirstOrDefault() as ReduceIndex; } /// <summary> /// Creates a Func{IIndex, object}; dynamically, based on GroupKey attributes /// this function will be used as the keySelector for Linq.Grouping /// </summary> private Func<IIndex, object> GetGroupingMetod(IndexDescriptor descriptor) { if (!_store.GroupMethods.TryGetValue(descriptor.Type, out var result)) { lock (_store.GroupMethods) { if (!_store.GroupMethods.TryGetValue(descriptor.Type, out result)) { // IIndex i => i var instance = Expression.Parameter(typeof(IIndex), "i"); // i => ((TIndex)i) var convertInstance = Expression.Convert(instance, descriptor.GroupKey.DeclaringType); // i => ((TIndex)i).{Property} var property = Expression.Property(convertInstance, descriptor.GroupKey); // i => (object)(((TIndex)i).{Property}) var convert = Expression.Convert(property, typeof(object)); result = Expression.Lambda<Func<IIndex, object>>(convert, instance).Compile(); _store.GroupMethods[descriptor.Type] = result; } } } return result; } /// <summary> /// Resolves all the descriptors registered on the Store and the Session /// </summary> private IEnumerable<IndexDescriptor> GetDescriptors(Type t, string collection) { _descriptors ??= new Dictionary<string, IEnumerable<IndexDescriptor>>(); var cacheKey = String.IsNullOrEmpty(collection) ? t.FullName : String.Concat(t.FullName + ":" + collection) ; if (!_descriptors.TryGetValue(cacheKey, out var typedDescriptors)) { typedDescriptors = _store.Describe(t, collection); if (_indexes != null) { typedDescriptors = typedDescriptors.Union(_store.CreateDescriptors(t, collection, _indexes)).ToArray(); } _descriptors.Add(cacheKey, typedDescriptors); } return typedDescriptors; } private async Task MapNew(Document document, object obj, string collection) { var descriptors = GetDescriptors(obj.GetType(), collection); var state = GetState(collection); foreach (var descriptor in descriptors) { // Ignore index if the object is filtered out if (descriptor.Filter != null && !descriptor.Filter.Invoke(obj)) { continue; } var mapped = await descriptor.Map(obj); if (mapped != null) { foreach (var index in mapped) { if (index == null) { continue; } _commands ??= new List<IIndexCommand>(); index.AddDocument(document); // if the mapped elements are not meant to be reduced, // then save them in db, as index if (descriptor.Reduce == null) { if (index.Id == 0) { _commands.Add(new CreateIndexCommand(index, Enumerable.Empty<int>(), Store, collection)); } else { _commands.Add(new UpdateIndexCommand(index, Enumerable.Empty<int>(), Enumerable.Empty<int>(), Store, collection)); } } else { // save for later reducing if (!state.Maps.TryGetValue(descriptor, out var listmap)) { state.Maps.Add(descriptor, listmap = new List<MapState>()); } listmap.Add(new MapState(index, MapStates.New)); } } } } } /// <summary> /// Update map and reduce indexes when an entity is deleted. /// </summary> private async Task MapDeleted(Document document, object obj, string collection) { var descriptors = GetDescriptors(obj.GetType(), collection); var state = GetState(collection); foreach (var descriptor in descriptors) { // Ignore index if the object is filtered out if (descriptor.Filter != null && !descriptor.Filter.Invoke(obj)) { continue; } _commands ??= new List<IIndexCommand>(); // If the mapped elements are not meant to be reduced, delete if (descriptor.Reduce == null || descriptor.Delete == null) { _commands.Add(new DeleteMapIndexCommand(descriptor.IndexType, document.Id, Store, collection)); } else { var mapped = await descriptor.Map(obj); if (mapped != null) { foreach (var index in mapped) { // save for later reducing if (!state.Maps.TryGetValue(descriptor, out var listmap)) { state.Maps.Add(descriptor, listmap = new List<MapState>()); } listmap.Add(new MapState(index, MapStates.Delete)); index.RemoveDocument(document); } } } } } /// <summary> /// Initializes a new connection if none has been yet. Use this method when reads need to be done. /// </summary> public async Task<DbConnection> CreateConnectionAsync() { CheckDisposed(); _connection ??= _store.Configuration.ConnectionFactory.CreateConnection(); if (_connection.State == ConnectionState.Closed) { await _connection.OpenAsync(); } return _connection; } public DbTransaction CurrentTransaction => _transaction; public Task<DbTransaction> BeginTransactionAsync() { return BeginTransactionAsync(Store.Configuration.IsolationLevel); } /// <summary> /// Begins a new transaction if none has been yet. Use this method when writes need to be done. /// </summary> public async Task<DbTransaction> BeginTransactionAsync(IsolationLevel isolationLevel) { CheckDisposed(); if (_transaction == null) { await CreateConnectionAsync(); // In the case of shared connections (InMemory) this can throw as the transation // might already be set by a concurrent thread on the same shared connection. #if SUPPORTS_ASYNC_TRANSACTIONS _transaction = await _connection.BeginTransactionAsync(isolationLevel); #else _transaction = _connection.BeginTransaction(isolationLevel); #endif } return _transaction; } public Task CancelAsync() { CheckDisposed(); _cancel = true; #if SUPPORTS_ASYNC_TRANSACTIONS return ReleaseTransactionAsync(); #else ReleaseTransaction(); return Task.CompletedTask; #endif } public IStore Store => _store; #region Storage implementation private struct IdString { #pragma warning disable 0649 public int Id; public string Content; #pragma warning restore 0649 } #endregion } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 UnityEngine; using System.Collections.Generic; /// <summary> /// Controls the player's movement in virtual reality. /// </summary> [RequireComponent(typeof(CharacterController))] public class OVRPlayerController : MonoBehaviour { /// <summary> /// The rate acceleration during movement. /// </summary> public float Acceleration = 0.1f; /// <summary> /// The rate of damping on movement. /// </summary> public float Damping = 0.3f; /// <summary> /// The rate of additional damping when moving sideways or backwards. /// </summary> public float BackAndSideDampen = 0.5f; /// <summary> /// The force applied to the character when jumping. /// </summary> public float JumpForce = 0.3f; /// <summary> /// The rate of rotation when using a gamepad. /// </summary> public float RotationAmount = 1.5f; /// <summary> /// The rate of rotation when using the keyboard. /// </summary> public float RotationRatchet = 45.0f; /// <summary> /// If true, reset the initial yaw of the player controller when the Hmd pose is recentered. /// </summary> public bool HmdResetsY = true; /// <summary> /// If true, tracking data from a child OVRCameraRig will update the direction of movement. /// </summary> public bool HmdRotatesY = true; /// <summary> /// Modifies the strength of gravity. /// </summary> public float GravityModifier = 0.379f; /// <summary> /// If true, each OVRPlayerController will use the player's physical height. /// </summary> public bool useProfileData = true; protected CharacterController Controller = null; protected OVRCameraRig CameraRig = null; private float MoveScale = 1.0f; private Vector3 MoveThrottle = Vector3.zero; private float FallSpeed = 0.0f; private OVRPose? InitialPose; private float InitialYRotation = 0.0f; private float MoveScaleMultiplier = 1.0f; private float RotationScaleMultiplier = 1.0f; private bool SkipMouseRotation = false; private bool HaltUpdateMovement = false; private bool prevHatLeft = false; private bool prevHatRight = false; private float SimulationRate = 60f; void Start() { // Add eye-depth as a camera offset from the player controller var p = CameraRig.transform.localPosition; p.z = OVRManager.profile.eyeDepth; CameraRig.transform.localPosition = p; } void Awake() { Controller = gameObject.GetComponent<CharacterController>(); if(Controller == null) Debug.LogWarning("OVRPlayerController: No CharacterController attached."); // We use OVRCameraRig to set rotations to cameras, // and to be influenced by rotation OVRCameraRig[] CameraRigs = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraRigs.Length == 0) Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached."); else if (CameraRigs.Length > 1) Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached."); else CameraRig = CameraRigs[0]; InitialYRotation = transform.rotation.eulerAngles.y; } void OnEnable() { OVRManager.display.RecenteredPose += ResetOrientation; if (CameraRig != null) { CameraRig.UpdatedAnchors += UpdateTransform; } } void OnDisable() { OVRManager.display.RecenteredPose -= ResetOrientation; if (CameraRig != null) { CameraRig.UpdatedAnchors -= UpdateTransform; } } protected virtual void Update() { if (useProfileData) { if (InitialPose == null) { // Save the initial pose so it can be recovered if useProfileData // is turned off later. InitialPose = new OVRPose() { position = CameraRig.transform.localPosition, orientation = CameraRig.transform.localRotation }; } var p = CameraRig.transform.localPosition; p.y = OVRManager.profile.eyeHeight - 0.5f * Controller.height + Controller.center.y; CameraRig.transform.localPosition = p; } else if (InitialPose != null) { // Return to the initial pose if useProfileData was turned off at runtime CameraRig.transform.localPosition = InitialPose.Value.position; CameraRig.transform.localRotation = InitialPose.Value.orientation; InitialPose = null; } UpdateMovement(); Vector3 moveDirection = Vector3.zero; float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime)); MoveThrottle.x /= motorDamp; MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y; MoveThrottle.z /= motorDamp; moveDirection += MoveThrottle * SimulationRate * Time.deltaTime; // Gravity if (Controller.isGrounded && FallSpeed <= 0) FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f))); else FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime); moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime; // Offset correction for uneven ground float bumpUpOffset = 0.0f; if (Controller.isGrounded && MoveThrottle.y <= 0.001f) { bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude); moveDirection -= bumpUpOffset * Vector3.up; } Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1)); // Move contoller Controller.Move(moveDirection); Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1)); if (predictedXZ != actualXZ) MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime); } public virtual void UpdateMovement() { if (HaltUpdateMovement) return; bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow); bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow); bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow); bool dpad_move = false; if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Up)) { moveForward = true; dpad_move = true; } if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down)) { moveBack = true; dpad_move = true; } MoveScale = 1.0f; if ( (moveForward && moveLeft) || (moveForward && moveRight) || (moveBack && moveLeft) || (moveBack && moveRight) ) MoveScale = 0.70710678f; // No positional movement if we are in the air if (!Controller.isGrounded) MoveScale = 0.0f; MoveScale *= SimulationRate * Time.deltaTime; // Compute this for key movement float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; // Run! if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) moveInfluence *= 2.0f; Quaternion ort = transform.rotation; Vector3 ortEuler = ort.eulerAngles; ortEuler.z = ortEuler.x = 0f; ort = Quaternion.Euler(ortEuler); if (moveForward) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward); if (moveBack) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if (moveLeft) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if (moveRight) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); Vector3 euler = transform.rotation.eulerAngles; bool curHatLeft = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.LeftShoulder); if (curHatLeft && !prevHatLeft) euler.y -= RotationRatchet; prevHatLeft = curHatLeft; bool curHatRight = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.RightShoulder); if(curHatRight && !prevHatRight) euler.y += RotationRatchet; prevHatRight = curHatRight; //Use keys to ratchet rotation if (Input.GetKeyDown(KeyCode.Q)) euler.y -= RotationRatchet; if (Input.GetKeyDown(KeyCode.E)) euler.y += RotationRatchet; float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier; #if !UNITY_ANDROID || UNITY_EDITOR if (!SkipMouseRotation) euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f; #endif moveInfluence = SimulationRate * Time.deltaTime * Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; #if !UNITY_ANDROID // LeftTrigger not avail on Android game pad moveInfluence *= 1.0f + OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftTrigger); #endif float leftAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftXAxis); float leftAxisY = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftYAxis); if(leftAxisY > 0.0f) MoveThrottle += ort * (leftAxisY * moveInfluence * Vector3.forward); if(leftAxisY < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisY) * moveInfluence * BackAndSideDampen * Vector3.back); if(leftAxisX < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisX) * moveInfluence * BackAndSideDampen * Vector3.left); if(leftAxisX > 0.0f) MoveThrottle += ort * (leftAxisX * moveInfluence * BackAndSideDampen * Vector3.right); float rightAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.RightXAxis); euler.y += rightAxisX * rotateInfluence; transform.rotation = Quaternion.Euler(euler); } /// <summary> /// Invoked by OVRCameraRig's UpdatedAnchors callback. Allows the Hmd rotation to update the facing direction of the player. /// </summary> public void UpdateTransform(OVRCameraRig rig) { Transform root = CameraRig.trackingSpace; Transform centerEye = CameraRig.centerEyeAnchor; if (HmdRotatesY) { Vector3 prevPos = root.position; Quaternion prevRot = root.rotation; transform.rotation = Quaternion.Euler(0.0f, centerEye.rotation.eulerAngles.y, 0.0f); root.position = prevPos; root.rotation = prevRot; } } /// <summary> /// Jump! Must be enabled manually. /// </summary> public bool Jump() { if (!Controller.isGrounded) return false; MoveThrottle += new Vector3(0, JumpForce, 0); return true; } /// <summary> /// Stop this instance. /// </summary> public void Stop() { Controller.Move(Vector3.zero); MoveThrottle = Vector3.zero; FallSpeed = 0.0f; } /// <summary> /// Gets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void GetMoveScaleMultiplier(ref float moveScaleMultiplier) { moveScaleMultiplier = MoveScaleMultiplier; } /// <summary> /// Sets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void SetMoveScaleMultiplier(float moveScaleMultiplier) { MoveScaleMultiplier = moveScaleMultiplier; } /// <summary> /// Gets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier) { rotationScaleMultiplier = RotationScaleMultiplier; } /// <summary> /// Sets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void SetRotationScaleMultiplier(float rotationScaleMultiplier) { RotationScaleMultiplier = rotationScaleMultiplier; } /// <summary> /// Gets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">Allow mouse rotation.</param> public void GetSkipMouseRotation(ref bool skipMouseRotation) { skipMouseRotation = SkipMouseRotation; } /// <summary> /// Sets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param> public void SetSkipMouseRotation(bool skipMouseRotation) { SkipMouseRotation = skipMouseRotation; } /// <summary> /// Gets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">Halt update movement.</param> public void GetHaltUpdateMovement(ref bool haltUpdateMovement) { haltUpdateMovement = HaltUpdateMovement; } /// <summary> /// Sets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param> public void SetHaltUpdateMovement(bool haltUpdateMovement) { HaltUpdateMovement = haltUpdateMovement; } /// <summary> /// Resets the player look rotation when the device orientation is reset. /// </summary> public void ResetOrientation() { if (HmdResetsY) { Vector3 euler = transform.rotation.eulerAngles; euler.y = InitialYRotation; transform.rotation = Quaternion.Euler(euler); } } }
// 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.Globalization; using System.Linq; using System.Text; using Xunit; namespace Test { public class EncodingTest : IClassFixture<CultureSetup> { public EncodingTest(CultureSetup setup) { // Setting up the culture happens externally, and only once, which is what we want. // xUnit will keep track of it, do nothing. } public static IEnumerable<object[]> CodePageInfo() { // The layout is code page, IANA(web) name, and query string. // Query strings may be undocumented, and IANA names will be returned from Encoding objects. // Entries are sorted by code page. yield return new object[] { 37, "ibm037", "ibm037" }; yield return new object[] { 37, "ibm037", "cp037" }; yield return new object[] { 37, "ibm037", "csibm037" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-ca" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-nl" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-us" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-wt" }; yield return new object[] { 437, "ibm437", "ibm437" }; yield return new object[] { 437, "ibm437", "437" }; yield return new object[] { 437, "ibm437", "cp437" }; yield return new object[] { 437, "ibm437", "cspc8codepage437" }; yield return new object[] { 500, "ibm500", "ibm500" }; yield return new object[] { 500, "ibm500", "cp500" }; yield return new object[] { 500, "ibm500", "csibm500" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-be" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-ch" }; yield return new object[] { 708, "asmo-708", "asmo-708" }; yield return new object[] { 720, "dos-720", "dos-720" }; yield return new object[] { 737, "ibm737", "ibm737" }; yield return new object[] { 775, "ibm775", "ibm775" }; yield return new object[] { 850, "ibm850", "ibm850" }; yield return new object[] { 850, "ibm850", "cp850" }; yield return new object[] { 852, "ibm852", "ibm852" }; yield return new object[] { 852, "ibm852", "cp852" }; yield return new object[] { 855, "ibm855", "ibm855" }; yield return new object[] { 855, "ibm855", "cp855" }; yield return new object[] { 857, "ibm857", "ibm857" }; yield return new object[] { 857, "ibm857", "cp857" }; yield return new object[] { 858, "ibm00858", "ibm00858" }; yield return new object[] { 858, "ibm00858", "ccsid00858" }; yield return new object[] { 858, "ibm00858", "cp00858" }; yield return new object[] { 858, "ibm00858", "cp858" }; yield return new object[] { 858, "ibm00858", "pc-multilingual-850+euro" }; yield return new object[] { 860, "ibm860", "ibm860" }; yield return new object[] { 860, "ibm860", "cp860" }; yield return new object[] { 861, "ibm861", "ibm861" }; yield return new object[] { 861, "ibm861", "cp861" }; yield return new object[] { 862, "dos-862", "dos-862" }; yield return new object[] { 862, "dos-862", "cp862" }; yield return new object[] { 862, "dos-862", "ibm862" }; yield return new object[] { 863, "ibm863", "ibm863" }; yield return new object[] { 863, "ibm863", "cp863" }; yield return new object[] { 864, "ibm864", "ibm864" }; yield return new object[] { 864, "ibm864", "cp864" }; yield return new object[] { 865, "ibm865", "ibm865" }; yield return new object[] { 865, "ibm865", "cp865" }; yield return new object[] { 866, "cp866", "cp866" }; yield return new object[] { 866, "cp866", "ibm866" }; yield return new object[] { 869, "ibm869", "ibm869" }; yield return new object[] { 869, "ibm869", "cp869" }; yield return new object[] { 870, "ibm870", "ibm870" }; yield return new object[] { 870, "ibm870", "cp870" }; yield return new object[] { 870, "ibm870", "csibm870" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-roece" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-yu" }; yield return new object[] { 874, "windows-874", "windows-874" }; yield return new object[] { 874, "windows-874", "dos-874" }; yield return new object[] { 874, "windows-874", "iso-8859-11" }; yield return new object[] { 874, "windows-874", "tis-620" }; yield return new object[] { 875, "cp875", "cp875" }; yield return new object[] { 932, "shift_jis", "shift_jis" }; yield return new object[] { 932, "shift_jis", "csshiftjis" }; yield return new object[] { 932, "shift_jis", "cswindows31j" }; yield return new object[] { 932, "shift_jis", "ms_kanji" }; yield return new object[] { 932, "shift_jis", "shift-jis" }; yield return new object[] { 932, "shift_jis", "sjis" }; yield return new object[] { 932, "shift_jis", "x-ms-cp932" }; yield return new object[] { 932, "shift_jis", "x-sjis" }; yield return new object[] { 936, "gb2312", "gb2312" }; yield return new object[] { 936, "gb2312", "chinese" }; yield return new object[] { 936, "gb2312", "cn-gb" }; yield return new object[] { 936, "gb2312", "csgb2312" }; yield return new object[] { 936, "gb2312", "csgb231280" }; yield return new object[] { 936, "gb2312", "csiso58gb231280" }; yield return new object[] { 936, "gb2312", "gb_2312-80" }; yield return new object[] { 936, "gb2312", "gb231280" }; yield return new object[] { 936, "gb2312", "gb2312-80" }; yield return new object[] { 936, "gb2312", "gbk" }; yield return new object[] { 936, "gb2312", "iso-ir-58" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1987" }; yield return new object[] { 949, "ks_c_5601-1987", "csksc56011987" }; yield return new object[] { 949, "ks_c_5601-1987", "iso-ir-149" }; yield return new object[] { 949, "ks_c_5601-1987", "korean" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601_1987" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1989" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c-5601" }; yield return new object[] { 950, "big5", "big5" }; yield return new object[] { 950, "big5", "big5-hkscs" }; yield return new object[] { 950, "big5", "cn-big5" }; yield return new object[] { 950, "big5", "csbig5" }; yield return new object[] { 950, "big5", "x-x-big5" }; yield return new object[] { 1026, "ibm1026", "ibm1026" }; yield return new object[] { 1026, "ibm1026", "cp1026" }; yield return new object[] { 1026, "ibm1026", "csibm1026" }; yield return new object[] { 1047, "ibm01047", "ibm01047" }; yield return new object[] { 1140, "ibm01140", "ibm01140" }; yield return new object[] { 1140, "ibm01140", "ccsid01140" }; yield return new object[] { 1140, "ibm01140", "cp01140" }; yield return new object[] { 1140, "ibm01140", "ebcdic-us-37+euro" }; yield return new object[] { 1141, "ibm01141", "ibm01141" }; yield return new object[] { 1141, "ibm01141", "ccsid01141" }; yield return new object[] { 1141, "ibm01141", "cp01141" }; yield return new object[] { 1141, "ibm01141", "ebcdic-de-273+euro" }; yield return new object[] { 1142, "ibm01142", "ibm01142" }; yield return new object[] { 1142, "ibm01142", "ccsid01142" }; yield return new object[] { 1142, "ibm01142", "cp01142" }; yield return new object[] { 1142, "ibm01142", "ebcdic-dk-277+euro" }; yield return new object[] { 1142, "ibm01142", "ebcdic-no-277+euro" }; yield return new object[] { 1143, "ibm01143", "ibm01143" }; yield return new object[] { 1143, "ibm01143", "ccsid01143" }; yield return new object[] { 1143, "ibm01143", "cp01143" }; yield return new object[] { 1143, "ibm01143", "ebcdic-fi-278+euro" }; yield return new object[] { 1143, "ibm01143", "ebcdic-se-278+euro" }; yield return new object[] { 1144, "ibm01144", "ibm01144" }; yield return new object[] { 1144, "ibm01144", "ccsid01144" }; yield return new object[] { 1144, "ibm01144", "cp01144" }; yield return new object[] { 1144, "ibm01144", "ebcdic-it-280+euro" }; yield return new object[] { 1145, "ibm01145", "ibm01145" }; yield return new object[] { 1145, "ibm01145", "ccsid01145" }; yield return new object[] { 1145, "ibm01145", "cp01145" }; yield return new object[] { 1145, "ibm01145", "ebcdic-es-284+euro" }; yield return new object[] { 1146, "ibm01146", "ibm01146" }; yield return new object[] { 1146, "ibm01146", "ccsid01146" }; yield return new object[] { 1146, "ibm01146", "cp01146" }; yield return new object[] { 1146, "ibm01146", "ebcdic-gb-285+euro" }; yield return new object[] { 1147, "ibm01147", "ibm01147" }; yield return new object[] { 1147, "ibm01147", "ccsid01147" }; yield return new object[] { 1147, "ibm01147", "cp01147" }; yield return new object[] { 1147, "ibm01147", "ebcdic-fr-297+euro" }; yield return new object[] { 1148, "ibm01148", "ibm01148" }; yield return new object[] { 1148, "ibm01148", "ccsid01148" }; yield return new object[] { 1148, "ibm01148", "cp01148" }; yield return new object[] { 1148, "ibm01148", "ebcdic-international-500+euro" }; yield return new object[] { 1149, "ibm01149", "ibm01149" }; yield return new object[] { 1149, "ibm01149", "ccsid01149" }; yield return new object[] { 1149, "ibm01149", "cp01149" }; yield return new object[] { 1149, "ibm01149", "ebcdic-is-871+euro" }; yield return new object[] { 1250, "windows-1250", "windows-1250" }; yield return new object[] { 1250, "windows-1250", "x-cp1250" }; yield return new object[] { 1251, "windows-1251", "windows-1251" }; yield return new object[] { 1251, "windows-1251", "x-cp1251" }; yield return new object[] { 1252, "windows-1252", "windows-1252" }; yield return new object[] { 1252, "windows-1252", "x-ansi" }; yield return new object[] { 1253, "windows-1253", "windows-1253" }; yield return new object[] { 1254, "windows-1254", "windows-1254" }; yield return new object[] { 1255, "windows-1255", "windows-1255" }; yield return new object[] { 1256, "windows-1256", "windows-1256" }; yield return new object[] { 1256, "windows-1256", "cp1256" }; yield return new object[] { 1257, "windows-1257", "windows-1257" }; yield return new object[] { 1258, "windows-1258", "windows-1258" }; yield return new object[] { 1361, "johab", "johab" }; yield return new object[] { 10000, "macintosh", "macintosh" }; yield return new object[] { 10001, "x-mac-japanese", "x-mac-japanese" }; yield return new object[] { 10002, "x-mac-chinesetrad", "x-mac-chinesetrad" }; yield return new object[] { 10003, "x-mac-korean", "x-mac-korean" }; yield return new object[] { 10004, "x-mac-arabic", "x-mac-arabic" }; yield return new object[] { 10005, "x-mac-hebrew", "x-mac-hebrew" }; yield return new object[] { 10006, "x-mac-greek", "x-mac-greek" }; yield return new object[] { 10007, "x-mac-cyrillic", "x-mac-cyrillic" }; yield return new object[] { 10008, "x-mac-chinesesimp", "x-mac-chinesesimp" }; yield return new object[] { 10010, "x-mac-romanian", "x-mac-romanian" }; yield return new object[] { 10017, "x-mac-ukrainian", "x-mac-ukrainian" }; yield return new object[] { 10021, "x-mac-thai", "x-mac-thai" }; yield return new object[] { 10029, "x-mac-ce", "x-mac-ce" }; yield return new object[] { 10079, "x-mac-icelandic", "x-mac-icelandic" }; yield return new object[] { 10081, "x-mac-turkish", "x-mac-turkish" }; yield return new object[] { 10082, "x-mac-croatian", "x-mac-croatian" }; yield return new object[] { 20000, "x-chinese-cns", "x-chinese-cns" }; yield return new object[] { 20001, "x-cp20001", "x-cp20001" }; yield return new object[] { 20002, "x-chinese-eten", "x-chinese-eten" }; yield return new object[] { 20003, "x-cp20003", "x-cp20003" }; yield return new object[] { 20004, "x-cp20004", "x-cp20004" }; yield return new object[] { 20005, "x-cp20005", "x-cp20005" }; yield return new object[] { 20105, "x-ia5", "x-ia5" }; yield return new object[] { 20105, "x-ia5", "irv" }; yield return new object[] { 20106, "x-ia5-german", "x-ia5-german" }; yield return new object[] { 20106, "x-ia5-german", "din_66003" }; yield return new object[] { 20106, "x-ia5-german", "german" }; yield return new object[] { 20107, "x-ia5-swedish", "x-ia5-swedish" }; yield return new object[] { 20107, "x-ia5-swedish", "sen_850200_b" }; yield return new object[] { 20107, "x-ia5-swedish", "swedish" }; yield return new object[] { 20108, "x-ia5-norwegian", "x-ia5-norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "ns_4551-1" }; yield return new object[] { 20261, "x-cp20261", "x-cp20261" }; yield return new object[] { 20269, "x-cp20269", "x-cp20269" }; yield return new object[] { 20273, "ibm273", "ibm273" }; yield return new object[] { 20273, "ibm273", "cp273" }; yield return new object[] { 20273, "ibm273", "csibm273" }; yield return new object[] { 20277, "ibm277", "ibm277" }; yield return new object[] { 20277, "ibm277", "csibm277" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-dk" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-no" }; yield return new object[] { 20278, "ibm278", "ibm278" }; yield return new object[] { 20278, "ibm278", "cp278" }; yield return new object[] { 20278, "ibm278", "csibm278" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-fi" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-se" }; yield return new object[] { 20280, "ibm280", "ibm280" }; yield return new object[] { 20280, "ibm280", "cp280" }; yield return new object[] { 20280, "ibm280", "csibm280" }; yield return new object[] { 20280, "ibm280", "ebcdic-cp-it" }; yield return new object[] { 20284, "ibm284", "ibm284" }; yield return new object[] { 20284, "ibm284", "cp284" }; yield return new object[] { 20284, "ibm284", "csibm284" }; yield return new object[] { 20284, "ibm284", "ebcdic-cp-es" }; yield return new object[] { 20285, "ibm285", "ibm285" }; yield return new object[] { 20285, "ibm285", "cp285" }; yield return new object[] { 20285, "ibm285", "csibm285" }; yield return new object[] { 20285, "ibm285", "ebcdic-cp-gb" }; yield return new object[] { 20290, "ibm290", "ibm290" }; yield return new object[] { 20290, "ibm290", "cp290" }; yield return new object[] { 20290, "ibm290", "csibm290" }; yield return new object[] { 20290, "ibm290", "ebcdic-jp-kana" }; yield return new object[] { 20297, "ibm297", "ibm297" }; yield return new object[] { 20297, "ibm297", "cp297" }; yield return new object[] { 20297, "ibm297", "csibm297" }; yield return new object[] { 20297, "ibm297", "ebcdic-cp-fr" }; yield return new object[] { 20420, "ibm420", "ibm420" }; yield return new object[] { 20420, "ibm420", "cp420" }; yield return new object[] { 20420, "ibm420", "csibm420" }; yield return new object[] { 20420, "ibm420", "ebcdic-cp-ar1" }; yield return new object[] { 20423, "ibm423", "ibm423" }; yield return new object[] { 20423, "ibm423", "cp423" }; yield return new object[] { 20423, "ibm423", "csibm423" }; yield return new object[] { 20423, "ibm423", "ebcdic-cp-gr" }; yield return new object[] { 20424, "ibm424", "ibm424" }; yield return new object[] { 20424, "ibm424", "cp424" }; yield return new object[] { 20424, "ibm424", "csibm424" }; yield return new object[] { 20424, "ibm424", "ebcdic-cp-he" }; yield return new object[] { 20833, "x-ebcdic-koreanextended", "x-ebcdic-koreanextended" }; yield return new object[] { 20838, "ibm-thai", "ibm-thai" }; yield return new object[] { 20838, "ibm-thai", "csibmthai" }; yield return new object[] { 20866, "koi8-r", "koi8-r" }; yield return new object[] { 20866, "koi8-r", "cskoi8r" }; yield return new object[] { 20866, "koi8-r", "koi" }; yield return new object[] { 20866, "koi8-r", "koi8" }; yield return new object[] { 20866, "koi8-r", "koi8r" }; yield return new object[] { 20871, "ibm871", "ibm871" }; yield return new object[] { 20871, "ibm871", "cp871" }; yield return new object[] { 20871, "ibm871", "csibm871" }; yield return new object[] { 20871, "ibm871", "ebcdic-cp-is" }; yield return new object[] { 20880, "ibm880", "ibm880" }; yield return new object[] { 20880, "ibm880", "cp880" }; yield return new object[] { 20880, "ibm880", "csibm880" }; yield return new object[] { 20880, "ibm880", "ebcdic-cyrillic" }; yield return new object[] { 20905, "ibm905", "ibm905" }; yield return new object[] { 20905, "ibm905", "cp905" }; yield return new object[] { 20905, "ibm905", "csibm905" }; yield return new object[] { 20905, "ibm905", "ebcdic-cp-tr" }; yield return new object[] { 20924, "ibm00924", "ibm00924" }; yield return new object[] { 20924, "ibm00924", "ccsid00924" }; yield return new object[] { 20924, "ibm00924", "cp00924" }; yield return new object[] { 20924, "ibm00924", "ebcdic-latin9--euro" }; yield return new object[] { 20936, "x-cp20936", "x-cp20936" }; yield return new object[] { 20949, "x-cp20949", "x-cp20949" }; yield return new object[] { 21025, "cp1025", "cp1025" }; yield return new object[] { 21866, "koi8-u", "koi8-u" }; yield return new object[] { 21866, "koi8-u", "koi8-ru" }; yield return new object[] { 28592, "iso-8859-2", "iso-8859-2" }; yield return new object[] { 28592, "iso-8859-2", "csisolatin2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2:1987" }; yield return new object[] { 28592, "iso-8859-2", "iso8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso-ir-101" }; yield return new object[] { 28592, "iso-8859-2", "l2" }; yield return new object[] { 28592, "iso-8859-2", "latin2" }; yield return new object[] { 28593, "iso-8859-3", "iso-8859-3" }; yield return new object[] { 28593, "iso-8859-3", "csisolatin3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3:1988" }; yield return new object[] { 28593, "iso-8859-3", "iso-ir-109" }; yield return new object[] { 28593, "iso-8859-3", "l3" }; yield return new object[] { 28593, "iso-8859-3", "latin3" }; yield return new object[] { 28594, "iso-8859-4", "iso-8859-4" }; yield return new object[] { 28594, "iso-8859-4", "csisolatin4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4:1988" }; yield return new object[] { 28594, "iso-8859-4", "iso-ir-110" }; yield return new object[] { 28594, "iso-8859-4", "l4" }; yield return new object[] { 28594, "iso-8859-4", "latin4" }; yield return new object[] { 28595, "iso-8859-5", "iso-8859-5" }; yield return new object[] { 28595, "iso-8859-5", "csisolatincyrillic" }; yield return new object[] { 28595, "iso-8859-5", "cyrillic" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5:1988" }; yield return new object[] { 28595, "iso-8859-5", "iso-ir-144" }; yield return new object[] { 28596, "iso-8859-6", "iso-8859-6" }; yield return new object[] { 28596, "iso-8859-6", "arabic" }; yield return new object[] { 28596, "iso-8859-6", "csisolatinarabic" }; yield return new object[] { 28596, "iso-8859-6", "ecma-114" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6:1987" }; yield return new object[] { 28596, "iso-8859-6", "iso-ir-127" }; yield return new object[] { 28597, "iso-8859-7", "iso-8859-7" }; yield return new object[] { 28597, "iso-8859-7", "csisolatingreek" }; yield return new object[] { 28597, "iso-8859-7", "ecma-118" }; yield return new object[] { 28597, "iso-8859-7", "elot_928" }; yield return new object[] { 28597, "iso-8859-7", "greek" }; yield return new object[] { 28597, "iso-8859-7", "greek8" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7:1987" }; yield return new object[] { 28597, "iso-8859-7", "iso-ir-126" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8" }; yield return new object[] { 28598, "iso-8859-8", "csisolatinhebrew" }; yield return new object[] { 28598, "iso-8859-8", "hebrew" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8:1988" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8 visual" }; yield return new object[] { 28598, "iso-8859-8", "iso-ir-138" }; yield return new object[] { 28598, "iso-8859-8", "logical" }; yield return new object[] { 28598, "iso-8859-8", "visual" }; yield return new object[] { 28599, "iso-8859-9", "iso-8859-9" }; yield return new object[] { 28599, "iso-8859-9", "csisolatin5" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9:1989" }; yield return new object[] { 28599, "iso-8859-9", "iso-ir-148" }; yield return new object[] { 28599, "iso-8859-9", "l5" }; yield return new object[] { 28599, "iso-8859-9", "latin5" }; yield return new object[] { 28603, "iso-8859-13", "iso-8859-13" }; yield return new object[] { 28605, "iso-8859-15", "iso-8859-15" }; yield return new object[] { 28605, "iso-8859-15", "csisolatin9" }; yield return new object[] { 28605, "iso-8859-15", "iso_8859-15" }; yield return new object[] { 28605, "iso-8859-15", "l9" }; yield return new object[] { 28605, "iso-8859-15", "latin9" }; yield return new object[] { 29001, "x-europa", "x-europa" }; yield return new object[] { 38598, "iso-8859-8-i", "iso-8859-8-i" }; yield return new object[] { 50220, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50221, "csiso2022jp", "csiso2022jp" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr" }; yield return new object[] { 50225, "iso-2022-kr", "csiso2022kr" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7bit" }; yield return new object[] { 50227, "x-cp50227", "x-cp50227" }; yield return new object[] { 50227, "x-cp50227", "cp50227" }; yield return new object[] { 51932, "euc-jp", "euc-jp" }; yield return new object[] { 51932, "euc-jp", "cseucpkdfmtjapanese" }; yield return new object[] { 51932, "euc-jp", "extended_unix_code_packed_format_for_japanese" }; yield return new object[] { 51932, "euc-jp", "iso-2022-jpeuc" }; yield return new object[] { 51932, "euc-jp", "x-euc" }; yield return new object[] { 51932, "euc-jp", "x-euc-jp" }; yield return new object[] { 51936, "euc-cn", "euc-cn" }; yield return new object[] { 51936, "euc-cn", "x-euc-cn" }; yield return new object[] { 51949, "euc-kr", "euc-kr" }; yield return new object[] { 51949, "euc-kr", "cseuckr" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8bit" }; yield return new object[] { 52936, "hz-gb-2312", "hz-gb-2312" }; yield return new object[] { 54936, "gb18030", "gb18030" }; yield return new object[] { 57002, "x-iscii-de", "x-iscii-de" }; yield return new object[] { 57003, "x-iscii-be", "x-iscii-be" }; yield return new object[] { 57004, "x-iscii-ta", "x-iscii-ta" }; yield return new object[] { 57005, "x-iscii-te", "x-iscii-te" }; yield return new object[] { 57006, "x-iscii-as", "x-iscii-as" }; yield return new object[] { 57007, "x-iscii-or", "x-iscii-or" }; yield return new object[] { 57008, "x-iscii-ka", "x-iscii-ka" }; yield return new object[] { 57009, "x-iscii-ma", "x-iscii-ma" }; yield return new object[] { 57010, "x-iscii-gu", "x-iscii-gu" }; yield return new object[] { 57011, "x-iscii-pa", "x-iscii-pa" }; } public static IEnumerable<object[]> SpecificCodepageEncodings() { // Layout is codepage encoding, bytes, and matching unicode string. yield return new object[] { "Windows-1256", new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }, "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F" }; yield return new object[] {"Windows-1252", new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF } , "\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"}; yield return new object[] { "GB2312", new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }, "\x5916\x8C4C\x5F2F" }; yield return new object[] {"GB18030", new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 } , "\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"}; } public static IEnumerable<object[]> MultibyteCharacterEncodings() { // Layout is the encoding, bytes, and expected result. yield return new object[] { "iso-2022-jp", new byte[] { 0xA, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 }, new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43} }; yield return new object[] { "GB18030", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 }, new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 } }; yield return new object[] { "shift_jis", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x42, 0xE0, 0x43, 0x44, 0x45 }, new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 } }; yield return new object[] { "iso-2022-kr", new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E }, new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E } }; yield return new object[] { "hz-gb-2312", new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 }, new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, } }; } private static IEnumerable<KeyValuePair<int, string>> CrossplatformDefaultEncodings() { yield return Map(1200, "utf-16"); yield return Map(12000, "utf-32"); yield return Map(20127, "us-ascii"); yield return Map(65000, "utf-7"); yield return Map(65001, "utf-8"); } private static KeyValuePair<int, string> Map(int codePage, string webName) { return new KeyValuePair<int, string>(codePage, webName); } [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void TestDefaultEncodings() { ValidateDefaultEncodings(); foreach (object[] mapping in CodePageInfo()) { Assert.Throws<NotSupportedException>(() => Encoding.GetEncoding((int)mapping[0])); Assert.Throws<ArgumentException>(() => Encoding.GetEncoding((string)mapping[2])); } // Currently the class EncodingInfo isn't present in corefx, so this checks none of the code pages are present. // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings, Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // The default encoding should be something from the known list. Encoding defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); KeyValuePair<int, string> mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings()); // Add the code page provider. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Make sure added code pages are identical between the provider and the Encoding class. foreach (object[] mapping in CodePageInfo()) { Encoding encoding = Encoding.GetEncoding((int)mapping[0]); Encoding codePageEncoding = CodePagesEncodingProvider.Instance.GetEncoding((int)mapping[0]); Assert.Equal(encoding, codePageEncoding); Assert.Equal(encoding.CodePage, (int)mapping[0]); Assert.Equal(encoding.WebName, (string)mapping[1]); // Get encoding via query string. Assert.Equal(Encoding.GetEncoding((string)mapping[2]), CodePagesEncodingProvider.Instance.GetEncoding((string)mapping[2])); } // Adding the code page provider should keep the originals, too. ValidateDefaultEncodings(); // Currently the class EncodingInfo isn't present in corefx, so this checks the complete list // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])).OrderBy(i => i.Key)), // Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // Default encoding may have changed, should still be something on the combined list. defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])))); } private static void ValidateDefaultEncodings() { foreach (var mapping in CrossplatformDefaultEncodings()) { Encoding encoding = Encoding.GetEncoding(mapping.Key); Assert.NotNull(encoding); Assert.Equal(encoding, Encoding.GetEncoding(mapping.Value)); Assert.Equal(mapping.Value, encoding.WebName); } } [Theory] [MemberData("SpecificCodepageEncodings")] public static void TestRoundtrippingSpecificCodepageEncoding(string encodingName, byte[] bytes, string expected) { Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingName); string encoded = encoding.GetString(bytes, 0, bytes.Length); Assert.Equal(expected, encoded); Assert.Equal(bytes, encoding.GetBytes(encoded)); byte[] resultBytes = encoding.GetBytes(encoded); } [Theory] [MemberData("CodePageInfo")] public static void TestCodepageEncoding(int codePage, string webName, string queryString) { Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString); Assert.NotNull(encoding); Assert.Equal(codePage, encoding.CodePage); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(codePage)); Assert.Equal(webName, encoding.WebName); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); // Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!) // Start with space. string asciiPrintable = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; char[] traveled = encoding.GetChars(encoding.GetBytes(asciiPrintable)); Assert.Equal(asciiPrintable.ToCharArray(), traveled); } [Theory] [MemberData("MultibyteCharacterEncodings")] public static void TestSpecificMultibyteCharacterEncodings(string codepageName, byte[] bytes, int[] expected) { Decoder decoder = CodePagesEncodingProvider.Instance.GetEncoding(codepageName).GetDecoder(); char[] buffer = new char[expected.Length]; for (int byteIndex = 0, charIndex = 0, charCount = 0; byteIndex < bytes.Length; byteIndex++, charIndex += charCount) { charCount = decoder.GetChars(bytes, byteIndex, 1, buffer, charIndex); } Assert.Equal(expected, buffer.Select(c => (int)c)); } [Theory] [MemberData("CodePageInfo")] public static void TestEncodingDisplayNames(int codePage, string webName, string queryString) { var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); string name = encoding.EncodingName; // Names can't be empty, and must be printable characters. Assert.False(string.IsNullOrWhiteSpace(name)); Assert.All(name, c => Assert.True(c >= ' ' && c < '~' + 1, "Name: " + name + " contains character: " + c)); } } public class CultureSetup : IDisposable { private readonly CultureInfo _originalUICulture; public CultureSetup() { _originalUICulture = CultureInfo.CurrentUICulture; CultureInfo.CurrentUICulture = new CultureInfo("en-US"); } public void Dispose() { CultureInfo.CurrentUICulture = _originalUICulture; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Newtonsoft.Json.Linq; using NUnit.Framework; using Templates.CodeGen; using Templates.CodeGen.Specialized; using Templates.CodeGen.Util; using Templates.Metadata; namespace Templates { [TestFixture] public class GeneratorForAst { public string ProjectFolder = "RethinkDb.Driver"; public string GenerateRootDir = @"./Generated"; public string ProtoDir = @"./Generated/Proto"; public string AstClasses = @"./Generated/Ast"; public string ModelDir = @"./Generated/Model"; [TestFixtureSetUp] public void BeforeRunningTestSession() { MetaDb.Initialize(@"..\..\Metadata"); //remount the working directory before we begin. var rootProjectPath = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..", ProjectFolder); Directory.SetCurrentDirectory(rootProjectPath); EnsurePathsExist(); } private void Clean() { if( Directory.Exists(GenerateRootDir) ) { Directory.Delete(GenerateRootDir, true); } } public void EnsurePathsExist() { if( !Directory.Exists(GenerateRootDir) ) Directory.CreateDirectory(GenerateRootDir); if( !Directory.Exists(ProtoDir) ) Directory.CreateDirectory(ProtoDir); if( !Directory.Exists(AstClasses) ) Directory.CreateDirectory(AstClasses); if( !Directory.Exists(ModelDir) ) Directory.CreateDirectory(ModelDir); } [Test] [Explicit] public void Generate_All() { Clean(); EnsurePathsExist(); Render_Proto_Enums(); Render_Ast_SubClasses(); Render_TopLevel(); Render_Funtion_Interfaces(); Render_Exceptions(); Render_OptArg_Enums(); } [Test] public void Render_Funtion_Interfaces() { //Determines the maximum reql lambda arity that shows up in any signature var maxArity = GetMaxArity(); foreach( var n in Enumerable.Range(1, maxArity) ) { var tmpl = new ReqlFunctionTemplate() { Arity = n }; File.WriteAllText(Path.Combine(ModelDir, $"ReqlFunction{n}.cs"), tmpl.TransformText()); } } public static int GetMaxArity() { var maxArity = MetaDb.JavaTermInfo.SelectTokens("..signatures") .SelectMany(t => t.ToObject<List<Signature>>()) .SelectMany(s => s.Args) .Select(s => s.Type) .Where(s => s.StartsWith("ReqlFunction")) .Max(s => int.Parse(s.Substring(12))); return maxArity; } [Test] public void Render_TopLevel() { var allTerms = MetaDb.JavaTermInfo.ToObject<Dictionary<string, JObject>>(); var mutator = new CSharpTermInfoMutator(allTerms); mutator.EnsureLanguageSafeTerms(); var tmpl = new TopLevelTemplate() { AllTerms = allTerms }; File.WriteAllText(Path.Combine(ModelDir, "TopLevel.cs"), tmpl.TransformText()); } [Test] public void Render_Proto_Enums() { RenderEnum("Version", MetaDb.Protocol["VersionDummy"]["Version"].ToObject<Dictionary<string, object>>()); RenderEnum("Protocol", MetaDb.Protocol["VersionDummy"]["Protocol"].ToObject<Dictionary<string, object>>()); RenderEnum("QueryType", MetaDb.Protocol["Query"]["QueryType"].ToObject<Dictionary<string, object>>()); RenderEnum("FrameType", MetaDb.Protocol["Frame"]["FrameType"].ToObject<Dictionary<string, object>>()); RenderEnum("ResponseType", MetaDb.Protocol["Response"]["ResponseType"].ToObject<Dictionary<string, object>>()); RenderEnum("ResponseNote", MetaDb.Protocol["Response"]["ResponseNote"].ToObject<Dictionary<string, object>>()); RenderEnum("ErrorType", MetaDb.Protocol["Response"]["ErrorType"].ToObject<Dictionary<string, object>>()); RenderEnum("DatumType", MetaDb.Protocol["Datum"]["DatumType"].ToObject<Dictionary<string, object>>()); RenderEnum("TermType", MetaDb.Protocol["Term"]["TermType"].ToObject<Dictionary<string, object>>()); } [Test] public void Render_Ast_SubClasses() { var allTerms = MetaDb.JavaTermInfo.ToObject<Dictionary<string, JObject>>(); var mutator = new CSharpTermInfoMutator(allTerms); mutator.EnsureLanguageSafeTerms(); RenderAstSubclass(null, "ReqlExpr", "ReqlAst", allTerms, null); foreach( var kvp in allTerms ) { var termName = kvp.Key; var termMeta = kvp.Value; if( !kvp.Value["deprecated"]?.ToObject<bool?>() ?? true ) { var className = termMeta["classname"].ToString(); var superclass = termMeta["superclass"].ToString(); RenderAstSubclass(termName, className, superclass, allTerms, termMeta); } else { Console.WriteLine("Deprcated:" + kvp.Key); } } } [Test] public void Render_Exceptions() { var errorHearchy = MetaDb.Global["exception_hierarchy"] as JObject; RenderExceptions(errorHearchy); } [Test] public void Render_OptArg_Enums() { var optArgs = MetaDb.Global["optarg_enums"].ToObject<Dictionary<string, string[]>>(); foreach( var kvp in optArgs ) { var enumName = kvp.Key.Substring(2).ToLower().ClassName(); var values = kvp.Value; RenderEnumString(enumName, values); } } private void RenderExceptions(JObject error, string superClass = "Exception") { foreach( var p in error.Properties() ) { RenderErrorClass(p.Name, superClass); RenderExceptions(p.Value as JObject, p.Name); } } public void RenderErrorClass(string className, string superClass) { var tmpl = new ExceptionTemplate() { ClassName = className, SuperClass = superClass }; File.WriteAllText(Path.Combine(GenerateRootDir, $"{className.ClassName()}.cs"), tmpl.TransformText()); } public void RenderAstSubclass(string termType, string className, string superClass, Dictionary<string, JObject> allTerms, JObject termMeta = null) { className = className ?? termType.ToLower(); var tmpl = GetSpeicalizedTemplate<AstSubclassTemplate>(className) ?? new AstSubclassTemplate(); tmpl.TermName = termType; tmpl.ClassName = className; tmpl.Superclass = superClass; tmpl.TermMeta = termMeta; tmpl.AllTerms = allTerms; File.WriteAllText(Path.Combine(AstClasses, $"{className.ClassName()}.cs"), tmpl.TransformText()); } public T GetSpeicalizedTemplate<T>(string className) { var type = typeof(MakeObj); var path = type.FullName.Replace(type.Name, ""); var lookingFor = $"{path}{className.ClassName()}"; var specialType = Assembly.GetExecutingAssembly().GetType(lookingFor, false, true); if( specialType != null ) { Console.WriteLine("Using Speical Template: " + lookingFor); return (T)Activator.CreateInstance(specialType); } return default(T); } public void RenderEnum(string enumName, Dictionary<string, object> enums ) { var tmpl = GetSpeicalizedTemplate<EnumTemplate>(enumName) ?? new EnumTemplate(); tmpl.EnumName = enumName; tmpl.Enums = enums; File.WriteAllText(Path.Combine(ProtoDir, $"{enumName.ClassName()}.cs"), tmpl.TransformText()); } public void RenderEnumString(string enumName, string[] enums) { var tmpl = GetSpeicalizedTemplate<EnumStringTemplate>(enumName) ?? new EnumStringTemplate(); tmpl.EnumName = enumName; tmpl.Enums = enums; File.WriteAllText(Path.Combine(ModelDir, $"{enumName.ClassName()}.cs"), tmpl.TransformText()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Linq; using System.Linq.Expressions; using System.Windows.Input; using System.Windows.Threading; using PropertyDependencyFramework; namespace WPFSample { /// <summary> /// An <see cref="ICommand"/> whose delegates can be attached for <see cref="Execute"/> and <see cref="CanExecute"/>. /// </summary> /// <typeparam name="T">Parameter type.</typeparam> public class DelegateCommand<T> : ICommand { private readonly Action<T> _executeMethod; private readonly Func<T, bool> _canExecuteMethod; private readonly Dispatcher _dispatcher; private readonly List<string> _triggerProperties; /// <summary> /// Constructor. Initializes delegate command with Execute delegate. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <remarks><seealso cref="CanExecute"/> will always return true.</remarks> public DelegateCommand(Action<T> executeMethod) : this(executeMethod, null) { } /// <summary> /// Constructor. Initializes delegate command with Execute delegate and CanExecute delegate /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod) : this(executeMethod, canExecuteMethod, new string[]{}) { } /// <summary> /// Initializes a new instance of the <see cref="DelegateCommand&lt;T&gt;"/> class. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <param name="updateTriggerProperties">The set of property names that should be used to trigger calls to CanExecute.</param> public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod, IEnumerable<string> updateTriggerProperties) { if (executeMethod == null && canExecuteMethod == null) throw new ArgumentNullException("executeMethod", "Both the executeMethod and the canExecuteMethod delegates cannot be null."); Contract.EndContractBlock(); _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; if (System.Windows.Application.Current != null) { _dispatcher = System.Windows.Application.Current.Dispatcher; } _triggerProperties = updateTriggerProperties != null ? new List<string>(updateTriggerProperties) : new List<string>(); if (_canExecuteMethod != null) { INotifyPropertyChanged target = _canExecuteMethod.Target as INotifyPropertyChanged; if (target != null) { target.PropertyChanged += TriggerPropertyChanged; } } } public DelegateCommand( Action<T> executeMethod, Func<T, bool> canExecuteMethod, params Expression<Func<object>>[] updateTriggerProperties ) { if ( executeMethod == null && canExecuteMethod == null ) throw new ArgumentNullException( "executeMethod", "Both the executeMethod and the canExecuteMethod delegates cannot be null." ); Contract.EndContractBlock(); _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; if ( System.Windows.Application.Current != null ) { _dispatcher = System.Windows.Application.Current.Dispatcher; } _triggerProperties = updateTriggerProperties != null ? new List<string>( updateTriggerProperties.Select( PropertyNameResolver.GetPropertyName ) ) : new List<string>(); if ( _canExecuteMethod != null ) { INotifyPropertyChanged target = _canExecuteMethod.Target as INotifyPropertyChanged; if ( target != null ) { target.PropertyChanged += TriggerPropertyChanged; } } } ///<summary> ///Defines the method that determines whether the command can execute in its current state. ///</summary> ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> ///<returns> ///true if this command can be executed; otherwise, false. ///</returns> public bool CanExecute(T parameter) { if (_canExecuteMethod == null) return true; return _canExecuteMethod(parameter); } ///<summary> ///Defines the method to be called when the command is invoked. ///</summary> ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> public void Execute(T parameter) { if (_executeMethod == null) return; _executeMethod(parameter); } private static T ConvertParameter(object parameter) { if (parameter != null) { if (parameter is T) return (T)parameter; TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter.IsValid(parameter)) return (T)converter.ConvertFrom(parameter); } return default(T); } ///<summary> ///Defines the method that determines whether the command can execute in its current state. ///</summary> ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> ///<returns> ///true if this command can be executed; otherwise, false. ///</returns> bool ICommand.CanExecute(object parameter) { return CanExecute(ConvertParameter(parameter)); } public event EventHandler CanExecuteChanged { add { if (this._canExecuteMethod != null) { CommandManager.RequerySuggested += value; } } remove { if (this._canExecuteMethod != null) { CommandManager.RequerySuggested -= value; } } } ///<summary> ///Defines the method to be called when the command is invoked. ///</summary> ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> void ICommand.Execute(object parameter) { Execute(ConvertParameter(parameter)); } /// <summary> /// Raises <see cref="CanExecuteChanged"/> so every command invoker can requery to check if the command can execute. /// <remarks>This will trigger the execution of <see cref="CanExecute"/> once for each invoker.</remarks> /// </summary> public void RaiseCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } private void TriggerPropertyChanged(object sender, PropertyChangedEventArgs e) { if (_triggerProperties.Contains(e.PropertyName)) RaiseCanExecuteChanged(); } } /// <summary> /// An <see cref="ICommand"/> whose delegates can be attached for <see cref="Execute"/> and <see cref="CanExecute"/>. /// </summary> public class DelegateCommand : ICommand { private readonly Action _executeMethod; private readonly Func<bool> _canExecuteMethod; private readonly Dispatcher _dispatcher; private readonly List<string> _triggerProperties; /// <summary> /// Constructor. Initializes delegate command with Execute delegate. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <remarks><seealso cref="CanExecute"/> will always return true.</remarks> public DelegateCommand( Action executeMethod ) : this( executeMethod, null ) { } /// <summary> /// Constructor. Initializes delegate command with Execute delegate and CanExecute delegate /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> public DelegateCommand( Action executeMethod, Func<bool> canExecuteMethod ) : this( executeMethod, canExecuteMethod, new string[]{} ) { } /// <summary> /// Initializes a new instance of the <see cref="DelegateCommand&lt;T&gt;"/> class. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <param name="updateTriggerProperties">The set of property names that should be used to trigger calls to CanExecute.</param> public DelegateCommand( Action executeMethod, Func<bool> canExecuteMethod, IEnumerable<string> updateTriggerProperties ) { if ( executeMethod == null && canExecuteMethod == null ) throw new ArgumentNullException( "executeMethod", "Both the executeMethod and the canExecuteMethod delegates cannot be null." ); Contract.EndContractBlock(); _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; if ( System.Windows.Application.Current != null ) { _dispatcher = System.Windows.Application.Current.Dispatcher; } _triggerProperties = updateTriggerProperties != null ? new List<string>( updateTriggerProperties ) : new List<string>(); if ( _canExecuteMethod != null ) { INotifyPropertyChanged target = _canExecuteMethod.Target as INotifyPropertyChanged; if ( target != null ) { target.PropertyChanged += TriggerPropertyChanged; } } } public DelegateCommand( Action executeMethod, Func<bool> canExecuteMethod, params Expression<Func<object>>[] updateTriggerProperties ) { if ( executeMethod == null && canExecuteMethod == null ) throw new ArgumentNullException( "executeMethod", "Both the executeMethod and the canExecuteMethod delegates cannot be null." ); Contract.EndContractBlock(); _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; if ( System.Windows.Application.Current != null ) { _dispatcher = System.Windows.Application.Current.Dispatcher; } _triggerProperties = updateTriggerProperties != null ? new List<string>( updateTriggerProperties.Select( PropertyNameResolver.GetPropertyName) ) : new List<string>(); if ( _canExecuteMethod != null ) { INotifyPropertyChanged target = _canExecuteMethod.Target as INotifyPropertyChanged; if ( target != null ) { target.PropertyChanged += TriggerPropertyChanged; } } } ///<summary> ///Defines the method that determines whether the command can execute in its current state. ///</summary> ///<returns> ///true if this command can be executed; otherwise, false. ///</returns> public bool CanExecute() { if ( _canExecuteMethod == null ) return true; return _canExecuteMethod(); } ///<summary> ///Defines the method to be called when the command is invoked. ///</summary> public void Execute() { if ( _executeMethod == null ) return; _executeMethod(); } ///<summary> ///Defines the method that determines whether the command can execute in its current state. ///</summary> ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> ///<returns> ///true if this command can be executed; otherwise, false. ///</returns> bool ICommand.CanExecute( object parameter ) { return CanExecute(); } ///<summary> ///Occurs when changes occur that affect whether or not the command should execute. ///</summary> public event EventHandler CanExecuteChanged = delegate { }; ///<summary> ///Defines the method to be called when the command is invoked. ///</summary> ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> void ICommand.Execute( object parameter ) { Execute(); } /// <summary> /// Raises <seealso cref="CanExecuteChanged"/> on the UI thread. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void OnCanExecuteChanged( object sender, EventArgs e ) { CanExecuteChanged( sender, e ); } /// <summary> /// Raises <see cref="CanExecuteChanged"/> so every command invoker can requery to check if the command can execute. /// <remarks>This will trigger the execution of <see cref="CanExecute"/> once for each invoker.</remarks> /// </summary> public void RaiseCanExecuteChanged() { OnCanExecuteChanged( this, EventArgs.Empty ); } private void TriggerPropertyChanged( object sender, PropertyChangedEventArgs e ) { if ( _triggerProperties.Contains( e.PropertyName ) ) RaiseCanExecuteChanged(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; using System.Runtime.Serialization; using System.IO; using System.Text.RegularExpressions; using System.Reflection; using System.Diagnostics; using Microsoft.Win32; using System.Threading; using System.Globalization; using System.Threading.Tasks; namespace ClangCompile { public static class StringSplitter { public static IEnumerable<string> Split(this string str, Func<char, bool> controller) { int nextPiece = 0; for (int c = 0; c < str.Length; c++) { if (controller(str[c])) { yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; } } yield return str.Substring(nextPiece); } public static IEnumerable<string> SplitCommandLine(string commandLine) { bool inQuotes = false; return commandLine.Split(c => { if (c == '\"') inQuotes = !inQuotes; return !inQuotes && c == ' '; }) .Select(arg => arg.Trim()) .Where(arg => !string.IsNullOrEmpty(arg)); } } [Rule(Name="Clang", PageTemplate="tool", DisplayName="Clang", Order="200")] [DataSource(Persistence="ProjectFile", ItemType="ClangCompile")] [PropertyCategory(Name="General", DisplayName="General", Order = 0)] [PropertyCategory(Name = "Paths", DisplayName = "Paths", Order = 1)] [PropertyCategory(Name = "Language", DisplayName = "Language", Order = 2)] [PropertyCategory(Name = "Preprocessor", DisplayName = "Preprocessor", Order = 3)] [PropertyCategory(Name = "All Options", DisplayName = "All Options", Subtype = "Search", Order = 4)] [PropertyCategory(Name = "Command Line", DisplayName = "Command Line", Subtype = "CommandLine", Order = 5)] [FileExtension(Name="*.c", ContentType="ClangCpp")] [FileExtension(Name="*.cpp", ContentType="ClangCpp")] [FileExtension(Name="*.cc", ContentType="ClangCpp")] [FileExtension(Name="*.cxx", ContentType="ClangCpp")] [FileExtension(Name="*.m", ContentType="ClangObjCpp")] [FileExtension(Name="*.mm", ContentType="ClangObjCpp")] [ItemType(Name="ClangCompile", DisplayName="Clang source")] [ContentType(Name="ClangCpp", DisplayName="Clang C/C++", ItemType="ClangCompile")] [ContentType(Name = "ClangObjCpp", DisplayName = "Clang Objective C/C++", ItemType = "ClangCompile")] public class Clang : ToolTask { /// <summary> /// This class holds an item to be compiled by clang. /// </summary> class ClangItem { private Clang clangTask = null; private List<string> stdOut; private List<string> stdErr; public ITaskItem Item { get; private set; } public string ObjFileName { get; private set; } public string DepFileName { get; private set; } public string CommandLine { get; private set; } public int ExitCode { get; private set; } public ClangItem(Clang clangTask, ITaskItem item, string objFileName, string depFileName, string commandLine) { this.clangTask = clangTask; this.Item = item; this.ObjFileName = objFileName; this.DepFileName = depFileName; this.CommandLine = commandLine; this.stdOut = new List<string>(); this.stdErr = new List<string>(); } public void RunClang(string executable) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = executable; startInfo.Arguments = this.CommandLine; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; string stdOutString = null; string stdErrString = null; Process process = Process.Start(startInfo); // Wait for the program to complete as we record all of its StdOut and StdErr Parallel.Invoke( () => { stdOutString = process.StandardOutput.ReadToEnd(); }, () => { stdErrString = process.StandardError.ReadToEnd(); } ); process.WaitForExit(); ExitCode = process.ExitCode; if (!string.IsNullOrEmpty(stdOutString)) { this.stdOut = (stdOutString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)).ToList(); } if (!string.IsNullOrEmpty(stdErrString)) { this.stdErr = (stdErrString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)).ToList(); } } public void LogOutput() { clangTask.LogEventsFromTextOutput(this.Item.ItemSpec, MessageImportance.High); for (int i = 0; i < this.stdOut.Count; i++) { clangTask.LogEventsFromTextOutput(this.stdOut[i], MessageImportance.Normal); } for (int i = 0; i < this.stdErr.Count; i++) { clangTask.LogEventsFromTextOutput(this.stdErr[i], MessageImportance.Normal); } } } // This is only used to output our .tlog files at a logical time, after the end of a build. class TLogWriter : IDisposable { public readonly static string cacheKey = "ClangTaskTLogWriter"; // Tracker has an AppDomain lifetime, so our cache should never be deleted before it. DependencyTracker tracker; public TLogWriter(DependencyTracker t) { tracker = t; } public void Dispose() { foreach (var file in tracker.cachedTlogMaps) { StreamWriter sw = null; try { // Write all the tlog files out to disk. sw = new StreamWriter(File.Open(file.Key, FileMode.Create)); foreach (var val in file.Value) { sw.WriteLine("^" + val.Key); foreach (string line in val.Value) { sw.WriteLine(line); } } sw.Close(); } catch (Exception) { Debug.WriteLine("Error writing TLog file: {0}", (object)file.Key); if (sw != null) { sw.Close(); } } } } } DependencyTracker Tracker { get { if (BuildEngine4 != null) { tracker = (DependencyTracker)BuildEngine4.GetRegisteredTaskObject(DependencyTracker.cacheKey, RegisteredTaskObjectLifetime.AppDomain); } if (tracker == null) { tracker = new DependencyTracker(); if (BuildEngine4 != null) { BuildEngine4.RegisterTaskObject(DependencyTracker.cacheKey, tracker, RegisteredTaskObjectLifetime.AppDomain, false); } } return tracker; } } TLogWriter TLogs { get { if (BuildEngine4 != null) { tlogWriter = (TLogWriter)BuildEngine4.GetRegisteredTaskObject(TLogWriter.cacheKey, RegisteredTaskObjectLifetime.Build); } if (tlogWriter == null) { tlogWriter = new TLogWriter(Tracker); if (BuildEngine4 != null) { BuildEngine4.RegisterTaskObject(TLogWriter.cacheKey, tlogWriter, RegisteredTaskObjectLifetime.Build, false); } } return tlogWriter; } } TLogWriter tlogWriter; static DependencyTracker tracker; // CanonicalTrackedInputFiles' caching behaviour isn't good enough. Visual Studio watches the filesystem // with vigour, so we'll do the same thing. // This has an app object lifetime, so from Visual Studio our incremental builds will be fast, but commandline // builds with be comparable to CL. class DependencyTracker { public static readonly string cacheKey = "ClangCompileDependencyTracker"; public Dictionary<string, Dictionary<string, List<string>>> cachedTlogMaps = new Dictionary<string, Dictionary<string, List<string>>>(); // Only use canonical paths please. DateTime GetModDate(string path) { if (!cachedFileModDates.ContainsKey(path)) { try { // Todo: Consider moving to using directories instead? FileSystemWatcher w = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path)); w.Changed += WatchedFileChanged; w.Renamed += WatchedFileRenamed; w.Deleted += WatchedFileDeleted; w.EnableRaisingEvents = true; watcher.Add(w); cachedFileModDates[path] = File.GetLastWriteTime(path); } catch (Exception) { // File likely doesn't exist, possibly from an old .tlog, or a moved project. // The watcher likely died at this point, so don't cache the date, since we'll probably want to retry later. return DateTime.MinValue; } } return cachedFileModDates[path]; } void WatchedFileRenamed(object sender, RenamedEventArgs e) { GetModDate(e.FullPath); // Track the 'new' file SetOutOfDate(e.FullPath); SetOutOfDate(e.OldFullPath); } void WatchedFileDeleted(object sender, FileSystemEventArgs e) { SetOutOfDate(e.FullPath); needsRebuilding[e.FullPath] = true; } void WatchedFileChanged(object sender, FileSystemEventArgs e) { switch(e.ChangeType) { case WatcherChangeTypes.Created: GetModDate(e.FullPath); // Track the new file SetOutOfDate(e.FullPath); break; case WatcherChangeTypes.Changed: SetOutOfDate(e.FullPath); break; default: // see w_Renamed break; } } public void SetDependencies(string source, List<string> deps) { dependencies.Remove(source); dependencies[source] = deps; GetModDate(source); // Start tracking the files // Clear old updates foreach (List<string> updateList in updates.Values) { updateList.Remove(source); } // Add them back foreach (var dep in deps) { if (!updates.Keys.Contains(dep)) { updates[dep] = new List<string>(); } GetModDate(dep); updates[dep].Add(source); } } public void SetUpToDate(string file, bool upToDate = true) { needsRebuilding[file] = !upToDate; } void SetOutOfDate(string file, int nTries = 2) { List<string> updateList; if (nTries > 0 && updates.TryGetValue(file, out updateList)) { foreach (string updFile in updateList) { needsRebuilding[updFile] = true; SetOutOfDate(updFile, --nTries); } } } DateTime GetNewestInTreeInner(string file, int nTries = 2) { DateTime newest = GetModDate(file); List<string> deps; if (nTries > 0 && dependencies.TryGetValue(file, out deps)) { foreach (string depFile in deps) { DateTime depMod = GetNewestInTreeInner(depFile, --nTries); if (depMod > newest) { newest = depMod; } } } return newest; } DateTime GetNewestInTree(string file) { DateTime newest = DateTime.MinValue; List<string> deps; if (dependencies.TryGetValue(file, out deps)) { foreach (string depFile in deps) { DateTime depMod = GetNewestInTreeInner(depFile); if (depMod > newest) { newest = depMod; } } } return newest; } public bool OutOfDate(string file) { bool ret; if (needsRebuilding.TryGetValue(file, out ret)) { return ret; } if (!File.Exists(file)) { return true; } DateTime fileModDate; DateTime newestModDate; try { fileModDate = GetModDate(file); newestModDate = GetNewestInTree(file); } catch (Exception) { // FileNotFoundException is never thrown, it just returns 00:00/1/1/1601 UTC needsRebuilding[file] = true; return true; } if (fileModDate > newestModDate) { needsRebuilding[file] = false; return false; } needsRebuilding[file] = true; return true; } List<FileSystemWatcher> watcher = new List<FileSystemWatcher>(); Dictionary<string, DateTime> cachedFileModDates = new Dictionary<string,DateTime>(); Dictionary<string, List<string>> dependencies = new Dictionary<string, List<string>>(); Dictionary<string, List<string>> updates = new Dictionary<string,List<string>>(); // Bottom up view of dependencies. Dictionary<string, bool> needsRebuilding = new Dictionary<string, bool>(); } #region Private and utils void LogMessage(MessageImportance importance, string message, params object[] list) { #if !LOWLEVEL_DEBUG if(importance == MessageImportance.High) #endif { if (BuildEngine4 != null) { Log.LogMessage(importance, message, list); } } } void LogWarning(string message, params object[] list) { if (BuildEngine4 != null) { Log.LogWarning(message, list); } } string DecorateFile(string path, string extension) { return Path.GetFileNameWithoutExtension(path) + "_" + Path.GetFullPath(path).GetHashCode().ToString("X") + extension; } string GetSpecial(string name, object value, ITaskItem input) { // ToLower is affected by localization. Need to be careful here. name = name.ToLower(new CultureInfo("en-US", false)); if (value == null) { if (name == "inputfilename") { return Path.GetFileName(input.ItemSpec); } else if (name == "inputabsdir") { return Path.GetDirectoryName(Path.GetFullPath(input.ToString())); } else if (name == "dependencyfile") { return GetSpecial("objectfilename", ObjectFileName, input) + ".d"; } else if (name == "dependencysource") { return GetSpecial("objectfilename", ObjectFileName, input); } } if (name == "objectfilename") { if (value.ToString().Last() == '\\' || value.ToString().Last() == '/') { return value + DecorateFile(input.ItemSpec, ".obj"); } } else if (name == "input") { return GetFullPath(input.ToString()); } return value == null ? null : value.ToString(); } static string GetFullPath(string path) { if (path == null || path == "") { return ""; } // Clang is not erroneously escaping quotes... per se. Windows allows quotes in filenames, but trims trailing whitespace. // eg. "C:\SomeDir\"SomeFile"" is a valid path. For clang to accept it you'd have to escape the filename quotes to "C:\SomeDir\\"SomeFile\"" // "C:\SomeDir\" is not valid, since it thinks you're trying to refer to a file in SomeDir by the name of " [and subsequent arguments since we didn't match the quote] string fullPath = Path.GetFullPath(path); if (fullPath.EndsWith("\\")) { fullPath = fullPath.Substring(0, fullPath.Length - 1); } return "\"" + fullPath + "\""; } string GetClangExe() { return LLVMDirectory + @"\bin\clang.exe"; } string GetClangResourceDir() { return LLVMDirectory + @"\lib\clang\" + LLVMClangVersion; } #endregion #region MSBuild Properties [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string LLVMClangVersion { get { if(LLVMClangVersionValue == null || LLVMClangVersionValue == "") { LogMessage(MessageImportance.Low, "Clang exe: {0}", GetClangExe()); ProcessStartInfo clangPsi = new ProcessStartInfo(GetClangExe(), @"-v"); Process clangVersionProc = new Process(); clangPsi.CreateNoWindow = true; clangPsi.RedirectStandardError = true; clangPsi.UseShellExecute = false; clangVersionProc.StartInfo = clangPsi; clangVersionProc.Start(); clangVersionProc.WaitForExit(); string versionString = clangVersionProc.StandardError.ReadToEnd(); LogMessage(MessageImportance.Low, "Clang version: {0}", versionString); // clang's version output: clang with Microsoft CodeGen version <version number> string version = versionString.Split(' ')[5]; LLVMClangVersion = version; } return LLVMClangVersionValue; } set { LLVMClangVersionValue = value; } } static string LLVMClangVersionValue; [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string LLVMResourceDir { get { if(LLVMResourceDirValue == null || LLVMResourceDirValue == "") { LLVMResourceDirValue = GetClangResourceDir(); } return LLVMResourceDirValue; } set { LLVMResourceDirValue = value; } } string LLVMResourceDirValue; [Required] [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string CommandTLogFile { get; set; } [Required] [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string ProjectFile { get; set; } [Required] [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string ReadTLogFile { get; set; } [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string InputFileName { get; set; } [PropertyPage(Visible = false, IncludeInCommandLine = false)] [ResolvePath()] public string InputAbsDir { get; set; } [Required] [PropertyPage( Category = "Command Line", Visible = false)] [DataSource( Persistence = "ProjectFile", ItemType = "ClangCompile", SourceType = "Item")] public ITaskItem[] Input { get; set; } // Don't build the outputs, just create the output items. public bool Autocomplete { get; set; } public enum HeaderMapEnum { [Field(DisplayName="Disabled", Description="Disable use of header maps.")] Disabled, [Field(DisplayName="Project", Description="User a header map containing all headers in the VS project.")] Project, [Field(DisplayName = "Combined", Description = "User a header map containing all headers in the VS project, as well as any headers found in the same directory as the source files being compiled.")] Combined, } [PropertyPage( Category = "General", Description = "Specify type of header map to use.", DisplayName = "Use Header Map", IncludeInCommandLine = false)] [EnumeratedValue(Enumeration = typeof(HeaderMapEnum))] public string HeaderMap { get { return HeaderMapValue.ToString(); } set { HeaderMapValue = (HeaderMapEnum)Enum.Parse(typeof(HeaderMapEnum), value, true); } } HeaderMapEnum HeaderMapValue; [PropertyPage( DisplayName = "Framework-style header map entries", Description = "Add framework-style entries to header map.", Category = "General", IncludeInCommandLine = false)] public bool HeaderMapAddFrameworkEntries { get; set; } [PropertyPage( Category = "General", DisplayName = "Header Map Include", Description = "Header Map Include", Visible = false)] public string HeaderMapInclude { get; set; } public enum RuntimeLibraryEnum { [Field(DisplayName = "Multi-threaded", Description = "Causes your application to use the multithread, static version of the run-time library.", Switch = "-D_MT --dependent-lib=libcmt --dependent-lib=oldnames")] MultiThreaded, [Field(DisplayName = "Multi-threaded Debug", Description = "Defines _DEBUG and _MT. This option also causes the compiler to place the library name LIBCMTD.lib into the .obj file so that the linker will use LIBCMTD.lib to resolve external symbols.", Switch="-D_DEBUG -D_MT --dependent-lib=libcmtd --dependent-lib=oldnames")] MultiThreadedDebug, [Field(DisplayName = "Multi-threaded DLL", Description = "Causes your application to use the multithread- and DLL-specific version of the run-time library. Defines _MT and _DLL and causes the compiler to place the library name MSVCRT.lib into the .obj file.", Switch = "-D_MT -D_DLL --dependent-lib=msvcrt --dependent-lib=oldnames")] MultiThreadedDLL, [Field(DisplayName = "Multi-threaded Debug DLL", Description = "Defines _DEBUG, _MT, and _DLL and causes your application to use the debug multithread- and DLL-specific version of the run-time library. It also causes the compiler to place the library name MSVCRTD.lib into the .obj file.", Switch = "-D_DEBUG -D_MT -D_DLL --dependent-lib=msvcrtd --dependent-lib=oldnames")] MultiThreadedDebugDLL } [PropertyPage( Category = "General", Description = "Specify runtime library for linking.", DisplayName = "Runtime Library")] [EnumeratedValue(Enumeration = typeof(RuntimeLibraryEnum))] public string RuntimeLibrary { get { return RuntimeLibraryValue.ToString(); } set { RuntimeLibraryValue = (RuntimeLibraryEnum)Enum.Parse(typeof(RuntimeLibraryEnum), value, true); } } RuntimeLibraryEnum RuntimeLibraryValue; public enum OptimizationLevelEnum { [Field(Switch="-O0 -mrelax-all", DisplayName="Disabled", Description="Disable optimization.")] Disabled, [Field(Switch="-Os -vectorize-loops -vectorize-slp", DisplayName="Optimize for size", Description="Medium level, with extra optimizations to reduce code size.")] MinSpace, [Field(Switch="-O2 -vectorize-loops -vectorize-slp", DisplayName="Optimize for speed", Description="More optimizations.")] MaxSpeed, [Field(Switch="-O3 -vectorize-loops -vectorize-slp", DisplayName="Maximum optimizations", Description="Even more optimizations.")] Full } [PropertyPage( Category="General", DisplayName="Optimization Level", Description="Select option for code optimization.")] [EnumeratedValue(Enumeration = typeof(OptimizationLevelEnum))] public string OptimizationLevel { get { return OptimizationLevelValue.ToString(); } set { OptimizationLevelValue = (OptimizationLevelEnum)Enum.Parse(typeof(OptimizationLevelEnum), value, true); } } OptimizationLevelEnum OptimizationLevelValue; [PropertyPage( DisplayName = "Debug Information", Description = "Specifies whether to keep debug information.", Category = "General", Switch = "-g")] public bool DebugInformation { get; set; } [PropertyPage( DisplayName = "Enable C++ Exceptions", Description = "Specifies the model of exception handling to be used by the compiler.", Category = "General", Switch = "-fexceptions -fobjc-exceptions -fcxx-exceptions")] public bool ExceptionHandling { get; set; } [PropertyPage( DisplayName = "Enable Objective-C ARC", Description = "Specifies whether to use Automatic Reference Counting.", Category = "General", Switch = "-fobjc-arc")] public bool ObjectiveCARC { get; set; } [PropertyPage( DisplayName = "Enable C and Objective-C Modules", Description = "Specifies whether to use Clang modules.", Category = "General", Switch = "-fmodules -fimplicit-module-maps")] public bool ObjectiveCModules { get; set; } [PropertyPage( DisplayName = "Path to Objective-C modules", Description = "Path to the directory where the modules will be cached", Category = "General", Visible = false, Switch = "-fmodules-cache-path=")] [ResolvePath()] public string ObjectiveCModulesCachePath { get; set; } [PropertyPage( Category = "Paths", DisplayName = "Hidden Include Paths", Description = "Hidden include Paths", Switch = "-internal-isystem ", Visible = false)] [ResolvePath()] public string[] InternalSystemIncludePaths { get; set; } [PropertyPage( Category = "Paths", DisplayName = "Excluded Search Path Subdirectories", Description = "Wildcard pattern for subdirectories to exclude from recursive search", IncludeInCommandLine = false)] public string[] ExcludedSearchPathSubdirectories { get { return ExcludedSearchPathSubdirectoriesValues; } set { ExcludedSearchPathSubdirectoriesValues = convertWildcardToRegEx(value); } } string[] ExcludedSearchPathSubdirectoriesValues; private static string[] convertWildcardToRegEx(string[] wildcardPaths) { List<string> patterns = new List<string>(); foreach (string wildcard in wildcardPaths) { string pattern = Regex.Escape(wildcard); pattern = pattern.Replace("/", "\\\\"); // Convert "*" to ".*", i.e. match any character except the path separator, zero or more times. pattern = pattern.Replace("\\*", "[^\\\\]*"); // Convert "?" to ".", i.e. match exactly one character except the path separator. pattern = pattern.Replace("\\?", "[^\\\\]"); patterns.Add(pattern + "$"); } return patterns.ToArray(); } private void dirSearch(string dirPath, ref List<string> outPaths) { int maxCount = outPaths.Count + 2048; outPaths.Add(dirPath); for (var i = outPaths.Count - 1; i < Math.Min(outPaths.Count, maxCount); i++) { try { foreach (string d in Directory.GetDirectories(outPaths[i])) { bool excluded = false; if (ExcludedSearchPathSubdirectories != null) { foreach (string pattern in ExcludedSearchPathSubdirectories) { if (Regex.IsMatch(d, pattern, RegexOptions.None)) { excluded = true; break; } } } if (!excluded) { outPaths.Add(d); } } } catch (System.Exception) { } } } private string[] expandPathGlobs(string[] inPaths) { List<string> outPaths = new List<string>(); foreach (string path in inPaths) { string winPath = path.Replace('/', '\\'); if (winPath.EndsWith("\\**")) dirSearch(winPath.Substring(0, path.Length - 3), ref outPaths); else outPaths.Add(winPath); } return outPaths.ToArray(); } [PropertyPage( Category = "Paths", DisplayName = "User Include Paths", Description = "User header search paths.", Switch = "-iquote ")] [ResolvePath()] public string[] UserIncludePaths { get { return UserIncludePathsValue; } set { UserIncludePathsValue = expandPathGlobs(value); } } string[] UserIncludePathsValue; [PropertyPage( Category = "Paths", DisplayName = "Include Paths", Description = "Header search paths.", Switch = "-I")] [ResolvePath()] public string[] IncludePaths { get { return IncludePathsValue; } set { IncludePathsValue = expandPathGlobs(value); } } string[] IncludePathsValue; [PropertyPage( Category = "Paths", Subtype = "file", DisplayName = "Object File Name", Description = "Specifies a name to override the default object file name.", Switch = "-o ", IncludeInCommandLine = false)] [ResolvePath()] public string ObjectFileName { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Preprocessor Definitions", Description = "Define preprocessor symbols for your source files.", Switch = "-D")] public string[] PreprocessorDefinitions { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Undefine Preprocessor Definitions", Description = "Specifies one or more preprocessor undefines.", Switch = "-U")] public string[] UndefinePreprocessorDefinitions { get; set; } public enum CompileAsEnum { [Field(DisplayName = "Default", Description = "Default", Switch = "")] Default, [Field(DisplayName = "Compile as C Code", Description = "Compile as C Code", Switch = "-x c")] CompileAsC, [Field(DisplayName = "Compile as C++ Code", Description = "Compile as C++ Code", Switch = "-x c++ -std=c++11 -fdeprecated-macro")] CompileAsCpp, [Field(DisplayName = "Compile as Objective C Code", Description = "Compile as Objective C Code", Switch = "-x objective-c")] CompileAsObjC, [Field(DisplayName = "Compile as Objective C++ Code", Description = "Compile as Objective C++ Code", Switch = "-x objective-c++ -std=c++11 -fdeprecated-macro")] CompileAsObjCpp } [PropertyPage( Category = "Language", DisplayName = "Compile As", Description = "Select compile language for [Objective] C/C++ files.")] [EnumeratedValue(Enumeration = typeof(CompileAsEnum))] public string CompileAs { get { return CompileAsValue.ToString(); } set { CompileAsValue = (CompileAsEnum)Enum.Parse(typeof(CompileAsEnum), value, true); } } CompileAsEnum CompileAsValue; [PropertyPage( Category = "Language", DisplayName = "LLVM Directory", Description = "Use LLVM from this directory for compilation", IncludeInCommandLine=false)] public string LLVMDirectory { get { if(LLVMDirectoryValue == null) { // The SDK should always set this? LLVMDirectoryValue = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) + "\\LLVM-3.6.0\\"; } return LLVMDirectoryValue; } set { LLVMDirectoryValue = value; } } string LLVMDirectoryValue; [PropertyPage( Category = "General", Subtype = "file", DisplayName = "Prefix Header", Description = "Specifies prefix header file to be included when compiling all source files.", Switch = "-include ")] [ResolvePath()] public string[] PrefixHeader { get; set; } [PropertyPage( Category = "General", DisplayName = "Maximum Clang Processes", Description = "Specifies the maximum number of clang processes to run in parallel. The argument can be -1 or any positive integer. A positive property value limits the number of concurrent operations to the set value. If it is -1, there is no limit on the number of concurrently running operations.", IncludeInCommandLine = false)] public int MaxClangProcesses { get; set; } [PropertyPage( Category = "Language", DisplayName = "Other C Flags", Description = "Other C Flags", IncludeInCommandLine = false)] public string OtherCFlags { get; set; } [PropertyPage( Category = "Language", DisplayName = "Other C++ Flags", Description = "Other C++ Flags", IncludeInCommandLine = false)] public string OtherCPlusPlusFlags { get; set; } [PropertyPage( Category = "Language", DisplayName = "Language-specific flags", Description = "Language-specific flags", Visible = false)] public string OtherFlags { get; set; } [PropertyPage( Category = "Language", DisplayName = "Use WinObjC standard library", Description = "Uses the WinObjC standard C/C++ library definitions when compiling. This can create some compatibility issues with COM interfaces and Windows-specific source code.")] public Boolean WOCStdLib { get; set; } [PropertyPage( DisplayName = "Command Line", Visible = false, IncludeInCommandLine = false)] public string CommandLineTemplate { get; set; } public string AutocompleteCommandLineTemplate { get; set; } [Output] [PropertyPage( DisplayName = "Outputs", Visible = false, IncludeInCommandLine = false)] public ITaskItem[] Outputs { get; set; } [PropertyPage( Subtype = "AdditionalOptions", Category = "Command Line", DisplayName = "Additional Options", Description = "Additional Options", IncludeInCommandLine=false)] public string AdditionalOptions { get { return AdditionalOptionsValue; } set { AdditionalOptionsValue = filterAdditionalOptions(value); } } string AdditionalOptionsValue; private string filterAdditionalOptions(string opts) { List<string> retTokens = new List<string>(); IEnumerable<string> tokens = StringSplitter.SplitCommandLine(opts); foreach (string t in tokens) { if (t == "-fobjc-arc") ObjectiveCARC = true; else if (t == "-fno-objc-arc") ObjectiveCARC = false; else retTokens.Add(t); } return String.Join(" ", retTokens); } [PropertyPage( Category = "Preprocessor", DisplayName = "Dependency File", Description = "Specifies a name to override the default dependency file name.", Switch = "-dependency-file ", IncludeInCommandLine = false)] [ResolvePath()] public string DependencyFile { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Dependency Source", Description = "Specifies a name to override the default dependency source file name.", Switch = "-MT ", IncludeInCommandLine = false)] [ResolvePath()] public string DependencySource { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Use System Headers For Dependencies", Description = "Don't ignore system headers when calculating dependencies.", Switch = "-sys-header-deps")] public bool SystemHeaderDeps { get; set; } #endregion #region ToolTask Overrides // ToLower() is affected by localization. // Be VERY careful when adding static strings to the dictionary, since lookup is also done with ToLower. static Dictionary<string, PropertyInfo> AllProps = typeof(Clang).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).ToDictionary(x => x.Name.ToLower()); protected override string GenerateFullPathToTool() { return GetClangExe(); } protected override string ToolName { get { return "clang.exe"; } } private string ReplaceOptions(string commandLine, ITaskItem input) { Match subst = Regex.Match(commandLine, @"\[\w+\]", RegexOptions.IgnoreCase); while (subst.Success) { string autoSubst = subst.Value.Substring(1, subst.Value.Length - 2); string substStr = ""; LogMessage(MessageImportance.Low, "Replace value: {0}", autoSubst); PropertyInfo pInfo; if (AllProps.TryGetValue(autoSubst.ToLower(), out pInfo)) { ResolvePathAttribute pathAttr = (ResolvePathAttribute)Attribute.GetCustomAttribute(pInfo, typeof(ResolvePathAttribute)); PropertyPageAttribute ppAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(pInfo, typeof(PropertyPageAttribute)); string propSwitch = ppAttr.Switch; object value = pInfo.GetValue(this); string propVal = GetSpecial(autoSubst, value, input); if (propVal != null && propVal != "") { if (propSwitch != null && propSwitch != "") { substStr += propSwitch; } if (pathAttr != null) { try { substStr += GetFullPath(propVal); } catch (Exception) { LogWarning(string.Format("Unable to resolve path {0} for property: {1}", value.ToString(), pInfo.Name)); } } else { substStr += propVal; } } } else { Log.LogError("Only [Input] [AllOptions] [AdditionalOptions] and task properties are acceptped substitutions for command line arguments; Unknown expansion: " + autoSubst); return null; } commandLine = commandLine.Replace(subst.Value, substStr); subst = subst.NextMatch(); } LogMessage(MessageImportance.Low, "Commandline: {0}", commandLine); // NOTE: See GetFullPath about escaping quotes. return commandLine; } protected override string GenerateCommandLineCommands() { return GenerateCommandLineCommands(CommandLineTemplate); } protected string GenerateCommandLineCommands(string template) { string commandToRun = template; Match subst = Regex.Match(commandToRun, @"\[alloptions\]", RegexOptions.IgnoreCase); if (subst.Success) { string autoSubst = subst.Value.Substring(1, subst.Value.Length - 2); string substStr = ""; LogMessage(MessageImportance.Low, "Replacing all options"); foreach (PropertyInfo pInfo in AllProps.Values) { PropertyPageAttribute ppAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(pInfo, typeof(PropertyPageAttribute)); EnumeratedValueAttribute enumAttr = (EnumeratedValueAttribute)Attribute.GetCustomAttribute(pInfo, typeof(EnumeratedValueAttribute)); ResolvePathAttribute pathAttr = (ResolvePathAttribute)Attribute.GetCustomAttribute(pInfo, typeof(ResolvePathAttribute)); if (ppAttr == null) { LogMessage(MessageImportance.Low, "Skipping {0}", pInfo.Name); continue; } if (!ppAttr.IncludeInCommandLine) { LogMessage(MessageImportance.Low, "Excluding {0}", pInfo.Name); continue; } if (enumAttr != null) { FieldInfo fInfo = enumAttr.Enumeration.GetField((string)pInfo.GetValue(this)); FieldAttribute fAttr = (FieldAttribute)Attribute.GetCustomAttribute(fInfo, typeof(FieldAttribute)); if (fAttr.Switch == null || fAttr.Switch == "") { continue; } LogMessage(MessageImportance.Low, "Field({0}) switch: {1}", fInfo.Name, fAttr.Switch); substStr += fAttr.Switch + " "; } else { if (pInfo.PropertyType.IsAssignableFrom(typeof(string[]))) { string concatStr = ppAttr.Switch; string[] propVal = (string[])pInfo.GetValue(this); LogMessage(MessageImportance.Low, "String array({0}) switch: {1}", pInfo.Name, concatStr); if (propVal != null) { foreach (var item in propVal) { if (pathAttr != null) // Just awful. { try { substStr += concatStr + GetFullPath((string)item) + " "; } catch (Exception) { LogWarning(string.Format("Unable to resolve path {0} for property: {1}", item, pInfo.Name)); } } else { substStr += concatStr + item + " "; } // substStr += string.Join(" ", Array.ConvertAll<string, string>(propVal, new Converter<string, string>(delegate(string x) { return concatStr + " " + x; }))) + " "; } } } else if (pInfo.PropertyType.IsAssignableFrom(typeof(bool))) { object propVal = pInfo.GetValue(this); string cmdStr = propVal.ToString(); string cmdSwitch = (bool)propVal ? ppAttr.Switch : ppAttr.ReverseSwitch; if (cmdSwitch != null && cmdSwitch != "") { LogMessage(MessageImportance.Low, "Bool({0}) switch: {1}", pInfo.Name, cmdSwitch); substStr += cmdSwitch + " "; } else if ((bool)propVal) { LogWarning("Boolean is visible, but has no switch: {0}", pInfo.Name); } } else if (pInfo.PropertyType.IsAssignableFrom(typeof(string))) { object propVal = pInfo.GetValue(this); if (propVal != null && (string)propVal != "") { LogMessage(MessageImportance.Low, "String({0}) prop: {1}", pInfo.Name, (string)propVal); if (ppAttr.Switch != null && ppAttr.Switch != "") { substStr += ppAttr.Switch; } if (pathAttr != null) // Just awful. { try { substStr += GetFullPath((string)propVal) + " "; } catch (Exception) { LogWarning(string.Format("Unable to resolve path {0} for property: {1}", propVal, pInfo.Name)); } } else { substStr += (string)propVal + " "; } } } } } commandToRun = commandToRun.Replace(subst.Value, substStr); } LogMessage(MessageImportance.Low, "Commandline: {0}", commandToRun); // NOTE: See GetFullPath about escaping quotes. return commandToRun; } protected override bool SkipTaskExecution() { if (Autocomplete) { return false; } // We need to wait until all the mod dates have been set before moving on, or we may get a race condition. object modDateSync = new object(); int nModDate = 0; bool skip = true; // Instantiate the writer. TLogWriter writer = TLogs; if (!Tracker.cachedTlogMaps.ContainsKey(Path.GetFullPath(ReadTLogFile))) { var deps = ReadTLog(Path.GetFullPath(ReadTLogFile)); var outs = ReadTLog(Path.GetFullPath(ReadTLogFile.Replace("read", "write"))); foreach (var dep in deps) { Tracker.SetDependencies(dep.Key, dep.Value); } foreach (var output in outs) { Tracker.SetDependencies(output.Value[0], new List<string>() { output.Key }); // Only one output per file } } Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f => { TaskItem i = new TaskItem(f); i.ItemSpec = GetSpecial("objectfilename", ObjectFileName, i); i.SetMetadata("ObjectFileName", i.ItemSpec); return i; })); foreach (ITaskItem item in Input) { string inputFileName = Path.GetFullPath(item.ItemSpec); string objFileName = Path.GetFullPath(GetSpecial("objectfilename", ObjectFileName, item)); string depFileName = Path.GetFullPath(GetSpecial("dependencyfile", DependencyFile, item)); WaitCallback waitCallback = new WaitCallback(f => { try { File.SetLastWriteTime(objFileName, DateTime.Now); if (File.Exists(depFileName)) { File.SetLastWriteTime(depFileName, DateTime.Now); } } catch (Exception e) { LogWarning("Caught exception trying to set last modification: {0}", e.ToString()); } lock (modDateSync) { if (--nModDate == 0) { Monitor.Pulse(modDateSync); } } }); if (tracker.OutOfDate(objFileName)) { skip = false; continue; } if (!File.Exists(objFileName)) { tracker.SetUpToDate(objFileName, false); skip = false; continue; } if (File.GetLastWriteTime(ProjectFile) < File.GetLastWriteTime(objFileName)) { // Touch the file so MSBuild is happy. lock (modDateSync) { nModDate++; } ThreadPool.QueueUserWorkItem(waitCallback); continue; } else { Dictionary<string, List<string>> cmdMap = ReadTLog(Path.GetFullPath(CommandTLogFile)); List<string> cmdLine; // If the commandlines are different, rebuild. if (cmdMap.TryGetValue(inputFileName, out cmdLine)) { if (cmdLine.First().Substring(1) == ReplaceOptions(GenerateCommandLineCommands(), item)) { // Touch the file so MSBuild is happy. lock (modDateSync) { nModDate++; } ThreadPool.QueueUserWorkItem(waitCallback); continue; } else { tracker.SetUpToDate(objFileName, false); } } } skip = false; } lock (modDateSync) { if (nModDate > 0) { Monitor.Wait(modDateSync); } } return skip; } protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { int retCode = 0; if (Autocomplete) { Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f => { TaskItem i = new TaskItem(f); i.SetMetadata("ObjectFileName", GetSpecial("objectfilename", ObjectFileName, i)); i.SetMetadata("AutocompleteCommand", ReplaceOptions(GenerateCommandLineCommands(AutocompleteCommandLineTemplate), f)); return i; })); return 0; } else { Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f => { TaskItem i = new TaskItem(f); i.ItemSpec = GetSpecial("objectfilename", ObjectFileName, i); i.SetMetadata("ObjectFileName", i.ItemSpec); return i; })); } List<ClangItem> clangItems = new List<ClangItem>(Input.Length); for (int i = 0; i < Input.Length; i++) { ITaskItem item = Input[i]; string objFileName = Path.GetFullPath(GetSpecial("objectfilename", ObjectFileName, item)); string depFileName = Path.GetFullPath(GetSpecial("dependencyfile", DependencyFile, item)); if (File.Exists(objFileName) && !tracker.OutOfDate(objFileName)) { continue; } string commandLine = ReplaceOptions(commandLineCommands, item); clangItems.Add(new ClangItem(this, item, objFileName, depFileName, commandLine)); } if ((MaxClangProcesses > 1) || (MaxClangProcesses == -1)) { Parallel.ForEach(clangItems, new ParallelOptions { MaxDegreeOfParallelism = MaxClangProcesses }, (clangItem) => { clangItem.RunClang(pathToTool); lock (this) { clangItem.LogOutput(); } }); } else { for(int i=0;i<clangItems.Count; i++) { clangItems[i].RunClang(pathToTool); clangItems[i].LogOutput(); if (clangItems[i].ExitCode != 0) { //Note: this break is for backward compatibility. We would previously return on the first file that failed to compile correctly. break; } } } for (int i = 0; i < clangItems.Count; i++) { ClangItem clangItem = clangItems[i]; retCode |= clangItem.ExitCode; string inputFullPath = Path.GetFullPath(clangItem.Item.ItemSpec); ReadTLog(Path.GetFullPath(CommandTLogFile))[inputFullPath] = new List<string>() { clangItem.CommandLine }; if (clangItem.ExitCode == 0) { if (File.Exists(clangItem.DepFileName)) { List<string> deps = ReadDependencyFile(clangItem.DepFileName); if (deps != null) { // Should we do anything special if we fail to parse the dependency file? // As it stands now, if we fail the object file will not be up to date, and it will continute to be built. Tracker.SetDependencies(inputFullPath, deps); Tracker.SetUpToDate(clangItem.ObjFileName); } Tracker.SetDependencies(clangItem.ObjFileName, new List<string>() { inputFullPath }); } } else { tracker.SetUpToDate(inputFullPath, false); // Probably an invalid object file, if it exists. if ((MaxClangProcesses > 1) || (MaxClangProcesses == -1)) { //Note: this return is for backward compatibility. We would previously return on the first file that failed to compile correctly. return retCode; } } } return retCode; } #endregion List<string> ReadDependencyFile(string file) { StreamReader sr = null; if (!File.Exists(file)) { return null; } List<string> deps = new List<string>(); try { sr = new StreamReader(File.Open(file, FileMode.Open)); Regex matchDep = new Regex(@"((\\\s|\S)+)"); string curLine = null; string sourceFile = null; string outputFile = null; // First line has the object file, everything before the ':' // The first dependency is the source file // The rest is a list of header files we depend on. The line ends with " \\\cl\rf" while ((curLine = sr.ReadLine()) != null) { if(curLine.Contains(@": ")) { outputFile = curLine.Substring(0, curLine.IndexOf(@": ")); curLine = curLine.Substring(curLine.IndexOf(@": ") + 1); } // Cull the trailed slash if (curLine[curLine.Length - 1] == '\\') { curLine = curLine.Substring(0, curLine.Length - 2); } Match depMatch = matchDep.Match(curLine); while (depMatch.Success) { // Replace escaped spaces string value = depMatch.Groups[0].Value.Replace("\\ ", " ").Replace("/", "\\"); if (sourceFile == null) { sourceFile = value; ReadTLog(Path.GetFullPath(ReadTLogFile))[sourceFile] = deps; if (outputFile == null) { LogWarning("Output file not found in dependency file ({0})", file); } else { ReadTLog(Path.GetFullPath(ReadTLogFile.Replace("read", "write")))[sourceFile] = new List<string>() { outputFile, file }; } } else { deps.Add(value); } depMatch = depMatch.NextMatch(); } } } catch (Exception e) { LogWarning("Caught exception reading dependency file: " + e.ToString()); } if (sr != null) { sr.Close(); } return deps; } Dictionary<string, List<string>> ReadTLog(string file) { if (Tracker.cachedTlogMaps.ContainsKey(file)) { return Tracker.cachedTlogMaps[file]; } Dictionary<string, List<string>> retMap = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); StreamReader sr = null; if (!File.Exists(file)) { Tracker.cachedTlogMaps[file] = retMap; return retMap; } try { sr = new StreamReader(File.Open(file, FileMode.Open)); string curLine = null; string keyVal = null; while ((curLine = sr.ReadLine()) != null) { if (curLine[0] == '^') { keyVal = curLine.Substring(1); retMap.Add(keyVal, new List<string>()); } else { if (keyVal == null) { // We got ourselves a malformed tlog. Throw it out. LogWarning("TLog file is malformed."); retMap = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); break; } retMap[keyVal].Add(curLine); } } } catch (Exception e) { LogWarning("Caught exception reading TLog: {0}", e.ToString()); } if (sr != null) { sr.Close(); } Tracker.cachedTlogMaps[file] = retMap; return retMap; } } }
namespace FakeItEasy.Tests.Core { using System; using System.Diagnostics.CodeAnalysis; using FakeItEasy.Core; using FakeItEasy.Creation; using NUnit.Framework; [TestFixture] public class DefaultFixtureInitializerTests { #pragma warning disable 649 [UnderTest] private DefaultFixtureInitializer initializer; [Fake] private IFakeAndDummyManager fakeAndDummyManager; [Fake] private IFoo fakeReturnedFromFakeAndDummyManager; [Fake] private ISutInitializer sutInitializer; #pragma warning restore 649 private FixtureType fixture; [SetUp] public void Setup() { this.OnSetup(); } [Test] public void Should_set_public_property_that_is_attributed() { // Arrange // Act this.initializer.InitializeFakes(this.fixture); // Assert Assert.That(this.fixture.FooProperty, Is.SameAs(this.fakeReturnedFromFakeAndDummyManager)); } [Test] public void Should_not_set_untagged_property() { // Arrange // Act this.initializer.InitializeFakes(this.fixture); // Assert Assert.That(this.fixture.NonFakedProperty, Is.Null); } [Test] public void Should_set_private_property_that_is_tagged() { // Arrange // Act this.initializer.InitializeFakes(this.fixture); // Assert Assert.That(this.fixture.GetValueOfPrivateFakeProperty(), Is.SameAs(this.fakeReturnedFromFakeAndDummyManager)); } [Test] public void Should_set_private_field_that_is_tagged() { // Arrange // Act this.initializer.InitializeFakes(this.fixture); // Assert Assert.That(this.fixture.GetValueOfPrivateFakeField(), Is.SameAs(this.fakeReturnedFromFakeAndDummyManager)); } [Test] public void Should_set_public_field_that_is_tagged() { // Arrange // Act this.initializer.InitializeFakes(this.fixture); // Assert Assert.That(this.fixture.PublicFakeField, Is.SameAs(this.fakeReturnedFromFakeAndDummyManager)); } [Test] public void Should_not_set_non_tagged_field() { // Arrange // Act this.initializer.InitializeFakes(this.fixture); // Assert Assert.That(this.fixture.NonFakeField, Is.Null); } [Test] public void Should_set_sut_from_sut_initializer() { // Arrange var sut = A.Dummy<Sut>(); A.CallTo(() => this.sutInitializer.CreateSut(A<Type>._, A<Action<Type, object>>._)) .Returns(sut); var sutFixture = new SutFixture(); // Act this.initializer.InitializeFakes(sutFixture); // Assert Assert.That(sutFixture.Sut, Is.SameAs(sut)); } [Test] public void Should_set_fake_from_sut_initializer_callback_when_available() { // Arrange var fake = A.Fake<IFoo>(); A.CallTo(() => this.sutInitializer.CreateSut(A<Type>._, A<Action<Type, object>>._)) .Invokes(x => x.GetArgument<Action<Type, object>>(1).Invoke(typeof(IFoo), fake)); var sutFixture = new SutFixture(); // Act this.initializer.InitializeFakes(sutFixture); // Assert Assert.That(sutFixture.Foo, Is.SameAs(fake)); } [Test] public void Should_fail_when_more_than_one_member_is_marked_as_sut() { // Arrange // Act // Assert Assert.That( () => this.initializer.InitializeFakes(new SutFixtureWithTwoSutMembers()), Throws.InstanceOf<InvalidOperationException>().With.Message.EqualTo("A fake fixture can only contain one member marked \"under test\".")); } protected virtual void OnSetup() { Fake.InitializeFixture(this); A.CallTo(() => this.fakeAndDummyManager.CreateFake(typeof(IFoo), A<FakeOptions>._)).Returns(this.fakeReturnedFromFakeAndDummyManager); this.fixture = new FixtureType(); } public class Sut { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "foo", Justification = "Required for testing.")] public Sut(IFoo foo) { } } public class SutFixture { [Fake] public IFoo Foo { get; set; } [UnderTest] public Sut Sut { get; set; } } public class SutFixtureWithTwoSutMembers { [UnderTest] public Sut Sut { get; set; } [UnderTest] public Sut Sut2 { get; set; } } public class FixtureType { [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Required for testing.")] [Fake] public IFoo PublicFakeField; [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Required for testing.")] public IFoo NonFakeField; #pragma warning disable 649 [Fake] private IFoo privateFakeField; #pragma warning restore 649 [Fake] public IFoo FooProperty { get; set; } public IFoo NonFakedProperty { get; set; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required for testing.")] [Fake] private IFoo PrivateFakeProperty { get; set; } [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Required for testing.")] public IFoo GetValueOfPrivateFakeProperty() { return this.PrivateFakeProperty; } [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Required for testing.")] public IFoo GetValueOfPrivateFakeField() { return this.privateFakeField; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.WebSites { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for RecommendationsOperations. /// </summary> public static partial class RecommendationsOperationsExtensions { /// <summary> /// List all recommendations for a subscription. /// </summary> /// <remarks> /// List all recommendations for a subscription. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='featured'> /// Specify &lt;code&gt;true&lt;/code&gt; to return only the most critical /// recommendations. The default is &lt;code&gt;false&lt;/code&gt;, which /// returns all recommendations. /// </param> /// <param name='filter'> /// Filter is specified by using OData syntax. Example: $filter=channels eq /// 'Api' or channel eq 'Notification' and startTime eq '2014-01-01T00:00:00Z' /// and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq /// duration'[PT1H|PT1M|P1D] /// </param> public static IList<Recommendation> List(this IRecommendationsOperations operations, bool? featured = default(bool?), string filter = default(string)) { return operations.ListAsync(featured, filter).GetAwaiter().GetResult(); } /// <summary> /// List all recommendations for a subscription. /// </summary> /// <remarks> /// List all recommendations for a subscription. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='featured'> /// Specify &lt;code&gt;true&lt;/code&gt; to return only the most critical /// recommendations. The default is &lt;code&gt;false&lt;/code&gt;, which /// returns all recommendations. /// </param> /// <param name='filter'> /// Filter is specified by using OData syntax. Example: $filter=channels eq /// 'Api' or channel eq 'Notification' and startTime eq '2014-01-01T00:00:00Z' /// and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq /// duration'[PT1H|PT1M|P1D] /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> ListAsync(this IRecommendationsOperations operations, bool? featured = default(bool?), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(featured, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Reset all recommendation opt-out settings for a subscription. /// </summary> /// <remarks> /// Reset all recommendation opt-out settings for a subscription. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void ResetAllFilters(this IRecommendationsOperations operations) { operations.ResetAllFiltersAsync().GetAwaiter().GetResult(); } /// <summary> /// Reset all recommendation opt-out settings for a subscription. /// </summary> /// <remarks> /// Reset all recommendation opt-out settings for a subscription. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ResetAllFiltersAsync(this IRecommendationsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.ResetAllFiltersWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get past recommendations for an app, optionally specified by the time /// range. /// </summary> /// <remarks> /// Get past recommendations for an app, optionally specified by the time /// range. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='filter'> /// Filter is specified by using OData syntax. Example: $filter=channels eq /// 'Api' or channel eq 'Notification' and startTime eq '2014-01-01T00:00:00Z' /// and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq /// duration'[PT1H|PT1M|P1D] /// </param> public static IList<Recommendation> ListHistoryForWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string filter = default(string)) { return operations.ListHistoryForWebAppAsync(resourceGroupName, siteName, filter).GetAwaiter().GetResult(); } /// <summary> /// Get past recommendations for an app, optionally specified by the time /// range. /// </summary> /// <remarks> /// Get past recommendations for an app, optionally specified by the time /// range. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='filter'> /// Filter is specified by using OData syntax. Example: $filter=channels eq /// 'Api' or channel eq 'Notification' and startTime eq '2014-01-01T00:00:00Z' /// and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq /// duration'[PT1H|PT1M|P1D] /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> ListHistoryForWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListHistoryForWebAppWithHttpMessagesAsync(resourceGroupName, siteName, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get all recommendations for an app. /// </summary> /// <remarks> /// Get all recommendations for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='featured'> /// Specify &lt;code&gt;true&lt;/code&gt; to return only the most critical /// recommendations. The default is &lt;code&gt;false&lt;/code&gt;, which /// returns all recommendations. /// </param> /// <param name='filter'> /// Return only channels specified in the filter. Filter is specified by using /// OData syntax. Example: $filter=channels eq 'Api' or channel eq /// 'Notification' /// </param> public static IList<Recommendation> ListRecommendedRulesForWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName, bool? featured = default(bool?), string filter = default(string)) { return operations.ListRecommendedRulesForWebAppAsync(resourceGroupName, siteName, featured, filter).GetAwaiter().GetResult(); } /// <summary> /// Get all recommendations for an app. /// </summary> /// <remarks> /// Get all recommendations for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='featured'> /// Specify &lt;code&gt;true&lt;/code&gt; to return only the most critical /// recommendations. The default is &lt;code&gt;false&lt;/code&gt;, which /// returns all recommendations. /// </param> /// <param name='filter'> /// Return only channels specified in the filter. Filter is specified by using /// OData syntax. Example: $filter=channels eq 'Api' or channel eq /// 'Notification' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> ListRecommendedRulesForWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, bool? featured = default(bool?), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRecommendedRulesForWebAppWithHttpMessagesAsync(resourceGroupName, siteName, featured, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Disable all recommendations for an app. /// </summary> /// <remarks> /// Disable all recommendations for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> public static void DisableAllForWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName) { operations.DisableAllForWebAppAsync(resourceGroupName, siteName).GetAwaiter().GetResult(); } /// <summary> /// Disable all recommendations for an app. /// </summary> /// <remarks> /// Disable all recommendations for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DisableAllForWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DisableAllForWebAppWithHttpMessagesAsync(resourceGroupName, siteName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Reset all recommendation opt-out settings for an app. /// </summary> /// <remarks> /// Reset all recommendation opt-out settings for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> public static void ResetAllFiltersForWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName) { operations.ResetAllFiltersForWebAppAsync(resourceGroupName, siteName).GetAwaiter().GetResult(); } /// <summary> /// Reset all recommendation opt-out settings for an app. /// </summary> /// <remarks> /// Reset all recommendation opt-out settings for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ResetAllFiltersForWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.ResetAllFiltersForWebAppWithHttpMessagesAsync(resourceGroupName, siteName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get a recommendation rule for an app. /// </summary> /// <remarks> /// Get a recommendation rule for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='name'> /// Name of the recommendation. /// </param> /// <param name='updateSeen'> /// Specify &lt;code&gt;true&lt;/code&gt; to update the last-seen timestamp of /// the recommendation object. /// </param> public static RecommendationRule GetRuleDetailsByWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string name, bool? updateSeen = default(bool?)) { return operations.GetRuleDetailsByWebAppAsync(resourceGroupName, siteName, name, updateSeen).GetAwaiter().GetResult(); } /// <summary> /// Get a recommendation rule for an app. /// </summary> /// <remarks> /// Get a recommendation rule for an app. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='siteName'> /// Name of the app. /// </param> /// <param name='name'> /// Name of the recommendation. /// </param> /// <param name='updateSeen'> /// Specify &lt;code&gt;true&lt;/code&gt; to update the last-seen timestamp of /// the recommendation object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RecommendationRule> GetRuleDetailsByWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string name, bool? updateSeen = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRuleDetailsByWebAppWithHttpMessagesAsync(resourceGroupName, siteName, name, updateSeen, null, cancellationToken).ConfigureAwait(false)) { return _result.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. using System; /// <summary> /// Int16.IConverible.ToSbyte(IFormatProvider) /// </summary> public class Int16IConvertibleToSByte { #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; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random int16 to sbyte "); try { Int16 i1 = 200; while (i1 > 127) { i1 = (Int16)TestLibrary.Generator.GetByte(-55); } IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != i1) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,tht int16 is:" + i1); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Convert zero to sbyte "); try { Int16 i1 = 0; IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != i1) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Convert a negative int16 to sbyte "); try { Int16 i1 = 200; while (i1 > 127) { i1 = (Int16)TestLibrary.Generator.GetByte(-55); } IConvertible Icon1 = (IConvertible)(-i1); if (Icon1.ToSByte(null) != (-i1)) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,the int16 is:" + i1); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Check the boundary value of sbyte.MinValue"); try { Int16 i1 = (Int16)sbyte.MinValue; IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != (i1)) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Check the boundary value of sbyte.MaxValue"); try { Int16 i1 = (Int16)sbyte.MaxValue; IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != (i1)) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Test the overflowException"); try { Int16 i1 = 0; while (i1 <= 127) { i1 = TestLibrary.Generator.GetInt16(-55); } IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != i1) { } TestLibrary.TestFramework.LogError("101", "An overflowException was not thrown as expected "); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { Int16IConvertibleToSByte test = new Int16IConvertibleToSByte(); TestLibrary.TestFramework.BeginTestCase("Int16IConvertibleToSByte"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using System; using System.Text; using TestLibrary; public class Shift_JisTest { public static int Main(string[] args) { Shift_JisTest test = new Shift_JisTest(); TestLibrary.TestFramework.BeginTestCase("Testing Shift_Jis encoding support in CoreCLR"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.Logging.WriteLine("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.Logging.WriteLine("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.Logging.WriteLine("[Positive]"); // We now support only Unicode and UTF8 encodings //retVal = PosTest1() && retVal; //retVal = PosTest2() && retVal; //retVal = PosTest3() && retVal; //retVal = PosTest4() && retVal; retVal = NegTest1() && retVal; return retVal; } public bool NegTest1() { bool ret = true; TestLibrary.TestFramework.BeginScenario("Creating the shift_jis encoding"); try { Encoding enc = Encoding.GetEncoding("shift_jis"); ret = false; TestFramework.LogError("00F", "Encoding created unexpectedly. Expected argument exception. Actual: Create encoding with name: " + enc.WebName); } catch (NotSupportedException) { // Expected } catch (ArgumentException) { // Expected } catch (Exception exc) { ret = false; TestFramework.LogError("010", "Unexpected error: " + exc.ToString()); } return ret; } public bool PosTest1() { bool ret = true; TestLibrary.TestFramework.BeginScenario("Creating the shift_jis encoding"); try { Encoding enc2 = Encoding.GetEncoding("shift_jis"); if (enc2.WebName != "shift_jis") { ret = false; TestFramework.LogError("002", "Error creating encoding. Web name not as expected. Expected: shift_jis Actual: " + enc2.WebName); } Encoding enc3 = Encoding.GetEncoding("sHiFT_JIs"); if (enc3.WebName != "shift_jis") { ret = false; TestFramework.LogError("003", "Error creating encoding. Web name not as expected. Expected: shift_jis Actual: " + enc3.WebName); } } catch (Exception exc) { ret = false; TestFramework.LogError("004", "Unexpected error: " + exc.ToString()); } return ret; } public bool PosTest2() { bool ret = true; TestLibrary.TestFramework.BeginScenario("Encoding strings with the shift_jis encoding"); try { Encoding enc = Encoding.GetEncoding("shift_jis"); string str = "ABc"; byte[] bytes = enc.GetBytes(str); byte[] expected = new byte[] { 0x41, 0x42, 0x63 }; if (!Utilities.CompareBytes(bytes, expected)) { ret = false; TestFramework.LogError("005", "Encoding str -> bytes not as expected. Str: " + str + " Expected bytes: " + Utilities.ByteArrayToString(expected) + " Actual bytes: " + Utilities.ByteArrayToString(bytes)); } str = ""; bytes = enc.GetBytes(str); expected = new byte[0]; if (!Utilities.CompareBytes(bytes, expected)) { ret = false; TestFramework.LogError("006", "Encoding str -> bytes not as expected. Str: " + str + " Expected bytes: " + Utilities.ByteArrayToString(expected) + " Actual bytes: " + Utilities.ByteArrayToString(bytes)); } str = "A\xff70\x3000\x00b6\x25ef\x044f\x9adc\x9ed1"; bytes = enc.GetBytes(str); expected = new byte[] { 0x41, 0xb0, 0x81, 0x40, 0x81, 0xf7, 0x81, 0xfc, 0x84, 0x91, 0xfc, 0x40, 0xfc, 0x4b }; if (!Utilities.CompareBytes(bytes, expected)) { ret = false; TestFramework.LogError("007", "Encoding str -> bytes not as expected. Str: " + str + " Expected bytes: " + Utilities.ByteArrayToString(expected) + " Actual bytes: " + Utilities.ByteArrayToString(bytes)); } } catch (Exception exc) { ret = false; TestFramework.LogError("008", "Unexpected error: " + exc.ToString()); } return ret; } public bool PosTest3() { bool ret = true; TestLibrary.TestFramework.BeginScenario("Encoding char[]s with the shift_jis encoding"); try { Encoding enc = Encoding.GetEncoding("shift_jis"); char[] str = new char[] { 'A', 'B', 'c' }; byte[] bytes = enc.GetBytes(str); byte[] expected = new byte[] { 0x41, 0x42, 0x63 }; if (!Utilities.CompareBytes(bytes, expected)) { ret = false; TestFramework.LogError("009", "Encoding char[] -> bytes not as expected. Str: " + new string(str) + " Expected bytes: " + Utilities.ByteArrayToString(expected) + " Actual bytes: " + Utilities.ByteArrayToString(bytes)); } str = new char[0]; bytes = enc.GetBytes(str); expected = new byte[0]; if (!Utilities.CompareBytes(bytes, expected)) { ret = false; TestFramework.LogError("00A", "Encoding char[] -> bytes not as expected. Str: " + new string(str) + " Expected bytes: " + Utilities.ByteArrayToString(expected) + " Actual bytes: " + Utilities.ByteArrayToString(bytes)); } str = new char[] { 'A', '\xff70', '\x3000', '\x00b6', '\x25ef', '\x044f', '\x9adc', '\x9ed1' }; bytes = enc.GetBytes(str); expected = new byte[] { 0x41, 0xb0, 0x81, 0x40, 0x81, 0xf7, 0x81, 0xfc, 0x84, 0x91, 0xfc, 0x40, 0xfc, 0x4b }; if (!Utilities.CompareBytes(bytes, expected)) { ret = false; TestFramework.LogError("00B", "Encoding char[] -> bytes not as expected. Str: " + new string(str) + " Expected bytes: " + Utilities.ByteArrayToString(expected) + " Actual bytes: " + Utilities.ByteArrayToString(bytes)); } } catch (Exception exc) { ret = false; TestFramework.LogError("00C", "Unexpected error: " + exc.ToString()); } return ret; } public bool PosTest4() { bool ret = true; TestLibrary.TestFramework.BeginScenario("Decoding byte[]s with the shift_jis encoding"); try { Encoding enc = Encoding.GetEncoding("shift_jis"); byte[] bytes = { 0x87, 0x90 }; char[] expected = new char[] {'\x2252'}; char[] actual = enc.GetChars(bytes); if (!Utilities.CompareChars(actual, expected)) { ret = false; TestFramework.LogError("00D", "Decoding byte[] -> char[] not as expected! Expected: 0x8786 Actual "); foreach (char c in actual) Logging.Write("0x" + ((int)c).ToString("x") + " "); } } catch (Exception exc) { ret = false; TestFramework.LogError("00E", "Unexpected error: " + exc.ToString()); } return ret; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using Franson.BlueTools; namespace SimpleService { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button bAdvertise; private System.Windows.Forms.Button bDeadvertise; private System.Windows.Forms.TextBox txtWriteData; private System.Windows.Forms.Button bWrite; private System.Windows.Forms.TextBox txtRead; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label lServiceStatus; private System.Windows.Forms.Label lStackID; private System.Windows.Forms.ListBox listSessions; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox txtRead2; private System.Windows.Forms.Button bWrite2; private System.Windows.Forms.Button bAdvertise2; private System.Windows.Forms.TextBox txtWriteData2; private System.Windows.Forms.ListBox listSessions2; private System.Windows.Forms.Label lServiceStatus2; private System.Windows.Forms.Button bDeadvertise2; private System.Windows.Forms.TextBox txtSCN; private System.Windows.Forms.TextBox txtSCN2; private System.Windows.Forms.CheckBox cbSerialPort2; private System.Windows.Forms.CheckBox cbSerialPort; private System.Windows.Forms.Button bCloseSession2; private System.Windows.Forms.Button bCloseSession1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.bAdvertise = new System.Windows.Forms.Button(); this.bDeadvertise = new System.Windows.Forms.Button(); this.txtWriteData = new System.Windows.Forms.TextBox(); this.bWrite = new System.Windows.Forms.Button(); this.txtRead = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.lServiceStatus = new System.Windows.Forms.Label(); this.lStackID = new System.Windows.Forms.Label(); this.listSessions = new System.Windows.Forms.ListBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.txtRead2 = new System.Windows.Forms.TextBox(); this.bWrite2 = new System.Windows.Forms.Button(); this.bAdvertise2 = new System.Windows.Forms.Button(); this.txtWriteData2 = new System.Windows.Forms.TextBox(); this.bDeadvertise2 = new System.Windows.Forms.Button(); this.lServiceStatus2 = new System.Windows.Forms.Label(); this.listSessions2 = new System.Windows.Forms.ListBox(); this.label8 = new System.Windows.Forms.Label(); this.txtSCN = new System.Windows.Forms.TextBox(); this.txtSCN2 = new System.Windows.Forms.TextBox(); this.cbSerialPort = new System.Windows.Forms.CheckBox(); this.cbSerialPort2 = new System.Windows.Forms.CheckBox(); this.bCloseSession2 = new System.Windows.Forms.Button(); this.bCloseSession1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // bAdvertise // this.bAdvertise.Location = new System.Drawing.Point(24, 24); this.bAdvertise.Name = "bAdvertise"; this.bAdvertise.Size = new System.Drawing.Size(96, 24); this.bAdvertise.TabIndex = 0; this.bAdvertise.Text = "Advertise"; this.bAdvertise.Click += new System.EventHandler(this.bAdvertise_Click); // // bDeadvertise // this.bDeadvertise.Location = new System.Drawing.Point(24, 56); this.bDeadvertise.Name = "bDeadvertise"; this.bDeadvertise.Size = new System.Drawing.Size(96, 24); this.bDeadvertise.TabIndex = 1; this.bDeadvertise.Text = "Deadvertise"; this.bDeadvertise.Click += new System.EventHandler(this.bDeadvertise_Click); // // txtWriteData // this.txtWriteData.Location = new System.Drawing.Point(32, 136); this.txtWriteData.Name = "txtWriteData"; this.txtWriteData.Size = new System.Drawing.Size(216, 20); this.txtWriteData.TabIndex = 2; this.txtWriteData.Text = "some data"; // // bWrite // this.bWrite.Location = new System.Drawing.Point(256, 136); this.bWrite.Name = "bWrite"; this.bWrite.Size = new System.Drawing.Size(56, 24); this.bWrite.TabIndex = 3; this.bWrite.Text = "Write"; this.bWrite.Click += new System.EventHandler(this.bWrite_Click); // // txtRead // this.txtRead.Location = new System.Drawing.Point(32, 184); this.txtRead.Name = "txtRead"; this.txtRead.Size = new System.Drawing.Size(216, 20); this.txtRead.TabIndex = 4; this.txtRead.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(32, 168); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(152, 16); this.label1.TabIndex = 5; this.label1.Text = "Data from client"; // // label2 // this.label2.Location = new System.Drawing.Point(32, 120); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(136, 16); this.label2.TabIndex = 6; this.label2.Text = "Data to client"; // // lServiceStatus // this.lServiceStatus.Location = new System.Drawing.Point(136, 24); this.lServiceStatus.Name = "lServiceStatus"; this.lServiceStatus.Size = new System.Drawing.Size(344, 16); this.lServiceStatus.TabIndex = 7; this.lServiceStatus.Text = "Service not active"; // // lStackID // this.lStackID.Location = new System.Drawing.Point(32, 488); this.lStackID.Name = "lStackID"; this.lStackID.Size = new System.Drawing.Size(232, 16); this.lStackID.TabIndex = 8; // // listSessions // this.listSessions.Location = new System.Drawing.Point(320, 136); this.listSessions.Name = "listSessions"; this.listSessions.Size = new System.Drawing.Size(152, 82); this.listSessions.TabIndex = 9; this.listSessions.SelectedIndexChanged += new System.EventHandler(this.listSessions_SelectedIndexChanged); // // label3 // this.label3.Location = new System.Drawing.Point(320, 112); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(88, 16); this.label3.TabIndex = 10; this.label3.Text = "Sessions:"; // // label4 // this.label4.Location = new System.Drawing.Point(32, 368); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(136, 16); this.label4.TabIndex = 6; this.label4.Text = "Data to client"; // // label5 // this.label5.Location = new System.Drawing.Point(32, 416); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(152, 16); this.label5.TabIndex = 5; this.label5.Text = "Data from client"; // // txtRead2 // this.txtRead2.Location = new System.Drawing.Point(32, 432); this.txtRead2.Name = "txtRead2"; this.txtRead2.Size = new System.Drawing.Size(216, 20); this.txtRead2.TabIndex = 4; this.txtRead2.Text = ""; // // bWrite2 // this.bWrite2.Location = new System.Drawing.Point(256, 384); this.bWrite2.Name = "bWrite2"; this.bWrite2.Size = new System.Drawing.Size(56, 24); this.bWrite2.TabIndex = 3; this.bWrite2.Text = "Write"; this.bWrite2.Click += new System.EventHandler(this.bWrite2_Click); // // bAdvertise2 // this.bAdvertise2.Location = new System.Drawing.Point(24, 272); this.bAdvertise2.Name = "bAdvertise2"; this.bAdvertise2.Size = new System.Drawing.Size(96, 24); this.bAdvertise2.TabIndex = 0; this.bAdvertise2.Text = "Advertise"; this.bAdvertise2.Click += new System.EventHandler(this.bAdvertise2_Click); // // txtWriteData2 // this.txtWriteData2.Location = new System.Drawing.Point(32, 384); this.txtWriteData2.Name = "txtWriteData2"; this.txtWriteData2.Size = new System.Drawing.Size(216, 20); this.txtWriteData2.TabIndex = 2; this.txtWriteData2.Text = "some data2"; // // bDeadvertise2 // this.bDeadvertise2.Location = new System.Drawing.Point(24, 304); this.bDeadvertise2.Name = "bDeadvertise2"; this.bDeadvertise2.Size = new System.Drawing.Size(96, 24); this.bDeadvertise2.TabIndex = 1; this.bDeadvertise2.Text = "Deadvertise"; this.bDeadvertise2.Click += new System.EventHandler(this.bDeadvertise2_Click); // // lServiceStatus2 // this.lServiceStatus2.Location = new System.Drawing.Point(136, 272); this.lServiceStatus2.Name = "lServiceStatus2"; this.lServiceStatus2.Size = new System.Drawing.Size(352, 16); this.lServiceStatus2.TabIndex = 7; this.lServiceStatus2.Text = "Service not active"; // // listSessions2 // this.listSessions2.Location = new System.Drawing.Point(320, 384); this.listSessions2.Name = "listSessions2"; this.listSessions2.Size = new System.Drawing.Size(152, 82); this.listSessions2.TabIndex = 9; // // label8 // this.label8.Location = new System.Drawing.Point(320, 360); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(88, 16); this.label8.TabIndex = 10; this.label8.Text = "Sessions:"; // // txtSCN // this.txtSCN.Location = new System.Drawing.Point(240, 56); this.txtSCN.Name = "txtSCN"; this.txtSCN.Size = new System.Drawing.Size(40, 20); this.txtSCN.TabIndex = 11; this.txtSCN.Text = "0"; // // txtSCN2 // this.txtSCN2.Location = new System.Drawing.Point(240, 304); this.txtSCN2.Name = "txtSCN2"; this.txtSCN2.Size = new System.Drawing.Size(40, 20); this.txtSCN2.TabIndex = 12; this.txtSCN2.Text = "0"; // // cbSerialPort // this.cbSerialPort.Location = new System.Drawing.Point(144, 56); this.cbSerialPort.Name = "cbSerialPort"; this.cbSerialPort.Size = new System.Drawing.Size(80, 16); this.cbSerialPort.TabIndex = 13; this.cbSerialPort.Text = "Serial Port"; // // cbSerialPort2 // this.cbSerialPort2.Location = new System.Drawing.Point(144, 304); this.cbSerialPort2.Name = "cbSerialPort2"; this.cbSerialPort2.Size = new System.Drawing.Size(80, 16); this.cbSerialPort2.TabIndex = 13; this.cbSerialPort2.Text = "Serial Port"; // // bCloseSession2 // this.bCloseSession2.Location = new System.Drawing.Point(320, 472); this.bCloseSession2.Name = "bCloseSession2"; this.bCloseSession2.Size = new System.Drawing.Size(64, 24); this.bCloseSession2.TabIndex = 14; this.bCloseSession2.Text = "Close"; this.bCloseSession2.Click += new System.EventHandler(this.bCloseSession2_Click); // // bCloseSession1 // this.bCloseSession1.Location = new System.Drawing.Point(320, 224); this.bCloseSession1.Name = "bCloseSession1"; this.bCloseSession1.Size = new System.Drawing.Size(64, 24); this.bCloseSession1.TabIndex = 15; this.bCloseSession1.Text = "Close"; this.bCloseSession1.Click += new System.EventHandler(this.bCloseSession1_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(504, 525); this.Controls.Add(this.bCloseSession1); this.Controls.Add(this.bCloseSession2); this.Controls.Add(this.cbSerialPort); this.Controls.Add(this.txtSCN2); this.Controls.Add(this.txtSCN); this.Controls.Add(this.label3); this.Controls.Add(this.listSessions); this.Controls.Add(this.lStackID); this.Controls.Add(this.lServiceStatus); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtRead); this.Controls.Add(this.bWrite); this.Controls.Add(this.txtWriteData); this.Controls.Add(this.bDeadvertise); this.Controls.Add(this.bAdvertise); this.Controls.Add(this.label4); this.Controls.Add(this.label5); this.Controls.Add(this.txtRead2); this.Controls.Add(this.bWrite2); this.Controls.Add(this.bAdvertise2); this.Controls.Add(this.txtWriteData2); this.Controls.Add(this.bDeadvertise2); this.Controls.Add(this.lServiceStatus2); this.Controls.Add(this.listSessions2); this.Controls.Add(this.label8); this.Controls.Add(this.cbSerialPort2); this.Name = "Form1"; this.Text = "SimpleService C#"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } Manager m_manager = null; Network m_network = null; LocalService m_service = null; LocalService m_service2 = null; private void Form1_Load(object sender, System.EventArgs e) { // You can get a valid evaluation key for BlueTools at // http://franson.com/bluetools/ // That key will be valid for 14 days. Just cut and paste that key into the statement below. // To get a key that do not expire you need to purchase a license Franson.BlueTools.License license = new Franson.BlueTools.License(); license.LicenseKey = "WoK6IL758ACCJORQUXVZQjpRERguNYEYWrTB"; try { m_manager = Manager.GetManager(); switch(Manager.StackID) { case StackID.STACK_MICROSOFT: lStackID.Text = "Microsoft stack"; break; case StackID.STACK_WIDCOMM: lStackID.Text = "WidComm stack"; break; } // Call events in GUI thread m_manager.Parent = this; // Call events in new thread (multi-threading) // manager.Parent = null // Get first netowrk (BlueTools 1.0 only supports one network == one dongle) m_network = m_manager.Networks[0]; // Clean up when form closes this.Closing += new System.ComponentModel.CancelEventHandler(Form1_Closing); // Buttons bAdvertise.Enabled = true; bDeadvertise.Enabled = false; bAdvertise2.Enabled = true; bDeadvertise2.Enabled = false; } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void m_service_ClientConnected(object sender, BlueToolsEventArgs eventArgs) { ConnectionEventArgs connectionEvent = (ConnectionEventArgs) eventArgs; Session connectedSession = connectionEvent.Session; if(connectedSession.LocalService.Equals(m_service)) { // Add new session to list listSessions.Items.Add(connectedSession); lServiceStatus.Text = "Client connected"; } else if(connectedSession.LocalService.Equals(m_service2)) { // Add new session to list listSessions2.Items.Add(connectedSession); lServiceStatus2.Text = "Client connected"; } else { lServiceStatus2.Text = "ERROR!"; } // Read data from stream System.IO.Stream connectedStream = connectedSession.Stream; byte[] buffer = new byte[20]; connectedStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), connectedStream); } private void m_service_ClientDisconnected(object sender, BlueToolsEventArgs eventArgs) { ConnectionEventArgs connectionEvent = (ConnectionEventArgs) eventArgs; Session connectedSession = connectionEvent.Session; if(connectedSession.LocalService.Equals(m_service)) { // Remove session from list listSessions.Items.Remove(connectedSession); lServiceStatus.Text = "Client disconnected"; } else if(connectedSession.LocalService.Equals(m_service2)) { listSessions2.Items.Remove(connectedSession); lServiceStatus2.Text = "Client disconnected"; } else { lServiceStatus2.Text = "Client disconnected ERROR"; } } private void bAdvertise_Click(object sender, System.EventArgs e) { try { // One more local service if(cbSerialPort.Checked == true) { m_service = new LocalService(ServiceType.SerialPort, "SerialPort", ""); } else { m_service = new LocalService(ServiceType.RFCOMM, "RFCOMM", ""); } // Called when client connected to service m_service.ClientConnected += new BlueToolsEventHandler(m_service_ClientConnected); // Called when client disconnected from service m_service.ClientDisconnected += new BlueToolsEventHandler(m_service_ClientDisconnected); // Called when service successfully is advertised to server m_service.Advertised += new BlueToolsEventHandler(m_service_Advertised); // Called when all connection to service closed, and service removed from server m_service.Deadvertised += new BlueToolsEventHandler(m_service_Deadvertised); m_network.Server.Advertise(m_service, int.Parse(txtSCN.Text)); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void bDeadvertise_Click(object sender, System.EventArgs e) { try { m_network.Server.Deadvertise(m_service); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void m_service_Advertised(object sender, BlueToolsEventArgs eventArgs) { if(m_service == (LocalService) sender) { lServiceStatus.Text = "Service advertised SCN: " + m_service.Address.ServiceChannelNumber; // Buttons bAdvertise.Enabled = false; bDeadvertise.Enabled = true; } else if(m_service2 == (LocalService) sender) { lServiceStatus2.Text = "Service advertised SCN: " + m_service2.Address.ServiceChannelNumber; // Buttons bAdvertise2.Enabled = false; bDeadvertise2.Enabled = true; } } private void m_service_Deadvertised(object sender, BlueToolsEventArgs eventArgs) { if(m_service.Equals((LocalService) sender)) { lServiceStatus.Text = "Service not active"; // Buttons bAdvertise.Enabled = true; bDeadvertise.Enabled = false; } else if(m_service2.Equals((LocalService) sender)) { lServiceStatus2.Text = "Service not active"; // Buttons bAdvertise2.Enabled = true; bDeadvertise2.Enabled = false; } } private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // Dispose must be called for the application to exit! Manager.GetManager().Dispose(); } private void bWrite_Click(object sender, System.EventArgs e) { writeToSession( (Session) listSessions.SelectedItem ); } private void writeToSession(Session selectedSession) { if(selectedSession != null) { System.IO.Stream selectedStream = selectedSession.Stream; char[] charWrite = txtWriteData.Text.ToCharArray(); byte[] byteWrite = new byte[charWrite.Length]; for(int inx = 0; inx < charWrite.Length; inx++) { byteWrite[inx] = (byte) charWrite[inx]; } selectedStream.BeginWrite(byteWrite, 0, byteWrite.Length, new AsyncCallback(writeCallback), selectedStream); } else { MessageBox.Show("Select a session first"); } } private void writeCallback(IAsyncResult result) { System.IO.Stream selectedStream = (System.IO.Stream) result.AsyncState; // EndWrite() must always be called if BegineWrite() was used! selectedStream.EndWrite(result); } private void readCallback(IAsyncResult result) { // Receives data from all connected devices! // IAsyncResult argument is of type BlueToolsAsyncResult BlueToolsAsyncResult blueResults = (BlueToolsAsyncResult) result; System.IO.Stream currentStream = (System.IO.Stream) blueResults.AsyncState; byte[] buffer = blueResults.Buffer; // EndRead() must always be called! int len = currentStream.EndRead(result); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); string str = enc.GetString(buffer, 0, len); txtRead.Text = str; // Start new async read currentStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), currentStream); } private void bAdvertise2_Click(object sender, System.EventArgs e) { // One more local service if(cbSerialPort2.Checked == true) { m_service2 = new LocalService(ServiceType.SerialPort, "SerialPort2", ""); } else { m_service2 = new LocalService(ServiceType.RFCOMM, "RFCOMM2", ""); } m_service2.ClientConnected += new BlueToolsEventHandler(m_service_ClientConnected); m_service2.ClientDisconnected += new BlueToolsEventHandler(m_service_ClientDisconnected); m_service2.Advertised += new BlueToolsEventHandler(m_service_Advertised); m_service2.Deadvertised += new BlueToolsEventHandler(m_service_Deadvertised); try { m_network.Server.Advertise(m_service2, int.Parse(txtSCN2.Text)); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void bDeadvertise2_Click(object sender, System.EventArgs e) { try { m_network.Server.Deadvertise(m_service2); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void bWrite2_Click(object sender, System.EventArgs e) { writeToSession( (Session) listSessions2.SelectedItem ); } private void bCloseSession1_Click(object sender, System.EventArgs e) { closeSession( (Session) listSessions.SelectedItem ); } private void closeSession(Session selectedSession) { if(selectedSession != null) { selectedSession.Close(); } else { MessageBox.Show("Select a session first!"); } } private void listSessions_SelectedIndexChanged(object sender, System.EventArgs e) { } private void bCloseSession2_Click(object sender, System.EventArgs e) { closeSession( (Session) listSessions2.SelectedItem ); } } }
// // In order to convert some functionality to Visual C#, the Java Language Conversion Assistant // creates "support classes" that duplicate the original functionality. // // Support classes replicate the functionality of the original code, but in some cases they are // substantially different architecturally. Although every effort is made to preserve the // original architecture of the application in the converted project, the user should be aware that // the primary goal of these support classes is to replicate functionality, and that at times // the architecture of the resulting solution may differ somewhat. // using System; namespace Comzept.Genesis.Tidy { /// <summary> /// Contains conversion support elements such as classes, interfaces and static methods. /// </summary> public class SupportClass { /// <summary> /// The class performs token processing in strings. /// </summary> public class Tokenizer : System.Collections.IEnumerator { /// Position over the string private long currentPos = 0; /// Include demiliters in the results. private bool includeDelims = false; /// Char representation of the String to tokenize. private char[] chars = null; //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character and the form-feed character private string delimiters = " \t\n\r\f"; /// <summary> /// Initializes a new class instance with a specified string to process /// </summary> /// <param name="source">String to tokenize</param> public Tokenizer(System.String source) { this.chars = source.ToCharArray(); } /// <summary> /// Initializes a new class instance with a specified string to process /// and the specified token delimiters to use /// </summary> /// <param name="source">String to tokenize</param> /// <param name="delimiters">String containing the delimiters</param> public Tokenizer(System.String source, System.String delimiters) : this(source) { this.delimiters = delimiters; } /// <summary> /// Initializes a new class instance with a specified string to process, the specified token /// delimiters to use, and whether the delimiters must be included in the results. /// </summary> /// <param name="source">String to tokenize</param> /// <param name="delimiters">String containing the delimiters</param> /// <param name="includeDelims">Determines if delimiters are included in the results.</param> public Tokenizer(System.String source, System.String delimiters, bool includeDelims) : this(source, delimiters) { this.includeDelims = includeDelims; } /// <summary> /// Returns the next token from the token list /// </summary> /// <returns>The string value of the token</returns> public System.String NextToken() { return NextToken(this.delimiters); } /// <summary> /// Returns the next token from the source string, using the provided /// token delimiters /// </summary> /// <param name="delimiters">String containing the delimiters to use</param> /// <returns>The string value of the token</returns> public System.String NextToken(System.String delimiters) { //According to documentation, the usage of the received delimiters should be temporary (only for this call). //However, it seems it is not true, so the following line is necessary. this.delimiters = delimiters; //at the end if (this.currentPos == this.chars.Length) throw new System.ArgumentOutOfRangeException(); //if over a delimiter and delimiters must be returned else if ((System.Array.IndexOf(delimiters.ToCharArray(), chars[this.currentPos]) != -1) && this.includeDelims) return "" + this.chars[this.currentPos++]; //need to get the token wo delimiters. else return nextToken(delimiters.ToCharArray()); } //Returns the nextToken wo delimiters private System.String nextToken(char[] delimiters) { string token = ""; long pos = this.currentPos; //skip possible delimiters while (System.Array.IndexOf(delimiters, this.chars[currentPos]) != -1) //The last one is a delimiter (i.e there is no more tokens) if (++this.currentPos == this.chars.Length) { this.currentPos = pos; throw new System.ArgumentOutOfRangeException(); } //getting the token while (System.Array.IndexOf(delimiters, this.chars[this.currentPos]) == -1) { token += this.chars[this.currentPos]; //the last one is not a delimiter if (++this.currentPos == this.chars.Length) break; } return token; } /// <summary> /// Determines if there are more tokens to return from the source string /// </summary> /// <returns>True or false, depending if there are more tokens</returns> public bool HasMoreTokens() { //keeping the current pos long pos = this.currentPos; try { this.NextToken(); } catch (System.ArgumentOutOfRangeException) { return false; } finally { this.currentPos = pos; } return true; } /// <summary> /// Remaining tokens count /// </summary> public int Count { get { //keeping the current pos long pos = this.currentPos; int i = 0; try { while (true) { this.NextToken(); i++; } } catch (System.ArgumentOutOfRangeException) { this.currentPos = pos; return i; } } } /// <summary> /// Performs the same action as NextToken. /// </summary> public System.Object Current { get { return (Object)this.NextToken(); } } /// <summary> // Performs the same action as HasMoreTokens. /// </summary> /// <returns>True or false, depending if there are more tokens</returns> public bool MoveNext() { return this.HasMoreTokens(); } /// <summary> /// Does nothing. /// </summary> public void Reset() { ; } } /*******************************/ /// <summary> /// Receives a byte array and returns it transformed in an sbyte array /// </summary> /// <param name="byteArray">Byte array to process</param> /// <returns>The transformed array</returns> public static sbyte[] ToSByteArray(byte[] byteArray) { sbyte[] sbyteArray = null; if (byteArray != null) { sbyteArray = new sbyte[byteArray.Length]; for (int index = 0; index < byteArray.Length; index++) sbyteArray[index] = (sbyte)byteArray[index]; } return sbyteArray; } /*******************************/ /// <summary> /// Converts an array of sbytes to an array of bytes /// </summary> /// <param name="sbyteArray">The array of sbytes to be converted</param> /// <returns>The new array of bytes</returns> public static byte[] ToByteArray(sbyte[] sbyteArray) { byte[] byteArray = null; if (sbyteArray != null) { byteArray = new byte[sbyteArray.Length]; for (int index = 0; index < sbyteArray.Length; index++) byteArray[index] = (byte)sbyteArray[index]; } return byteArray; } /// <summary> /// Converts a string to an array of bytes /// </summary> /// <param name="sourceString">The string to be converted</param> /// <returns>The new array of bytes</returns> public static byte[] ToByteArray(System.String sourceString) { return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); } /// <summary> /// Converts a array of object-type instances to a byte-type array. /// </summary> /// <param name="tempObjectArray">Array to convert.</param> /// <returns>An array of byte type elements.</returns> public static byte[] ToByteArray(System.Object[] tempObjectArray) { byte[] byteArray = null; if (tempObjectArray != null) { byteArray = new byte[tempObjectArray.Length]; for (int index = 0; index < tempObjectArray.Length; index++) byteArray[index] = (byte)tempObjectArray[index]; } return byteArray; } /*******************************/ /// <summary> /// SupportClass for the Stack class. /// </summary> public class StackSupport { /// <summary> /// Removes the element at the top of the stack and returns it. /// </summary> /// <param name="stack">The stack where the element at the top will be returned and removed.</param> /// <returns>The element at the top of the stack.</returns> public static System.Object Pop(System.Collections.ArrayList stack) { System.Object obj = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); return obj; } } /*******************************/ /// <summary> /// Converts an array of sbytes to an array of chars /// </summary> /// <param name="sByteArray">The array of sbytes to convert</param> /// <returns>The new array of chars</returns> public static char[] ToCharArray(sbyte[] sByteArray) { return System.Text.UTF8Encoding.UTF8.GetChars(ToByteArray(sByteArray)); } /// <summary> /// Converts an array of bytes to an array of chars /// </summary> /// <param name="byteArray">The array of bytes to convert</param> /// <returns>The new array of chars</returns> public static char[] ToCharArray(byte[] byteArray) { return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); } } }
using Signum.Engine.Authorization; using Signum.Engine.Translation; using Signum.Engine.UserAssets; using Signum.Engine.ViewLog; using Signum.Entities.Authorization; using Signum.Entities.Basics; using Signum.Entities.Chart; using Signum.Entities.UserAssets; using Signum.Entities.UserQueries; namespace Signum.Engine.Chart; public static class UserChartLogic { public static ResetLazy<Dictionary<Lite<UserChartEntity>, UserChartEntity>> UserCharts = null!; public static ResetLazy<Dictionary<Type, List<Lite<UserChartEntity>>>> UserChartsByTypeForQuickLinks = null!; public static ResetLazy<Dictionary<object, List<Lite<UserChartEntity>>>> UserChartsByQuery = null!; public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { UserAssetsImporter.Register<UserChartEntity>("UserChart", UserChartOperation.Save); sb.Schema.Synchronizing += Schema_Synchronizing; sb.Include<UserChartEntity>() .WithSave(UserChartOperation.Save) .WithDelete(UserChartOperation.Delete) .WithQuery(() => uq => new { Entity = uq, uq.Id, uq.Query, uq.EntityType, uq.DisplayName, uq.ChartScript, uq.Owner, }); sb.Schema.EntityEvents<UserChartEntity>().Retrieved += ChartLogic_Retrieved; sb.Schema.Table<QueryEntity>().PreDeleteSqlSync += e => Administrator.UnsafeDeletePreCommand(Database.Query<UserChartEntity>().Where(a => a.Query.Is(e))); UserCharts = sb.GlobalLazy(() => Database.Query<UserChartEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(UserChartEntity))); UserChartsByQuery = sb.GlobalLazy(() => UserCharts.Value.Values.Where(a => a.EntityType == null).SelectCatch(uc => KeyValuePair.Create(uc.Query.ToQueryName(), uc.ToLite())).GroupToDictionary(), new InvalidateWith(typeof(UserChartEntity))); UserChartsByTypeForQuickLinks = sb.GlobalLazy(() => UserCharts.Value.Values.Where(a => a.EntityType != null && !a.HideQuickLink) .SelectCatch(a => KeyValuePair.Create(TypeLogic.IdToType.GetOrThrow(a.EntityType!.Id), a.ToLite())) .GroupToDictionary(), new InvalidateWith(typeof(UserChartEntity))); } } public static UserChartEntity ParseData(this UserChartEntity userChart) { if (!userChart.IsNew || userChart.queryName == null) throw new InvalidOperationException("userChart should be new and have queryName"); userChart.Query = QueryLogic.GetQueryEntity(userChart.queryName); QueryDescription description = QueryLogic.Queries.QueryDescription(userChart.queryName); userChart.ParseData(description); return userChart; } static void ChartLogic_Retrieved(UserChartEntity userChart, PostRetrievingContext ctx) { object? queryName = userChart.Query.ToQueryNameCatch(); if (queryName == null) return; QueryDescription description = QueryLogic.Queries.QueryDescription(queryName); foreach (var item in userChart.Columns) { item.parentChart = userChart; } userChart.ParseData(description); } public static List<Lite<UserChartEntity>> GetUserCharts(object queryName) { var isAllowed = Schema.Current.GetInMemoryFilter<UserChartEntity>(userInterface: false); return UserChartsByQuery.Value.TryGetC(queryName).EmptyIfNull() .Select(lite => UserCharts.Value.GetOrThrow(lite)) .Where(uc => isAllowed(uc)) .Select(uc => uc.ToLite(TranslatedInstanceLogic.TranslatedField(uc, d => d.DisplayName))) .ToList(); } public static List<Lite<UserChartEntity>> GetUserChartsEntity(Type entityType) { var isAllowed = Schema.Current.GetInMemoryFilter<UserChartEntity>(userInterface: false); return UserChartsByTypeForQuickLinks.Value.TryGetC(entityType).EmptyIfNull() .Select(lite => UserCharts.Value.GetOrThrow(lite)) .Where(uc => isAllowed(uc)) .Select(uc => uc.ToLite(TranslatedInstanceLogic.TranslatedField(uc, d => d.DisplayName))) .ToList(); } public static List<Lite<UserChartEntity>> Autocomplete(string subString, int limit) { var isAllowed = Schema.Current.GetInMemoryFilter<UserChartEntity>(userInterface: false); return UserCharts.Value.Values.Where(uc => uc.EntityType == null && isAllowed(uc)) .Select(d => d.ToLite(TranslatedInstanceLogic.TranslatedField(d, d => d.DisplayName))) .Autocomplete(subString, limit) .ToList(); } public static UserChartEntity RetrieveUserChart(this Lite<UserChartEntity> userChart) { using (ViewLogLogic.LogView(userChart, "UserChart")) { var result = UserCharts.Value.GetOrThrow(userChart); var isAllowed = Schema.Current.GetInMemoryFilter<UserChartEntity>(userInterface: false); if (!isAllowed(result)) throw new EntityNotFoundException(userChart.EntityType, userChart.Id); return result; } } internal static ChartRequestModel ToChartRequest(this UserChartEntity userChart) { var cr = new ChartRequestModel(userChart.Query.ToQueryName()) { ChartScript = userChart.ChartScript, Filters = userChart.Filters.ToFilterList(), Parameters = userChart.Parameters.ToMList(), MaxRows = userChart.MaxRows, }; cr.Columns.ZipForeach(userChart.Columns, (a, b) => { a.Token = b.Token == null ? null : new QueryTokenEmbedded(b.Token.Token); a.DisplayName = b.DisplayName; a.OrderByIndex = b.OrderByIndex; a.OrderByType = b.OrderByType; }); return cr; } public static void RegisterUserTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition) { sb.Schema.Settings.AssertImplementedBy((UserChartEntity uq) => uq.Owner, typeof(UserEntity)); TypeConditionLogic.RegisterCompile<UserChartEntity>(typeCondition, uq => uq.Owner.Is(UserEntity.Current)); } public static void RegisterRoleTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition) { sb.Schema.Settings.AssertImplementedBy((UserChartEntity uq) => uq.Owner, typeof(RoleEntity)); TypeConditionLogic.RegisterCompile<UserChartEntity>(typeCondition, uq => AuthLogic.CurrentRoles().Contains(uq.Owner) || uq.Owner == null); } public static void RegisterTranslatableRoutes() { TranslatedInstanceLogic.AddRoute((UserChartEntity uc) => uc.DisplayName); TranslatedInstanceLogic.AddRoute((UserChartEntity uq) => uq.Columns[0].DisplayName); TranslatedInstanceLogic.AddRoute((UserChartEntity uq) => uq.Filters[0].Pinned!.Label); } static SqlPreCommand? Schema_Synchronizing(Replacements replacements) { if (!replacements.Interactive) return null; var list = Database.Query<UserChartEntity>().ToList(); var table = Schema.Current.Table(typeof(UserChartEntity)); using (replacements.WithReplacedDatabaseName()) { SqlPreCommand? cmd = list.Select(uq => ProcessUserChart(replacements, table, uq)).Combine(Spacing.Double); return cmd; } } static SqlPreCommand? ProcessUserChart(Replacements replacements, Table table, UserChartEntity uc) { Console.Write("."); using (DelayedConsole.Delay(() => SafeConsole.WriteLineColor(ConsoleColor.White, "UserChart: " + uc.DisplayName))) using (DelayedConsole.Delay(() => Console.WriteLine(" ChartScript: " + uc.ChartScript.ToString()))) using (DelayedConsole.Delay(() => Console.WriteLine(" Query: " + uc.Query.Key))) { try { if (uc.Filters.Any(a => a.Token?.ParseException != null) || uc.Columns.Any(a => a.Token?.ParseException != null)) { QueryDescription qd = QueryLogic.Queries.QueryDescription(uc.Query.ToQueryName()); if (uc.Filters.Any()) { using (DelayedConsole.Delay(() => Console.WriteLine(" Filters:"))) { foreach (var item in uc.Filters.ToList()) { if (item.Token != null) { QueryTokenEmbedded token = item.Token; switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | SubTokensOptions.CanAggregate, " {0} {1}".FormatWith(item.Operation, item.ValueString), allowRemoveToken: true, allowReCreate: false)) { case FixTokenResult.Nothing: break; case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc, u => u.Guid == uc.Guid); case FixTokenResult.RemoveToken: uc.Filters.Remove(item); break; case FixTokenResult.SkipEntity: return null; case FixTokenResult.Fix: item.Token = token; break; default: break; } } } } } if (uc.Columns.Any()) { using (DelayedConsole.Delay(() => Console.WriteLine(" Columns:"))) { foreach (var item in uc.Columns.ToList()) { if (item.Token == null) continue; QueryTokenEmbedded token = item.Token; switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement | SubTokensOptions.CanAggregate, " " + item.ScriptColumn.DisplayName, allowRemoveToken: item.ScriptColumn.IsOptional, allowReCreate: false)) { case FixTokenResult.Nothing: break; case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc, u => u.Guid == uc.Guid); case FixTokenResult.RemoveToken: item.Token = null; break; case FixTokenResult.SkipEntity: return null; case FixTokenResult.Fix: item.Token = token; break; default: break; } } } } } foreach (var item in uc.Filters.Where(f => !f.IsGroup).ToList()) { retry: string? val = item.ValueString; switch (QueryTokenSynchronizer.FixValue(replacements, item.Token!.Token.Type, ref val, allowRemoveToken: true, isList: item.Operation!.Value.IsList())) { case FixTokenResult.Nothing: break; case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc, u => u.Guid == uc.Guid); case FixTokenResult.RemoveToken: uc.Filters.Remove(item); break; case FixTokenResult.SkipEntity: return null; case FixTokenResult.Fix: item.ValueString = val; goto retry; } } foreach (var item in uc.Columns) { uc.FixParameters(item); } foreach (var item in uc.Parameters) { string? val = item.Value; retry: switch (FixParameter(item, ref val)) { case FixTokenResult.Nothing: break; case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc, u => u.Guid == uc.Guid); case FixTokenResult.RemoveToken: uc.Parameters.Remove(item); break; case FixTokenResult.SkipEntity: return null; case FixTokenResult.Fix: { item.Value = val; goto retry; } } } try { return table.UpdateSqlSync(uc, u => u.Guid == uc.Guid, includeCollections: true); } catch (Exception e) { DelayedConsole.Flush(); Console.WriteLine("Integrity Error:"); SafeConsole.WriteLineColor(ConsoleColor.DarkRed, e.Message); while (true) { SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity"); SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity"); string? answer = Console.ReadLine(); if (answer == null) throw new InvalidOperationException("Impossible to synchronize interactively without Console"); answer = answer.ToLower(); if (answer == "s") return null; if (answer == "d") return table.DeleteSqlSync(uc, u => u.Guid == uc.Guid); } } } catch (Exception e) { return new SqlPreCommandSimple("-- Exception in {0}: {1}".FormatWith(uc.BaseToString(), e.Message)); } } } private static FixTokenResult FixParameter(ChartParameterEmbedded item, ref string? val) { var error = item.PropertyCheck(nameof(item.Value)); if (error == null) return FixTokenResult.Nothing; DelayedConsole.Flush(); SafeConsole.WriteLineColor(ConsoleColor.White, "Parameter Name: {0}".FormatWith(item.ScriptParameter.Name)); SafeConsole.WriteLineColor(ConsoleColor.White, "Parameter Definition: {0}".FormatWith(item.ScriptParameter.ValueDefinition)); SafeConsole.WriteLineColor(ConsoleColor.White, "CurrentValue: {0}".FormatWith(item.Value)); SafeConsole.WriteLineColor(ConsoleColor.White, "Error: {0}.".FormatWith(error)); SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity"); SafeConsole.WriteLineColor(ConsoleColor.DarkRed, "- r: Remove parame"); SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity"); SafeConsole.WriteLineColor(ConsoleColor.Green, "- freeText: New value"); string? answer = Console.ReadLine(); if (answer == null) throw new InvalidOperationException("Impossible to synchronize interactively without Console"); string a = answer.ToLower(); if (a == "s") return FixTokenResult.SkipEntity; if (a == "r") return FixTokenResult.RemoveToken; if (a == "d") return FixTokenResult.DeleteEntity; val = answer; return FixTokenResult.Fix; } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.CatAliases1 { public partial class CatAliases1YamlTests { [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class Help1Tests : YamlTestsBase { [Test] public void Help1Test() { //do cat.aliases this.Do(()=> _client.CatAliases(nv=>nv .AddQueryString("help", @"true") )); //match this._status: this.IsMatch(this._status, @"/^ alias .+ \n index .+ \n filter .+ \n routing.index .+ \n routing.search .+ \n $/ "); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class EmptyCluster2Tests : YamlTestsBase { [Test] public void EmptyCluster2Test() { //do cat.aliases this.Do(()=> _client.CatAliases()); //match this._status: this.IsMatch(this._status, @"/^ $/ "); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class SimpleAlias3Tests : YamlTestsBase { [Test] public void SimpleAlias3Test() { //do indices.create this.Do(()=> _client.IndicesCreate("test", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test", "test_alias", null)); //do cat.aliases this.Do(()=> _client.CatAliases()); //match this._status: this.IsMatch(this._status, @"/^ test_alias \s+ test \s+ - \s+ - \s+ - \s+ $/ "); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class ComplexAlias4Tests : YamlTestsBase { [Test] public void ComplexAlias4Test() { //do indices.create this.Do(()=> _client.IndicesCreate("test", null)); //do indices.put_alias _body = new { index_routing= "ir", search_routing= "sr1,sr2", filter= new { term= new { foo= "bar" } } }; this.Do(()=> _client.IndicesPutAlias("test", "test_alias", _body)); //do cat.aliases this.Do(()=> _client.CatAliases()); //match this._status: this.IsMatch(this._status, @"/^ test_alias \s+ test \s+ [*] \s+ ir \s+ sr1,sr2 \s+ $/ "); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class AliasName5Tests : YamlTestsBase { [Test] public void AliasName5Test() { //do indices.create this.Do(()=> _client.IndicesCreate("test", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test", "test_1", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test", "test_2", null)); //do cat.aliases this.Do(()=> _client.CatAliases("test_1")); //match this._status: this.IsMatch(this._status, @"/^test_1 .+ \n$/"); //do cat.aliases this.Do(()=> _client.CatAliases("test_2")); //match this._status: this.IsMatch(this._status, @"/^test_2 .+ \n$/"); //do cat.aliases this.Do(()=> _client.CatAliases("test_*")); //match this._status: this.IsMatch(this._status, @"/ (^|\n)test_1 .+ \n/"); //match this._status: this.IsMatch(this._status, @"/ (^|\n)test_2 .+ \n/"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class ColumnHeaders6Tests : YamlTestsBase { [Test] public void ColumnHeaders6Test() { //do indices.create this.Do(()=> _client.IndicesCreate("test", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test", "test_1", null)); //do cat.aliases this.Do(()=> _client.CatAliases(nv=>nv .AddQueryString("v", @"true") )); //match this._status: this.IsMatch(this._status, @"/^ alias \s+ index \s+ filter \s+ routing.index \s+ routing.search \s+ \n test_1 \s+ test \s+ - \s+ - \s+ - \s+ $/ "); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class SelectColumns7Tests : YamlTestsBase { [Test] public void SelectColumns7Test() { //do indices.create this.Do(()=> _client.IndicesCreate("test", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test", "test_1", null)); //do cat.aliases this.Do(()=> _client.CatAliases(nv=>nv .AddQueryString("h", new [] { @"index", @"alias" }) )); //match this._status: this.IsMatch(this._status, @"/^ test \s+ test_1 \s+ $/"); //do cat.aliases this.Do(()=> _client.CatAliases(nv=>nv .AddQueryString("h", new [] { @"index", @"alias" }) .AddQueryString("v", @"true") )); //match this._status: this.IsMatch(this._status, @"/^ index \s+ alias \s+ \n test \s+ test_1 \s+ \n $/ "); } } } }
/* * CP1256.cs - Arabic (Windows) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-5352.ucm". namespace I18N.MidEast { using System; using I18N.Common; public class CP1256 : ByteEncoding { public CP1256() : base(1256, ToChars, "Arabic (Windows)", "windows-1256", "windows-1256", "windows-1256", true, true, true, true, 1256) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F', '\u20AC', '\u067E', '\u201A', '\u0192', '\u201E', '\u2026', '\u2020', '\u2021', '\u02C6', '\u2030', '\u0679', '\u2039', '\u0152', '\u0686', '\u0698', '\u0688', '\u06AF', '\u2018', '\u2019', '\u201C', '\u201D', '\u2022', '\u2013', '\u2014', '\u06A9', '\u2122', '\u0691', '\u203A', '\u0153', '\u200C', '\u200D', '\u06BA', '\u00A0', '\u060C', '\u00A2', '\u00A3', '\u00A4', '\u00A5', '\u00A6', '\u00A7', '\u00A8', '\u00A9', '\u06BE', '\u00AB', '\u00AC', '\u00AD', '\u00AE', '\u00AF', '\u00B0', '\u00B1', '\u00B2', '\u00B3', '\u00B4', '\u00B5', '\u00B6', '\u00B7', '\u00B8', '\u00B9', '\u061B', '\u00BB', '\u00BC', '\u00BD', '\u00BE', '\u061F', '\u06C1', '\u0621', '\u0622', '\u0623', '\u0624', '\u0625', '\u0626', '\u0627', '\u0628', '\u0629', '\u062A', '\u062B', '\u062C', '\u062D', '\u062E', '\u062F', '\u0630', '\u0631', '\u0632', '\u0633', '\u0634', '\u0635', '\u0636', '\u00D7', '\u0637', '\u0638', '\u0639', '\u063A', '\u0640', '\u0641', '\u0642', '\u0643', '\u00E0', '\u0644', '\u00E2', '\u0645', '\u0646', '\u0647', '\u0648', '\u00E7', '\u00E8', '\u00E9', '\u00EA', '\u00EB', '\u0649', '\u064A', '\u00EE', '\u00EF', '\u064B', '\u064C', '\u064D', '\u064E', '\u00F4', '\u064F', '\u0650', '\u00F7', '\u0651', '\u00F9', '\u0652', '\u00FB', '\u00FC', '\u200E', '\u200F', '\u06D2', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 128) switch(ch) { case 0x00A0: case 0x00A2: case 0x00A3: case 0x00A4: case 0x00A5: case 0x00A6: case 0x00A7: case 0x00A8: case 0x00A9: case 0x00AB: case 0x00AC: case 0x00AD: case 0x00AE: case 0x00AF: case 0x00B0: case 0x00B1: case 0x00B2: case 0x00B3: case 0x00B4: case 0x00B5: case 0x00B6: case 0x00B7: case 0x00B8: case 0x00B9: case 0x00BB: case 0x00BC: case 0x00BD: case 0x00BE: case 0x00D7: case 0x00E0: case 0x00E2: case 0x00E7: case 0x00E8: case 0x00E9: case 0x00EA: case 0x00EB: case 0x00EE: case 0x00EF: case 0x00F4: case 0x00F7: case 0x00F9: case 0x00FB: case 0x00FC: break; case 0x0152: ch = 0x8C; break; case 0x0153: ch = 0x9C; break; case 0x0192: ch = 0x83; break; case 0x02C6: ch = 0x88; break; case 0x060C: ch = 0xA1; break; case 0x061B: ch = 0xBA; break; case 0x061F: ch = 0xBF; break; case 0x0621: case 0x0622: case 0x0623: case 0x0624: case 0x0625: case 0x0626: case 0x0627: case 0x0628: case 0x0629: case 0x062A: case 0x062B: case 0x062C: case 0x062D: case 0x062E: case 0x062F: case 0x0630: case 0x0631: case 0x0632: case 0x0633: case 0x0634: case 0x0635: case 0x0636: ch -= 0x0560; break; case 0x0637: case 0x0638: case 0x0639: case 0x063A: ch -= 0x055F; break; case 0x0640: case 0x0641: case 0x0642: case 0x0643: ch -= 0x0564; break; case 0x0644: ch = 0xE1; break; case 0x0645: case 0x0646: case 0x0647: case 0x0648: ch -= 0x0562; break; case 0x0649: ch = 0xEC; break; case 0x064A: ch = 0xED; break; case 0x064B: case 0x064C: case 0x064D: case 0x064E: ch -= 0x055B; break; case 0x064F: ch = 0xF5; break; case 0x0650: ch = 0xF6; break; case 0x0651: ch = 0xF8; break; case 0x0652: ch = 0xFA; break; case 0x0660: case 0x0661: case 0x0662: case 0x0663: case 0x0664: case 0x0665: case 0x0666: case 0x0667: case 0x0668: case 0x0669: ch -= 0x0630; break; case 0x066B: ch = 0x2C; break; case 0x066C: ch = 0x2E; break; case 0x0679: ch = 0x8A; break; case 0x067E: ch = 0x81; break; case 0x0686: ch = 0x8D; break; case 0x0688: ch = 0x8F; break; case 0x0691: ch = 0x9A; break; case 0x0698: ch = 0x8E; break; case 0x06A9: ch = 0x98; break; case 0x06AF: ch = 0x90; break; case 0x06BA: ch = 0x9F; break; case 0x06BE: ch = 0xAA; break; case 0x06C1: ch = 0xC0; break; case 0x06D2: ch = 0xFF; break; case 0x06F0: case 0x06F1: case 0x06F2: case 0x06F3: case 0x06F4: case 0x06F5: case 0x06F6: case 0x06F7: case 0x06F8: case 0x06F9: ch -= 0x06C0; break; case 0x200C: ch = 0x9D; break; case 0x200D: ch = 0x9E; break; case 0x200E: ch = 0xFD; break; case 0x200F: ch = 0xFE; break; case 0x2013: ch = 0x96; break; case 0x2014: ch = 0x97; break; case 0x2018: ch = 0x91; break; case 0x2019: ch = 0x92; break; case 0x201A: ch = 0x82; break; case 0x201C: ch = 0x93; break; case 0x201D: ch = 0x94; break; case 0x201E: ch = 0x84; break; case 0x2020: ch = 0x86; break; case 0x2021: ch = 0x87; break; case 0x2022: ch = 0x95; break; case 0x2026: ch = 0x85; break; case 0x2030: ch = 0x89; break; case 0x2039: ch = 0x8B; break; case 0x203A: ch = 0x9B; break; case 0x20AC: ch = 0x80; break; case 0x2122: ch = 0x99; break; case 0xFB56: ch = 0x81; break; case 0xFB58: ch = 0x81; break; case 0xFB66: ch = 0x8A; break; case 0xFB68: ch = 0x8A; break; case 0xFB7A: ch = 0x8D; break; case 0xFB7C: ch = 0x8D; break; case 0xFB88: ch = 0x8F; break; case 0xFB8A: ch = 0x8E; break; case 0xFB8C: ch = 0x9A; break; case 0xFB8E: ch = 0x98; break; case 0xFB90: ch = 0x98; break; case 0xFB92: ch = 0x90; break; case 0xFB94: ch = 0x90; break; case 0xFB9E: ch = 0x9F; break; case 0xFBA6: ch = 0xC0; break; case 0xFBA8: ch = 0xC0; break; case 0xFBAA: ch = 0xAA; break; case 0xFBAC: ch = 0xAA; break; case 0xFBAE: ch = 0xFF; break; case 0xFE70: ch = 0xF0; break; case 0xFE71: ch = 0xF0; break; case 0xFE72: ch = 0xF1; break; case 0xFE74: ch = 0xF2; break; case 0xFE76: ch = 0xF3; break; case 0xFE77: ch = 0xF3; break; case 0xFE78: ch = 0xF5; break; case 0xFE79: ch = 0xF5; break; case 0xFE7A: ch = 0xF6; break; case 0xFE7B: ch = 0xF6; break; case 0xFE7C: ch = 0xF8; break; case 0xFE7D: ch = 0xF8; break; case 0xFE7E: ch = 0xFA; break; case 0xFE7F: ch = 0xFA; break; case 0xFE80: ch = 0xC1; break; case 0xFE81: ch = 0xC2; break; case 0xFE82: ch = 0xC2; break; case 0xFE83: ch = 0xC3; break; case 0xFE84: ch = 0xC3; break; case 0xFE85: ch = 0xC4; break; case 0xFE86: ch = 0xC4; break; case 0xFE87: ch = 0xC5; break; case 0xFE88: ch = 0xC5; break; case 0xFE89: ch = 0xC6; break; case 0xFE8A: ch = 0xC6; break; case 0xFE8B: ch = 0xC6; break; case 0xFE8C: ch = 0xC6; break; case 0xFE8D: ch = 0xC7; break; case 0xFE8E: ch = 0xC7; break; case 0xFE8F: ch = 0xC8; break; case 0xFE90: ch = 0xC8; break; case 0xFE91: ch = 0xC8; break; case 0xFE92: ch = 0xC8; break; case 0xFE93: ch = 0xC9; break; case 0xFE94: ch = 0xC9; break; case 0xFE95: ch = 0xCA; break; case 0xFE96: ch = 0xCA; break; case 0xFE97: ch = 0xCA; break; case 0xFE98: ch = 0xCA; break; case 0xFE99: ch = 0xCB; break; case 0xFE9A: ch = 0xCB; break; case 0xFE9B: ch = 0xCB; break; case 0xFE9C: ch = 0xCB; break; case 0xFE9D: ch = 0xCC; break; case 0xFE9E: ch = 0xCC; break; case 0xFE9F: ch = 0xCC; break; case 0xFEA0: ch = 0xCC; break; case 0xFEA1: ch = 0xCD; break; case 0xFEA2: ch = 0xCD; break; case 0xFEA3: ch = 0xCD; break; case 0xFEA4: ch = 0xCD; break; case 0xFEA5: ch = 0xCE; break; case 0xFEA6: ch = 0xCE; break; case 0xFEA7: ch = 0xCE; break; case 0xFEA8: ch = 0xCE; break; case 0xFEA9: ch = 0xCF; break; case 0xFEAA: ch = 0xCF; break; case 0xFEAB: ch = 0xD0; break; case 0xFEAC: ch = 0xD0; break; case 0xFEAD: ch = 0xD1; break; case 0xFEAE: ch = 0xD1; break; case 0xFEAF: ch = 0xD2; break; case 0xFEB0: ch = 0xD2; break; case 0xFEB1: ch = 0xD3; break; case 0xFEB2: ch = 0xD3; break; case 0xFEB3: ch = 0xD3; break; case 0xFEB4: ch = 0xD3; break; case 0xFEB5: ch = 0xD4; break; case 0xFEB6: ch = 0xD4; break; case 0xFEB7: ch = 0xD4; break; case 0xFEB8: ch = 0xD4; break; case 0xFEB9: ch = 0xD5; break; case 0xFEBA: ch = 0xD5; break; case 0xFEBB: ch = 0xD5; break; case 0xFEBC: ch = 0xD5; break; case 0xFEBD: ch = 0xD6; break; case 0xFEBE: ch = 0xD6; break; case 0xFEBF: ch = 0xD6; break; case 0xFEC0: ch = 0xD6; break; case 0xFEC1: ch = 0xD8; break; case 0xFEC2: ch = 0xD8; break; case 0xFEC3: ch = 0xD8; break; case 0xFEC4: ch = 0xD8; break; case 0xFEC5: ch = 0xD9; break; case 0xFEC6: ch = 0xD9; break; case 0xFEC7: ch = 0xD9; break; case 0xFEC8: ch = 0xD9; break; case 0xFEC9: ch = 0xDA; break; case 0xFECA: ch = 0xDA; break; case 0xFECB: ch = 0xDA; break; case 0xFECC: ch = 0xDA; break; case 0xFECD: ch = 0xDB; break; case 0xFECE: ch = 0xDB; break; case 0xFECF: ch = 0xDB; break; case 0xFED0: ch = 0xDB; break; case 0xFED1: ch = 0xDD; break; case 0xFED2: ch = 0xDD; break; case 0xFED3: ch = 0xDD; break; case 0xFED4: ch = 0xDD; break; case 0xFED5: ch = 0xDE; break; case 0xFED6: ch = 0xDE; break; case 0xFED7: ch = 0xDE; break; case 0xFED8: ch = 0xDE; break; case 0xFED9: ch = 0xDF; break; case 0xFEDA: ch = 0xDF; break; case 0xFEDB: ch = 0xDF; break; case 0xFEDC: ch = 0xDF; break; case 0xFEDD: ch = 0xE1; break; case 0xFEDE: ch = 0xE1; break; case 0xFEDF: ch = 0xE1; break; case 0xFEE0: ch = 0xE1; break; case 0xFEE1: ch = 0xE3; break; case 0xFEE2: ch = 0xE3; break; case 0xFEE3: ch = 0xE3; break; case 0xFEE4: ch = 0xE3; break; case 0xFEE5: ch = 0xE4; break; case 0xFEE6: ch = 0xE4; break; case 0xFEE7: ch = 0xE4; break; case 0xFEE8: ch = 0xE4; break; case 0xFEE9: ch = 0xE5; break; case 0xFEEA: ch = 0xE5; break; case 0xFEEB: ch = 0xE5; break; case 0xFEEC: ch = 0xE5; break; case 0xFEED: ch = 0xE6; break; case 0xFEEE: ch = 0xE6; break; case 0xFEEF: ch = 0xEC; break; case 0xFEF0: ch = 0xEC; break; case 0xFEF1: ch = 0xED; break; case 0xFEF2: ch = 0xED; break; case 0xFEF3: ch = 0xED; break; case 0xFEF4: ch = 0xED; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 128) switch(ch) { case 0x00A0: case 0x00A2: case 0x00A3: case 0x00A4: case 0x00A5: case 0x00A6: case 0x00A7: case 0x00A8: case 0x00A9: case 0x00AB: case 0x00AC: case 0x00AD: case 0x00AE: case 0x00AF: case 0x00B0: case 0x00B1: case 0x00B2: case 0x00B3: case 0x00B4: case 0x00B5: case 0x00B6: case 0x00B7: case 0x00B8: case 0x00B9: case 0x00BB: case 0x00BC: case 0x00BD: case 0x00BE: case 0x00D7: case 0x00E0: case 0x00E2: case 0x00E7: case 0x00E8: case 0x00E9: case 0x00EA: case 0x00EB: case 0x00EE: case 0x00EF: case 0x00F4: case 0x00F7: case 0x00F9: case 0x00FB: case 0x00FC: break; case 0x0152: ch = 0x8C; break; case 0x0153: ch = 0x9C; break; case 0x0192: ch = 0x83; break; case 0x02C6: ch = 0x88; break; case 0x060C: ch = 0xA1; break; case 0x061B: ch = 0xBA; break; case 0x061F: ch = 0xBF; break; case 0x0621: case 0x0622: case 0x0623: case 0x0624: case 0x0625: case 0x0626: case 0x0627: case 0x0628: case 0x0629: case 0x062A: case 0x062B: case 0x062C: case 0x062D: case 0x062E: case 0x062F: case 0x0630: case 0x0631: case 0x0632: case 0x0633: case 0x0634: case 0x0635: case 0x0636: ch -= 0x0560; break; case 0x0637: case 0x0638: case 0x0639: case 0x063A: ch -= 0x055F; break; case 0x0640: case 0x0641: case 0x0642: case 0x0643: ch -= 0x0564; break; case 0x0644: ch = 0xE1; break; case 0x0645: case 0x0646: case 0x0647: case 0x0648: ch -= 0x0562; break; case 0x0649: ch = 0xEC; break; case 0x064A: ch = 0xED; break; case 0x064B: case 0x064C: case 0x064D: case 0x064E: ch -= 0x055B; break; case 0x064F: ch = 0xF5; break; case 0x0650: ch = 0xF6; break; case 0x0651: ch = 0xF8; break; case 0x0652: ch = 0xFA; break; case 0x0660: case 0x0661: case 0x0662: case 0x0663: case 0x0664: case 0x0665: case 0x0666: case 0x0667: case 0x0668: case 0x0669: ch -= 0x0630; break; case 0x066B: ch = 0x2C; break; case 0x066C: ch = 0x2E; break; case 0x0679: ch = 0x8A; break; case 0x067E: ch = 0x81; break; case 0x0686: ch = 0x8D; break; case 0x0688: ch = 0x8F; break; case 0x0691: ch = 0x9A; break; case 0x0698: ch = 0x8E; break; case 0x06A9: ch = 0x98; break; case 0x06AF: ch = 0x90; break; case 0x06BA: ch = 0x9F; break; case 0x06BE: ch = 0xAA; break; case 0x06C1: ch = 0xC0; break; case 0x06D2: ch = 0xFF; break; case 0x06F0: case 0x06F1: case 0x06F2: case 0x06F3: case 0x06F4: case 0x06F5: case 0x06F6: case 0x06F7: case 0x06F8: case 0x06F9: ch -= 0x06C0; break; case 0x200C: ch = 0x9D; break; case 0x200D: ch = 0x9E; break; case 0x200E: ch = 0xFD; break; case 0x200F: ch = 0xFE; break; case 0x2013: ch = 0x96; break; case 0x2014: ch = 0x97; break; case 0x2018: ch = 0x91; break; case 0x2019: ch = 0x92; break; case 0x201A: ch = 0x82; break; case 0x201C: ch = 0x93; break; case 0x201D: ch = 0x94; break; case 0x201E: ch = 0x84; break; case 0x2020: ch = 0x86; break; case 0x2021: ch = 0x87; break; case 0x2022: ch = 0x95; break; case 0x2026: ch = 0x85; break; case 0x2030: ch = 0x89; break; case 0x2039: ch = 0x8B; break; case 0x203A: ch = 0x9B; break; case 0x20AC: ch = 0x80; break; case 0x2122: ch = 0x99; break; case 0xFB56: ch = 0x81; break; case 0xFB58: ch = 0x81; break; case 0xFB66: ch = 0x8A; break; case 0xFB68: ch = 0x8A; break; case 0xFB7A: ch = 0x8D; break; case 0xFB7C: ch = 0x8D; break; case 0xFB88: ch = 0x8F; break; case 0xFB8A: ch = 0x8E; break; case 0xFB8C: ch = 0x9A; break; case 0xFB8E: ch = 0x98; break; case 0xFB90: ch = 0x98; break; case 0xFB92: ch = 0x90; break; case 0xFB94: ch = 0x90; break; case 0xFB9E: ch = 0x9F; break; case 0xFBA6: ch = 0xC0; break; case 0xFBA8: ch = 0xC0; break; case 0xFBAA: ch = 0xAA; break; case 0xFBAC: ch = 0xAA; break; case 0xFBAE: ch = 0xFF; break; case 0xFE70: ch = 0xF0; break; case 0xFE71: ch = 0xF0; break; case 0xFE72: ch = 0xF1; break; case 0xFE74: ch = 0xF2; break; case 0xFE76: ch = 0xF3; break; case 0xFE77: ch = 0xF3; break; case 0xFE78: ch = 0xF5; break; case 0xFE79: ch = 0xF5; break; case 0xFE7A: ch = 0xF6; break; case 0xFE7B: ch = 0xF6; break; case 0xFE7C: ch = 0xF8; break; case 0xFE7D: ch = 0xF8; break; case 0xFE7E: ch = 0xFA; break; case 0xFE7F: ch = 0xFA; break; case 0xFE80: ch = 0xC1; break; case 0xFE81: ch = 0xC2; break; case 0xFE82: ch = 0xC2; break; case 0xFE83: ch = 0xC3; break; case 0xFE84: ch = 0xC3; break; case 0xFE85: ch = 0xC4; break; case 0xFE86: ch = 0xC4; break; case 0xFE87: ch = 0xC5; break; case 0xFE88: ch = 0xC5; break; case 0xFE89: ch = 0xC6; break; case 0xFE8A: ch = 0xC6; break; case 0xFE8B: ch = 0xC6; break; case 0xFE8C: ch = 0xC6; break; case 0xFE8D: ch = 0xC7; break; case 0xFE8E: ch = 0xC7; break; case 0xFE8F: ch = 0xC8; break; case 0xFE90: ch = 0xC8; break; case 0xFE91: ch = 0xC8; break; case 0xFE92: ch = 0xC8; break; case 0xFE93: ch = 0xC9; break; case 0xFE94: ch = 0xC9; break; case 0xFE95: ch = 0xCA; break; case 0xFE96: ch = 0xCA; break; case 0xFE97: ch = 0xCA; break; case 0xFE98: ch = 0xCA; break; case 0xFE99: ch = 0xCB; break; case 0xFE9A: ch = 0xCB; break; case 0xFE9B: ch = 0xCB; break; case 0xFE9C: ch = 0xCB; break; case 0xFE9D: ch = 0xCC; break; case 0xFE9E: ch = 0xCC; break; case 0xFE9F: ch = 0xCC; break; case 0xFEA0: ch = 0xCC; break; case 0xFEA1: ch = 0xCD; break; case 0xFEA2: ch = 0xCD; break; case 0xFEA3: ch = 0xCD; break; case 0xFEA4: ch = 0xCD; break; case 0xFEA5: ch = 0xCE; break; case 0xFEA6: ch = 0xCE; break; case 0xFEA7: ch = 0xCE; break; case 0xFEA8: ch = 0xCE; break; case 0xFEA9: ch = 0xCF; break; case 0xFEAA: ch = 0xCF; break; case 0xFEAB: ch = 0xD0; break; case 0xFEAC: ch = 0xD0; break; case 0xFEAD: ch = 0xD1; break; case 0xFEAE: ch = 0xD1; break; case 0xFEAF: ch = 0xD2; break; case 0xFEB0: ch = 0xD2; break; case 0xFEB1: ch = 0xD3; break; case 0xFEB2: ch = 0xD3; break; case 0xFEB3: ch = 0xD3; break; case 0xFEB4: ch = 0xD3; break; case 0xFEB5: ch = 0xD4; break; case 0xFEB6: ch = 0xD4; break; case 0xFEB7: ch = 0xD4; break; case 0xFEB8: ch = 0xD4; break; case 0xFEB9: ch = 0xD5; break; case 0xFEBA: ch = 0xD5; break; case 0xFEBB: ch = 0xD5; break; case 0xFEBC: ch = 0xD5; break; case 0xFEBD: ch = 0xD6; break; case 0xFEBE: ch = 0xD6; break; case 0xFEBF: ch = 0xD6; break; case 0xFEC0: ch = 0xD6; break; case 0xFEC1: ch = 0xD8; break; case 0xFEC2: ch = 0xD8; break; case 0xFEC3: ch = 0xD8; break; case 0xFEC4: ch = 0xD8; break; case 0xFEC5: ch = 0xD9; break; case 0xFEC6: ch = 0xD9; break; case 0xFEC7: ch = 0xD9; break; case 0xFEC8: ch = 0xD9; break; case 0xFEC9: ch = 0xDA; break; case 0xFECA: ch = 0xDA; break; case 0xFECB: ch = 0xDA; break; case 0xFECC: ch = 0xDA; break; case 0xFECD: ch = 0xDB; break; case 0xFECE: ch = 0xDB; break; case 0xFECF: ch = 0xDB; break; case 0xFED0: ch = 0xDB; break; case 0xFED1: ch = 0xDD; break; case 0xFED2: ch = 0xDD; break; case 0xFED3: ch = 0xDD; break; case 0xFED4: ch = 0xDD; break; case 0xFED5: ch = 0xDE; break; case 0xFED6: ch = 0xDE; break; case 0xFED7: ch = 0xDE; break; case 0xFED8: ch = 0xDE; break; case 0xFED9: ch = 0xDF; break; case 0xFEDA: ch = 0xDF; break; case 0xFEDB: ch = 0xDF; break; case 0xFEDC: ch = 0xDF; break; case 0xFEDD: ch = 0xE1; break; case 0xFEDE: ch = 0xE1; break; case 0xFEDF: ch = 0xE1; break; case 0xFEE0: ch = 0xE1; break; case 0xFEE1: ch = 0xE3; break; case 0xFEE2: ch = 0xE3; break; case 0xFEE3: ch = 0xE3; break; case 0xFEE4: ch = 0xE3; break; case 0xFEE5: ch = 0xE4; break; case 0xFEE6: ch = 0xE4; break; case 0xFEE7: ch = 0xE4; break; case 0xFEE8: ch = 0xE4; break; case 0xFEE9: ch = 0xE5; break; case 0xFEEA: ch = 0xE5; break; case 0xFEEB: ch = 0xE5; break; case 0xFEEC: ch = 0xE5; break; case 0xFEED: ch = 0xE6; break; case 0xFEEE: ch = 0xE6; break; case 0xFEEF: ch = 0xEC; break; case 0xFEF0: ch = 0xEC; break; case 0xFEF1: ch = 0xED; break; case 0xFEF2: ch = 0xED; break; case 0xFEF3: ch = 0xED; break; case 0xFEF4: ch = 0xED; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP1256 public class ENCwindows_1256 : CP1256 { public ENCwindows_1256() : base() {} }; // class ENCwindows_1256 }; // namespace I18N.MidEast
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using Microsoft.Ink; namespace Scout { public partial class ToDoItemControl : UserControl { private InkOverlay overlay; public ToDoItemControl() { InitializeComponent(); ResizeRedraw = true; HandleCreated += new EventHandler(ToDoItemControl_HandleCreated); center.LineAlignment = StringAlignment.Center; center.Alignment = StringAlignment.Center; left.LineAlignment = StringAlignment.Center; left.Alignment = StringAlignment.Near; bluePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; MouseClick += new MouseEventHandler(ToDoItemControl_MouseClick); } void ToDoItemControl_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (Editing != null) Editing(this, EventArgs.Empty); } } public event EventHandler Editing; Font personFont; void ToDoItemControl_HandleCreated(object sender, EventArgs e) { panel1.BackColor = Color.Transparent; overlay = new InkOverlay(panel1); overlay.Enabled = true; overlay.CollectionMode = CollectionMode.InkAndGesture; overlay.SetGestureStatus(ApplicationGesture.Up, true); overlay.SetGestureStatus(ApplicationGesture.Down, true); overlay.SetGestureStatus(ApplicationGesture.Right, true); overlay.SetGestureStatus(ApplicationGesture.ArrowUp, true); overlay.SetGestureStatus(ApplicationGesture.ArrowDown, true); overlay.SetGestureStatus(ApplicationGesture.Check, true); overlay.SetGestureStatus(ApplicationGesture.Square, true); overlay.SetGestureStatus(ApplicationGesture.Circle, true); //overlay.Gesture += new InkCollectorGestureEventHandler(overlay_Gesture); overlay.Stroke += new InkCollectorStrokeEventHandler(overlay_Stroke); CreateRecognizer(overlay); personFont = new Font(Font, FontStyle.Bold); } private void CreateRecognizer(InkOverlay overlay) { Recognizers recognizers = new Recognizers(); Recognizer english = recognizers.GetDefaultRecognizer(); context = english.CreateRecognizerContext(); WordList wordList = new WordList(); for (int i = 0; i < 100; ++i) wordList.Add(i.ToString()); context.WordList = wordList; context.Factoid = Factoid.WordList; context.RecognitionFlags = RecognitionModes.Coerce; } RecognizerContext context; void overlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { StartTimer(); } private void RecognizeNumber() { context.Strokes = overlay.Ink.Strokes; if (ToDoItem != null && context.Strokes.Count > 0) { RecognitionStatus status; RecognitionResult result = context.Recognize(out status); if (status == RecognitionStatus.NoError && result.TopConfidence == RecognitionConfidence.Strong) { int newValue; if (int.TryParse(result.ToString(), out newValue)) { if (newValue > 0) { ToDoItem.IsCompleted = false; ToDoItem.Position = newValue; } else if (newValue == 0) AssumeToggle(); } } else { AssumeToggle(); } } overlay.Ink.DeleteStrokes(); Refresh(); } private void AssumeToggle() { ToDoItem.IsCompleted = !ToDoItem.IsCompleted; } void overlay_Gesture(object sender, InkCollectorGestureEventArgs e) { if (ToDoItem != null && e.Gestures.Length > 0) { overlay.Ink.DeleteStrokes(); switch (e.Gestures[0].Id) { case ApplicationGesture.ArrowUp: case ApplicationGesture.Up: ToDoItem.Position -= 1; break; case ApplicationGesture.ArrowDown: case ApplicationGesture.Down: ToDoItem.Position += 1; break; case ApplicationGesture.Check: case ApplicationGesture.Right: ToDoItem.IsCompleted = true; break; case ApplicationGesture.Square: ToDoItem.IsCompleted = false; break; case ApplicationGesture.Circle: ToDoItem.IsCompleted = !ToDoItem.IsCompleted; break; } } else { e.Cancel = true; } } private void StartTimer() { Timer timer = new Timer(); timer.Interval = 1000; timer.Tick += delegate { StopTimer(timer); RecognizeNumber(); }; timer.Enabled = true; } private void StopTimer(Timer timer) { timer.Enabled = false; timer.Dispose(); } public BasecampAPI.ToDoItem ToDoItem; public BasecampAPI.Person Person; protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); DrawNumber(e); DrawText(e); DrawNotebookLine(e); } StringFormat center = StringFormat.GenericTypographic.Clone() as StringFormat; StringFormat left = StringFormat.GenericTypographic.Clone() as StringFormat; private void DrawText(PaintEventArgs e) { if (ToDoItem == null) return; int startX = panel1.Right + 5; if (Person != null) { string name = Person.Name + ": "; SizeF size = e.Graphics.MeasureString(name, personFont); Rectangle personRect = Rectangle.FromLTRB(startX, 0, startX + (int)size.Width, Height); e.Graphics.DrawString( name, personFont, ToDoItem.IsCompleted ? Brushes.Gray : Brushes.Black, personRect, left); startX += (int)size.Width + 5; } RectangleF r = Rectangle.FromLTRB(startX, 0, Width, Height); e.Graphics.DrawString( ToDoItem.Content, Font, ToDoItem.IsCompleted ? Brushes.Gray : Brushes.Black, r, left); } private void DrawNumber(PaintEventArgs e) { if (ToDoItem == null || ToDoItem.IsCompleted) return; RectangleF r = Rectangle.FromLTRB(0, 0, panel1.Right, panel1.Height - 15); e.Graphics.DrawString(ToDoItem.Position.ToString(), Font, Brushes.Black, r, center); } Pen bluePen = new Pen(Color.LightBlue, 1); private void DrawNotebookLine(PaintEventArgs e) { int bottom = Height - 2; e.Graphics.DrawLine(bluePen, 0, bottom, Width, bottom); e.Graphics.DrawLine(Pens.LightPink, panel1.Right - 3, 0, panel1.Right - 3, Height); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.HSSF.UserModel; using System.Collections.Generic; using System; using NPOI.Util; using NPOI.SS.UserModel; using System.Text; using System.IO; using NUnit.Framework; namespace TestCases.SS.Util { /** * Creates a spreadsheet that demonstrates Excel's rendering of various IEEE double values. * * @author Josh Micich */ public class NumberRenderingSpreadsheetGenerator { private class SheetWriter { private ISheet _sheet; private int _rowIndex; private List<long> _ReplacementNaNs; public SheetWriter(HSSFWorkbook wb) { ISheet sheet = wb.CreateSheet("Sheet1"); WriteHeaderRow(wb, sheet); _sheet = sheet; _rowIndex = 1; _ReplacementNaNs = new List<long>(); } public void AddTestRow(long rawBits, String expectedExcelRendering) { WriteDataRow(_sheet, _rowIndex++, rawBits, expectedExcelRendering); if (Double.IsNaN(BitConverter.Int64BitsToDouble(rawBits))) { _ReplacementNaNs.Add(rawBits); } } public long[] GetReplacementNaNs() { int nRepls = _ReplacementNaNs.Count; long[] result = new long[nRepls]; for (int i = 0; i < nRepls; i++) { result[i] = _ReplacementNaNs[i]; } return result; } } /** 0x7ff8000000000000 encoded in little endian order */ private static byte[] JAVA_NAN_BYTES = HexRead.ReadFromString("00 00 00 00 00 00 F8 7F"); private static void WriteHeaderCell(IRow row, int i, String text, ICellStyle style) { ICell cell = row.CreateCell(i); cell.SetCellValue(new HSSFRichTextString(text)); cell.CellStyle = (style); } static void WriteHeaderRow(IWorkbook wb, ISheet sheet) { sheet.SetColumnWidth(0, 3000); sheet.SetColumnWidth(1, 6000); sheet.SetColumnWidth(2, 6000); sheet.SetColumnWidth(3, 6000); sheet.SetColumnWidth(4, 6000); sheet.SetColumnWidth(5, 1600); sheet.SetColumnWidth(6, 20000); IRow row = sheet.CreateRow(0); ICellStyle style = wb.CreateCellStyle(); IFont font = wb.CreateFont(); WriteHeaderCell(row, 0, "Value", style); font.Boldweight = (short)FontBoldWeight.Bold; style.SetFont(font); WriteHeaderCell(row, 1, "Raw Long Bits", style); WriteHeaderCell(row, 2, "JDK Double Rendering", style); WriteHeaderCell(row, 3, "Actual Rendering", style); WriteHeaderCell(row, 4, "Expected Rendering", style); WriteHeaderCell(row, 5, "Match", style); WriteHeaderCell(row, 6, "Java Metadata", style); } static void WriteDataRow(ISheet sheet, int rowIx, long rawLongBits, String expectedExcelRendering) { double d = BitConverter.Int64BitsToDouble(rawLongBits); IRow row = sheet.CreateRow(rowIx); int rowNum = rowIx + 1; String cel0ref = "A" + rowNum; String rawBitsText = FormatLongAsHex(rawLongBits); String jmExpr = "'ec(" + rawBitsText + ", ''\" & C" + rowNum + " & \"'', ''\" & D" + rowNum + " & \"''),'"; // The 'Match' column will contain 'OK' if the metadata (from NumberToTextConversionExamples) // matches Excel's rendering. String matchExpr = "if(D" + rowNum + "=E" + rowNum + ", \"OK\", \"ERROR\")"; row.CreateCell(0).SetCellValue(d); row.CreateCell(1).SetCellValue(new HSSFRichTextString(rawBitsText)); row.CreateCell(2).SetCellValue(new HSSFRichTextString(d.ToString())); row.CreateCell(3).CellFormula = ("\"\" & " + cel0ref); row.CreateCell(4).SetCellValue(new HSSFRichTextString(expectedExcelRendering)); row.CreateCell(5).CellFormula = (matchExpr); row.CreateCell(6).CellFormula = (jmExpr.Replace("'", "\"")); //if (false) //{ // // for observing arithmetic near numeric range boundaries // row.CreateCell(7).CellFormula=(cel0ref + " * 1.0001"); // row.CreateCell(8).CellFormula=(cel0ref + " / 1.0001"); //} } private static String FormatLongAsHex(long l) { StringBuilder sb = new StringBuilder(20); sb.Append(HexDump.LongToHex(l)).Append('L'); return sb.ToString(); } //[Test] public void Test() { WriteJavaDoc(); HSSFWorkbook wb = new HSSFWorkbook(); SheetWriter sw = new SheetWriter(wb); NumberToTextConversionExamples.ExampleConversion[] exampleValues = NumberToTextConversionExamples.GetExampleConversions(); for (int i = 0; i < exampleValues.Length; i++) { TestCases.SS.Util.NumberToTextConversionExamples.ExampleConversion example = exampleValues[i]; sw.AddTestRow(example.RawDoubleBits, example.ExcelRendering); } MemoryStream baos = new MemoryStream(); wb.Write(baos); byte[] fileContent = baos.ToArray(); ReplaceNaNs(fileContent, sw.GetReplacementNaNs()); FileInfo outputFile = new FileInfo("ExcelNumberRendering.xls"); FileStream os = File.OpenWrite(outputFile.FullName); os.Write(fileContent, 0, fileContent.Length); os.Close(); Console.WriteLine("Finished writing '" + outputFile.FullName + "'"); } public static void WriteJavaDoc() { NumberToTextConversionExamples.ExampleConversion[] exampleConversions = NumberToTextConversionExamples.GetExampleConversions(); for (int i = 0; i < exampleConversions.Length; i++) { NumberToTextConversionExamples.ExampleConversion ec = exampleConversions[i]; String line = " * <tr><td>" + FormatLongAsHex(ec.RawDoubleBits) + "</td><td>" + ec.DoubleValue.ToString() + "</td><td>" + ec.ExcelRendering + "</td></tr>"; Console.WriteLine(line); } } private static void ReplaceNaNs(byte[] fileContent, long[] ReplacementNaNs) { int countFound = 0; for (int i = 0; i < fileContent.Length; i++) { if (IsNaNBytes(fileContent, i)) { WriteLong(fileContent, i, ReplacementNaNs[countFound]); countFound++; } } if (countFound < ReplacementNaNs.Length) { throw new Exception("wrong repl count"); } } private static void WriteLong(byte[] bb, int i, long val) { String oldVal = InterpretLong(bb, i); bb[i + 7] = (byte)(val >> 56); bb[i + 6] = (byte)(val >> 48); bb[i + 5] = (byte)(val >> 40); bb[i + 4] = (byte)(val >> 32); bb[i + 3] = (byte)(val >> 24); bb[i + 2] = (byte)(val >> 16); bb[i + 1] = (byte)(val >> 8); bb[i + 0] = (byte)(val >> 0); //if (false) //{ // String newVal = interpretLong(bb, i); // Console.WriteLine("Changed offset " + i + " from " + oldVal + " to " + newVal); //} } private static String InterpretLong(byte[] fileContent, int offset) { Stream is1 = new MemoryStream(fileContent, offset, 8); long l; l = LittleEndian.ReadLong(is1); return "0x" + StringUtil.ToHexString(l).ToUpper(); } private static bool IsNaNBytes(byte[] fileContent, int offset) { if (offset + JAVA_NAN_BYTES.Length > fileContent.Length) { return false; } // excel NaN bits: 0xFFFF0420003C0000L // java NaN bits :0x7ff8000000000000L return AreArraySectionsEqual(fileContent, offset, JAVA_NAN_BYTES); } private static bool AreArraySectionsEqual(byte[] bb, int off, byte[] section) { for (int i = section.Length - 1; i >= 0; i--) { if (bb[off + i] != section[i]) { return false; } } return true; } } }
#nullable enable using System; using System.Collections.Generic; using System.Linq; using Content.Shared.GameObjects.Components.Instruments; using Content.Shared.Physics; using Robust.Client.Audio.Midi; using Robust.Shared.Audio.Midi; using Robust.Shared.GameObjects; using Robust.Shared.GameObjects.Components.Timers; using Robust.Shared.Interfaces.Network; using Robust.Shared.Interfaces.Timing; using Robust.Shared.IoC; using Robust.Shared.Players; using Robust.Shared.Serialization; using Robust.Shared.Timers; using Robust.Shared.ViewVariables; namespace Content.Client.GameObjects.Components.Instruments { [RegisterComponent] public class InstrumentComponent : SharedInstrumentComponent { /// <summary> /// Called when a midi song stops playing. /// </summary> public event Action? OnMidiPlaybackEnded; [Dependency] private readonly IMidiManager _midiManager = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly IClientNetManager _netManager = default!; private IMidiRenderer? _renderer; private byte _instrumentProgram = 1; private byte _instrumentBank; private uint _sequenceDelay; private uint _sequenceStartTick; private bool _allowPercussion; private bool _allowProgramChange; /// <summary> /// A queue of MidiEvents to be sent to the server. /// </summary> [ViewVariables] private readonly List<MidiEvent> _midiEventBuffer = new List<MidiEvent>(); /// <summary> /// Whether a midi song will loop or not. /// </summary> [ViewVariables(VVAccess.ReadWrite)] public bool LoopMidi { get => _renderer?.LoopMidi ?? false; set { if (_renderer != null) { _renderer.LoopMidi = value; } } } /// <summary> /// Changes the instrument the midi renderer will play. /// </summary> [ViewVariables(VVAccess.ReadWrite)] public override byte InstrumentProgram { get => _instrumentProgram; set { _instrumentProgram = value; if (_renderer != null) { _renderer.MidiProgram = _instrumentProgram; } } } /// <summary> /// Changes the instrument bank the midi renderer will use. /// </summary> [ViewVariables(VVAccess.ReadWrite)] public override byte InstrumentBank { get => _instrumentBank; set { _instrumentBank = value; if (_renderer != null) { _renderer.MidiBank = _instrumentBank; } } } [ViewVariables(VVAccess.ReadWrite)] public override bool AllowPercussion { get => _allowPercussion; set { _allowPercussion = value; if (_renderer != null) { _renderer.DisablePercussionChannel = !_allowPercussion; } } } [ViewVariables(VVAccess.ReadWrite)] public override bool AllowProgramChange { get => _allowProgramChange; set { _allowProgramChange = value; if (_renderer != null) { _renderer.DisableProgramChangeEvent = !_allowProgramChange; } } } /// <summary> /// Whether this instrument is handheld or not. /// </summary> [ViewVariables] public bool Handheld { get; set; } // TODO: Replace this by simply checking if the entity has an ItemComponent. /// <summary> /// Whether there's a midi song being played or not. /// </summary> [ViewVariables] public bool IsMidiOpen => _renderer?.Status == MidiRendererStatus.File; /// <summary> /// Whether the midi renderer is listening for midi input or not. /// </summary> [ViewVariables] public bool IsInputOpen => _renderer?.Status == MidiRendererStatus.Input; /// <summary> /// Whether the midi renderer is alive or not. /// </summary> [ViewVariables] public bool IsRendererAlive => _renderer != null; public override void Initialize() { base.Initialize(); IoCManager.InjectDependencies(this); } protected virtual void SetupRenderer(bool fromStateChange = false) { if (IsRendererAlive) return; _sequenceDelay = 0; _sequenceStartTick = 0; _midiManager.OcclusionCollisionMask = (int) CollisionGroup.Impassable; _renderer = _midiManager.GetNewRenderer(); if (_renderer != null) { _renderer.MidiBank = _instrumentBank; _renderer.MidiProgram = _instrumentProgram; _renderer.TrackingEntity = Owner; _renderer.DisablePercussionChannel = !_allowPercussion; _renderer.DisableProgramChangeEvent = !_allowProgramChange; _renderer.OnMidiPlayerFinished += () => { OnMidiPlaybackEnded?.Invoke(); EndRenderer(fromStateChange); }; } if (!fromStateChange) { SendNetworkMessage(new InstrumentStartMidiMessage()); } } protected void EndRenderer(bool fromStateChange = false) { if (IsInputOpen) { CloseInput(fromStateChange); return; } if (IsMidiOpen) { CloseMidi(fromStateChange); return; } _renderer?.StopAllNotes(); var renderer = _renderer; // We dispose of the synth two seconds from now to allow the last notes to stop from playing. Owner.SpawnTimer(2000, () => { renderer?.Dispose(); }); _renderer = null; _midiEventBuffer.Clear(); if (!fromStateChange) { SendNetworkMessage(new InstrumentStopMidiMessage()); } } protected override void Shutdown() { base.Shutdown(); EndRenderer(); } public override void ExposeData(ObjectSerializer serializer) { base.ExposeData(serializer); serializer.DataField(this, x => Handheld, "handheld", false); serializer.DataField(ref _instrumentProgram, "program", (byte) 1); serializer.DataField(ref _instrumentBank, "bank", (byte) 0); serializer.DataField(ref _allowPercussion, "allowPercussion", false); serializer.DataField(ref _allowProgramChange, "allowProgramChange", false); } public override void HandleNetworkMessage(ComponentMessage message, INetChannel channel, ICommonSession? session = null) { base.HandleNetworkMessage(message, channel, session); switch (message) { case InstrumentMidiEventMessage midiEventMessage: if (IsRendererAlive) { // If we're the ones sending the MidiEvents, we ignore this message. if (IsInputOpen || IsMidiOpen) break; } else { // if we haven't started or finished some sequence if (_sequenceStartTick == 0) { // we may have arrived late SetupRenderer(true); } // might be our own notes after we already finished playing return; } if (_sequenceStartTick <= 0) { _sequenceStartTick = midiEventMessage.MidiEvent .Min(x => x.Tick) - 1; } var sqrtLag = MathF.Sqrt(_netManager.ServerChannel!.Ping / 1000f); var delay = (uint) (_renderer!.SequencerTimeScale * (.2 + sqrtLag)); var delta = delay - _sequenceStartTick; _sequenceDelay = Math.Max(_sequenceDelay, delta); var currentTick = _renderer.SequencerTick; // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < midiEventMessage.MidiEvent.Length; i++) { var ev = midiEventMessage.MidiEvent[i]; var scheduled = ev.Tick + _sequenceDelay; if (scheduled <= currentTick) { _sequenceDelay += currentTick - ev.Tick; scheduled = ev.Tick + _sequenceDelay; } _renderer?.ScheduleMidiEvent(ev, scheduled, true); } break; case InstrumentStartMidiMessage _: { SetupRenderer(true); break; } case InstrumentStopMidiMessage _: { EndRenderer(true); break; } } } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) { base.HandleComponentState(curState, nextState); if (!(curState is InstrumentState state)) return; if (state.Playing) { SetupRenderer(true); } else { EndRenderer(true); } AllowPercussion = state.AllowPercussion; AllowProgramChange = state.AllowProgramChange; InstrumentBank = state.InstrumentBank; InstrumentProgram = state.InstrumentProgram; } /// <inheritdoc cref="MidiRenderer.OpenInput"/> public bool OpenInput() { SetupRenderer(); if (_renderer != null && _renderer.OpenInput()) { _renderer.OnMidiEvent += RendererOnMidiEvent; return true; } return false; } /// <inheritdoc cref="MidiRenderer.CloseInput"/> public bool CloseInput(bool fromStateChange = false) { if (_renderer == null || !_renderer.CloseInput()) { return false; } EndRenderer(fromStateChange); return true; } /// <inheritdoc cref="MidiRenderer.OpenMidi(string)"/> public bool OpenMidi(string filename) { SetupRenderer(); if (_renderer == null || !_renderer.OpenMidi(filename)) { return false; } _renderer.OnMidiEvent += RendererOnMidiEvent; return true; } /// <inheritdoc cref="MidiRenderer.CloseMidi"/> public bool CloseMidi(bool fromStateChange = false) { if (_renderer == null || !_renderer.CloseMidi()) { return false; } EndRenderer(fromStateChange); return true; } /// <summary> /// Called whenever the renderer receives a midi event. /// </summary> /// <param name="midiEvent">The received midi event</param> private void RendererOnMidiEvent(MidiEvent midiEvent) { // avoid of out-of-band, unimportant or unsupported events switch (midiEvent.Type) { case 0x80: // NOTE_OFF case 0x90: // NOTE_ON case 0xa0: // KEY_PRESSURE case 0xb0: // CONTROL_CHANGE case 0xd0: // CHANNEL_PRESSURE case 0xe0: // PITCH_BEND break; default: return; } _midiEventBuffer.Add(midiEvent); } private TimeSpan _lastMeasured = TimeSpan.MinValue; private int _sentWithinASec; private static readonly TimeSpan OneSecAgo = TimeSpan.FromSeconds(-1); private static readonly Comparer<MidiEvent> SortMidiEventTick = Comparer<MidiEvent>.Create((x, y) => x.Tick.CompareTo(y.Tick)); public override void Update(float delta) { if (!IsMidiOpen && !IsInputOpen) return; var now = _gameTiming.RealTime; var oneSecAGo = now.Add(OneSecAgo); if (_lastMeasured <= oneSecAGo) { _lastMeasured = now; _sentWithinASec = 0; } if (_midiEventBuffer.Count == 0) return; var max = Math.Min(MaxMidiEventsPerBatch, MaxMidiEventsPerSecond - _sentWithinASec); if (max <= 0) { // hit event/sec limit, have to lag the batch or drop events return; } // fix cross-fade events generating retroactive events // also handle any significant backlog of events after midi finished _midiEventBuffer.Sort(SortMidiEventTick); var bufferTicks = IsRendererAlive && _renderer!.Status != MidiRendererStatus.None ? _renderer.SequencerTimeScale * .2f : 0; var bufferedTick = IsRendererAlive ? _renderer!.SequencerTick - bufferTicks : int.MaxValue; var events = _midiEventBuffer .TakeWhile(x => x.Tick < bufferedTick) .Take(max) .ToArray(); var eventCount = events.Length; if (eventCount == 0) return; SendNetworkMessage(new InstrumentMidiEventMessage(events)); _sentWithinASec += eventCount; _midiEventBuffer.RemoveRange(0, eventCount); } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using HtmlHelp; namespace HtmlHelp.UIComponents { /// <summary> /// The class <c>TocTree</c> implements a user control which displays the HtmlHelp table of contents pane to the user. /// </summary> public class TocTree : System.Windows.Forms.UserControl { /// <summary> /// Event if the user changes the selection in the toc tree /// </summary> public event TocSelectedEventHandler TocSelected; private System.Windows.Forms.TreeView tocTreeView; private System.Windows.Forms.ImageList hhImages; private System.ComponentModel.IContainer components; /// <summary> /// Constructor of the class /// </summary> public TocTree() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); ReloadImageList(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tocTreeView = new System.Windows.Forms.TreeView(); this.hhImages = new System.Windows.Forms.ImageList(this.components); this.SuspendLayout(); // // tocTreeView // this.tocTreeView.HideSelection = false; this.tocTreeView.ImageIndex = 0; this.tocTreeView.ImageList = this.hhImages; this.tocTreeView.Location = new System.Drawing.Point(5, 5); this.tocTreeView.Name = "tocTreeView"; this.tocTreeView.SelectedImageIndex = 0; this.tocTreeView.Size = new System.Drawing.Size(263, 329); this.tocTreeView.TabIndex = 0; this.tocTreeView.AfterCollapse += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterCollapse); this.tocTreeView.AfterExpand += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterExpand); this.tocTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterSelect); // // hhImages // this.hhImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit; this.hhImages.ImageSize = new System.Drawing.Size(16, 16); this.hhImages.TransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); // // TocTree // this.Controls.Add(this.tocTreeView); this.Name = "TocTree"; this.Padding = new System.Windows.Forms.Padding(2); this.Size = new System.Drawing.Size(456, 394); this.ResumeLayout(false); } #endregion /// <summary> /// Fireing the on selected event /// </summary> /// <param name="e">event parameters</param> protected virtual void OnTocSelected(TocEventArgs e) { if(TocSelected != null) { TocSelected(this,e); } } /// <summary> /// Reloads the imagelist using the HtmlHelpSystem.UseHH2TreePics preference /// </summary> public void ReloadImageList() { ResourceHelper resHelper = new ResourceHelper( this.GetType().Assembly ); resHelper.DefaultBitmapNamespace = "Resources"; if(hhImages.Images.Count > 0) { hhImages.Images.Clear(); } hhImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit; if(HtmlHelpSystem.UseHH2TreePics) { hhImages.TransparentColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(64)), ((System.Byte)(0))); hhImages.Images.AddStrip(resHelper.LoadBitmap("ContentTree.bmp")); } else { hhImages.TransparentColor = Color.Fuchsia; hhImages.Images.AddStrip(resHelper.LoadBitmap("HH11.bmp")); } } /// <summary> /// Clears the items displayed in the toc pane /// </summary> public void ClearContents() { tocTreeView.Nodes.Clear(); } /// <summary> /// Call this method to build the table of contents (TOC) tree. /// </summary> /// <param name="tocItems">TOC instance (tree) extracted from the chm file</param> public void BuildTOC(TableOfContents tocItems) { BuildTOC(tocItems, null); } /// <summary> /// Call this method to build the table of contents (TOC) tree. /// </summary> /// <param name="tocItems">TOC instance (tree) extracted from the chm file</param> /// <param name="filter">information type/category filter</param> public void BuildTOC(TableOfContents tocItems, InfoTypeCategoryFilter filter) { tocTreeView.Nodes.Clear(); BuildTOC(tocItems.TOC, tocTreeView.Nodes, filter); tocTreeView.Update(); } /// <summary> /// Snychronizes the table of content tree with the currently displayed browser url. /// </summary> /// <param name="URL">url to search</param> public void Synchronize(string URL) { string local = URL; string sFile = ""; if( URL.StartsWith(HtmlHelpSystem.UrlPrefix) ) { local = local.Substring(HtmlHelpSystem.UrlPrefix.Length); } if( local.IndexOf("::")>-1) { sFile = local.Substring(0, local.IndexOf("::")); local = local.Substring( local.IndexOf("::")+2 ); } SelectTOCItem(tocTreeView.Nodes, sFile, local); } /// <summary> /// Called if the user has expanded a tree item /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event parameter</param> private void tocTreeView_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e) { TOCItem curItem = (TOCItem)(e.Node.Tag); if(curItem != null) { if(HtmlHelpSystem.UseHH2TreePics) { if(curItem.ImageIndex <= 15) { e.Node.ImageIndex = curItem.ImageIndex+2; e.Node.SelectedImageIndex = curItem.ImageIndex+2; } } else { if(curItem.ImageIndex < 8) { e.Node.ImageIndex = curItem.ImageIndex+1; e.Node.SelectedImageIndex = curItem.ImageIndex+1; } } } } /// <summary> /// Called if the user has collapsed a tree item /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event parameter</param> private void tocTreeView_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e) { TOCItem curItem = (TOCItem)(e.Node.Tag); if(curItem != null) { if(HtmlHelpSystem.UseHH2TreePics) { if(curItem.ImageIndex <= 15) { e.Node.ImageIndex = curItem.ImageIndex; e.Node.SelectedImageIndex = curItem.ImageIndex; } } else { if(curItem.ImageIndex < 8) { e.Node.ImageIndex = curItem.ImageIndex; e.Node.SelectedImageIndex = curItem.ImageIndex; } } } } /// <summary> /// Called if the user selects a tree item. /// This method will fire the <c>TocSelected</c> event notifying the parent window, that the user whants /// to view a new help topic. /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event parameter</param> private void tocTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { OnTocSelected( new TocEventArgs((TOCItem)(e.Node.Tag)) ); } /// <summary> /// Selects a node identified by its chm file and local /// </summary> /// <param name="col">treenode collection to search</param> /// <param name="chmFile">chm filename</param> /// <param name="local">local of the toc item</param> private void SelectTOCItem(TreeNodeCollection col, string chmFile, string local) { foreach(TreeNode curNode in col) { TOCItem curItem = curNode.Tag as TOCItem; if(curItem!=null) { if((curItem.Local == local)||(("/"+curItem.Local) == local)) { if(chmFile.Length>0) { if(curItem.AssociatedFile.ChmFilePath == chmFile) { tocTreeView.SelectedNode = curNode; return; } } else { tocTreeView.SelectedNode = curNode; return; } } } SelectTOCItem(curNode.Nodes, chmFile, local); } } /// <summary> /// Recursively builds the toc tree and fills the treeview /// </summary> /// <param name="tocItems">list of toc-items</param> /// <param name="col">treenode collection of the current level</param> /// <param name="filter">information type/category filter</param> private void BuildTOC(ArrayList tocItems, TreeNodeCollection col, InfoTypeCategoryFilter filter) { foreach( TOCItem curItem in tocItems ) { bool bAdd = true; if(filter!=null) { bAdd=false; if(curItem.InfoTypeStrings.Count <= 0) { bAdd=true; } else { for(int i=0;i<curItem.InfoTypeStrings.Count;i++) { bAdd |= filter.Match( curItem.InfoTypeStrings[i].ToString() ); } } } if(bAdd) { TreeNode newNode = new TreeNode( curItem.Name, curItem.ImageIndex, curItem.ImageIndex ); newNode.Tag = curItem; if(curItem.Children.Count > 0) { BuildTOC(curItem.Children, newNode.Nodes, filter); } // check if we have a book/folder which doesn't have any children // after applied filter. if( (curItem.Children.Count > 0) && (newNode.Nodes.Count <= 0) ) { // check if the item has a local value // if not, this don't display this item in the tree if( curItem.Local.Length > 0) { col.Add(newNode); } } else { col.Add(newNode); } } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; #if DEBUG using System.Diagnostics; #endif using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Base type of all asynchronous tagger providers (<see cref="ITaggerProvider"/> and <see cref="IViewTaggerProvider"/>). /// </summary> internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> where TTag : ITag { private readonly object _uniqueKey = new object(); private readonly IAsynchronousOperationListener _asyncListener; private readonly IForegroundNotificationService _notificationService; /// <summary> /// The behavior the tagger engine will have when text changes happen to the subject buffer /// it is attached to. Most taggers can simply use <see cref="TaggerTextChangeBehavior.None"/>. /// However, advanced taggers that want to perform specialized behavior depending on what has /// actually changed in the file can specify <see cref="TaggerTextChangeBehavior.TrackTextChanges"/>. /// /// If this is specified the tagger engine will track text changes and pass them along as /// <see cref="TaggerContext{TTag}.TextChangeRange"/> when calling /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.None; /// <summary> /// The bahavior the tagger will have when changes happen to the caret. /// </summary> protected virtual TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.None; /// <summary> /// The behavior of tags that are created by the async tagger. This will matter for tags /// created for a previous version of a document that are mapped forward by the async /// tagging architecture. This value cannot be <see cref="SpanTrackingMode.Custom"/>. /// </summary> protected virtual SpanTrackingMode SpanTrackingMode => SpanTrackingMode.EdgeExclusive; /// <summary> /// Comparer used to determine if two <see cref="ITag"/>s are the same. This is used by /// the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> to determine if a previous set of /// computed tags and a current set of computed tags should be considered the same or not. /// If they are the same, then the UI will not be updated. If they are different then /// the UI will be updated for sets of tags that have been removed or added. /// </summary> protected virtual IEqualityComparer<TTag> TagComparer => EqualityComparer<TTag>.Default; /// <summary> /// Options controlling this tagger. The tagger infrastructure will check this option /// against the buffer it is associated with to see if it should tag or not. /// /// An empty enumerable, or null, can be returned to indicate that this tagger should /// run unconditionally. /// </summary> protected virtual IEnumerable<Option<bool>> Options => SpecializedCollections.EmptyEnumerable<Option<bool>>(); protected virtual IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.EmptyEnumerable<PerLanguageOption<bool>>(); #if DEBUG public readonly string StackTrace; #endif protected AbstractAsynchronousTaggerProvider( IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService) { _asyncListener = asyncListener; _notificationService = notificationService; #if DEBUG StackTrace = new StackTrace().ToString(); #endif } private TagSource CreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return new TagSource(textViewOpt, subjectBuffer, this, _asyncListener, _notificationService); } internal IAccurateTagger<T> GetOrCreateTagger<T>(ITextView textViewOpt, ITextBuffer subjectBuffer) where T : ITag { if (!subjectBuffer.GetOption(EditorComponentOnOffOptions.Tagger)) { return null; } var tagSource = GetOrCreateTagSource(textViewOpt, subjectBuffer); return tagSource == null ? null : new Tagger(this._asyncListener, this._notificationService, tagSource, subjectBuffer) as IAccurateTagger<T>; } private TagSource GetOrCreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { TagSource tagSource; if (!this.TryRetrieveTagSource(textViewOpt, subjectBuffer, out tagSource)) { tagSource = this.CreateTagSource(textViewOpt, subjectBuffer); if (tagSource == null) { return null; } this.StoreTagSource(textViewOpt, subjectBuffer, tagSource); tagSource.Disposed += (s, e) => this.RemoveTagSource(textViewOpt, subjectBuffer); } return tagSource; } private bool TryRetrieveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, out TagSource tagSource) { return textViewOpt != null ? textViewOpt.TryGetPerSubjectBufferProperty(subjectBuffer, _uniqueKey, out tagSource) : subjectBuffer.Properties.TryGetProperty(_uniqueKey, out tagSource); } private void RemoveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { if (textViewOpt != null) { textViewOpt.RemovePerSubjectBufferProperty<TagSource, ITextView>(subjectBuffer, _uniqueKey); } else { subjectBuffer.Properties.RemoveProperty(_uniqueKey); } } private void StoreTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, TagSource tagSource) { if (textViewOpt != null) { textViewOpt.AddPerSubjectBufferProperty(subjectBuffer, _uniqueKey, tagSource); } else { subjectBuffer.Properties.AddProperty(_uniqueKey, tagSource); } } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to /// determine the caret position. This value will be passed in as the value to /// <see cref="TaggerContext{TTag}.CaretPosition"/> in the call to /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer) { return textViewOpt?.GetCaretPoint(subjectBuffer); } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to determine /// the set of spans that it should asynchronously tag. This will be called in response to /// notifications from the <see cref="ITaggerEventSource"/> that something has changed, and /// will only be called from the UI thread. The tagger infrastructure will then determine /// the <see cref="DocumentSnapshotSpan"/>s associated with these <see cref="SnapshotSpan"/>s /// and will asycnhronously call into <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> at some point in /// the future to produce tags for these spans. /// </summary> protected virtual IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer) { // For a standard tagger, the spans to tag is the span of the entire snapshot. return new[] { subjectBuffer.CurrentSnapshot.GetFullSpan() }; } /// <summary> /// Creates the <see cref="ITaggerEventSource"/> that notifies the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> /// that it should recompute tags for the text buffer after an appropriate <see cref="TaggerDelay"/>. /// </summary> protected abstract ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer); internal Task ProduceTagsAsync_ForTestingPurposesOnly(TaggerContext<TTag> context) { return ProduceTagsAsync(context); } /// <summary> /// Produce tags for the given context. /// </summary> protected virtual async Task ProduceTagsAsync(TaggerContext<TTag> context) { foreach (var spanToTag in context.SpansToTag) { context.CancellationToken.ThrowIfCancellationRequested(); await ProduceTagsAsync(context, spanToTag, GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan)).ConfigureAwait(false); } } private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan) { return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot ? caretPosition.Value.Position : (int?)null; } protected virtual Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { return SpecializedTasks.EmptyTask; } } }
// 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.AcceptanceTestsBodyBoolean { using Microsoft.Rest; using Models; /// <summary> /// BoolModel operations. /// </summary> public partial class BoolModel : Microsoft.Rest.IServiceOperations<AutoRestBoolTestService>, IBoolModel { /// <summary> /// Initializes a new instance of the BoolModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public BoolModel(AutoRestBoolTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestBoolTestService /// </summary> public AutoRestBoolTestService Client { get; private set; } /// <summary> /// Get true Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<bool?>> GetTrueWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetTrue", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/true").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Set Boolean value true /// </summary> /// <param name='boolBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutTrueWithHttpMessagesAsync(bool boolBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("boolBody", boolBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutTrue", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/true").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get false Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<bool?>> GetFalseWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetFalse", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/false").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Set Boolean value false /// </summary> /// <param name='boolBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutFalseWithHttpMessagesAsync(bool boolBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("boolBody", boolBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutFalse", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/false").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get null Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<bool?>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/null").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<bool?>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/invalid").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; namespace ICSimulator { public class SortNode { public delegate int Steer(Flit f); public delegate int Rank(Flit f1, Flit f2); Steer m_s; Rank m_r; public Flit in_0, in_1, out_0, out_1; public SortNode(Steer s, Rank r) { m_s = s; m_r = r; } public void doStep() { Flit winner, loser; if (m_r(in_0, in_1) < 0) { winner = in_0; loser = in_1; } else { loser = in_0; winner = in_1; } if (winner != null) winner.sortnet_winner = true; if (loser != null) loser.sortnet_winner = false; int dir = m_s(winner); if (dir == 0) { out_0 = winner; out_1 = loser; } else { out_0 = loser; out_1 = winner; } } } public abstract class SortNet { public abstract void route(Flit[] input, out bool injected); } public class SortNet_CALF : SortNet { SortNode[] nodes; public SortNet_CALF(SortNode.Rank r) { nodes = new SortNode[4]; SortNode.Steer stage1_steer = delegate(Flit f) { if (f == null) return 0; return (f.prefDir == Simulator.DIR_UP || f.prefDir == Simulator.DIR_DOWN) ? 0 : // NS switch 1; // EW switch }; // node 0: {N,E} -> {NS, EW} nodes[0] = new SortNode(stage1_steer, r); // node 1: {S,W} -> {NS, EW} nodes[1] = new SortNode(stage1_steer, r); // node 2: {in_top,in_bottom} -> {N,S} nodes[2] = new SortNode(delegate(Flit f) { if (f == null) return 0; return (f.prefDir == Simulator.DIR_UP) ? 0 : 1; }, r); // node 3: {in_top,in_bottm} -> {E,W} nodes[3] = new SortNode(delegate(Flit f) { if (f == null) return 0; return (f.prefDir == Simulator.DIR_RIGHT) ? 0 : 1; }, r); } // takes Flit[5] as input; indices DIR_{UP,DOWN,LEFT,RIGHT} and 4 for local. // permutes in-place. input[4] is left null; if flit was injected, 'injected' is set to true. public override void route(Flit[] input, out bool injected) { injected = false; if (!Config.calf_new_inj_ej) { // injection: if free slot, insert flit if (input[4] != null) { for (int i = 0; i < 4; i++) if (input[i] == null) { input[i] = input[4]; injected = true; break; } input[4] = null; } } if (Config.sortnet_twist) { nodes[0].in_0 = input[Simulator.DIR_UP]; nodes[0].in_1 = input[Simulator.DIR_RIGHT]; nodes[1].in_0 = input[Simulator.DIR_DOWN]; nodes[1].in_1 = input[Simulator.DIR_LEFT]; } else { nodes[0].in_0 = input[Simulator.DIR_UP]; nodes[0].in_1 = input[Simulator.DIR_DOWN]; nodes[1].in_0 = input[Simulator.DIR_LEFT]; nodes[1].in_1 = input[Simulator.DIR_RIGHT]; } nodes[0].doStep(); nodes[1].doStep(); nodes[2].in_0 = nodes[0].out_0; nodes[2].in_1 = nodes[1].out_0; nodes[3].in_0 = nodes[0].out_1; nodes[3].in_1 = nodes[1].out_1; nodes[2].doStep(); nodes[3].doStep(); input[Simulator.DIR_UP] = nodes[2].out_0; input[Simulator.DIR_DOWN] = nodes[2].out_1; input[Simulator.DIR_RIGHT] = nodes[3].out_0; input[Simulator.DIR_LEFT] = nodes[3].out_1; } } public class SortNet_COW : SortNet // Cheap Ordered Wiring? { SortNode[] nodes; public SortNet_COW(SortNode.Rank r) { nodes = new SortNode[6]; SortNode.Steer stage1_steer = delegate(Flit f) { if (f == null) return 0; return (f.sortnet_winner) ? 0 : 1; }; SortNode.Steer stage2_steer = delegate(Flit f) { if (f == null) return 0; return (f.prefDir == Simulator.DIR_UP || f.prefDir == Simulator.DIR_RIGHT) ? 0 : 1; }; nodes[0] = new SortNode(stage1_steer, r); nodes[1] = new SortNode(stage1_steer, r); nodes[2] = new SortNode(stage2_steer, r); nodes[3] = new SortNode(stage2_steer, r); nodes[4] = new SortNode(delegate(Flit f) { if (f == null) return 0; return (f.prefDir == Simulator.DIR_UP) ? 0 : 1; }, r); nodes[5] = new SortNode(delegate(Flit f) { if (f == null) return 0; return (f.prefDir == Simulator.DIR_DOWN) ? 0 : 1; }, r); } // takes Flit[5] as input; indices DIR_{UP,DOWN,LEFT,RIGHT} and 4 for local. // permutes in-place. input[4] is left null; if flit was injected, 'injected' is set to true. public override void route(Flit[] input, out bool injected) { injected = false; if (!Config.calf_new_inj_ej) { // injection: if free slot, insert flit if (input[4] != null) { for (int i = 0; i < 4; i++) if (input[i] == null) { input[i] = input[4]; injected = true; break; } input[4] = null; } } // NS, EW -> NS, EW if (!Config.sortnet_twist) { nodes[0].in_0 = input[Simulator.DIR_UP]; nodes[0].in_1 = input[Simulator.DIR_RIGHT]; nodes[1].in_0 = input[Simulator.DIR_DOWN]; nodes[1].in_1 = input[Simulator.DIR_LEFT]; } else { nodes[0].in_0 = input[Simulator.DIR_UP]; nodes[0].in_1 = input[Simulator.DIR_DOWN]; nodes[1].in_0 = input[Simulator.DIR_LEFT]; nodes[1].in_1 = input[Simulator.DIR_RIGHT]; } nodes[0].doStep(); nodes[1].doStep(); nodes[2].in_0 = nodes[0].out_0; nodes[3].in_0 = nodes[1].out_0; nodes[3].in_1 = nodes[0].out_1; nodes[2].in_1 = nodes[1].out_1; nodes[2].doStep(); nodes[3].doStep(); nodes[4].in_0 = nodes[2].out_0; nodes[4].in_1 = nodes[3].out_0; nodes[5].in_0 = nodes[2].out_1; nodes[5].in_1 = nodes[3].out_1; nodes[4].doStep(); nodes[5].doStep(); input[Simulator.DIR_UP] = nodes[4].out_0; input[Simulator.DIR_RIGHT] = nodes[4].out_1; input[Simulator.DIR_DOWN] = nodes[5].out_0; input[Simulator.DIR_LEFT] = nodes[5].out_1; } } public abstract class Router_SortNet : Router { // injectSlot is from Node; injectSlot2 is higher-priority from // network-level re-injection (e.g., placeholder schemes) protected Flit m_injectSlot, m_injectSlot2; Queue<Flit>[] ejectBuffer; SortNet m_sort; public Router_SortNet(Coord myCoord) : base(myCoord) { m_injectSlot = null; m_injectSlot2 = null; ejectBuffer = new Queue<Flit>[4]; for (int n =0 ;n < 4; n++) ejectBuffer[n] = new Queue<Flit>(); if (Config.sortnet_full) m_sort = new SortNet_COW(new SortNode.Rank(rank)); else m_sort = new SortNet_CALF(new SortNode.Rank(rank)); if (!Config.edge_loop) throw new Exception("SortNet (CALF) router does not support mesh without edge loop. Use -edge_loop option."); } Flit handleGolden(Flit f) { if (f == null) return f; if (f.state == Flit.State.Normal) return f; if (f.state == Flit.State.Rescuer) { if (m_injectSlot == null) { m_injectSlot = f; f.state = Flit.State.Placeholder; } else m_injectSlot.state = Flit.State.Carrier; return null; } if (f.state == Flit.State.Carrier) { f.state = Flit.State.Normal; Flit newPlaceholder = new Flit(null, 0); newPlaceholder.state = Flit.State.Placeholder; if (m_injectSlot != null) m_injectSlot2 = newPlaceholder; else m_injectSlot = newPlaceholder; return f; } if (f.state == Flit.State.Placeholder) throw new Exception("Placeholder should never be ejected!"); return null; } // accept one ejected flit into rxbuf void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } Flit ejectLocal() { // eject locally-destined flit (highest-ranked, if multiple) Flit ret = null; int bestDir = -1; for (int dir = 0; dir < 4; dir++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.state != Flit.State.Placeholder && linkIn[dir].Out.dest.ID == ID && (ret == null || rank(linkIn[dir].Out, ret) < 0)) { ret = linkIn[dir].Out; bestDir = dir; } if (bestDir != -1) linkIn[bestDir].Out = null; #if DEBUG if (ret != null) Console.WriteLine("ejecting flit {0}.{1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound); #endif ret = handleGolden(ret); return ret; } Flit[] m_ej = new Flit[4] { null, null, null, null }; int m_ej_rr = 0; Flit ejectLocalNew() { for (int dir = 0; dir < 4; dir++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.dest.ID == ID && m_ej[dir] == null) { m_ej[dir] = linkIn[dir].Out; linkIn[dir].Out = null; } m_ej_rr++; m_ej_rr %= 4; Flit ret = null; if (m_ej[m_ej_rr] != null) { ret = m_ej[m_ej_rr]; m_ej[m_ej_rr] = null; } return ret; } Flit[] input = new Flit[5]; // keep this as a member var so we don't // have to allocate on every step (why can't // we have arrays on the stack like in C?) protected override void _doStep() { if (Config.InfEjectBuffer) { for (int dir = 0; dir < 4; dir ++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.packet.dest.ID == ID) { ejectBuffer[dir].Enqueue(linkIn[dir].Out); linkIn[dir].Out = null; } int bestdir = -1; for (int dir = 0; dir < 4; dir ++) if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Peek().injectionTime < ejectBuffer[bestdir].Peek().injectionTime)) bestdir = dir; if (bestdir != -1) acceptFlit(ejectBuffer[bestdir].Dequeue()); } else if (Config.EjectBufferSize != -1) { for (int dir =0; dir < 4; dir ++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.packet.dest.ID == ID && ejectBuffer[dir].Count < Config.EjectBufferSize) { ejectBuffer[dir].Enqueue(linkIn[dir].Out); linkIn[dir].Out = null; } int bestdir = -1; for (int dir = 0; dir < 4; dir ++) if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Peek().injectionTime < ejectBuffer[bestdir].Peek().injectionTime)) bestdir = dir; if (bestdir != -1) acceptFlit(ejectBuffer[bestdir].Dequeue()); } else { Flit eject = null; if (Config.calf_new_inj_ej) eject = ejectLocalNew(); else { Flit f1 = null,f2 = null; int flitsTryToEject = 0; for (int dir = 0; dir < 4; dir ++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.dest.ID == ID) flitsTryToEject ++; Simulator.stats.flitsTryToEject[flitsTryToEject].Add(); for (int i = 0; i < Config.meshEjectTrial; i++) { eject = ejectLocal(); if (i == 0) f1 = eject; else if (i == 1) f2 = eject; if (eject != null) acceptFlit(eject); } if (f1 != null && f2 != null && f1.packet == f2.packet) Simulator.stats.ejectsFromSamePacket.Add(1); else if (f1 != null && f2 != null) Simulator.stats.ejectsFromSamePacket.Add(0); } } for (int dir = 0; dir < 4; dir++) { if (linkIn[dir] != null && linkIn[dir].Out != null) { input[dir] = linkIn[dir].Out; input[dir].inDir = dir; } else input[dir] = null; } Flit inj = null; bool injected = false; if (m_injectSlot2 != null) { inj = m_injectSlot2; m_injectSlot2 = null; } else if (m_injectSlot != null) { inj = m_injectSlot; m_injectSlot = null; } input[4] = inj; if (inj != null) inj.inDir = -1; for (int i = 0; i < 5; i++) if (input[i] != null) { PreferredDirection pd = determineDirection(input[i]); if (pd.xDir != Simulator.DIR_NONE) input[i].prefDir = pd.xDir; else input[i].prefDir = pd.yDir; } m_sort.route(input, out injected); //Console.WriteLine("---"); for (int i = 0; i < 4; i++) { if (input[i] != null) { //Console.WriteLine("input dir {0} pref dir {1} output dir {2} age {3}", // input[i].inDir, input[i].prefDir, i, Router_Flit_OldestFirst.age(input[i])); input[i].Deflected = input[i].prefDir != i; } } if (Config.calf_new_inj_ej) { if (inj != null && input[inj.prefDir] == null) { input[inj.prefDir] = inj; injected = true; } } if (!injected) { if (m_injectSlot == null) m_injectSlot = inj; else m_injectSlot2 = inj; } else statsInjectFlit(inj); for (int dir = 0; dir < 4; dir++) if (input[dir] != null) { if (linkOut[dir] == null) throw new Exception(String.Format("router {0} does not have link in dir {1}", coord, dir)); linkOut[dir].In = input[dir]; } } public override bool canInjectFlit(Flit f) { return m_injectSlot == null; } public override void InjectFlit(Flit f) { if (m_injectSlot != null) throw new Exception("Trying to inject twice in one cycle"); m_injectSlot = f; } public override void visitFlits(Flit.Visitor fv) { if (m_injectSlot != null) fv(m_injectSlot); if (m_injectSlot2 != null) fv(m_injectSlot2); } //protected abstract int rank(Flit f1, Flit f2); } public class Router_SortNet_GP : Router_SortNet { public Router_SortNet_GP(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_GP._rank(f1, f2); } } public class Router_SortNet_OldestFirst : Router_SortNet { public Router_SortNet_OldestFirst(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_OldestFirst._rank(f1, f2); } } }
// 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.Net; using System.Diagnostics; using System.Data.SqlClient; using System.Collections.Generic; using Microsoft.Win32; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Test.Data.SqlClient { public static class NetUtils { // according to RFC 5737 (http://tools.ietf.org/html/rfc5737): The blocks 192.0.2.0/24 (TEST-NET-1), 198.51.100.0/24 (TEST-NET-2), // and 203.0.113.0/24 (TEST-NET-3) are provided for use in documentation and should not be in use by any public network private static readonly IPAddress[] s_testNets = new IPAddress[] { IPAddress.Parse("192.0.2.0"), IPAddress.Parse("198.51.100.0"), IPAddress.Parse("203.0.113.0") }; private const int TestNetAddressRangeLength = 256; public static readonly int NonExistingIPv4AddressCount = TestNetAddressRangeLength * s_testNets.Length; public static IPAddress GetNonExistingIPv4(int index) { if (index < 0 || index > NonExistingIPv4AddressCount) { throw new ArgumentOutOfRangeException("index"); } byte[] address = s_testNets[index / TestNetAddressRangeLength].GetAddressBytes(); Debug.Assert(address[3] == 0, "address ranges above must end with .0"); address[3] = checked((byte)(index % TestNetAddressRangeLength)); return new IPAddress(address); } public static IEnumerable<IPAddress> EnumerateIPv4Addresses(string hostName) { hostName = hostName.Trim(); if ((hostName == ".") || (string.Compare("(local)", hostName, StringComparison.OrdinalIgnoreCase) == 0)) { hostName = Dns.GetHostName(); } Task<IPAddress[]> task = Dns.GetHostAddressesAsync(hostName); IPAddress[] allAddresses = task.Result; foreach (var addr in allAddresses) { if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { yield return addr; } } } /// <summary> /// Splits data source into protocol, host name, instance name and port. /// /// Note that this algorithm does not cover all valid combinations of data source; only those we actually use in tests are supported now. /// Please update as needed. /// </summary> public static void ParseDataSource(string dataSource, out string protocol, out string hostName, out string instanceName, out int? port) { // check for protocol prefix int i = dataSource.IndexOf(':'); if (i >= 0) { protocol = dataSource.Substring(0, i); // remove the protocol dataSource = dataSource.Substring(i + 1); } else { protocol = null; } // check for server port i = dataSource.IndexOf(','); if (i >= 0) { // there is a port value in connection string port = int.Parse(dataSource.Substring(i + 1)); dataSource = dataSource.Substring(0, i); } else { port = null; } // check for the instance name i = dataSource.IndexOf('\\'); if (i >= 0) { instanceName = dataSource.Substring(i + 1); dataSource = dataSource.Substring(0, i); } else { instanceName = null; } // trim redundant whitespace dataSource = dataSource.Trim(); hostName = dataSource; } private static Dictionary<string, int> s_dataSourceToPortCache = new Dictionary<string, int>(); /// <summary> /// the method converts the regular connection string to one supported by MultiSubnetFailover (connect to the port, bypassing the browser) /// it does the following: /// * removes Failover Partner, if presents /// * removes the network library and protocol prefix (only TCP is supported) /// * if instance name is specified without port value, data source is replaced with "server, port" format instead of "server\name" /// /// Note that this method can create a connection to the server in case TCP port is needed. The port value is cached per data source, to avoid round trip to the server on next use. /// </summary> /// <param name="connectionString">original connection string, must be valid</param> /// <param name="replaceServerName">optionally, replace the (network) server name with a different one</param> /// <param name="originalServerName">holds the original server name on return</param> /// <returns>MultiSubnetFailover-enabled connection string builder</returns> public static SqlConnectionStringBuilder GetMultiSubnetFailoverConnectionString(string connectionString, string replaceServerName, out string originalServerName) { SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(connectionString); sb["Network Library"] = null; // MSF supports TCP only, no need to specify the protocol explicitly sb["Failover Partner"] = null; // not supported, remove it if present string protocol, instance; int? serverPort; ParseDataSource(sb.DataSource, out protocol, out originalServerName, out instance, out serverPort); // Note: protocol value is ignored, connection to the server will fail if TCP is not enabled on the server if (!serverPort.HasValue) { // to get server listener's TCP port, connect to it using the original string, with TCP protocol enforced // to improve stress performance, cache the port value to avoid round trip every time new connection string is needed lock (s_dataSourceToPortCache) { int cachedPort; string cacheKey = sb.DataSource; if (s_dataSourceToPortCache.TryGetValue(cacheKey, out cachedPort)) { serverPort = cachedPort; } else { string originalServerNameWithInstance = sb.DataSource; int protocolEndIndex = originalServerNameWithInstance.IndexOf(':'); if (protocolEndIndex >= 0) { originalServerNameWithInstance = originalServerNameWithInstance.Substring(protocolEndIndex + 1); } sb.DataSource = "tcp:" + originalServerNameWithInstance; string tcpConnectionString = sb.ConnectionString; using (SqlConnection con = new SqlConnection(tcpConnectionString)) { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "select [local_tcp_port] from sys.dm_exec_connections where [session_id] = @@SPID"; serverPort = Convert.ToInt32(cmd.ExecuteScalar()); } s_dataSourceToPortCache[cacheKey] = serverPort.Value; } } } // override it with user-provided one string retDataSource; if (replaceServerName != null) { retDataSource = replaceServerName; } else { retDataSource = originalServerName; } // reconstruct the connection string (with the new server name and port) // also, no protocol is needed since TCP is enforced anyway if MultiSubnetFailover is set to true Debug.Assert(serverPort.HasValue, "Server port must be initialized"); retDataSource += ", " + serverPort.Value; sb.DataSource = retDataSource; sb.MultiSubnetFailover = true; return sb; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type decimal with 3 columns and 3 rows. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct decmat3 : IEnumerable<decimal>, IEquatable<decmat3> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> public decimal m00; /// <summary> /// Column 0, Rows 1 /// </summary> public decimal m01; /// <summary> /// Column 0, Rows 2 /// </summary> public decimal m02; /// <summary> /// Column 1, Rows 0 /// </summary> public decimal m10; /// <summary> /// Column 1, Rows 1 /// </summary> public decimal m11; /// <summary> /// Column 1, Rows 2 /// </summary> public decimal m12; /// <summary> /// Column 2, Rows 0 /// </summary> public decimal m20; /// <summary> /// Column 2, Rows 1 /// </summary> public decimal m21; /// <summary> /// Column 2, Rows 2 /// </summary> public decimal m22; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public decmat3(decimal m00, decimal m01, decimal m02, decimal m10, decimal m11, decimal m12, decimal m20, decimal m21, decimal m22) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m20 = m20; this.m21 = m21; this.m22 = m22; } /// <summary> /// Constructs this matrix from a decmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0m; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0m; this.m20 = 0m; this.m21 = 0m; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a decmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0m; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0m; this.m20 = m.m20; this.m21 = m.m21; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a decmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0m; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0m; this.m20 = m.m20; this.m21 = m.m21; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a decmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = 0m; this.m21 = 0m; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a decmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a decmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a decmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = 0m; this.m21 = 0m; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a decmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a decmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decvec2 c0, decvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = 0m; this.m10 = c1.x; this.m11 = c1.y; this.m12 = 0m; this.m20 = 0m; this.m21 = 0m; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decvec2 c0, decvec2 c1, decvec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = 0m; this.m10 = c1.x; this.m11 = c1.y; this.m12 = 0m; this.m20 = c2.x; this.m21 = c2.y; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decvec3 c0, decvec3 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = 0m; this.m21 = 0m; this.m22 = 1m; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public decmat3(decvec3 c0, decvec3 c1, decvec3 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; } /// <summary> /// Creates a rotation matrix from a decquat. /// </summary> public decmat3(decquat q) : this(q.ToMat3) { } #endregion #region Explicit Operators /// <summary> /// Creates a rotation matrix from a decquat. /// </summary> public static explicit operator decmat3(decquat q) => q.ToMat3; #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public decimal[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 }, { m20, m21, m22 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public decimal[] Values1D => new[] { m00, m01, m02, m10, m11, m12, m20, m21, m22 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public decvec3 Column0 { get { return new decvec3(m00, m01, m02); } set { m00 = value.x; m01 = value.y; m02 = value.z; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public decvec3 Column1 { get { return new decvec3(m10, m11, m12); } set { m10 = value.x; m11 = value.y; m12 = value.z; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public decvec3 Column2 { get { return new decvec3(m20, m21, m22); } set { m20 = value.x; m21 = value.y; m22 = value.z; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public decvec3 Row0 { get { return new decvec3(m00, m10, m20); } set { m00 = value.x; m10 = value.y; m20 = value.z; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public decvec3 Row1 { get { return new decvec3(m01, m11, m21); } set { m01 = value.x; m11 = value.y; m21 = value.z; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public decvec3 Row2 { get { return new decvec3(m02, m12, m22); } set { m02 = value.x; m12 = value.y; m22 = value.z; } } /// <summary> /// Creates a quaternion from the rotational part of this matrix. /// </summary> public decquat ToQuaternion => decquat.FromMat3(this); #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static decmat3 Zero { get; } = new decmat3(0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m); /// <summary> /// Predefined all-ones matrix /// </summary> public static decmat3 Ones { get; } = new decmat3(1m, 1m, 1m, 1m, 1m, 1m, 1m, 1m, 1m); /// <summary> /// Predefined identity matrix /// </summary> public static decmat3 Identity { get; } = new decmat3(1m, 0m, 0m, 0m, 1m, 0m, 0m, 0m, 1m); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static decmat3 AllMaxValue { get; } = new decmat3(decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static decmat3 DiagonalMaxValue { get; } = new decmat3(decimal.MaxValue, 0m, 0m, 0m, decimal.MaxValue, 0m, 0m, 0m, decimal.MaxValue); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static decmat3 AllMinValue { get; } = new decmat3(decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static decmat3 DiagonalMinValue { get; } = new decmat3(decimal.MinValue, 0m, 0m, 0m, decimal.MinValue, 0m, 0m, 0m, decimal.MinValue); /// <summary> /// Predefined all-MinusOne matrix /// </summary> public static decmat3 AllMinusOne { get; } = new decmat3(decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne); /// <summary> /// Predefined diagonal-MinusOne matrix /// </summary> public static decmat3 DiagonalMinusOne { get; } = new decmat3(decimal.MinusOne, 0m, 0m, 0m, decimal.MinusOne, 0m, 0m, 0m, decimal.MinusOne); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<decimal> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m10; yield return m11; yield return m12; yield return m20; yield return m21; yield return m22; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (3 x 3 = 9). /// </summary> public int Count => 9; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public decimal this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m10; case 4: return m11; case 5: return m12; case 6: return m20; case 7: return m21; case 8: return m22; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m10 = value; break; case 4: this.m11 = value; break; case 5: this.m12 = value; break; case 6: this.m20 = value; break; case 7: this.m21 = value; break; case 8: this.m22 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public decimal this[int col, int row] { get { return this[col * 3 + row]; } set { this[col * 3 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(decmat3 rhs) => ((((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m12.Equals(rhs.m12) && m20.Equals(rhs.m20)) && (m21.Equals(rhs.m21) && m22.Equals(rhs.m22)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is decmat3 && Equals((decmat3) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(decmat3 lhs, decmat3 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(decmat3 lhs, decmat3 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m22.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public decmat3 Transposed => new decmat3(m00, m10, m20, m01, m11, m21, m02, m12, m22); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public decimal MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m10), m11), m12), m20), m21), m22); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public decimal MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m10), m11), m12), m20), m21), m22); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public decimal Length => (decimal)(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))).Sqrt(); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public decimal LengthSqr => ((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22))); /// <summary> /// Returns the sum of all fields. /// </summary> public decimal Sum => ((((m00 + m01) + m02) + (m10 + m11)) + ((m12 + m20) + (m21 + m22))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public decimal Norm => (decimal)(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))).Sqrt(); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public decimal Norm1 => ((((Math.Abs(m00) + Math.Abs(m01)) + Math.Abs(m02)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m12) + Math.Abs(m20)) + (Math.Abs(m21) + Math.Abs(m22)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public decimal Norm2 => (decimal)(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))).Sqrt(); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public decimal NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m22)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow(((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + Math.Pow((double)Math.Abs(m02), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m20), p)) + (Math.Pow((double)Math.Abs(m21), p) + Math.Pow((double)Math.Abs(m22), p)))), 1 / p); /// <summary> /// Returns determinant of this matrix. /// </summary> public decimal Determinant => m00 * (m11 * m22 - m21 * m12) - m10 * (m01 * m22 - m21 * m02) + m20 * (m01 * m12 - m11 * m02); /// <summary> /// Returns the adjunct of this matrix. /// </summary> public decmat3 Adjugate => new decmat3(m11 * m22 - m21 * m12, -m01 * m22 + m21 * m02, m01 * m12 - m11 * m02, -m10 * m22 + m20 * m12, m00 * m22 - m20 * m02, -m00 * m12 + m10 * m02, m10 * m21 - m20 * m11, -m00 * m21 + m20 * m01, m00 * m11 - m10 * m01); /// <summary> /// Returns the inverse of this matrix (use with caution). /// </summary> public decmat3 Inverse => Adjugate / Determinant; /// <summary> /// Executes a matrix-matrix-multiplication decmat3 * decmat2x3 -> decmat2x3. /// </summary> public static decmat2x3 operator*(decmat3 lhs, decmat2x3 rhs) => new decmat2x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12)); /// <summary> /// Executes a matrix-matrix-multiplication decmat3 * decmat3 -> decmat3. /// </summary> public static decmat3 operator*(decmat3 lhs, decmat3 rhs) => new decmat3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22)); /// <summary> /// Executes a matrix-matrix-multiplication decmat3 * decmat4x3 -> decmat4x3. /// </summary> public static decmat4x3 operator*(decmat3 lhs, decmat4x3 rhs) => new decmat4x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32), ((lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31) + lhs.m22 * rhs.m32)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static decvec3 operator*(decmat3 m, decvec3 v) => new decvec3(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z), ((m.m02 * v.x + m.m12 * v.y) + m.m22 * v.z)); /// <summary> /// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution). /// </summary> public static decmat3 operator/(decmat3 A, decmat3 B) => A * B.Inverse; /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static decmat3 CompMul(decmat3 A, decmat3 B) => new decmat3(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m20 * B.m20, A.m21 * B.m21, A.m22 * B.m22); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static decmat3 CompDiv(decmat3 A, decmat3 B) => new decmat3(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m20 / B.m20, A.m21 / B.m21, A.m22 / B.m22); /// <summary> /// Executes a component-wise + (add). /// </summary> public static decmat3 CompAdd(decmat3 A, decmat3 B) => new decmat3(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m20 + B.m20, A.m21 + B.m21, A.m22 + B.m22); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static decmat3 CompSub(decmat3 A, decmat3 B) => new decmat3(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m20 - B.m20, A.m21 - B.m21, A.m22 - B.m22); /// <summary> /// Executes a component-wise + (add). /// </summary> public static decmat3 operator+(decmat3 lhs, decmat3 rhs) => new decmat3(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m22 + rhs.m22); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static decmat3 operator+(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m22 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static decmat3 operator+(decimal lhs, decmat3 rhs) => new decmat3(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m22); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static decmat3 operator-(decmat3 lhs, decmat3 rhs) => new decmat3(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m22 - rhs.m22); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static decmat3 operator-(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m22 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static decmat3 operator-(decimal lhs, decmat3 rhs) => new decmat3(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m22); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static decmat3 operator/(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m22 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static decmat3 operator/(decimal lhs, decmat3 rhs) => new decmat3(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m22); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static decmat3 operator*(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m22 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static decmat3 operator*(decimal lhs, decmat3 rhs) => new decmat3(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m22); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat3 operator<(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m22 < rhs.m22); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat3 operator<(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m22 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat3 operator<(decimal lhs, decmat3 rhs) => new bmat3(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m22); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat3 operator<=(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m22 <= rhs.m22); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat3 operator<=(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m22 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat3 operator<=(decimal lhs, decmat3 rhs) => new bmat3(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m22); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat3 operator>(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m22 > rhs.m22); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat3 operator>(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m22 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat3 operator>(decimal lhs, decmat3 rhs) => new bmat3(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m22); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat3 operator>=(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m22 >= rhs.m22); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat3 operator>=(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m22 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat3 operator>=(decimal lhs, decmat3 rhs) => new bmat3(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m22); } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; namespace DotSpatial.Data { /// <summary> /// This can be used as a component to work as a DataManager. This also provides the very important DefaultDataManager property, /// which is where the developer controls what DataManager should be used for their project. /// </summary> public class DataManager : IDataManager { #region Private Variables // If this doesn't exist, a new one is created when you "get" this data manager. private static IDataManager defaultDataManager; private IEnumerable<IDataProvider> _dataProviders; private string _dialogReadFilter; private string _dialogWriteFilter; private string _imageReadFilter; private string _imageWriteFilter; private string _rasterReadFilter; private string _rasterWriteFilter; private string _vectorReadFilter; private string _vectorWriteFilter; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DataManager"/> class. /// A data manager is more or less just a list of data providers to use. The very important /// DataManager.DefaultDataManager property controls which DataManager will be used /// to load data. By default, each DataManager sets itself as the default in its constructor. /// </summary> public DataManager() { Configure(); } #endregion #region Events /// <summary> /// Occurs after the directory providers have been loaded into the project. /// </summary> public event EventHandler<DataProviderEventArgs> DirectoryProvidersLoaded; #endregion #region Properties /// <summary> /// Gets or sets the implementation of IDataManager for the project to use when accessing data. /// This is THE place where the DataManager can be replaced by a different data manager. /// If you add this data manager to your project, this will automatically set itself as the DefaultDataManager. /// However, since each DM will do this, you may have to control this manually /// if you add more than one DataManager to the project in order to set the one that will be chosen. /// </summary> public static IDataManager DefaultDataManager { get { return defaultDataManager ?? (defaultDataManager = new DataManager()); } set { defaultDataManager = value; } } /// <summary> /// Gets or sets the list of IDataProviders that should be used in the project. /// </summary> [Browsable(false)] [ImportMany(AllowRecomposition = true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IEnumerable<IDataProvider> DataProviders { get { return _dataProviders; } set { _dataProviders = value; _imageReadFilter = null; _imageWriteFilter = null; _rasterReadFilter = null; _rasterWriteFilter = null; _vectorReadFilter = null; _vectorWriteFilter = null; OnProvidersLoaded(value); } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open files.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string DialogReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_dialogReadFilter != null) return _dialogReadFilter; var rasterExtensions = new List<string>(); var vectorExtensions = new List<string>(); var imageExtensions = new List<string>(); var extensions = PreferredProviders.Select(item => item.Key).ToList(); foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogReadFilter.Split('|'); // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { if (extensions.Contains(potentialExtension) == false) { extensions.Add(potentialExtension); if (dp is IRasterProvider) rasterExtensions.Add(potentialExtension); if (dp is IVectorProvider && potentialExtension != "*.shx" && potentialExtension != "*.dbf") vectorExtensions.Add(potentialExtension); if (dp is IImageDataProvider) imageExtensions.Add(potentialExtension); } } } } // We now have a list of all the file extensions supported extensions.Remove("*.dbf"); extensions.Remove("*.shx"); var result = new StringBuilder("All Supported Formats|" + string.Join(";", extensions.ToArray())); if (vectorExtensions.Count > 0) result.Append("|Vectors|" + string.Join(";", vectorExtensions.ToArray())); if (rasterExtensions.Count > 0) result.Append("|Rasters|" + string.Join(";", rasterExtensions.ToArray())); if (imageExtensions.Count > 0) result.Append("|Images|" + string.Join(";", imageExtensions.ToArray())); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { // we don't have to check for uniqueness here because it is enforced by the HashTable result.AppendFormat("|{1} - [{0}]| {0}", item.Key, item.Value.Name); } // Now add each of the individual lines, prepended with the provider name foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogReadFilter.Split('|'); string potentialFormat = null; for (int i = 0; i < formats.Length; i++) { if (i % 2 == 0) { // For descriptions, prepend the name: potentialFormat = "|" + dp.Name + " - " + formats[i]; } else { // don't add this format if it was already added by a "preferred data provider" if (PreferredProviders.ContainsKey(formats[i]) == false) { string res = formats[i].Replace(";*.shx", string.Empty).Replace("*.shx", string.Empty); res = res.Replace(";*.dbf", string.Empty).Replace("*.dbf", string.Empty); if (formats[i] != "*.shx" && formats[i] != "*.shp") { result.Append(potentialFormat); result.Append("|" + res); } } } } } result.Append("|All Files (*.*) |*.*"); return result.ToString(); } set { _dialogReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save files.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string DialogWriteFilter { get { // Setting this to something overrides the default if (_dialogWriteFilter != null) return _dialogWriteFilter; var rasterExtensions = new List<string>(); var vectorExtensions = new List<string>(); var imageExtensions = new List<string>(); var extensions = PreferredProviders.Select(item => item.Key).ToList(); foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogWriteFilter.Split('|'); // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { if (extensions.Contains(potentialExtension) == false) { extensions.Add(potentialExtension); if (dp is IRasterProvider) rasterExtensions.Add(potentialExtension); if (dp is IVectorProvider) vectorExtensions.Add(potentialExtension); if (dp is IImageDataProvider) imageExtensions.Add(potentialExtension); } } } } // We now have a list of all the file extensions supported var result = new StringBuilder("All Supported Formats|" + string.Join(";", extensions.ToArray())); if (vectorExtensions.Count > 0) result.Append("|Vectors|" + string.Join(";", vectorExtensions.ToArray())); if (rasterExtensions.Count > 0) result.Append("|Rasters|" + string.Join(";", rasterExtensions.ToArray())); if (imageExtensions.Count > 0) result.Append("|Images|" + string.Join(";", imageExtensions.ToArray())); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { // we don't have to check for uniqueness here because it is enforced by the HashTable result.AppendFormat("| [{0}] - {1}| {0}", item.Key, item.Value.Name); } // Now add each of the individual lines, prepended with the provider name foreach (IDataProvider dp in DataProviders) { string[] formats = dp.DialogWriteFilter.Split('|'); string potentialFormat = null; for (int i = 0; i < formats.Length; i++) { if (i % 2 == 0) { // For descriptions, prepend the name: potentialFormat = "|" + dp.Name + " - " + formats[i]; } else { if (PreferredProviders.ContainsKey(formats[i]) == false) { result.Append(potentialFormat); result.Append("|" + formats[i]); } } } } result.Append("|All Files (*.*) |*.*"); return result.ToString(); } set { _dialogWriteFilter = value; } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files that are specifically raster formats. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open rasters.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string RasterReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_rasterReadFilter != null) return _rasterReadFilter; return GetReadFilter<IRasterProvider>("Rasters"); } set { _rasterReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save rasters.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string RasterWriteFilter { get { // Setting this to something overrides the default if (_rasterWriteFilter != null) return _rasterWriteFilter; return GetWriteFilter<IRasterProvider>("Rasters"); } set { _rasterWriteFilter = value; } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open vectors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string VectorReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_vectorReadFilter != null) return _vectorReadFilter; return GetReadFilter<IVectorProvider>("Vectors"); } set { _vectorReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save vectors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string VectorWriteFilter { get { // Setting this to something overrides the default if (_vectorWriteFilter != null) return _vectorWriteFilter; return GetWriteFilter<IVectorProvider>("Vectors"); } set { _vectorWriteFilter = value; } } /// <summary> /// Gets or sets the dialog read filter to use for opening data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when using this data manager is used to open images.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string ImageReadFilter { get { // The developer can bypass the default behavior simply by caching something here. if (_imageReadFilter != null) return _imageReadFilter; return GetReadFilter<IImageDataProvider>("Images"); } set { _imageReadFilter = value; } } /// <summary> /// Gets or sets the dialog write filter to use for saving data files. /// </summary> [Category("Filters")] [Description("Gets or sets the string that should be used when this data manager is used to save images.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string ImageWriteFilter { get { // Setting this to something overrides the default if (_imageWriteFilter != null) return _imageWriteFilter; return GetWriteFilter<IImageDataProvider>("Images"); } set { _imageWriteFilter = value; } } /// <summary> /// Gets or sets a value indicating whether the this data manager should try to load layers by default. /// This will be overridden if the inRam property is specified as a parameter. /// </summary> [Category("Behavior")] [Description("Gets or sets the default condition for subsequent load operations which may be overridden by specifying inRam in the parameters.")] public bool LoadInRam { get; set; } = true; /// <summary> /// Gets or sets a dictionary of IDataProviders with corresponding extensions. The standard order is to try to load /// the data using a PreferredProvider. If that fails, then it will check the list of dataProviders, and finally, /// if that fails, it will check the plugin Data Providers in directories. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual Dictionary<string, IDataProvider> PreferredProviders { get; set; } /// <summary> /// Gets or sets a progress handler for any open operations that are intiated by this /// DataManager and don't override this value with an IProgressHandler specified in the parameters. /// </summary> [Category("Handlers")] [Description("Gets or sets the object that implements the IProgressHandler interface for recieving status messages.")] public virtual IProgressHandler ProgressHandler { get; set; } #endregion #region Methods /// <summary> /// Creates a new class of vector that matches the given fileName. /// </summary> /// <param name="fileName">The string fileName from which to create a vector.</param> /// <param name="featureType">Specifies the type of feature for this vector file.</param> /// <returns>An IFeatureSet that allows working with the dataset.</returns> public IFeatureSet CreateVector(string fileName, FeatureType featureType) { return CreateVector(fileName, featureType, ProgressHandler); } /// <summary> /// Creates a new class of vector that matches the given fileName. /// </summary> /// <param name="fileName">The string fileName from which to create a vector.</param> /// <param name="featureType">Specifies the type of feature for this vector file.</param> /// <param name="progHandler">Overrides the default progress handler with the specified progress handler.</param> /// <returns>An IFeatureSet that allows working with the dataset.</returns> /// <exception cref="ArgumentNullException">Raised when fileName is null.</exception> /// <exception cref="IOException">Raised when suitable DataProvider not found.</exception> public IFeatureSet CreateVector(string fileName, FeatureType featureType, IProgressHandler progHandler) { if (fileName == null) throw new ArgumentNullException(nameof(fileName), DataStrings.FileNameShouldNotBeNull); // To Do: Add Customization that allows users to specify which plugins to use in priority order. // First check for the extension in the preferred plugins list var ext = Path.GetExtension(fileName); if (PreferredProviders.TryGetValue(ext, out IDataProvider pdp)) { var vp = pdp as IVectorProvider; var result = vp?.CreateNew(fileName, featureType, true, progHandler); if (result != null) return result; // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (var dp in DataProviders.OfType<IVectorProvider>()) { if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) { // attempt to open with the fileName. var result = dp.CreateNew(fileName, featureType, true, progHandler); if (result != null) return result; } } throw new IOException(DataStrings.FileTypeNotSupported); } /// <summary> /// Checks a dialog filter and returns a list of just the extensions. /// </summary> /// <param name="dialogFilter">The Dialog Filter to read extensions from.</param> /// <returns>A list of extensions.</returns> public virtual List<string> GetSupportedExtensions(string dialogFilter) { List<string> extensions = new List<string>(); string[] formats = dialogFilter.Split('|'); char[] wild = { '*' }; // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { string ext = potentialExtension.TrimStart(wild); if (extensions.Contains(ext) == false) extensions.Add(ext); } } return extensions; } /// <summary> /// This can help determine what kind of file format a file is, without actually opening the file. /// </summary> /// <param name="fileName">Path of the file that the file type should be determined for.</param> /// <returns>The file format that was detected.</returns> public virtual DataFormat GetFileFormat(string fileName) { string ext = Path.GetExtension(fileName); foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) { if (dp is IVectorProvider) return DataFormat.Vector; if (dp is IRasterProvider) return DataFormat.Raster; if (dp is IImageDataProvider) return DataFormat.Image; return DataFormat.Custom; } } return DataFormat.Custom; } /// <summary> /// Instead of opening the specified file, this simply determines the correct provider, /// and requests that the provider check the feature type for vector formats. /// </summary> /// <param name="fileName">Path of the file that the feature type should be determined for.</param> /// <returns>The feature type that was detected.</returns> public virtual FeatureType GetFeatureType(string fileName) { string ext = Path.GetExtension(fileName); if (GetFileFormat(fileName) != DataFormat.Vector) return FeatureType.Unspecified; foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) { if (!(dp is IVectorProvider vp)) continue; return vp.GetFeatureType(fileName); } } return FeatureType.Unspecified; } /// <summary> /// Opens the specified fileName, returning an IRaster. This will return null if a manager /// either returns the wrong data format. /// </summary> /// <param name="fileName">The string fileName to open.</param> /// <returns>An IRaster loaded from the specified file.</returns> public virtual IRaster OpenRaster(string fileName) { return OpenFileAsIRaster(fileName, true, ProgressHandler); } /// <summary> /// Opens the specified fileName, returning an IRaster. This will return null if a manager /// either returns the wrong data format. /// </summary> /// <param name="fileName">The string fileName to open.</param> /// <param name="inRam">boolean, true if this should be loaded into ram.</param> /// <param name="prog">a progress interface.</param> /// <returns>An IRaster loaded from the specified file.</returns> public virtual IRaster OpenRaster(string fileName, bool inRam, IProgressHandler prog) { return OpenFileAsIRaster(fileName, inRam, prog); } /// <summary> /// Opens a specified file as an IFeatureSet. /// </summary> /// <param name="fileName">The string fileName to open.</param> /// <param name="inRam">boolean, true if this should be loaded into ram.</param> /// <param name="prog">a progress interface.</param> /// <returns>An IFeatureSet loaded from the specified file.</returns> public virtual IFeatureSet OpenVector(string fileName, bool inRam, IProgressHandler prog) { return OpenFile(fileName, inRam, prog) as IFeatureSet; } /// <summary> /// Opens the file as an Image and returns an IImageData object for interacting with the file. /// </summary> /// <param name="fileName">The string fileName.</param> /// <returns>An IImageData object.</returns> public virtual IImageData OpenImage(string fileName) { return OpenFile(fileName, LoadInRam, ProgressHandler) as IImageData; } /// <summary> /// Opens the file as an Image and returns an IImageData object. /// </summary> /// <param name="fileName">The string fileName to open.</param> /// <param name="progressHandler">The progressHandler to receive progress updates.</param> /// <returns>An IImageData.</returns> public virtual IImageData OpenImage(string fileName, IProgressHandler progressHandler) { return OpenFile(fileName, LoadInRam, progressHandler) as IImageData; } /// <summary> /// Attempts to call the open fileName method for any IDataProvider plugin /// that matches the extension on the string. /// </summary> /// <param name="fileName">A String fileName to attempt to open.</param> /// <returns>The opened IDataSet.</returns> public virtual IDataSet OpenFile(string fileName) { return OpenFile(fileName, LoadInRam, ProgressHandler); } /// <summary> /// Attempts to call the open fileName method for any IDataProvider plugin that matches the extension on the string. /// </summary> /// <param name="fileName">A String fileName to attempt to open.</param> /// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this DataManager.</param> /// <returns>The opened IDataSet.</returns> public virtual IDataSet OpenFile(string fileName, bool inRam) { return OpenFile(fileName, inRam, ProgressHandler); } /// <summary> /// Attempts to call the open fileName method for any IDataProvider plugin that matches the extension on the string. /// </summary> /// <param name="fileName">A String fileName to attempt to open.</param> /// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this DataManager.</param> /// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this DataManager.</param> /// <param name="providerName">Name of the provider that should be used for opening. If it is not set or the provider can't open the file, DS takes the first provider that can open the file.</param> /// <returns>The opened IDataSet.</returns> public virtual IDataSet OpenFile(string fileName, bool inRam, IProgressHandler progressHandler, string providerName = "") { string ext = Path.GetExtension(fileName)?.ToLower(); if (ext != null) { IDataSet result; if (providerName != string.Empty) { // if a provider name was given we try to find this provider and use it to open the file var provider = PreferredProviders.FirstOrDefault(kvp => kvp.Value.Name == providerName); if (provider.Value != null) { if (GetSupportedExtensions(provider.Value.DialogReadFilter).Contains(ext)) { result = provider.Value.Open(fileName); if (result != null) return result; } } var dp = DataProviders.FirstOrDefault(kvp => kvp.Name == providerName); if (dp != null) { if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) { result = dp.Open(fileName); if (result != null) return result; } } } // Check for the extension in the preferred plugins list if (PreferredProviders.ContainsKey(ext)) { result = PreferredProviders[ext].Open(fileName); if (result != null) return result; // if we get here, we found the provider, but it did not succeed in opening the file. } // Check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (!GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) continue; // attempt to open with the fileName. dp.ProgressHandler = ProgressHandler; result = dp.Open(fileName); if (result != null) return result; } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } /// <summary> /// Creates a new image using an appropriate data provider. /// </summary> /// <param name="fileName">The string fileName to open an image for.</param> /// <param name="width">The integer width in pixels.</param> /// <param name="height">The integer height in pixels.</param> /// <param name="bandType">The band color type.</param> /// <returns>An IImageData interface allowing access to image data.</returns> public virtual IImageData CreateImage(string fileName, int width, int height, ImageBandType bandType) { return CreateImage(fileName, width, height, LoadInRam, ProgressHandler, bandType); } /// <summary> /// Creates a new image using an appropriate data provider. /// </summary> /// <param name="fileName">The string fileName to open an image for.</param> /// <param name="width">The integer width in pixels.</param> /// <param name="height">The integer height in pixels.</param> /// <param name="inRam">Boolean, true if the entire file should be created in memory.</param> /// <param name="bandType">The band color type.</param> /// <returns>An IImageData interface allowing access to image data.</returns> public virtual IImageData CreateImage(string fileName, int width, int height, bool inRam, ImageBandType bandType) { return CreateImage(fileName, width, height, inRam, ProgressHandler, bandType); } /// <summary> /// Creates a new image using an appropriate data provider. /// </summary> /// <param name="fileName">The string fileName to open an image for.</param> /// <param name="width">The integer width in pixels.</param> /// <param name="height">The integer height in pixels.</param> /// <param name="inRam">Boolean, true if the entire file should be created in memory.</param> /// <param name="progHandler">A Progress handler.</param> /// <param name="bandType">The band color type.</param> /// <returns>An IImageData interface allowing access to image data.</returns> public virtual IImageData CreateImage(string fileName, int width, int height, bool inRam, IProgressHandler progHandler, ImageBandType bandType) { // First check for the extension in the preferred plugins list string ext = Path.GetExtension(fileName)?.ToLower(); if (ext != null) { IImageData result; if (PreferredProviders.ContainsKey(ext)) { if (PreferredProviders[ext] is IImageDataProvider rp) { result = rp.Create(fileName, width, height, inRam, progHandler, bandType); if (result != null) return result; } // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogWriteFilter).Contains(ext)) { if (dp is IImageDataProvider rp) { // attempt to open with the fileName. result = rp.Create(fileName, width, height, inRam, progHandler, bandType); if (result != null) return result; } } } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } /// <summary> /// Creates a new raster using the specified raster provider and the Data Manager's Progress Handler, /// as well as its LoadInRam property. /// </summary> /// <param name="name">The fileName of the new file to create.</param> /// <param name="driverCode">The string code identifying the driver to use to create the raster. If no code is specified /// the manager will attempt to match the extension with a code specified in the Dialog write filter. </param> /// <param name="xSize">The number of columns in the raster.</param> /// <param name="ySize">The number of rows in the raster.</param> /// <param name="numBands">The number of bands in the raster.</param> /// <param name="dataType">The data type for the raster.</param> /// <param name="options">Any additional, driver specific options for creation.</param> /// <returns>An IRaster representing the created raster.</returns> public virtual IRaster CreateRaster(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options) { // First check for the extension in the preferred plugins list string ext = Path.GetExtension(name)?.ToLower(); if (ext != null) { IRaster result; if (PreferredProviders.ContainsKey(ext)) { if (PreferredProviders[ext] is IRasterProvider rp) { result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options); if (result != null) return result; } // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (GetSupportedExtensions(dp.DialogWriteFilter).Contains(ext)) { if (dp is IRasterProvider rp) { // attempt to open with the fileName. result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options); if (result != null) return result; } } } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } /// <summary> /// Opens the file making sure it can be returned as an IRaster. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="inRam">Indicates whether the file should be loaded into ram.</param> /// <param name="progressHandler">The progress handler.</param> /// <returns>The IRaster that was opened.</returns> public virtual IRaster OpenFileAsIRaster(string fileName, bool inRam, IProgressHandler progressHandler) { // First check for the extension in the preferred plugins list string ext = Path.GetExtension(fileName); if (ext != null) { ext = ext.ToLower(); IRaster result; if (PreferredProviders.ContainsKey(ext)) { result = PreferredProviders[ext].Open(fileName) as IRaster; if (result != null) return result; // if we get here, we found the provider, but it did not succeed in opening the file. } // Then check the general list of developer specified providers... but not the directory providers foreach (IDataProvider dp in DataProviders) { if (!GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) continue; // attempt to open with the fileName. dp.ProgressHandler = ProgressHandler; result = dp.Open(fileName) as IRaster; if (result != null) return result; } } throw new ApplicationException(DataStrings.FileTypeNotSupported); } /// <summary> /// Triggers the DirectoryProvidersLoaded event. /// </summary> /// <param name="list">List of the providers that were loaded.</param> protected virtual void OnProvidersLoaded(IEnumerable<IDataProvider> list) { DirectoryProvidersLoaded?.Invoke(this, new DataProviderEventArgs(list)); } private void Configure() { defaultDataManager = this; PreferredProviders = new Dictionary<string, IDataProvider>(); // Provide a number of default providers _dataProviders = new List<IDataProvider> { new ShapefileDataProvider(), new BinaryRasterProvider(), new DotNetImageProvider() }; } private string GetFilter<T>(string description, Func<IDataProvider, string> dpFilter) where T : IDataProvider { var extensions = new List<string>(); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { if (item.Value is T) { // we don't have to check for uniqueness here because it is enforced by the HashTable extensions.Add(item.Key); } } foreach (IDataProvider dp in DataProviders) { string[] formats = dpFilter(dp).Split('|'); // We don't care about the description strings, just the extensions. for (int i = 1; i < formats.Length; i += 2) { // Multiple extension types are separated by semicolons string[] potentialExtensions = formats[i].Split(';'); foreach (string potentialExtension in potentialExtensions) { if (extensions.Contains(potentialExtension) == false) { if (dp is T) extensions.Add(potentialExtension); } } } } var result = new StringBuilder(); // We now have a list of all the file extensions supported if (extensions.Count > 0) result.Append($"{description}|" + string.Join(";", extensions.ToArray())); foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders) { if (item.Value is T) { // we don't have to check for uniqueness here because it is enforced by the HashTable result.AppendFormat("| [{0}] - {1}| {0}", item.Key, item.Value.Name); } } // Now add each of the individual lines, prepended with the provider name foreach (IDataProvider dp in DataProviders) { string[] formats = dpFilter(dp).Split('|'); string potentialFormat = null; for (int i = 0; i < formats.Length; i++) { if (i % 2 == 0) { // For descriptions, prepend the name: potentialFormat = "|" + dp.Name + " - " + formats[i]; } else { // don't add this format if it was already added by a "preferred data provider" if (PreferredProviders.ContainsKey(formats[i]) == false) { if (dp is T) { result.Append(potentialFormat); result.Append("|" + formats[i]); } } } } } result.Append("|All Files (*.*) |*.*"); return result.ToString(); } private string GetReadFilter<T>(string description) where T : IDataProvider { return GetFilter<T>(description, d => d.DialogReadFilter); } private string GetWriteFilter<T>(string description) where T : IDataProvider { return GetFilter<T>(description, d => d.DialogWriteFilter); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Localization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using OrchardCore.Admin; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Navigation; using OrchardCore.Routing; using OrchardCore.Settings; using OrchardCore.Workflows.Activities; using OrchardCore.Workflows.Helpers; using OrchardCore.Workflows.Indexes; using OrchardCore.Workflows.Models; using OrchardCore.Workflows.Services; using OrchardCore.Workflows.ViewModels; using YesSql; using YesSql.Services; namespace OrchardCore.Workflows.Controllers { [Admin] public class WorkflowTypeController : Controller { private readonly ISiteService _siteService; private readonly ISession _session; private readonly IActivityLibrary _activityLibrary; private readonly IWorkflowManager _workflowManager; private readonly IWorkflowTypeStore _workflowTypeStore; private readonly IWorkflowTypeIdGenerator _workflowTypeIdGenerator; private readonly IAuthorizationService _authorizationService; private readonly IActivityDisplayManager _activityDisplayManager; private readonly INotifier _notifier; private readonly ISecurityTokenService _securityTokenService; private readonly IUpdateModelAccessor _updateModelAccessor; private readonly dynamic New; private readonly IStringLocalizer S; private readonly IHtmlLocalizer H; public WorkflowTypeController ( ISiteService siteService, ISession session, IActivityLibrary activityLibrary, IWorkflowManager workflowManager, IWorkflowTypeStore workflowTypeStore, IWorkflowTypeIdGenerator workflowTypeIdGenerator, IAuthorizationService authorizationService, IActivityDisplayManager activityDisplayManager, IShapeFactory shapeFactory, INotifier notifier, ISecurityTokenService securityTokenService, IStringLocalizer<WorkflowTypeController> s, IHtmlLocalizer<WorkflowTypeController> h, IUpdateModelAccessor updateModelAccessor) { _siteService = siteService; _session = session; _activityLibrary = activityLibrary; _workflowManager = workflowManager; _workflowTypeStore = workflowTypeStore; _workflowTypeIdGenerator = workflowTypeIdGenerator; _authorizationService = authorizationService; _activityDisplayManager = activityDisplayManager; _notifier = notifier; _securityTokenService = securityTokenService; _updateModelAccessor = updateModelAccessor; New = shapeFactory; S = s; H = h; } public async Task<IActionResult> Index(WorkflowTypeIndexOptions options, PagerParameters pagerParameters) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } var siteSettings = await _siteService.GetSiteSettingsAsync(); var pager = new Pager(pagerParameters, siteSettings.PageSize); if (options == null) { options = new WorkflowTypeIndexOptions(); } var query = _session.Query<WorkflowType, WorkflowTypeIndex>(); switch (options.Filter) { case WorkflowTypeFilter.All: default: break; } if (!string.IsNullOrWhiteSpace(options.Search)) { query = query.Where(w => w.Name.Contains(options.Search)); } switch (options.Order) { case WorkflowTypeOrder.Name: query = query.OrderBy(u => u.Name); break; } var count = await query.CountAsync(); var workflowTypes = await query .Skip(pager.GetStartIndex()) .Take(pager.PageSize) .ListAsync(); var workflowTypeIds = workflowTypes.Select(x => x.WorkflowTypeId).ToList(); var workflowGroups = (await _session.QueryIndex<WorkflowIndex>(x => x.WorkflowTypeId.IsIn(workflowTypeIds)) .ListAsync()) .GroupBy(x => x.WorkflowTypeId) .ToDictionary(x => x.Key); // Maintain previous route data when generating page links. var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.Order", options.Order); var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData); var model = new WorkflowTypeIndexViewModel { WorkflowTypes = workflowTypes .Select(x => new WorkflowTypeEntry { WorkflowType = x, Id = x.Id, WorkflowCount = workflowGroups.ContainsKey(x.WorkflowTypeId) ? workflowGroups[x.WorkflowTypeId].Count() : 0, Name = x.Name }) .ToList(), Options = options, Pager = pagerShape }; model.Options.WorkflowTypesBulkAction = new List<SelectListItem>() { new SelectListItem() { Text = S["Delete"].Value, Value = nameof(WorkflowTypeBulkAction.Delete) } }; return View(model); } [HttpPost, ActionName("Index")] [FormValueRequired("submit.Filter")] public ActionResult IndexFilterPOST(WorkflowTypeIndexViewModel model) { return RedirectToAction("Index", new RouteValueDictionary { { "Options.Search", model.Options.Search } }); } [HttpPost] [ActionName(nameof(Index))] [FormValueRequired("submit.BulkAction")] public async Task<IActionResult> BulkEdit(WorkflowTypeIndexOptions options, IEnumerable<int> itemIds) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } if (itemIds?.Count() > 0) { var checkedEntries = await _session.Query<WorkflowType, WorkflowTypeIndex>().Where(x => x.DocumentId.IsIn(itemIds)).ListAsync(); switch (options.BulkAction) { case WorkflowTypeBulkAction.None: break; case WorkflowTypeBulkAction.Delete: foreach (var entry in checkedEntries) { var workflowType = await _workflowTypeStore.GetAsync(entry.Id); if (workflowType != null) { await _workflowTypeStore.DeleteAsync(workflowType); _notifier.Success(H["Workflow {0} has been deleted.", workflowType.Name]); } } break; default: throw new ArgumentOutOfRangeException(); } } return RedirectToAction("Index"); } public async Task<IActionResult> EditProperties(int? id, string returnUrl = null) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } if (id == null) { return View(new WorkflowTypePropertiesViewModel { IsEnabled = true, ReturnUrl = returnUrl }); } else { var workflowType = await _session.GetAsync<WorkflowType>(id.Value); return View(new WorkflowTypePropertiesViewModel { Id = workflowType.Id, Name = workflowType.Name, IsEnabled = workflowType.IsEnabled, IsSingleton = workflowType.IsSingleton, DeleteFinishedWorkflows = workflowType.DeleteFinishedWorkflows, ReturnUrl = returnUrl }); } } [HttpPost] public async Task<IActionResult> EditProperties(WorkflowTypePropertiesViewModel viewModel, int? id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } if (!ModelState.IsValid) { return View(viewModel); } var isNew = id == null; var workflowType = default(WorkflowType); if (isNew) { workflowType = new WorkflowType(); workflowType.WorkflowTypeId = _workflowTypeIdGenerator.GenerateUniqueId(workflowType); } else { workflowType = await _session.GetAsync<WorkflowType>(id.Value); if (workflowType == null) { return NotFound(); } } workflowType.Name = viewModel.Name?.Trim(); workflowType.IsEnabled = viewModel.IsEnabled; workflowType.IsSingleton = viewModel.IsSingleton; workflowType.DeleteFinishedWorkflows = viewModel.DeleteFinishedWorkflows; await _workflowTypeStore.SaveAsync(workflowType); return isNew ? RedirectToAction("Edit", new { workflowType.Id }) : Url.IsLocalUrl(viewModel.ReturnUrl) ? (IActionResult)Redirect(viewModel.ReturnUrl) : RedirectToAction("Index"); } public async Task<IActionResult> Duplicate(int id, string returnUrl = null) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } var workflowType = await _session.GetAsync<WorkflowType>(id); if (workflowType == null) { return NotFound(); } return View(new WorkflowTypePropertiesViewModel { Id = id, IsSingleton = workflowType.IsSingleton, Name = "Copy-" + workflowType.Name, IsEnabled = workflowType.IsEnabled, ReturnUrl = returnUrl }); } [HttpPost] public async Task<IActionResult> Duplicate(WorkflowTypePropertiesViewModel viewModel, int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } if (!ModelState.IsValid) { return View(viewModel); } var existingWorkflowType = await _session.GetAsync<WorkflowType>(id); var workflowType = new WorkflowType(); workflowType.WorkflowTypeId = _workflowTypeIdGenerator.GenerateUniqueId(workflowType); workflowType.Name = viewModel.Name?.Trim(); workflowType.IsEnabled = viewModel.IsEnabled; workflowType.IsSingleton = viewModel.IsSingleton; workflowType.DeleteFinishedWorkflows = viewModel.DeleteFinishedWorkflows; workflowType.Activities = existingWorkflowType.Activities; workflowType.Transitions = existingWorkflowType.Transitions; await _workflowTypeStore.SaveAsync(workflowType); return RedirectToAction("Edit", new { workflowType.Id }); } public async Task<IActionResult> Edit(int id, string localId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } var newLocalId = string.IsNullOrWhiteSpace(localId) ? Guid.NewGuid().ToString() : localId; var availableActivities = _activityLibrary.ListActivities(); var workflowType = await _session.GetAsync<WorkflowType>(id); if (workflowType == null) { return NotFound(); } var workflow = _workflowManager.NewWorkflow(workflowType); var workflowContext = await _workflowManager.CreateWorkflowExecutionContextAsync(workflowType, workflow); var activityContexts = await Task.WhenAll(workflowType.Activities.Select(x => _workflowManager.CreateActivityExecutionContextAsync(x, x.Properties))); var workflowCount = await _session.QueryIndex<WorkflowIndex>(x => x.WorkflowTypeId == workflowType.WorkflowTypeId).CountAsync(); var activityThumbnailShapes = new List<dynamic>(); var index = 0; foreach (var activity in availableActivities) { activityThumbnailShapes.Add(await BuildActivityDisplay(activity, index++, id, newLocalId, "Thumbnail")); } var activityDesignShapes = new List<dynamic>(); index = 0; foreach (var activityContext in activityContexts) { activityDesignShapes.Add(await BuildActivityDisplay(activityContext, index++, id, newLocalId, "Design")); } var activitiesDataQuery = activityContexts.Select(x => new { Id = x.ActivityRecord.ActivityId, X = x.ActivityRecord.X, Y = x.ActivityRecord.Y, Name = x.ActivityRecord.Name, IsStart = x.ActivityRecord.IsStart, IsEvent = x.Activity.IsEvent(), Outcomes = x.Activity.GetPossibleOutcomes(workflowContext, x).ToArray() }); var workflowTypeData = new { Id = workflowType.Id, Name = workflowType.Name, IsEnabled = workflowType.IsEnabled, Activities = activitiesDataQuery.ToArray(), Transitions = workflowType.Transitions }; var viewModel = new WorkflowTypeViewModel { WorkflowType = workflowType, WorkflowTypeJson = JsonConvert.SerializeObject(workflowTypeData, Formatting.None, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }), ActivityThumbnailShapes = activityThumbnailShapes, ActivityDesignShapes = activityDesignShapes, ActivityCategories = _activityLibrary.ListCategories().ToList(), LocalId = newLocalId, LoadLocalState = !string.IsNullOrWhiteSpace(localId), WorkflowCount = workflowCount }; return View(viewModel); } [HttpPost] public async Task<IActionResult> Edit(WorkflowTypeUpdateModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } var workflowType = await _workflowTypeStore.GetAsync(model.Id); dynamic state = JObject.Parse(model.State); var currentActivities = workflowType.Activities.ToDictionary(x => x.ActivityId); var postedActivities = ((IEnumerable<dynamic>)state.activities).ToDictionary(x => (string)x.id); var removedActivityIdsQuery = from activityId in currentActivities.Keys where !postedActivities.ContainsKey(activityId) select activityId; var removedActivityIds = removedActivityIdsQuery.ToList(); // Remove any orphans (activities deleted on the client). foreach (var activityId in removedActivityIds) { var activityToRemove = currentActivities[activityId]; workflowType.Activities.Remove(activityToRemove); currentActivities.Remove(activityId); } // Update activities. foreach (var activityState in state.activities) { var activity = currentActivities[(string)activityState.id]; activity.X = activityState.x; activity.Y = activityState.y; activity.IsStart = activityState.isStart; } // Update transitions. workflowType.Transitions.Clear(); foreach (var transitionState in state.transitions) { workflowType.Transitions.Add(new Transition { SourceActivityId = transitionState.sourceActivityId, DestinationActivityId = transitionState.destinationActivityId, SourceOutcomeName = transitionState.sourceOutcomeName }); } await _workflowTypeStore.SaveAsync(workflowType); await _session.CommitAsync(); _notifier.Success(H["Workflow type has been saved."]); return RedirectToAction(nameof(Edit), new { id = model.Id }); } [HttpPost] public async Task<IActionResult> Delete(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows)) { return Forbid(); } var workflowType = await _workflowTypeStore.GetAsync(id); if (workflowType == null) { return NotFound(); } await _workflowTypeStore.DeleteAsync(workflowType); _notifier.Success(H["Workflow type {0} deleted", workflowType.Name]); return RedirectToAction("Index"); } private async Task<dynamic> BuildActivityDisplay(IActivity activity, int index, int workflowTypeId, string localId, string displayType) { dynamic activityShape = await _activityDisplayManager.BuildDisplayAsync(activity, _updateModelAccessor.ModelUpdater, displayType); activityShape.Metadata.Type = $"Activity_{displayType}"; activityShape.Activity = activity; activityShape.WorkflowTypeId = workflowTypeId; activityShape.Index = index; activityShape.ReturnUrl = Url.Action(nameof(Edit), new { id = workflowTypeId, localId = localId }); return activityShape; } private async Task<dynamic> BuildActivityDisplay(ActivityContext activityContext, int index, int workflowTypeId, string localId, string displayType) { dynamic activityShape = await _activityDisplayManager.BuildDisplayAsync(activityContext.Activity, _updateModelAccessor.ModelUpdater, displayType); activityShape.Metadata.Type = $"Activity_{displayType}"; activityShape.Activity = activityContext.Activity; activityShape.ActivityRecord = activityContext.ActivityRecord; activityShape.WorkflowTypeId = workflowTypeId; activityShape.Index = index; activityShape.ReturnUrl = Url.Action(nameof(Edit), new { id = workflowTypeId, localId = localId }); return activityShape; } } }
namespace SimpleInjector.Diagnostics.Tests.Unit { using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using SimpleInjector.Diagnostics.Analyzers; using SimpleInjector.Diagnostics.Debugger; using SimpleInjector.Diagnostics.Tests.Unit.Helpers; using SimpleInjector.Extensions; public interface IGenericPlugin<T> { } [TestClass] public class SingleResponsibilityViolationsAnalyzerTests { [TestMethod] public void Analyze_OnEmptyConfiguration_ReturnsNull() { // Arrange var container = new Container(); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container); // Assert Assert.AreEqual("No warnings detected.", results.Description); } [TestMethod] public void Analyze_OnValidConfiguration_ReturnsNull() { // Arrange Container container = CreateContainerWithRegistrations(typeof(PluginWith7Dependencies)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container); // Assert Assert.AreEqual("No warnings detected.", results.Description, "6 dependencies is still considered valid (to prevent too many false positives)."); } [TestMethod] public void Analyze_OpenGenericRegistrationWithValidAmountOfDependencies_ReturnsNull() { // Arrange Container container = CreateContainerWithRegistrations(); // Consumer class contains a IGenericPlugin<IDisposable> dependency container.Register<Consumer<IGenericPlugin<IDisposable>>>(); // Register open generic type with 6 dependencies. container.RegisterOpenGeneric(typeof(IGenericPlugin<>), typeof(GenericPluginWith6Dependencies<>)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container); // Assert Assert.AreEqual("No warnings detected.", results.Description, "The registration is considered to be valid, since both the type and decorator do not " + "exceed the maximum number of dependencies. Message: {0}", results == null ? null : results.Items().FirstOrDefault()); } [TestMethod] public void Analyze_OnConfigurationWithOneViolation_ReturnsThatViolation() { // Arrange Container container = CreateContainerWithRegistrations(typeof(PluginWith8Dependencies)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container).Value as DebuggerViewItem[]; // Assert Assert.AreEqual(1, results.Length); Assert.AreEqual(typeof(PluginWith8Dependencies).Name, results[0].Name); Assert.AreEqual(typeof(PluginWith8Dependencies).Name + " has 8 dependencies which might indicate a SRP violation.", results[0].Description); } [TestMethod] public void Analyze_WithInvalidConfiguration_ReturnsResultsWithExpectedViolationInformation() { // Arrange var expectedImplementationTypeInformation = new DebuggerViewItem( name: "ImplementationType", description: typeof(PluginWith8Dependencies).Name, value: typeof(PluginWith8Dependencies)); var expectedDependenciesInformation = new DebuggerViewItem( name: "Dependencies", description: "8 dependencies.", value: null); Container container = CreateContainerWithRegistrations(typeof(PluginWith8Dependencies)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container).Value as DebuggerViewItem[]; var result = results.Single(); var violationInformation = result.Value as DebuggerViewItem[]; // Assert Assert_AreEqual(expectedImplementationTypeInformation, violationInformation[0]); Assert_AreEqual(expectedDependenciesInformation, violationInformation[1], validateValue: false); } [TestMethod] public void Analyze_OnConfigurationWithMultipleViolations_ReturnsThoseTwoViolations() { // Arrange Container container = CreateContainerWithRegistrations( typeof(PluginWith8Dependencies), typeof(AnotherPluginWith8Dependencies)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container).Value as DebuggerViewItem[]; // Assert Assert.AreEqual(2, results.Length); var plugin1 = results.Single(r => r.Name == typeof(PluginWith8Dependencies).Name); Assert.AreEqual( typeof(PluginWith8Dependencies).Name + " has 8 dependencies which might indicate a SRP violation.", plugin1.Description); var plugin2 = results.Single(r => r.Name == typeof(AnotherPluginWith8Dependencies).Name); Assert.AreEqual( typeof(AnotherPluginWith8Dependencies).Name + " has 8 dependencies which might indicate a SRP violation.", plugin2.Description); } [TestMethod] public void Analyze_ConfigurationWithTwoViolationsOnSingleService_ReturnsOneViewItemForBothViolations() { // Arrange Container container = CreateContainerWithRegistration<IPlugin, PluginWith8Dependencies>(); container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecoratorWith8Dependencies)); container.Verify(); var ip = container.GetRegistration(typeof(IPlugin)); // Act var items = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container).Value as DebuggerViewItem[]; // Assert Assert.AreEqual(1, items.Length); Assert.AreEqual(typeof(IPlugin).Name, items[0].Name); Assert.AreEqual("2 possible violations.", items[0].Description); } [TestMethod] public void Analyze_ConfigurationWithTwoViolationsOnSingleService_ReturnsOneViewItemThatWrapsFirstViolation() { // Arrange Container container = CreateContainerWithRegistration<IPlugin, PluginWith8Dependencies>(); container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecoratorWith8Dependencies)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container).Value as DebuggerViewItem[]; var items = results.Single().Value as DebuggerViewItem[]; var item = items.Single(i => i.Description.Contains(typeof(PluginWith8Dependencies).Name)); // Assert Assert.AreEqual("IPlugin", item.Name); Assert.AreEqual(typeof(PluginWith8Dependencies).Name + " has 8 dependencies which might indicate a SRP violation.", item.Description); } [TestMethod] public void Analyze_ConfigurationWithTwoViolationsOnSingleService_ReturnsOneViewItemThatWrapsSecondViolation() { // Arrange Container container = CreateContainerWithRegistration<IPlugin, PluginWith8Dependencies>(); container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecoratorWith8Dependencies)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container).Value as DebuggerViewItem[]; var items = results.Single().Value as DebuggerViewItem[]; var item = items.Single(i => i.Description.Contains(typeof(PluginDecoratorWith8Dependencies).Name)); // Assert Assert.AreEqual("IPlugin", item.Name); Assert.AreEqual(typeof(PluginDecoratorWith8Dependencies).Name + " has 8 dependencies which might indicate a SRP violation.", item.Description); } [TestMethod] public void Analyze_CollectionWithTypeWithTooManyDependencies_WarnsAboutThatViolation() { // Arrange Container container = CreateContainerWithRegistrations(Type.EmptyTypes); container.RegisterAll<IPlugin>(typeof(PluginWith8Dependencies)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container).Value as DebuggerViewItem[]; // Assert Assert.IsNotNull(results, "A warning should have been detected."); Assert.AreEqual(1, results.Length); Assert.AreEqual( typeof(PluginWith8Dependencies).Name + " has 8 dependencies which might indicate a SRP violation.", results[0].Description); } [TestMethod] public void Analyze_ConfigurationWithCollectionWithMultipleDecoratorsWithValidNumberOfDependencies_DoesNotWarnAboutThatDecorator() { // Arrange Container container = CreateContainerWithRegistrations(Type.EmptyTypes); container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecoratorWith5Dependencies)); container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecoratorWith5Dependencies)); container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecoratorWith5Dependencies)); // Non of these types have too many dependencies. container.RegisterAll<IPlugin>(typeof(PluginImpl), typeof(SomePluginImpl)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container); // Assert Assert.AreEqual("No warnings detected.", results.Description, @" Although the decorator has too many dependencies, the system has not enough information to differentiate between a decorator with too many dependencies and a decorator that wraps many elements. The diagnostic system simply registers all dependencies that this decorator has, and all elements it decorates are a dependency and its hard to see the real number of dependencies it has. Because of this, we have to suppress violations on collections completely."); } [TestMethod] public void Analyze_ConfigurationWithCollectionADecoratorsWithTooManyDependencies_WarnsAboutThatDecorator() { // Arrange Container container = CreateContainerWithRegistrations(Type.EmptyTypes); // This decorator has too many dependencies container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecoratorWith8Dependencies)); // Non of these types have too many dependencies. container.RegisterAll<IPlugin>(typeof(PluginImpl), typeof(SomePluginImpl)); container.Verify(); // Act var results = DebuggerGeneralWarningsContainerAnalyzer.Analyze(container); // Assert // We expect two violations here, since the decorator is wrapping two different registrations. Assert.AreEqual("2 possible single responsibility violations.", results.Description); } private static Container CreateContainerWithRegistrations(params Type[] implementationTypes) { var container = new Container(); container.RegisterOpenGeneric(typeof(IGeneric<>), typeof(GenericType<>)); foreach (var type in implementationTypes) { container.Register(type); } return container; } private static Container CreateContainerWithRegistration<TService, TImplementation>() where TService : class, IPlugin where TImplementation : class, TService { var container = new Container(); container.RegisterOpenGeneric(typeof(IGeneric<>), typeof(GenericType<>)); container.Register<TService, TImplementation>(); return container; } private static void Assert_AreEqual(DebuggerViewItem expected, DebuggerViewItem actual, bool validateValue = true) { Assert.AreEqual(expected.Name, actual.Name, "Names do not match"); Assert.AreEqual(expected.Description, actual.Description, "Descriptions do not match"); if (validateValue) { Assert.AreEqual(expected.Value, actual.Value, "Values do not match"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace PolyhydraGames.Extensions { public static partial class Text { public static string ToNumericWordAbreviation(this int value) { switch (value) { case 1: return "1st"; case 2: return "2nd"; case 3: return "3rd"; default: return value + "th"; } } public static string FirstInt(this string value) { string output = ""; bool foundInt = false; for (int x = 0; x < value.Length; x++) { int outint; if (value[x].IsNumeric(out outint)) { output += outint.ToString(); foundInt = true; } else { if (foundInt) break; } } return output; } public static string FirstWord(this string value) { string output = ""; for (int x = 0; x < value.Length; x++) { if (value[x].IsNumeric()) break; output += value[x]; } return output; } public static IEnumerable<string> FirstLetters<T>(this IEnumerable<T> items) { return (from item in items select item.ToString()[0].ToString()).ToArray(); } public static string TextAfterString(this string value, string test) { if (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(test)) return ""; int index = value.LastIndexOf(test, StringComparison.Ordinal); return index > 0 ? value.Substring(index + test.Length) : ""; } public static string TextBeforeString(this string value, string test) { if (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(test)) return ""; int index = value.LastIndexOf(test, StringComparison.Ordinal); return index > 0 ? value.Substring(0, index) : ""; } //public static string ToJson<T>(this T item) //{ // string myval = JsonConvert.SerializeObject(item); // return myval; //} //public static T FromJson<T>(this string code) where T : new() //{ // var item = JsonConvert.DeserializeObject<T>(code); // return item; //} public static string RemoveIllegalCharacters(this string aString) { if (!String.IsNullOrEmpty(aString)) { aString = aString.Replace(Environment.NewLine, "(VBNEWLINE)"); aString = aString.Replace("\"", "(QUOTES)"); aString = aString.Replace("@", "(ANDSYMBOL)"); aString = aString.Replace("#", "(POUNDSYMBOL)"); aString = aString.Replace(":", "(COLINSYMBOL)"); } return aString; } public static string Between(this string aString, string character1, string character2, bool between) { int index1 = string.IsNullOrEmpty(character1) ? 0 : aString.IndexOf(character1, StringComparison.Ordinal); if (character2 == null) return aString.Substring(index1); int length = character1 != character2 ? (aString.IndexOf(character2, StringComparison.Ordinal) + 1 - index1) : aString.LastIndexOf(character2, StringComparison.Ordinal) + 1 - index1; if (index1 >= 0 && length > 0) return aString.Substring(index1, length); return ""; } public static string Between(this string aString, string character1, string character2) { int index1 = string.IsNullOrEmpty(character1) ? 0 : aString.IndexOf(character1, StringComparison.Ordinal) + 1; if (character2 == null) return aString.Substring(index1); int length = character1 != character2 ? (aString.IndexOf(character2, StringComparison.Ordinal) - index1) : aString.LastIndexOf(character2, StringComparison.Ordinal) - index1; if (index1 >= 0 && length > 0) return aString.Substring(index1, length); return ""; } public static string RestoreIllegalCharacters(this string aString) { aString = aString.Replace("(QUOTES)", "\""); aString = aString.Replace("(VBNEWLINE)", Environment.NewLine); aString = aString.Replace("(ANDSYMBOL)", "@"); aString = aString.Replace("(POUNDSYMBOL)", "#"); aString = aString.Replace("(COLINSYMBOL)", ":"); return aString; } public static string[] FromCodedArray(this string code, char split = '#') { return code.Split(split); } public static string ToCodedArray<T>(this IEnumerable<T> aryArray, string store = "#") { if (aryArray == null) return ""; T[] items = aryArray.ToArray(); return (items.Any()) ? (from object itemLoopVariable in items select itemLoopVariable.ToString()).Aggregate( (current, item) => current + store + item.ToString()) : ""; } public static string ToCodedArrayBuilder<T>(this IEnumerable<T> aryArray, string store = "#") { if (aryArray == null) return ""; T[] enumerable = aryArray as T[] ?? aryArray.ToArray(); StringBuilder builder = enumerable.Aggregate( new StringBuilder(), (sb, s) => sb.AppendLine(s.ToString() + store) ); string final = builder.ToString(); int length = final.Length - store.Length; return final.Substring(0, length); } public static string ToDictionaryCodedString<T, TE>(this Dictionary<T, TE> aryArray, string mergevalue = ":", string store = "#") { return aryArray == null ? "" : aryArray.Select(item => item.Key + mergevalue + item.Value).ToCodedArray(store); } public static string[] ToDictionaryCodedArray<T, TE>(this Dictionary<T, TE> aryArray, string mergevalue = ":", string store = "#") { return aryArray == null ? new string[0] : aryArray.Select(item => item.Key + mergevalue + item.Value).ToArray(); } public static string ToCodedArrayWithSpace<T>(this IEnumerable<T> aryArray, string store = "#") { if (aryArray == null) return ""; T[] items = aryArray.ToArray(); return (items.Length > 0) ? (from object itemLoopVariable in items select itemLoopVariable.ToString()).Aggregate( (current, item) => current + store + item.ToString().InsSpace()) : ""; } public static string InsSpace(this string aString) { return !(aString.Length > 2) ? aString : aString[0] + Regex.Replace(aString.Substring(1), "[A-Z]", " $&"); } public static string InsSpaceBeforeInt(this string aString) { if (String.IsNullOrEmpty(aString)) return ""; if (!(aString.Length > 2)) return aString; string newString = ""; for (int x = 0; x < aString.Length - 1; x++) { newString += (Char.IsLower(aString[x]) && Char.IsNumber(aString[x + 1])) ? aString[x] + " " : aString[x].ToString(); } newString += aString[aString.Length - 1]; return newString; } public static string VbMe(this string input) { return input + Environment.NewLine; } public static string ToLettersNumbersUnderscoreNoDash(this string value) { return Regex.Replace(value, @"[^A-Za-z0-9_]", ""); } public static string ToProperCase(this string value) { if (value == null) return null; if (value.Length == 0) return value; var result = new StringBuilder(value); result[0] = char.ToUpper(result[0]); for (int i = 1; i < result.Length; ++i) { if (char.IsWhiteSpace(result[i - 1])) result[i] = char.ToUpper(result[i]); else result[i] = char.ToLower(result[i]); } return result.ToString(); } public static string Capitalize(this string value) { if (String.IsNullOrEmpty(value)) return value; char letter1 = char.ToUpperInvariant(value[0]); return value.Length >= 2 ? letter1 + value.Substring(1) : letter1.ToString(); } public static string ToCapitalizedWords(this string value) { string[] items = value.Split(' '); if (items.Length == 1) return items[0].Capitalize(); string[] returnList = items.Select(item => item.Capitalize()).ToArray(); return returnList.ToCodedArray(" "); } public static string ToNumbers(this string value) { return Regex.Replace(value, @"[^0-9\-]", ""); } public static string[] ToStringArray<T>(this IEnumerable<T> aryArray) { var returnMe = new List<string>(); if (aryArray == null) return returnMe.ToArray(); returnMe.AddRange(aryArray.Cast<object>().Select(itemLoopVariable => itemLoopVariable.ToString())); return returnMe.ToArray(); } public static bool IsNumeric(this char value) { int outnum; return value.IsNumeric(out outnum); } public static string StringFromCodedArray(this string code, string replaceWith, char split = '#') { return code.Replace(split.ToString(), replaceWith); } public static string ReplaceAllBetween(this string aString, string character1, string character2, Boolean characters) { if (aString.Contains(character1) && aString.Contains(character2)) { aString = aString.Replace(aString.Between(character1, character2, characters), ""); aString = aString.ReplaceAllBetween(character1, character2, characters); } return aString; } public static string ToLettersNumbersUnderscoreSpace(this string value) { return Regex.Replace(value, @"[^A-Za-z0-9_ ]", ""); } public static string ToEnumNormalized(this string value) { return Regex.Replace(value, @"[^A-Za-z0-9_]", ""); } public static string ToLettersNumbersUnderscore(this string value) { return Regex.Replace(value, @"[^A-Za-z0-9_\-]", ""); } public static string ToAlphaNumeric(this string value) { return Regex.Replace(value, @"[^A-Za-z0-9\- ]", ""); } public static string[] SplitText(this string code) { string newline = Environment.NewLine; if (newline == "\r\n") { code = code.Replace(Environment.NewLine, "\r"); code = code.Replace("\n", ""); return code.Split('\r'); } return code.Split('\n'); } public static string[] ToStringArrayFromEnum<T>(this IEnumerable<T> aryArray) { var returnMe = new List<string>(); if (aryArray == null) return returnMe.ToArray(); returnMe.AddRange(aryArray.Cast<object>().Select(itemLoopVariable => itemLoopVariable.ToString().InsSpace())); return returnMe.ToArray(); } } }
/* | 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.Collections.Generic; using System.Diagnostics; using ESRI.ArcLogistics.Data; using ESRI.ArcLogistics.DomainObjects.Attributes; using ESRI.ArcLogistics.Geometry; using ESRI.ArcLogistics.Routing; using ESRI.ArcLogistics.Utility; using DataModel = ESRI.ArcLogistics.Data.DataModel; namespace ESRI.ArcLogistics.DomainObjects { /// <summary> /// Structure that represents a direction. /// </summary> public struct Direction { /// <summary> /// Direction length. /// </summary> public double Length { get; set; } /// <summary> /// Direction time. /// </summary> public double Time { get; set; } /// <summary> /// Direction text. /// </summary> public string Text { get; set; } /// <summary> /// Direction shape in compact format. /// </summary> /// <remarks> /// Use <c>CompactGeometryConverter</c> to get array of points from the string. /// </remarks> public string Geometry { get; set; } /// <summary> /// Type of direction maneuver. /// </summary> public StopManeuverType ManeuverType { get; set; } } /// <summary> /// Class that represents a stop. /// </summary> /// <remarks> /// Stop can be either start/end/renewal location visit or order visit or break. /// </remarks> public class Stop : DataObject { #region constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <c>Stop</c> class. /// </summary> internal Stop() : base(DataModel.Stops.CreateStops(Guid.NewGuid())) { } internal Stop(DataModel.Stops entity) : base(entity) { } #endregion constructors #region public static properties /// <summary> /// Gets name of the IsLocked property. /// </summary> public static string PropertyNameIsLocked { get { return PROPERTY_NAME_ISLOCKED; } } /// <summary> /// Gets name of the MapLocation property. /// </summary> public static string PropertyNameMapLocation { get { return PROPERTY_NAME_MAPLOCATION; } } /// <summary> /// Gets name of the SequenceNumber property. /// </summary> public static string PropertyNameSequenceNumber { get { return PROPERTY_NAME_SEQUENCE_NUMBER; } } /// <summary> /// Gets name of the StopType property. /// </summary> public static string PropertyNameStopType { get { return PROPERTY_NAME_STOPTYPE; } } /// <summary> /// Gets TravelTime property name. /// </summary> public static string PropertyNameTravelTime { get { return PROPERTY_NAME_TRAVEL_TIME; } } /// <summary> /// Gets ArriveTime property name. /// </summary> public static string PropertyNameArriveTime { get { return PROPERTY_NAME_ARRIVE_TIME; } } /// <summary> /// Wait time property name. /// </summary> public static string PropertyNameWaitTime { get { return PROPERTY_NAME_WAIT_TIME; } } /// <summary> /// Gets TimeAtStop property name. /// </summary> public static string PropertyNameTimeAtStop { get { return PROPERTY_NAME_TIME_AT_STOP; } } /// <summary> /// Gets Status property name. /// </summary> public static string PropertyNameStatus { get { return PROPERTY_NAME_STATUS; } } #endregion #region public members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets the object's type title. /// </summary> public override string TypeTitle { get { return Properties.Resources.Stop; } } /// <summary> /// Gets the object's globally unique identifier. /// </summary> public override Guid Id { get { return _Entity.Id; } } /// <summary> /// Gets\sets object creation time. /// </summary> public override long? CreationTime { get { Debug.Assert(false); // NOTE: not supported return 0; } set { } } /// <summary> /// Gets either location or order stop name or "Lunch" for a stop with <c>Lunch</c> type. /// </summary> public override string Name { get { string name = null; switch (StopType) { case StopType.Location: case StopType.Order: name = AssociatedObject.ToString(); break; case StopType.Lunch: name = Properties.Resources.Break; break; default: Debug.Assert(false); // NOTE: not supported break; } return name; } set { throw new NotSupportedException(Properties.Messages.Error_StopNameReadOnly); } } /// <summary> /// Stop arrive time. /// </summary> [DomainProperty("DomainPropertyNameArriveTime")] public DateTime? ArriveTime { get { return _Entity.ArriveTime; } internal set { _Entity.ArriveTime = value; NotifyPropertyChanged(PROPERTY_NAME_ARRIVE_TIME); } } /// <summary> /// Distance to the stop from previous stop. /// </summary> [DomainProperty("DomainPropertyNameDistance")] [UnitPropertyAttribute(Unit.Mile, Unit.Mile, Unit.Kilometer)] public double Distance { get { return _Entity.Distance; } internal set { _Entity.Distance = value; NotifyPropertyChanged(PROPERTY_NAME_DISTANCE); } } /// <summary> /// Stop's sequence number on the route. /// </summary> [DomainProperty("DomainPropertyNameSequenceNumber")] public int SequenceNumber { get { return _Entity.SequenceNumber; } internal set { _Entity.SequenceNumber = value; NotifyPropertyChanged(PROPERTY_NAME_SEQUENCE_NUMBER); } } /// <summary> /// Returns sequence number of order in case stop has <c>Order</c> type or <c>null</c> otherwise. /// </summary> [DomainProperty("DomainPropertyNameOrderSequenceNumber")] public int? OrderSequenceNumber { get { return _Entity.OrderSequenceNumber; } internal set { _Entity.OrderSequenceNumber = value; NotifyPropertyChanged(PROPERTY_NAME_ORDER_SEQUENCE_NUMBER); } } /// <summary> /// Type of the stop. /// </summary> [DomainProperty("DomainPropertyNameType")] public StopType StopType { get { return (StopType)_Entity.Type; } internal set { _Entity.Type = (int)value; NotifyPropertyChanged(PROPERTY_NAME_STOPTYPE); } } /// <summary> /// Time spent at stop in minutes. /// </summary> [DomainProperty("DomainPropertyNameTimeAtStop")] [UnitPropertyAttribute(Unit.Minute, Unit.Minute, Unit.Minute)] public double TimeAtStop { get { return _Entity.TimeAtStop; } internal set { _Entity.TimeAtStop = value; NotifyPropertyChanged(PROPERTY_NAME_TIME_AT_STOP); } } /// <summary> /// Driving time to this stop from previous one in minutes. /// </summary> /// <remarks> /// For the first stop this property value is 0. /// </remarks> [DomainProperty("DomainPropertyNameTravelTime")] [UnitPropertyAttribute(Unit.Minute, Unit.Minute, Unit.Minute)] public double TravelTime { get { return _Entity.TravelTime; } internal set { _Entity.TravelTime = value; NotifyPropertyChanged(PROPERTY_NAME_TRAVEL_TIME); } } /// <summary> /// Time that driver should spend waiting before servicing this stop. /// </summary> [DomainProperty("DomainPropertyNameWaitTime")] [UnitPropertyAttribute(Unit.Minute, Unit.Minute, Unit.Minute)] public double WaitTime { get { return _Entity.WaitTime; } internal set { _Entity.WaitTime = value; NotifyPropertyChanged(PROPERTY_NAME_WAIT_TIME); } } /// <summary> /// Indicates whether stop is locked. /// </summary> /// <remarks> /// This property affects only stops with <c>Order</c> type. If order is locked it means that it cannot be unassigned or reassigned to another route. /// </remarks> [DomainProperty("DomainPropertyNameIsLocked")] public bool IsLocked { get { return _Entity.Locked; } set { _Entity.Locked = value; NotifyPropertyChanged(PROPERTY_NAME_ISLOCKED); } } /// <summary> /// Object associated with this stop. /// </summary> /// <remarks> /// If stop type is <c>Order</c> then this property returns corresponding <c>Order</c> object. /// If stop type is <c>Location</c> then this property returns corresponding <c>Location</c> object. /// If stop type is <c>Lunch</c> then this property returns null. /// </remarks> public DataObject AssociatedObject { get { DataObject obj = null; if (this.StopType == StopType.Order) obj = _OrderWrap.Value; else if (this.StopType == StopType.Location) obj = _LocationWrap.Value; return obj; } internal set { if (this.StopType == StopType.Order) _OrderWrap.Value = value as Order; else if (this.StopType == StopType.Location) _LocationWrap.Value = value as Location; } } /// <summary> /// Gets stop location on a map. /// </summary> [DomainProperty("DomainPropertyNameMapLocation")] public Point? MapLocation { get { Point? pt = null; if (this.StopType == StopType.Order && _OrderWrap.Value != null) { pt = _OrderWrap.Value.GeoLocation; } else if (this.StopType == StopType.Location && _LocationWrap.Value != null) { pt = _LocationWrap.Value.GeoLocation; } return pt; } } /// <summary> /// Gets stop parent route. /// </summary> public Route Route { get { return _RouteWrap.Value; } } /// <summary> /// Indicates whether stop's time window(s) are violated. /// </summary> public bool IsViolated { get { bool isViolated = false; // If stop isn't assigned to route it cannot be violated. if (Route != null) { switch (StopType) { case StopType.Location: Debug.Assert(AssociatedObject is Location); isViolated = _IsLocationTimeWindowViolated((Location)AssociatedObject); break; case StopType.Order: Debug.Assert(AssociatedObject is Order); isViolated = _IsOrderTimeWindowViolated((Order)AssociatedObject); break; case StopType.Lunch: isViolated = false; break; default: Debug.Assert(false); // NOTE: not supported break; } // switch (StopType) } // if (Route != null) else { isViolated = false; } return isViolated; } } /// <summary> /// Gets path to this stop from previous one. /// </summary> /// <remarks> /// Returns <c>null</c> for the first stop. /// </remarks> public Polyline Path { get { if (_path == null) { if (_Entity.PathTo != null) _path = new Polyline(_Entity.PathTo); } return _path; } internal set { _Entity.PathTo = (value != null ? value.ToByteArray() : null); _path = value; } } /// <summary> /// Gets array of driving directions to this stop from previous one. /// </summary> /// <remarks> /// Returns <c>null</c> or the first stop. /// </remarks> public Direction[] Directions { get { if (_directions == null) { if (_Entity.Directions != null) { _directions = DirectionsHelper.ConvertFromBytes( _Entity.Directions); } } return _directions; } internal set { _Entity.Directions = (value != null ? DirectionsHelper.ConvertToBytes(value) : null); _directions = value; } } #endregion public members #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the name of the stop. /// </summary> /// <returns></returns> public override string ToString() { return this.Name; } internal static Stop CreateFromData(StopData stopData) { Debug.Assert(stopData != null); Stop stop = new Stop(); stop.Distance = stopData.Distance; stop.SequenceNumber = stopData.SequenceNumber; stop.WaitTime = stopData.WaitTime; stop.TimeAtStop = stopData.TimeAtStop; stop.TravelTime = stopData.TravelTime; stop.ArriveTime = stopData.ArriveTime; stop.StopType = stopData.StopType; stop.AssociatedObject = stopData.AssociatedObject; stop.OrderSequenceNumber = stopData.OrderSequenceNumber; stop.Path = stopData.Path; stop.Directions = stopData.Directions; stop.IsLocked = stopData.IsLocked; return stop; } internal StopData GetData() { StopData stopData = new StopData(); stopData.Distance = this.Distance; stopData.SequenceNumber = this.SequenceNumber; stopData.WaitTime = this.WaitTime; stopData.TimeAtStop = this.TimeAtStop; stopData.TravelTime = this.TravelTime; stopData.ArriveTime = this.ArriveTime != null ? (DateTime)this.ArriveTime : DateTime.MinValue; stopData.StopType = this.StopType; stopData.AssociatedObject = this.AssociatedObject; stopData.OrderSequenceNumber = this.OrderSequenceNumber; stopData.Path = this.Path; stopData.Directions = this.Directions; stopData.IsLocked = this.IsLocked; return stopData; } #endregion public methods #region ICloneable interface members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns></returns> public override object Clone() { Stop obj = new Stop(); obj.ArriveTime = this.ArriveTime; obj.Distance = this.Distance; obj.SequenceNumber = this.SequenceNumber; obj.OrderSequenceNumber = this.OrderSequenceNumber; obj.StopType = this.StopType; obj.TimeAtStop = this.TimeAtStop; obj.TravelTime = this.TravelTime; obj.WaitTime = this.WaitTime; obj.IsLocked = this.IsLocked; obj.AssociatedObject = this.AssociatedObject; if (this.Path != null) obj.Path = (Polyline)this.Path.Clone(); if (this.Directions != null) { List<Direction> dirs = new List<Direction>(); foreach (Direction dir in this.Directions) dirs.Add(dir); obj.Directions = dirs.ToArray(); } return obj; } #endregion ICloneable interface members #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Checks if stop's arrive date time violates given time windows. /// </summary> /// <param name="timeWindow1">First time window.</param> /// <param name="timeWindow2">Second time window.</param> /// <returns>True - if both time windows violated, false - otherwise.</returns> private bool _AreTimeWindowsViolated(TimeWindow timeWindow1, TimeWindow timeWindow2) { Debug.Assert(timeWindow1 != null); Debug.Assert(timeWindow2 != null); // Violation check result. bool isViolated = false; // Location's time window is violated when 1-st and 2-d time window is violated. if (ArriveTime.HasValue && Route.Schedule.PlannedDate.HasValue) { DateTime arriveDateTime = ArriveTime.Value; DateTime plannedDateTime = Route.Schedule.PlannedDate.Value; isViolated = !timeWindow1.DoesIncludeTime(arriveDateTime, plannedDateTime) && !timeWindow2.DoesIncludeTime(arriveDateTime, plannedDateTime); } else { isViolated = false; } return isViolated; } /// <summary> /// Checks if location's time window is violated. /// </summary> /// <param name="location">Location object.</param> /// <returns>True - if location's time window is violated, false - otherwise.</returns> private bool _IsLocationTimeWindowViolated(Location location) { Debug.Assert(location != null); // Violation check result. bool isViolated = _AreTimeWindowsViolated(location.TimeWindow, location.TimeWindow2); return isViolated; } /// <summary> /// Checks if order's time window is violated. /// </summary> /// <param name="order">Order object.</param> /// <returns>True - if order's time window is violated, false - otherwise.</returns> private bool _IsOrderTimeWindowViolated(Order order) { Debug.Assert(order != null); // Violation check result. bool isViolated = _AreTimeWindowsViolated(order.TimeWindow, order.TimeWindow2); return isViolated; } #endregion // private methods #region private properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private DataModel.Stops _Entity { get { return (DataModel.Stops)base.RawEntity; } } private EntityRefWrapper<Location, DataModel.Locations> _LocationWrap { get { if (_locationRef == null) { _locationRef = new EntityRefWrapper<Location, DataModel.Locations>(_Entity.LocationsReference, this); } return _locationRef; } } private EntityRefWrapper<Order, DataModel.Orders> _OrderWrap { get { if (_orderRef == null) { _orderRef = new EntityRefWrapper<Order, DataModel.Orders>(_Entity.OrdersReference, this); } return _orderRef; } } private EntityRefWrapper<Route, DataModel.Routes> _RouteWrap { get { if (_routeRef == null) { _routeRef = new EntityRefWrapper<Route, DataModel.Routes>(_Entity.RoutesReference, this); } return _routeRef; } } #endregion private properties #region private constants /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // property names private const string PROPERTY_NAME_ISLOCKED = "IsLocked"; private const string PROPERTY_NAME_DISTANCE = "Distance"; private const string PROPERTY_NAME_STATUS = "Status"; private const string PROPERTY_NAME_WAIT_TIME = "WaitTime"; private const string PROPERTY_NAME_TIME_AT_STOP = "TimeAtStop"; private const string PROPERTY_NAME_TRAVEL_TIME = "TravelTime"; private const string PROPERTY_NAME_MAPLOCATION = "MapLocation"; private const string PROPERTY_NAME_SEQUENCE_NUMBER = "SequenceNumber"; private const string PROPERTY_NAME_ORDER_SEQUENCE_NUMBER = "OrderSequenceNumber"; private const string PROPERTY_NAME_STOPTYPE = "StopType"; private const string PROPERTY_NAME_ARRIVE_TIME = "ArriveTime"; #endregion #region private members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private EntityRefWrapper<Location, DataModel.Locations> _locationRef; private EntityRefWrapper<Order, DataModel.Orders> _orderRef; private EntityRefWrapper<Route, DataModel.Routes> _routeRef; private Direction[] _directions; private Polyline _path; #endregion private members } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Threading; namespace System.Net.Sockets { internal static class SocketPal { public const bool SupportsMultipleConnectAttempts = true; private readonly static int s_protocolInformationSize = Marshal.SizeOf<Interop.Winsock.WSAPROTOCOL_INFO>(); public static int ProtocolInformationSize { get { return s_protocolInformationSize; } } private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime) { const int microcnv = 1000000; socketTime.Seconds = (int)(microseconds / microcnv); socketTime.Microseconds = (int)(microseconds % microcnv); } public static void Initialize() { // Ensure that WSAStartup has been called once per process. // The System.Net.NameResolution contract is responsible for the initialization. Dns.GetHostName(); } public static SocketError GetLastSocketError() { return (SocketError)Marshal.GetLastWin32Error(); } public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket) { socket = SafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType); return socket.IsInvalid ? GetLastSocketError() : SocketError.Success; } public static SocketError SetBlocking(SafeCloseSocket handle, bool shouldBlock, out bool willBlock) { int intBlocking = shouldBlock ? 0 : -1; SocketError errorCode; errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref intBlocking); if (errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } willBlock = intBlocking == 0; return errorCode; } public static SocketError GetSockName(SafeCloseSocket handle, byte[] buffer, ref int nameLen) { SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, ref nameLen); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetAvailable(SafeCloseSocket handle, out int available) { int value = 0; SocketError errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONREAD, ref value); available = value; return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetPeerName(SafeCloseSocket handle, byte[] buffer, ref int nameLen) { SocketError errorCode = Interop.Winsock.getpeername(handle, buffer, ref nameLen); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Bind(SafeCloseSocket handle, byte[] buffer, int nameLen) { SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Listen(SafeCloseSocket handle, int backlog) { SocketError errorCode = Interop.Winsock.listen(handle, backlog); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Accept(SafeCloseSocket handle, byte[] buffer, ref int nameLen, out SafeCloseSocket socket) { socket = SafeCloseSocket.Accept(handle, buffer, ref nameLen); return socket.IsInvalid ? GetLastSocketError() : SocketError.Success; } public static SocketError Connect(SafeCloseSocket handle, byte[] peerAddress, int peerAddressLen) { SocketError errorCode = Interop.Winsock.WSAConnect( handle.DangerousGetHandle(), peerAddress, peerAddressLen, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Send(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred) { int count = buffers.Count; WSABuffer[] WSABuffers = new WSABuffer[count]; GCHandle[] objectsToPin = null; try { objectsToPin = new GCHandle[count]; for (int i = 0; i < count; ++i) { ArraySegment<byte> buffer = buffers[i]; RangeValidationHelpers.ValidateSegment(buffer); objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned); WSABuffers[i].Length = buffer.Count; WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset); } // This may throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.WSASend_Blocking( handle.DangerousGetHandle(), WSABuffers, count, out bytesTransferred, socketFlags, SafeNativeOverlapped.Zero, IntPtr.Zero); if ((SocketError)errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } return errorCode; } finally { if (objectsToPin != null) { for (int i = 0; i < objectsToPin.Length; ++i) { if (objectsToPin[i].IsAllocated) { objectsToPin[i].Free(); } } } } } public static unsafe SocketError Send(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) { int bytesSent; if (buffer.Length == 0) { bytesSent = Interop.Winsock.send(handle.DangerousGetHandle(), null, 0, socketFlags); } else { fixed (byte* pinnedBuffer = buffer) { bytesSent = Interop.Winsock.send( handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags); } } if (bytesSent == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesSent; return SocketError.Success; } public static unsafe SocketError SendTo(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred) { int bytesSent; if (buffer.Length == 0) { bytesSent = Interop.Winsock.sendto( handle.DangerousGetHandle(), null, 0, socketFlags, peerAddress, peerAddressSize); } else { fixed (byte* pinnedBuffer = buffer) { bytesSent = Interop.Winsock.sendto( handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags, peerAddress, peerAddressSize); } } if (bytesSent == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesSent; return SocketError.Success; } public static SocketError Receive(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred) { int count = buffers.Count; WSABuffer[] WSABuffers = new WSABuffer[count]; GCHandle[] objectsToPin = null; try { objectsToPin = new GCHandle[count]; for (int i = 0; i < count; ++i) { ArraySegment<byte> buffer = buffers[i]; RangeValidationHelpers.ValidateSegment(buffer); objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned); WSABuffers[i].Length = buffer.Count; WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset); } // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.WSARecv_Blocking( handle.DangerousGetHandle(), WSABuffers, count, out bytesTransferred, ref socketFlags, SafeNativeOverlapped.Zero, IntPtr.Zero); if ((SocketError)errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } return errorCode; } finally { if (objectsToPin != null) { for (int i = 0; i < objectsToPin.Length; ++i) { if (objectsToPin[i].IsAllocated) { objectsToPin[i].Free(); } } } } } public static unsafe SocketError Receive(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) { int bytesReceived; if (buffer.Length == 0) { bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), null, 0, socketFlags); } else { fixed (byte* pinnedBuffer = buffer) { bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags); } } if (bytesReceived == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesReceived; return SocketError.Success; } public static SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred) { ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(socket, null, null); asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags); SocketError errorCode = SocketError.Success; bytesTransferred = 0; try { // This can throw ObjectDisposedException (retrieving the delegate AND resolving the handle). if (socket.WSARecvMsgBlocking( handle.DangerousGetHandle(), Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0), out bytesTransferred, IntPtr.Zero, IntPtr.Zero) == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } } finally { asyncResult.SyncReleaseUnmanagedStructures(); } socketFlags = asyncResult.SocketFlags; receiveAddress = asyncResult.SocketAddress; ipPacketInformation = asyncResult.IPPacketInformation; return errorCode; } public static unsafe SocketError ReceiveFrom(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred) { int bytesReceived; if (buffer.Length == 0) { bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress, ref addressLength); } else { fixed (byte* pinnedBuffer = buffer) { bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags, socketAddress, ref addressLength); } } if (bytesReceived == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesReceived; return SocketError.Success; } public static SocketError WindowsIoctl(SafeCloseSocket handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength) { if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO) { throw new InvalidOperationException(SR.net_sockets_useblocking); } SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking( handle.DangerousGetHandle(), ioControlCode, optionInValue, optionInValue != null ? optionInValue.Length : 0, optionOutValue, optionOutValue != null ? optionOutValue.Length : 0, out optionLength, SafeNativeOverlapped.Zero, IntPtr.Zero); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) { SocketError errorCode = Interop.Winsock.setsockopt( handle, optionLevel, optionName, ref optionValue, sizeof(int)); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue) { SocketError errorCode = Interop.Winsock.setsockopt( handle, optionLevel, optionName, optionValue, optionValue != null ? optionValue.Length : 0); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static void SetReceivingDualModeIPv4PacketInformation(Socket socket) { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); } public static SocketError SetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, MulticastOption optionValue) { Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest(); ipmr.MulticastAddress = unchecked((int)optionValue.Group.GetAddress()); if (optionValue.LocalAddress != null) { ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.GetAddress()); } else { //this structure works w/ interfaces as well int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex); ipmr.InterfaceAddress = unchecked((int)ifIndex); } #if BIGENDIAN ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) | (((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) | (((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) | ((uint) ipmr.MulticastAddress >> 24)); if (optionValue.LocalAddress != null) { ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) | (((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) | (((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) | ((uint) ipmr.InterfaceAddress >> 24)); } #endif // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.IP, optionName, ref ipmr, Interop.Winsock.IPMulticastRequest.Size); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError SetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, IPv6MulticastOption optionValue) { Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest(); ipmr.MulticastAddress = optionValue.Group.GetAddressBytes(); ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex); // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.IPv6, optionName, ref ipmr, Interop.Winsock.IPv6MulticastRequest.Size); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue) { Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger(); lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0; lngopt.Time = (ushort)optionValue.LingerTime; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref lngopt, 4); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue) { int optionLength = 4; // sizeof(int) SocketError errorCode = Interop.Winsock.getsockopt( handle, optionLevel, optionName, out optionValue, ref optionLength); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength) { SocketError errorCode = Interop.Winsock.getsockopt( handle, optionLevel, optionName, optionValue, ref optionLength); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out MulticastOption optionValue) { Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest(); int optlen = Interop.Winsock.IPMulticastRequest.Size; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.getsockopt( handle, SocketOptionLevel.IP, optionName, out ipmr, ref optlen); if (errorCode == SocketError.SocketError) { optionValue = default(MulticastOption); return GetLastSocketError(); } #if BIGENDIAN ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) | (((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) | (((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) | ((uint) ipmr.MulticastAddress >> 24)); ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) | (((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) | (((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) | ((uint) ipmr.InterfaceAddress >> 24)); #endif // BIGENDIAN IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress); IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress); optionValue = new MulticastOption(multicastAddr, multicastIntr); return SocketError.Success; } public static SocketError GetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out IPv6MulticastOption optionValue) { Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest(); int optlen = Interop.Winsock.IPv6MulticastRequest.Size; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.getsockopt( handle, SocketOptionLevel.IP, optionName, out ipmr, ref optlen); if (errorCode == SocketError.SocketError) { optionValue = default(IPv6MulticastOption); return GetLastSocketError(); } optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex); return SocketError.Success; } public static SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue) { Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger(); int optlen = 4; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.getsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, out lngopt, ref optlen); if (errorCode == SocketError.SocketError) { optionValue = default(LingerOption); return GetLastSocketError(); } optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time); return SocketError.Success; } public static SocketError Poll(SafeCloseSocket handle, int microseconds, SelectMode mode, out bool status) { IntPtr rawHandle = handle.DangerousGetHandle(); IntPtr[] fileDescriptorSet = new IntPtr[2] { (IntPtr)1, rawHandle }; Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue(); // A negative timeout value implies an indefinite wait. int socketCount; if (microseconds != -1) { MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait); socketCount = Interop.Winsock.select( 0, mode == SelectMode.SelectRead ? fileDescriptorSet : null, mode == SelectMode.SelectWrite ? fileDescriptorSet : null, mode == SelectMode.SelectError ? fileDescriptorSet : null, ref IOwait); } else { socketCount = Interop.Winsock.select( 0, mode == SelectMode.SelectRead ? fileDescriptorSet : null, mode == SelectMode.SelectWrite ? fileDescriptorSet : null, mode == SelectMode.SelectError ? fileDescriptorSet : null, IntPtr.Zero); } if ((SocketError)socketCount == SocketError.SocketError) { status = false; return GetLastSocketError(); } status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle; return SocketError.Success; } public static SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds) { IntPtr[] readfileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkRead); IntPtr[] writefileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkWrite); IntPtr[] errfileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkError); // This code used to erroneously pass a non-null timeval structure containing zeroes // to select() when the caller specified (-1) for the microseconds parameter. That // caused select to actually have a *zero* timeout instead of an infinite timeout // turning the operation into a non-blocking poll. // // Now we pass a null timeval struct when microseconds is (-1). // // Negative microsecond values that weren't exactly (-1) were originally successfully // converted to a timeval struct containing unsigned non-zero integers. This code // retains that behavior so that any app working around the original bug with, // for example, (-2) specified for microseconds, will continue to get the same behavior. int socketCount; if (microseconds != -1) { Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue(); MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait); socketCount = Interop.Winsock.select( 0, // ignored value readfileDescriptorSet, writefileDescriptorSet, errfileDescriptorSet, ref IOwait); } else { socketCount = Interop.Winsock.select( 0, // ignored value readfileDescriptorSet, writefileDescriptorSet, errfileDescriptorSet, IntPtr.Zero); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Socket::Select() Interop.Winsock.select returns socketCount:" + socketCount); } if ((SocketError)socketCount == SocketError.SocketError) { return GetLastSocketError(); } Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet); Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet); Socket.SelectFileDescriptor(checkError, errfileDescriptorSet); return SocketError.Success; } public static SocketError Shutdown(SafeCloseSocket handle, bool isConnected, bool isDisconnected, SocketShutdown how) { SocketError err = Interop.Winsock.shutdown(handle, (int)how); if (err != SocketError.SocketError) { return SocketError.Success; } err = GetLastSocketError(); Debug.Assert(err != SocketError.NotConnected || (!isConnected && !isDisconnected)); return err; } public static unsafe SocketError ConnectAsync(Socket socket, SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult) { // This will pin the socketAddress buffer. asyncResult.SetUnmanagedStructures(socketAddress); int ignoreBytesSent; if (!socket.ConnectEx( handle, Marshal.UnsafeAddrOfPinnedArrayElement(socketAddress, 0), socketAddressLen, IntPtr.Zero, 0, out ignoreBytesSent, asyncResult.OverlappedHandle)) { return GetLastSocketError(); } return SocketError.Success; } public static unsafe SocketError SendAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSASend. // This call will use completion ports. asyncResult.SetUnmanagedStructures(buffer, offset, count, null, false /*don't pin null remoteEP*/); // This can throw ObjectDisposedException. int bytesTransferred; SocketError errorCode = Interop.Winsock.WSASend( handle, ref asyncResult._singleBuffer, 1, // There is only ever 1 buffer being sent. out bytesTransferred, socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode != SocketError.Success) { errorCode = GetLastSocketError(); } return errorCode; } public static unsafe SocketError SendAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSASend. // This call will use completion ports. asyncResult.SetUnmanagedStructures(buffers); // This can throw ObjectDisposedException. int bytesTransferred; SocketError errorCode = Interop.Winsock.WSASend( handle, asyncResult._wsaBuffers, asyncResult._wsaBuffers.Length, out bytesTransferred, socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode != SocketError.Success) { errorCode = GetLastSocketError(); } return errorCode; } public static unsafe SocketError SendToAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSASendTo. // This call will use completion ports. asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, false /* don't pin RemoteEP*/); int bytesTransferred; SocketError errorCode = Interop.Winsock.WSASendTo( handle, ref asyncResult._singleBuffer, 1, // There is only ever 1 buffer being sent. out bytesTransferred, socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.SocketAddress.Size, asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode != SocketError.Success) { errorCode = GetLastSocketError(); } return errorCode; } public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSARecv. // This call will use completion ports. asyncResult.SetUnmanagedStructures(buffer, offset, count, null, false /* don't pin null RemoteEP*/); // This can throw ObjectDisposedException. int bytesTransferred; SocketError errorCode = Interop.Winsock.WSARecv( handle, ref asyncResult._singleBuffer, 1, out bytesTransferred, ref socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode != SocketError.Success) { errorCode = GetLastSocketError(); } return errorCode; } public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSASend. // This call will use completion ports. asyncResult.SetUnmanagedStructures(buffers); // This can throw ObjectDisposedException. int bytesTransferred; SocketError errorCode = Interop.Winsock.WSARecv( handle, asyncResult._wsaBuffers, asyncResult._wsaBuffers.Length, out bytesTransferred, ref socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode != SocketError.Success) { errorCode = GetLastSocketError(); } return errorCode; } public static unsafe SocketError ReceiveFromAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSARecvFrom. // This call will use completion ports on WinNT and Overlapped IO on Win9x. asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, true); int bytesTransferred; SocketError errorCode = Interop.Winsock.WSARecvFrom( handle, ref asyncResult._singleBuffer, 1, out bytesTransferred, ref socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.GetSocketAddressSizePtr(), asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode != SocketError.Success) { errorCode = GetLastSocketError(); } return errorCode; } public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult) { asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags); int bytesTransfered; SocketError errorCode = (SocketError)socket.WSARecvMsg( handle, Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0), out bytesTransfered, asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode != SocketError.Success) { errorCode = GetLastSocketError(); } return errorCode; } public static unsafe SocketError AcceptAsync(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult) { // The buffer needs to contain the requested data plus room for two sockaddrs and 16 bytes // of associated data for each. int addressBufferSize = socketAddressSize + 16; byte[] buffer = new byte[receiveSize + ((addressBufferSize) * 2)]; // Set up asyncResult for overlapped AcceptEx. // This call will use completion ports on WinNT. asyncResult.SetUnmanagedStructures(buffer, addressBufferSize); // This can throw ObjectDisposedException. int bytesTransferred; SocketError errorCode = SocketError.Success; if (!socket.AcceptEx( handle, acceptHandle, Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0), receiveSize, addressBufferSize, addressBufferSize, out bytesTransferred, asyncResult.OverlappedHandle)) { errorCode = GetLastSocketError(); } return errorCode; } public static void CheckDualModeReceiveSupport(Socket socket) { // Dual-mode sockets support received packet info on Windows. } } }
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.Runtime.Serialization; using System.Management.Automation.Internal; #if CORECLR // Use stubs for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types. using Microsoft.PowerShell.CoreClr.Stubs; #else using System.Security.Permissions; #endif namespace System.Management.Automation.Remoting { /// <summary> /// This enum defines the error message ids used by the resource manager to get /// localized messages. /// /// Related error ids are organized in a pre-defined range of values. /// </summary> internal enum PSRemotingErrorId : uint { // OS related 1-9 DefaultRemotingExceptionMessage = 0, OutOfMemory = 1, // Pipeline related range: 10-99 PipelineIdsDoNotMatch = 10, PipelineNotFoundOnServer = 11, PipelineStopped = 12, // Runspace, Host, UI and RawUI related range: 200-299 RunspaceAlreadyExists = 200, RunspaceIdsDoNotMatch = 201, RemoteRunspaceOpenFailed = 202, RunspaceCannotBeFound = 203, ResponsePromptIdCannotBeFound = 204, RemoteHostCallFailed = 205, RemoteHostMethodNotImplemented = 206, RemoteHostDataEncodingNotSupported = 207, RemoteHostDataDecodingNotSupported = 208, NestedPipelineNotSupported = 209, RelativeUriForRunspacePathNotSupported = 210, RemoteHostDecodingFailed = 211, MustBeAdminToOverrideThreadOptions = 212, RemoteHostPromptForCredentialModifiedCaption = 213, RemoteHostPromptForCredentialModifiedMessage = 214, RemoteHostReadLineAsSecureStringPrompt = 215, RemoteHostGetBufferContents = 216, RemoteHostPromptSecureStringPrompt = 217, WinPERemotingNotSupported = 218, // reserved range: 300-399 // Encoding/Decoding and fragmentation related range: 400-499 ReceivedUnsupportedRemoteHostCall = 400, ReceivedUnsupportedAction = 401, ReceivedUnsupportedDataType = 402, MissingDestination = 403, MissingTarget = 404, MissingRunspaceId = 405, MissingDataType = 406, MissingCallId = 407, MissingMethodName = 408, MissingIsStartFragment = 409, MissingProperty = 410, ObjectIdsNotMatching = 411, FragmentIdsNotInSequence = 412, ObjectIsTooBig = 413, MissingIsEndFragment = 414, DeserializedObjectIsNull = 415, BlobLengthNotInRange = 416, DecodingErrorForErrorRecord = 417, DecodingErrorForPipelineStateInfo = 418, DecodingErrorForRunspaceStateInfo = 419, ReceivedUnsupportedRemotingTargetInterfaceType = 420, UnknownTargetClass = 421, MissingTargetClass = 422, DecodingErrorForRunspacePoolStateInfo = 423, DecodingErrorForMinRunspaces = 424, DecodingErrorForMaxRunspaces = 425, DecodingErrorForPowerShellStateInfo = 426, DecodingErrorForThreadOptions = 427, CantCastPropertyToExpectedType = 428, CantCastRemotingDataToPSObject = 429, CantCastCommandToPSObject = 430, CantCastParameterToPSObject = 431, ObjectIdCannotBeLessThanZero = 432, NotEnoughHeaderForRemoteDataObject = 433, // reserved range: 500-599 // Remote Session related range: 600-699 RemotingDestinationNotForMe = 600, ClientNegotiationTimeout = 601, ClientNegotiationFailed = 602, ServerRequestedToCloseSession = 603, ServerNegotiationFailed = 604, ServerNegotiationTimeout = 605, ClientRequestedToCloseSession = 606, FatalErrorCausingClose = 607, ClientKeyExchangeFailed = 608, ServerKeyExchangeFailed = 609, ClientNotFoundCapabilityProperties = 610, ServerNotFoundCapabilityProperties = 611, // reserved range: 700-799 // Transport related range: 800-899 ConnectFailed = 801, CloseIsCalled = 802, ForceClosed = 803, CloseFailed = 804, CloseCompleted = 805, UnsupportedWaitHandleType = 806, ReceivedDataStreamIsNotStdout = 807, StdInIsNotOpen = 808, NativeWriteFileFailed = 809, NativeReadFileFailed = 810, InvalidSchemeValue = 811, ClientReceiveFailed = 812, ClientSendFailed = 813, CommandHandleIsNull = 814, StdInCannotBeSetToNoWait = 815, PortIsOutOfRange = 816, ServerProcessExited = 817, CannotGetStdInHandle = 818, CannotGetStdOutHandle = 819, CannotGetStdErrHandle = 820, CannotSetStdInHandle = 821, CannotSetStdOutHandle = 822, CannotSetStdErrHandle = 823, InvalidConfigurationName = 824, // Error codes added to support new WSMan Fan-In Model API CreateSessionFailed = 851, CreateExFailed = 853, ConnectExCallBackError = 854, SendExFailed = 855, SendExCallBackError = 856, ReceiveExFailed = 857, ReceiveExCallBackError = 858, RunShellCommandExFailed = 859, RunShellCommandExCallBackError = 860, CommandSendExFailed = 861, CommandSendExCallBackError = 862, CommandReceiveExFailed = 863, CommandReceiveExCallBackError = 864, CloseExCallBackError = 866, // END: Error codes added to support new WSMan Fan-In Model API // BEGIN: Error IDs introduced for URI redirection RedirectedURINotWellFormatted = 867, URIEndPointNotResolved = 868, // END: Error IDs introduced for URI redirection // BEGIN: Error IDs introduced for Quota Management ReceivedObjectSizeExceededMaximumClient = 869, ReceivedDataSizeExceededMaximumClient = 870, ReceivedObjectSizeExceededMaximumServer = 871, ReceivedDataSizeExceededMaximumServer = 872, // END: Error IDs introduced for Quota Management // BEGIN: Error IDs introduced for startup script StartupScriptThrewTerminatingError = 873, // END: Error IDs introduced for startup script TroubleShootingHelpTopic = 874, // BEGIN: Error IDs introduced for disconnect/reconnect DisconnectShellExFailed = 875, DisconnectShellExCallBackErrr = 876, ReconnectShellExFailed = 877, ReconnectShellExCallBackErrr = 878, // END: Error IDs introduced for disconnect/reconnect // Cmdlets related range: 900-999 RemoteRunspaceInfoHasDuplicates = 900, RemoteRunspaceInfoLimitExceeded = 901, RemoteRunspaceOpenUnknownState = 902, UriSpecifiedNotValid = 903, RemoteRunspaceClosed = 904, RemoteRunspaceNotAvailableForSpecifiedComputer = 905, RemoteRunspaceNotAvailableForSpecifiedRunspaceId = 906, StopPSJobWhatIfTarget = 907, InvalidJobStateGeneral = 909, JobWithSpecifiedNameNotFound = 910, JobWithSpecifiedInstanceIdNotFound = 911, JobWithSpecifiedSessionIdNotFound = 912, JobWithSpecifiedNameNotCompleted = 913, JobWithSpecifiedSessionIdNotCompleted = 914, JobWithSpecifiedInstanceIdNotCompleted = 915, RemovePSJobWhatIfTarget = 916, ComputerNameParamNotSupported = 917, RunspaceParamNotSupported = 918, RemoteRunspaceNotAvailableForSpecifiedName = 919, RemoteRunspaceNotAvailableForSpecifiedSessionId = 920, ItemNotFoundInRepository = 921, CannotRemoveJob = 922, NewRunspaceAmbiguousAuthentication = 923, WildCardErrorFilePathParameter = 924, FilePathNotFromFileSystemProvider = 925, FilePathShouldPS1Extension = 926, PSSessionConfigurationName = 927, PSSessionAppName = 928, // Custom Shell commands CSCDoubleParameterOutOfRange = 929, URIRedirectionReported = 930, NoMoreInputWrites = 931, InvalidComputerName = 932, ProxyAmbiguousAuthentication = 933, ProxyCredentialWithoutAccess = 934, // Start-PSSession related error codes. PushedRunspaceMustBeOpen = 951, HostDoesNotSupportPushRunspace = 952, RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId = 953, RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId = 954, RemoteRunspaceHasMultipleMatchesForSpecifiedName = 955, RemoteRunspaceDoesNotSupportPushRunspace = 956, HostInNestedPrompt = 957, RemoteHostDoesNotSupportPushRunspace = 958, InvalidVMId = 959, InvalidVMNameNoVM = 960, InvalidVMNameMultipleVM = 961, HyperVModuleNotAvailable = 962, InvalidUsername = 963, InvalidCredential = 964, VMSessionConnectFailed = 965, InvalidContainerId = 966, CannotCreateProcessInContainer = 967, CannotTerminateProcessInContainer = 968, ContainersFeatureNotEnabled = 969, RemoteSessionHyperVSocketServerConstructorFailure = 970, ContainerSessionConnectFailed = 973, RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure = 974, InvalidVMState = 975, // Invoke-Command related error codes. InvalidVMIdNotSingle = 981, InvalidVMNameNotSingle = 982, // SessionState Description related messages WsmanMaxRedirectionCountVariableDescription = 1001, PSDefaultSessionOptionDescription = 1002, PSSenderInfoDescription = 1004, // IPC for Background jobs related errors: 2000 IPCUnknownNodeType = 2001, IPCInsufficientDataforElement = 2002, IPCWrongAttributeCountForDataElement = 2003, IPCOnlyTextExpectedInDataElement = 2004, IPCWrongAttributeCountForElement = 2005, IPCUnknownElementReceived = 2006, IPCSupportsOnlyDefaultAuth = 2007, IPCWowComponentNotPresent = 2008, IPCServerProcessReportedError = 2100, IPCServerProcessExited = 2101, IPCErrorProcessingServerData = 2102, IPCUnknownCommandGuid = 2103, IPCNoSignalForSession = 2104, IPCSignalTimedOut = 2105, IPCCloseTimedOut = 2106, IPCExceptionLaunchingProcess = 2107, } /// <summary> /// This static class defines the resource base name used by remoting errors. /// It also provides a convenience method to get the localized strings. /// </summary> internal static class PSRemotingErrorInvariants { /// <summary> /// This method is a convenience method to retrieve the localized string. /// </summary> /// <param name="resourceString"> /// This parameter holds the string in the resource file. /// </param> /// <param name="args"> /// Optional parameters required by the resource string formating information. /// </param> /// <returns> /// The formatted localized string. /// </returns> internal static string FormatResourceString(string resourceString, params object[] args) { string resourceFormatedString = StringUtil.Format(resourceString, args); return resourceFormatedString; } } /// <summary> /// This exception is used by remoting code to indicated a data structure handler related error. /// </summary> [Serializable] public class PSRemotingDataStructureException : RuntimeException { #region Constructors /// <summary> /// Default constructor. /// </summary> public PSRemotingDataStructureException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingDataStructureException).FullName)) { SetDefaultErrorRecord(); } /// <summary> /// This constuctor takes a localized string as the error message. /// </summary> /// <param name="message"> /// A localized string as an error message. /// </param> public PSRemotingDataStructureException(string message) : base(message) { SetDefaultErrorRecord(); } /// <summary> /// This constuctor takes a localized string as the error message, and an inner exception. /// </summary> /// <param name="message"> /// A localized string as an error message. /// </param> /// <param name="innerException"> /// Inner exception. /// </param> public PSRemotingDataStructureException(string message, Exception innerException) : base(message, innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes an error id and optional parameters. /// </summary> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingDataStructureException(string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args)) { SetDefaultErrorRecord(); } /// <summary> /// This constuctor takes an inner exception and an error id. /// </summary> /// <param name="innerException"> /// Inner exception. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingDataStructureException(Exception innerException, string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor is required by serialization. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected PSRemotingDataStructureException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Constructors /// <summary> /// Set the default ErrorRecord. /// </summary> private void SetDefaultErrorRecord() { SetErrorCategory(ErrorCategory.ResourceUnavailable); SetErrorId(typeof(PSRemotingDataStructureException).FullName); } } /// <summary> /// This exception is used by remoting code to indicate an error condition in network operations. /// </summary> [Serializable] public class PSRemotingTransportException : RuntimeException { private int _errorCode; private string _transportMessage; #region Constructors /// <summary> /// This is the default constructor. /// </summary> public PSRemotingTransportException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingTransportException).FullName)) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized error message. /// </summary> /// <param name="message"> /// A localized error message. /// </param> public PSRemotingTransportException(string message) : base(message) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized message and an inner exception. /// </summary> /// <param name="message"> /// Localized error message. /// </param> /// <param name="innerException"> /// Inner exception. /// </param> public PSRemotingTransportException(string message, Exception innerException) : base(message, innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes an error id and optional parameters. /// </summary> /// <param name="errorId"> /// The error id in the base resource file. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportException(PSRemotingErrorId errorId, string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args)) { SetDefaultErrorRecord(); _errorCode = (int)errorId; } /// <summary> /// This constuctor takes an inner exception and an error id. /// </summary> /// <param name="innerException"> /// Inner exception. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportException(Exception innerException, string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor is required by serialization. /// </summary> /// <param name="info"></param> /// <param name="context"></param> /// <exception cref="ArgumentNullException"> /// 1. info is null. /// </exception> protected PSRemotingTransportException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new PSArgumentNullException("info"); } _errorCode = info.GetInt32("ErrorCode"); _transportMessage = info.GetString("TransportMessage"); } #endregion Constructors /// <summary> /// Serializes the exception data. /// </summary> /// <param name="info"> serialization information </param> /// <param name="context"> streaming context </param> [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException("info"); } base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue info.AddValue("ErrorCode", _errorCode); info.AddValue("TransportMessage", _transportMessage); } /// <summary> /// Set the default ErrorRecord. /// </summary> protected void SetDefaultErrorRecord() { SetErrorCategory(ErrorCategory.ResourceUnavailable); SetErrorId(typeof(PSRemotingDataStructureException).FullName); } /// <summary> /// The error code from native library API call. /// </summary> public int ErrorCode { get { return _errorCode; } set { _errorCode = value; } } /// <summary> /// This the message from the native transport layer. /// </summary> public string TransportMessage { get { return _transportMessage; } set { _transportMessage = value; } } } /// <summary> /// This exception is used by PowerShell's remoting infrastructure to notify a URI redirection /// exception. /// </summary> [Serializable] public class PSRemotingTransportRedirectException : PSRemotingTransportException { #region Constructor /// <summary> /// This is the default constructor. /// </summary> public PSRemotingTransportRedirectException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingTransportRedirectException).FullName)) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized error message. /// </summary> /// <param name="message"> /// A localized error message. /// </param> public PSRemotingTransportRedirectException(string message) : base(message) { } /// <summary> /// This constructor takes a localized message and an inner exception. /// </summary> /// <param name="message"> /// Localized error message. /// </param> /// <param name="innerException"> /// Inner exception. /// </param> public PSRemotingTransportRedirectException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// This constuctor takes an inner exception and an error id. /// </summary> /// <param name="innerException"> /// Inner exception. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportRedirectException(Exception innerException, string resourceString, params object[] args) : base(innerException, resourceString, args) { } /// <summary> /// This constructor is required by serialization. /// </summary> /// <param name="info"></param> /// <param name="context"></param> /// <exception cref="ArgumentNullException"> /// 1. info is null. /// </exception> protected PSRemotingTransportRedirectException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new PSArgumentNullException("info"); } RedirectLocation = info.GetString("RedirectLocation"); } /// <summary> /// This constructor takes an redirect URI, error id and optional parameters. /// </summary> /// <param name="redirectLocation"> /// String specifying a redirect location. /// </param> /// <param name="errorId"> /// The error id in the base resource file. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportRedirectException(string redirectLocation, PSRemotingErrorId errorId, string resourceString, params object[] args) : base(errorId, resourceString, args) { RedirectLocation = redirectLocation; } #endregion #region Public overrides /// <summary> /// Serializes the exception data. /// </summary> /// <param name="info"> serialization information </param> /// <param name="context"> streaming context </param> [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException("info"); } base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue info.AddValue("RedirectLocation", RedirectLocation); } #endregion #region Properties /// <summary> /// String specifying a redirect location. /// </summary> public string RedirectLocation { get; } #endregion } /// <summary> /// This exception is used by PowerShell Direct errors. /// </summary> [Serializable] public class PSDirectException : RuntimeException { #region Constructor /// <summary> /// This constuctor takes a localized string as the error message. /// </summary> /// <param name="message"> /// A localized string as an error message. /// </param> public PSDirectException(string message) : base(message) { } #endregion Constructor } }
/* Copyright 2011 - 2022 Adrian Popescu 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.Diagnostics; using System.Xml; using System.Xml.Serialization; using Newtonsoft.Json; using Redmine.Net.Api.Extensions; using Redmine.Net.Api.Internals; using Redmine.Net.Api.Serialization; namespace Redmine.Net.Api.Types { /// <summary> /// Availability 2.1 /// </summary> [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [XmlRoot(RedmineKeys.GROUP)] public sealed class Group : IdentifiableName, IEquatable<Group> { /// <summary> /// /// </summary> public Group() { } /// <summary> /// /// </summary> /// <param name="name"></param> public Group(string name) { Name = name; } #region Properties /// <summary> /// Represents the group's users. /// </summary> public IList<GroupUser> Users { get; set; } /// <summary> /// Gets or sets the custom fields. /// </summary> /// <value>The custom fields.</value> public IList<IssueCustomField> CustomFields { get; internal set; } /// <summary> /// Gets or sets the custom fields. /// </summary> /// <value>The custom fields.</value> public IList<Membership> Memberships { get; internal set; } #endregion #region Implementation of IXmlSerializable /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="System.Xml.XmlReader"/> stream from which the object is deserialized. </param> public override void ReadXml(XmlReader reader) { reader.Read(); while (!reader.EOF) { if (reader.IsEmptyElement && !reader.HasAttributes) { reader.Read(); continue; } switch (reader.Name) { case RedmineKeys.ID: Id = reader.ReadElementContentAsInt(); break; case RedmineKeys.CUSTOM_FIELDS: CustomFields = reader.ReadElementContentAsCollection<IssueCustomField>(); break; case RedmineKeys.MEMBERSHIPS: Memberships = reader.ReadElementContentAsCollection<Membership>(); break; case RedmineKeys.NAME: Name = reader.ReadElementContentAsString(); break; case RedmineKeys.USERS: Users = reader.ReadElementContentAsCollection<GroupUser>(); break; default: reader.Read(); break; } } } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="System.Xml.XmlWriter"/> stream to which the object is serialized. </param> public override void WriteXml(XmlWriter writer) { writer.WriteElementString(RedmineKeys.NAME, Name); writer.WriteArrayIds(RedmineKeys.USER_IDS, Users, typeof(int), GetGroupUserId); } #endregion #region Implementation of IJsonSerialization /// <summary> /// /// </summary> /// <param name="reader"></param> public override void ReadJson(JsonReader reader) { while (reader.Read()) { if (reader.TokenType == JsonToken.EndObject) { return; } if (reader.TokenType != JsonToken.PropertyName) { continue; } switch (reader.Value) { case RedmineKeys.ID: Id = reader.ReadAsInt(); break; case RedmineKeys.CUSTOM_FIELDS: CustomFields = reader.ReadAsCollection<IssueCustomField>(); break; case RedmineKeys.MEMBERSHIPS: Memberships = reader.ReadAsCollection<Membership>(); break; case RedmineKeys.NAME: Name = reader.ReadAsString(); break; case RedmineKeys.USERS: Users = reader.ReadAsCollection<GroupUser>(); break; default: reader.Read(); break; } } } /// <summary> /// /// </summary> /// <param name="writer"></param> public override void WriteJson(JsonWriter writer) { using (new JsonObject(writer, RedmineKeys.GROUP)) { writer.WriteProperty(RedmineKeys.NAME, Name); writer.WriteRepeatableElement(RedmineKeys.USER_IDS, (IEnumerable<IValue>)Users); } } #endregion #region Implementation of IEquatable<Group> /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(Group other) { if (other == null) return false; return Id == other.Id && Name == other.Name && (Users != null ? Users.Equals<GroupUser>(other.Users) : other.Users == null) && (CustomFields != null ? CustomFields.Equals<IssueCustomField>(other.CustomFields) : other.CustomFields == null) && (Memberships != null ? Memberships.Equals<Membership>(other.Memberships) : other.Memberships == null); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></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(obj as Group); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { unchecked { var hashCode = 13; hashCode = HashCodeHelper.GetHashCode(Id, hashCode); hashCode = HashCodeHelper.GetHashCode(Name, hashCode); hashCode = HashCodeHelper.GetHashCode(Users, hashCode); hashCode = HashCodeHelper.GetHashCode(CustomFields, hashCode); hashCode = HashCodeHelper.GetHashCode(Memberships, hashCode); return hashCode; } } #endregion /// <summary> /// /// </summary> /// <returns></returns> private string DebuggerDisplay => $"[{nameof(Group)}: {ToString()}, Users={Users.Dump()}, CustomFields={CustomFields.Dump()}, Memberships={Memberships.Dump()}]"; /// <summary> /// /// </summary> /// <param name="gu"></param> /// <returns></returns> public static int GetGroupUserId(object gu) { return ((GroupUser)gu).Id; } } }
/****************************************************************************** * 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. *******************************************************************************/ // // System.DirectoryServices.DirectorySearcher.cs // // Authors: // Sunil Kumar (sunilk@novell.com) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // // (C) Novell Inc. // using System.ComponentModel; using Novell.Directory.Ldap; using Novell.Directory.Ldap.Utilclass; using System.Collections.Specialized; namespace System.DirectoryServices { /// <summary> ///Performs queries against Ldap directory. /// </summary> public class DirectorySearcher : Component { private static readonly TimeSpan DefaultTimeSpan = new TimeSpan(-TimeSpan.TicksPerSecond); private DirectoryEntry _SearchRoot=null; private bool _CacheResults=true; private TimeSpan _ClientTimeout = DefaultTimeSpan; private string _Filter="(objectClass=*)"; private int _PageSize=0; private StringCollection _PropertiesToLoad=new StringCollection(); private bool _PropertyNamesOnly=false; private ReferralChasingOption _ReferralChasing= System.DirectoryServices.ReferralChasingOption.External; private SearchScope _SearchScope= System.DirectoryServices.SearchScope.Subtree; private TimeSpan _ServerPageTimeLimit = DefaultTimeSpan; private TimeSpan _serverTimeLimit = DefaultTimeSpan; private int _SizeLimit=0; private LdapConnection _conn = null; private string _Host=null; private int _Port=389; private SearchResultCollection _SrchColl=null; internal SearchResultCollection SrchColl { get { if (_SrchColl == null) { _SrchColl = new SearchResultCollection(); DoSearch(); } return _SrchColl; } } private void InitBlock() { _conn = new LdapConnection(); LdapUrl lUrl=new LdapUrl(SearchRoot.Path); _Host=lUrl.Host; _Port=lUrl.Port; _conn.Connect(_Host,_Port); _conn.Bind(SearchRoot.Username,SearchRoot.Password); } /// <summary> /// Gets or sets a value indicating whether the result is /// cached on the client computer. /// </summary> /// <value> /// true if the result is cached on the client computer; otherwise, /// false. The default is true /// </value> /// <remarks> /// If the search returns a large result set, it is better to set /// this property to false. /// </remarks> [DSDescription ("The cacheability of results.")] [DefaultValue (true)] public bool CacheResults { get { return _CacheResults; } set { _CacheResults = value; } } /// <summary> /// Gets or sets the maximum amount of time that the client waits for /// the server to return results. If the server does not respond /// within this time, the search is aborted and no results are /// returned. /// </summary> /// <value> /// A TimeSpan that represents the maximum amount of time (in seconds) /// for the client to wait for the server to return results. The /// default is -1, which means to wait indefinitely. /// </value> /// <remarks> /// If the ServerTimeLimit is reached before the client times out, /// the server returns its results and the client stops waiting. The /// maximum server time limit is 120 seconds. /// </remarks> [DSDescription ("The maximum amount of time that the client waits for the server to return results.")] public TimeSpan ClientTimeout { get { return _ClientTimeout; } set { _ClientTimeout = value; } } /// <summary> /// Gets or sets the Lightweight Directory Access Protocol (Ldap) /// format filter string. /// </summary> /// <value> /// The search filter string in Ldap format, such as /// "(objectClass=user)". The default is "(objectClass=*)", which /// retrieves all objects. /// </value> /// <remarks> /// The filter uses the following guidelines: /// 1. The string must be enclosed in parentheses. /// 2. Expressions can use the relational operators: <, <=, =, >=, /// and >. An example is "(objectClass=user)". Another example is /// "(lastName>=Davis)". /// 3. Compound expressions are formed with the prefix operators & /// and |. Anexampleis"(&(objectClass=user)(lastName= Davis))". /// Anotherexampleis"(&(objectClass=printer)(|(building=42) /// (building=43)))". /// </remarks> [DSDescription ("The Lightweight Directory Access Protocol (Ldap) format filter string.")] [DefaultValue ("(objectClass=*)")] [RecommendedAsConfigurable (true)] [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)] public string Filter { get { return _Filter; } set { _Filter = value; ClearCachedResults(); } } /// <summary> /// Gets or sets the page size in a paged search. /// </summary> /// <value> /// The maximum number of objects the server can return in a paged /// search. The default is zero, which means do not do a paged search. /// </value> /// <remarks> /// After the server has found a PageSize object, it will stop /// searching and return the results to the client. When the client /// requests more data, the server will restart the search where it /// left off. /// </remarks> [DSDescription ("The page size in a paged search.")] [DefaultValue (0)] public int PageSize { get { return _PageSize; } set { _PageSize = value; } } /// <summary> /// Gets the set of properties retrieved during the search. /// </summary> /// <value> /// The set of properties retrieved during the search. The default is /// an empty StringCollection, which retrieves all properties. /// </value> /// <remarks> /// To retrieve specific properties, add them to this collection /// before you begin the search. For example, searcher. /// PropertiesToLoad.Add("phone");. /// </remarks> [DSDescription ("The set of properties retrieved during the search.")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)] [Editor ("System.Windows.Forms.Design.StringCollectionEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)] public StringCollection PropertiesToLoad { get { return _PropertiesToLoad; } } /// <summary> /// Gets or sets a value indicating whether the search retrieves only the /// names of attributes to which values have been assigned. /// </summary> /// <value> /// true if the search obtains only the names of attributes to which /// values have been assigned; false if the search obtains the names /// and values for all the requested attributes. The default is false. /// </value> [DSDescription ("A value indicating whether the search retrieves only the names of attributes to which values have been assigned.")] [DefaultValue (false)] public bool PropertyNamesOnly { get { return _PropertyNamesOnly; } set { _PropertyNamesOnly = value; } } /// <summary> /// Gets or sets how referrals are chased. /// </summary> /// <value> /// One of the ReferralChasingOption values. The default is External. /// </value> /// <remarks> /// If the root search is not specified in the naming context of the /// server or when the search results cross a naming context (for /// example, when you have child domains and search in the parent /// domain), the server sends a referral message to the client that /// the client can choose to ignore or chase. /// </remarks> [DSDescription ("How referrals are chased.")] [DefaultValue (ReferralChasingOption.External)] public ReferralChasingOption ReferralChasing { get { return _ReferralChasing; } set { _ReferralChasing = value; } } /// <summary> /// Gets or sets the node in the Ldap Directory hierarchy where the /// search starts. /// </summary> /// <value> /// The DirectoryEntry in the Ldap Directory hierarchy where the /// search starts. The default is a null reference /// </value> [DSDescription ("The node in the Ldap Directory hierarchy where the search starts.")] [DefaultValue (null)] public DirectoryEntry SearchRoot { get { return _SearchRoot; } set { _SearchRoot = value; ClearCachedResults(); } } /// <summary> /// Gets or sets the scope of the search that is observed by the /// server. /// </summary> /// <value> /// One of the SearchScope values. The default is Subtree. /// </value> [DSDescription ("The scope of the search that is observed by the server.")] [DefaultValue (SearchScope.Subtree)] [RecommendedAsConfigurable (true)] public SearchScope SearchScope { get { return _SearchScope; } set { _SearchScope = value; ClearCachedResults(); } } /// <summary> /// Gets or sets the time limit the server should observe to search an /// individual page of results (as opposed to the time limit for the /// entire search). /// </summary> /// <value> /// A TimeSpan that represents the amount of time the server should /// observe to search a page of results. The default is -1, which /// means to search indefinitely. /// </value> /// <remarks> /// When the time limit is reached, the server stops searching and /// returns the result obtained up to that point, along with a cookie /// containing the information about where to resume searching. /// A negative value means to search indefinitely. /// Note: This property only applies to searches where PageSize /// is set to a value that is not the default of -1. /// </remarks> [DSDescription ("The time limit the server should observe to search an individual page of results.")] public TimeSpan ServerPageTimeLimit { get { return _ServerPageTimeLimit; } set { _ServerPageTimeLimit = value; } } /// <summary> /// Gets or sets the time limit the server should observe to search. /// </summary> /// <value> /// A TimeSpan that represents the amount of time the server should /// observe to search. /// </value> /// <remarks> /// Not implemented /// </remarks> [DSDescription ("The time limit the server should observe to search.")] public TimeSpan ServerTimeLimit { [MonoTODO] get { return _serverTimeLimit; } [MonoTODO] set { _serverTimeLimit = value; } } /// <summary> /// Gets or sets the maximum number of objects the server returns in /// a search. /// </summary> /// <value> /// The maximum number of objects the server returns in a search. The /// default of zero means to use the server-determined default size /// limit of 1000 entries. /// </value> /// <remarks> /// The server stops searching after the size limit is reached and /// returns the results accumulated up to that point. /// Note: If you set SizeLimit to a value that is larger /// than the server-determined default of 1000 entries, the /// server-determined default is used. /// </remarks> [DSDescription ("The maximum number of objects the server returns in a search.")] [DefaultValue (0)] public int SizeLimit { get { return _SizeLimit; } set { if (value < 0) { throw new ArgumentException(); } _SizeLimit = value; } } [DSDescription ("An object that defines how the data should be sorted.")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)] [TypeConverter (typeof (ExpandableObjectConverter))] public SortOption Sort { [MonoTODO] get { throw new NotImplementedException(); } [MonoTODO] set { throw new NotImplementedException(); } } /// <summary> /// Initializes a new instance of the DirectorySearcher class with /// SearchRoot, Filter, PropertiesToLoad, and SearchScope set to the /// default values. /// </summary> public DirectorySearcher() { } /// <summary> /// Initializes a new instance of the DirectorySearcher class with /// Filter, PropertiesToLoad, and SearchScope set to the default /// values. SearchRoot is set to the specified value. /// </summary> /// <param name="searchRoot"> /// The node in the Active Directory hierarchy where the search starts. /// The SearchRoot property is initialized to this value. /// </param> public DirectorySearcher(DirectoryEntry searchRoot) { _SearchRoot = searchRoot; } /// <summary> /// Initializes a new instance of the DirectorySearcher class with /// SearchRoot, PropertiesToLoad, and SearchScope set to the default /// values. Filter is set to the specified value. /// </summary> /// <param name="filter"> /// The search filter string in Lightweight Directory Access Protocol /// (Ldap) format. The Filter property is initialized to this value. /// </param> public DirectorySearcher(string filter) { _Filter = filter; } /// <summary> /// Initializes a new instance of the DirectorySearcher class with /// PropertiesToLoad and SearchScope set to the default values. /// SearchRoot and Filter are set to the specified values. /// </summary> /// <param name="searchRoot"> /// The node in the Active Directory hierarchy where the search starts. /// The SearchRoot property is initialized to this value. /// </param> /// <param name="filter"> /// The search filter string in Lightweight Directory Access Protocol /// (Ldap) format. The Filter property is initialized to this value. /// </param> public DirectorySearcher( DirectoryEntry searchRoot, string filter ) { _SearchRoot = searchRoot; _Filter = filter; } /// <summary> /// Initializes a new instance of the DirectorySearcher class with /// SearchRoot and SearchScope set to the default values. Filter and /// PropertiesToLoad are set to the specified values. /// </summary> /// <param name="filter"> /// The search filter string in Lightweight Directory Access Protocol /// (Ldap) format. The Filter property is initialized to this value. /// </param> /// <param name="propertiesToLoad"> /// The set of properties to retrieve during the search. The /// PropertiesToLoad property is initialized to this value. /// </param> public DirectorySearcher( string filter, string[] propertiesToLoad ) { _Filter = filter; PropertiesToLoad.AddRange(propertiesToLoad); } /// <summary> /// Initializes a new instance of the DirectorySearcher class with /// SearchScope set to its default value. SearchRoot, Filter, and /// PropertiesToLoad are set to the specified values. /// </summary> /// <param name="searchRoot"> /// The node in the Active Directory hierarchy where the search starts. /// The SearchRoot property is initialized to this value /// </param> /// <param name="filter"> /// The search filter string in Lightweight Directory Access Protocol /// (Ldap) format. The Filter property is initialized to this value. /// </param> /// <param name="propertiesToLoad"> /// The set of properties retrieved during the search. The /// PropertiesToLoad property is initialized to this value. /// </param> public DirectorySearcher( DirectoryEntry searchRoot, string filter, string[] propertiesToLoad ) { _SearchRoot = searchRoot; _Filter = filter; PropertiesToLoad.AddRange(propertiesToLoad); } /// <summary> /// Initializes a new instance of the DirectorySearcher class with /// SearchRoot set to its default value. Filter, PropertiesToLoad, /// and SearchScope are set to the specified values /// </summary> /// <param name="filter"> /// The search filter string in Lightweight Directory Access Protocol /// (Ldap) format. The Filter property is initialized to this value. /// </param> /// <param name="propertiesToLoad"> /// The set of properties to retrieve during the search. The /// PropertiesToLoad property is initialized to this value. /// </param> /// <param name="scope"> /// The scope of the search that is observed by the server. The /// SearchScope property is initialized to this value. /// </param> public DirectorySearcher( string filter, string[] propertiesToLoad, SearchScope scope ) { _SearchScope = scope; _Filter = filter; PropertiesToLoad.AddRange(propertiesToLoad); } /// <summary> /// Initializes a new instance of the DirectorySearcher class with the /// SearchRoot, Filter, PropertiesToLoad, and SearchScope properties /// set to the specified values /// </summary> /// <param name="searchRoot"> /// The node in the Active Directory hierarchy where the search starts. /// The SearchRoot property is initialized to this value. /// </param> /// <param name="filter"> /// The search filter string in Lightweight Directory Access Protocol /// (Ldap) format. The Filter property is initialized to this value. /// </param> /// <param name="propertiesToLoad"> /// The set of properties to retrieve during the search. The /// PropertiesToLoad property is initialized to this value. /// </param> /// <param name="scope"> /// The scope of the search that is observed by the server. The /// SearchScope property is initialized to this value. /// </param> public DirectorySearcher( DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope ) { _SearchRoot = searchRoot; _SearchScope = scope; _Filter = filter; PropertiesToLoad.AddRange(propertiesToLoad); } /// <summary> /// Executes the Search and returns only the first entry found /// </summary> /// <returns> /// A SearchResult that is the first entry found during the Search /// </returns> public SearchResult FindOne() { // TBD : should search for no more than single result if (SrchColl.Count == 0) { return null; } return SrchColl[0]; } /// <summary> /// Executes the Search and returns a collection of the entries that are found /// </summary> /// <returns> /// A SearchResultCollection collection of entries from the director /// </returns> public SearchResultCollection FindAll() { return SrchColl; } private void DoSearch() { InitBlock(); if (!PropertiesToLoad.Contains("ADsPath")) { PropertiesToLoad.Add("ADsPath"); } String[] attrs= new String[PropertiesToLoad.Count]; PropertiesToLoad.CopyTo(attrs,0); LdapSearchConstraints cons = _conn.SearchConstraints; if (SizeLimit > 0) { cons.MaxResults = SizeLimit; } if (ServerTimeLimit != DefaultTimeSpan) { cons.ServerTimeLimit = (int)ServerTimeLimit.TotalSeconds; } int connScope = LdapConnection.SCOPE_SUB; switch (_SearchScope) { case SearchScope.Base: connScope = LdapConnection.SCOPE_BASE; break; case SearchScope.OneLevel: connScope = LdapConnection.SCOPE_ONE; break; case SearchScope.Subtree: connScope = LdapConnection.SCOPE_SUB; break; default: connScope = LdapConnection.SCOPE_SUB; break; } LdapSearchResults lsc=_conn.Search( SearchRoot.Fdn, connScope, Filter, attrs, false,cons); while(lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch(LdapException e) { switch (e.ResultCode) { // in case of this return codes exception should not be thrown case LdapException.SIZE_LIMIT_EXCEEDED: case LdapException.TIME_LIMIT_EXCEEDED: continue; default : throw e; } } DirectoryEntry de = new DirectoryEntry(_conn); PropertyCollection pcoll = new PropertyCollection(); // de.SetProperties(); de.Path="LDAP://" + _Host+ ":" + _Port + "/" + nextEntry.DN; LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum=attributeSet.GetEnumerator(); if(ienum!=null) { while(ienum.MoveNext()) { LdapAttribute attribute=(LdapAttribute)ienum.Current; string attributeName = attribute.Name; pcoll[attributeName].AddRange(attribute.StringValueArray); // de.Properties[attributeName].AddRange(attribute.StringValueArray); // de.Properties[attributeName].Mbit=false; } } if (!pcoll.Contains("ADsPath")) { pcoll["ADsPath"].Add(de.Path); } // _SrchColl.Add(new SearchResult(de,PropertiesToLoad)); _SrchColl.Add(new SearchResult(de,pcoll)); } return; } [MonoTODO] protected override void Dispose(bool disposing) { if (disposing) { if(_conn.Connected) { _conn.Disconnect(); } } base.Dispose(disposing); } private void ClearCachedResults() { _SrchColl = null; } } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, 2003 // // File: eventproxy.cs //------------------------------------------------------------------------------ #pragma warning disable 1634, 1691 // Allow suppression of certain presharp messages using System.Windows.Media; using System; using MS.Internal; using MS.Win32; using System.Reflection; using System.Collections; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; using MS.Internal.PresentationCore; // TODOTODO Make our own namespace for internal stuff. namespace System.Windows.Media { #region EventProxyDescriptor [StructLayout(LayoutKind.Sequential)] internal struct EventProxyDescriptor { internal delegate void Dispose( ref EventProxyDescriptor pEPD ); internal delegate int RaiseEvent( ref EventProxyDescriptor pEPD, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] buffer, uint cb ); internal Dispose pfnDispose; internal RaiseEvent pfnRaiseEvent; ///<SecurityNote> /// Critical: calls GCHandle.get_Target which LinkDemands /// TreatAsSafe: can't pass in an arbitrary class, only EventProxyDescriptor. Also, it's OK to dispose this. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal static void StaticDispose(ref EventProxyDescriptor pEPD) { Debug.Assert(((IntPtr)pEPD.m_handle) != IntPtr.Zero, "If this asserts fires: Why is it firing? It might be legal in future."); EventProxyWrapper epw = (EventProxyWrapper)(pEPD.m_handle.Target); ((System.Runtime.InteropServices.GCHandle)(pEPD.m_handle)).Free(); } internal System.Runtime.InteropServices.GCHandle m_handle; } #endregion #region EventProxyStaticPtrs /// <summary> /// We need to keep the delegates alive. /// </summary> internal static class EventProxyStaticPtrs { static EventProxyStaticPtrs() { EventProxyStaticPtrs.pfnDispose = new EventProxyDescriptor.Dispose(EventProxyDescriptor.StaticDispose); EventProxyStaticPtrs.pfnRaiseEvent = new EventProxyDescriptor.RaiseEvent(EventProxyWrapper.RaiseEvent); } internal static EventProxyDescriptor.Dispose pfnDispose; internal static EventProxyDescriptor.RaiseEvent pfnRaiseEvent; } #endregion #region EventProxyWrapper /// <summary> /// Event proxy wrapper will relay events from unmanaged code to managed code /// </summary> internal class EventProxyWrapper { private WeakReference target; #region Constructor private EventProxyWrapper(IInvokable invokable) { target = new WeakReference(invokable); } #endregion #region Verify private void Verify() { if (target == null) { throw new System.ObjectDisposedException("EventProxyWrapper"); } } #endregion #region Public methods ///<SecurityNote> /// Critical: calls Marshal.GetHRForException which LinkDemands /// TreatAsSafe: ok to return an hresult in partial trust ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] public int RaiseEvent(byte[] buffer, uint cb) { #pragma warning disable 6500 try { Verify(); IInvokable invokable = (IInvokable)target.Target; if (invokable != null) { invokable.RaiseEvent(buffer, (int)cb); } else { // return E_HANDLE to notify that object is no longer alive return NativeMethods.E_HANDLE; } } catch (Exception e) { return Marshal.GetHRForException(e); } #pragma warning restore 6500 return NativeMethods.S_OK; } #endregion #region Delegate Implemetations /// <SecurityNote> /// Critical: This code calls into handle to get Target which has a link demand /// TreatAsSafe: EventProxyWrapper is safe to expose /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal static EventProxyWrapper FromEPD(ref EventProxyDescriptor epd) { Debug.Assert(((IntPtr)epd.m_handle) != IntPtr.Zero, "Stream is disposed."); System.Runtime.InteropServices.GCHandle handle = (System.Runtime.InteropServices.GCHandle)(epd.m_handle); return (EventProxyWrapper)(handle.Target); } internal static int RaiseEvent(ref EventProxyDescriptor pEPD, byte[] buffer, uint cb) { EventProxyWrapper target = EventProxyWrapper.FromEPD(ref pEPD); if (target != null) { return target.RaiseEvent(buffer, cb); } else { return NativeMethods.E_HANDLE; } } #endregion #region Static Create Method(s) /// <SecurityNote> /// Critical: This code hooks up event sinks for unmanaged events /// It also calls into a native method via MILCreateEventProxy /// </SecurityNote> [SecurityCritical] internal static SafeMILHandle CreateEventProxyWrapper(IInvokable invokable) { if (invokable == null) { throw new System.ArgumentNullException("invokable"); } SafeMILHandle eventProxy = null; EventProxyWrapper epw = new EventProxyWrapper(invokable); EventProxyDescriptor epd = new EventProxyDescriptor(); epd.pfnDispose = EventProxyStaticPtrs.pfnDispose; epd.pfnRaiseEvent = EventProxyStaticPtrs.pfnRaiseEvent; epd.m_handle = System.Runtime.InteropServices.GCHandle.Alloc(epw, System.Runtime.InteropServices.GCHandleType.Normal); HRESULT.Check(MILCreateEventProxy(ref epd, out eventProxy)); return eventProxy; } #endregion /// <SecurityNote> /// Critical: Elevates to unmanaged code permission /// </SecurityNote> [SuppressUnmanagedCodeSecurity] [SecurityCritical] [DllImport(DllImport.MilCore)] private extern static int /* HRESULT */ MILCreateEventProxy(ref EventProxyDescriptor pEPD, out SafeMILHandle ppEventProxy); } #endregion }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Conversations.V1.Service { /// <summary> /// Add a new conversation user to your service /// </summary> public class CreateUserOptions : IOptions<UserResource> { /// <summary> /// The SID of the Conversation Service that the resource is associated with /// </summary> public string PathChatServiceSid { get; } /// <summary> /// The string that identifies the resource's User /// </summary> public string Identity { get; } /// <summary> /// The string that you assigned to describe the resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// The JSON Object string that stores application-specific data /// </summary> public string Attributes { get; set; } /// <summary> /// The SID of a service-level Role to assign to the user /// </summary> public string RoleSid { get; set; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public UserResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new CreateUserOptions /// </summary> /// <param name="pathChatServiceSid"> The SID of the Conversation Service that the resource is associated with </param> /// <param name="identity"> The string that identifies the resource's User </param> public CreateUserOptions(string pathChatServiceSid, string identity) { PathChatServiceSid = pathChatServiceSid; Identity = identity; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Identity != null) { p.Add(new KeyValuePair<string, string>("Identity", Identity)); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } if (RoleSid != null) { p.Add(new KeyValuePair<string, string>("RoleSid", RoleSid.ToString())); } return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } /// <summary> /// Update an existing conversation user in your service /// </summary> public class UpdateUserOptions : IOptions<UserResource> { /// <summary> /// The SID of the Conversation Service that the resource is associated with /// </summary> public string PathChatServiceSid { get; } /// <summary> /// The SID of the User resource to update /// </summary> public string PathSid { get; } /// <summary> /// The string that you assigned to describe the resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// The JSON Object string that stores application-specific data /// </summary> public string Attributes { get; set; } /// <summary> /// The SID of a service-level Role to assign to the user /// </summary> public string RoleSid { get; set; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public UserResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new UpdateUserOptions /// </summary> /// <param name="pathChatServiceSid"> The SID of the Conversation Service that the resource is associated with </param> /// <param name="pathSid"> The SID of the User resource to update </param> public UpdateUserOptions(string pathChatServiceSid, string pathSid) { PathChatServiceSid = pathChatServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } if (RoleSid != null) { p.Add(new KeyValuePair<string, string>("RoleSid", RoleSid.ToString())); } return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } /// <summary> /// Remove a conversation user from your service /// </summary> public class DeleteUserOptions : IOptions<UserResource> { /// <summary> /// The SID of the Conversation Service to delete the resource from /// </summary> public string PathChatServiceSid { get; } /// <summary> /// The SID of the User resource to delete /// </summary> public string PathSid { get; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public UserResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new DeleteUserOptions /// </summary> /// <param name="pathChatServiceSid"> The SID of the Conversation Service to delete the resource from </param> /// <param name="pathSid"> The SID of the User resource to delete </param> public DeleteUserOptions(string pathChatServiceSid, string pathSid) { PathChatServiceSid = pathChatServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } /// <summary> /// Fetch a conversation user from your service /// </summary> public class FetchUserOptions : IOptions<UserResource> { /// <summary> /// The SID of the Conversation Service to fetch the resource from /// </summary> public string PathChatServiceSid { get; } /// <summary> /// The SID of the User resource to fetch /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchUserOptions /// </summary> /// <param name="pathChatServiceSid"> The SID of the Conversation Service to fetch the resource from </param> /// <param name="pathSid"> The SID of the User resource to fetch </param> public FetchUserOptions(string pathChatServiceSid, string pathSid) { PathChatServiceSid = pathChatServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Retrieve a list of all conversation users in your service /// </summary> public class ReadUserOptions : ReadOptions<UserResource> { /// <summary> /// The SID of the Conversation Service to read the User resources from /// </summary> public string PathChatServiceSid { get; } /// <summary> /// Construct a new ReadUserOptions /// </summary> /// <param name="pathChatServiceSid"> The SID of the Conversation Service to read the User resources from </param> public ReadUserOptions(string pathChatServiceSid) { PathChatServiceSid = pathChatServiceSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } }
//#define USE_GENERICS //#define DELETE_AFTER_TEST using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Orleans; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Providers.Streams.AzureQueue; using Orleans.Runtime; using Orleans.TestingHost; using Tester; using Tester.AzureUtils.Streaming; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using UnitTests.StreamingTests; using Xunit; using Xunit.Abstractions; using Tester.AzureUtils; // ReSharper disable ConvertToConstant.Local // ReSharper disable CheckNamespace namespace UnitTests.Streaming.Reliability { [TestCategory("Streaming"), TestCategory("Reliability")] public class StreamReliabilityTests : TestClusterPerTest { private readonly ITestOutputHelper output; public const string SMS_STREAM_PROVIDER_NAME = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; public const string AZURE_QUEUE_STREAM_PROVIDER_NAME = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; private const int queueCount = 8; private Guid _streamId; private string _streamProviderName; private int numExpectedSilos; #if DELETE_AFTER_TEST private HashSet<IStreamReliabilityTestGrain> _usedGrains; #endif protected override void ConfigureTestCluster(TestClusterBuilder builder) { TestUtils.CheckForAzureStorage(); this.numExpectedSilos = 2; builder.CreateSiloAsync = StandaloneSiloHandle.CreateForAssembly(this.GetType().Assembly); builder.Options.InitialSilosCount = (short) this.numExpectedSilos; builder.Options.UseTestClusterMembership = false; builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<ClientBuilderConfigurator>(); } public class ClientBuilderConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder.UseAzureStorageClustering(gatewayOptions => { gatewayOptions.ConfigureTestDefaults(); }) .AddAzureQueueStreams(AZURE_QUEUE_STREAM_PROVIDER_NAME, ob => ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); })) .AddSimpleMessageStreamProvider(SMS_STREAM_PROVIDER_NAME) .Configure<GatewayOptions>(options => options.GatewayListRefreshPeriod = TimeSpan.FromSeconds(5)); } } public class SiloBuilderConfigurator : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder.UseAzureStorageClustering(options => { options.ConfigureTestDefaults(); }) .AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConfigureTestDefaults(); options.DeleteStateOnClear = true; })) .AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1) .AddSimpleMessageStreamProvider(SMS_STREAM_PROVIDER_NAME) .AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.DeleteStateOnClear = true; options.ConfigureTestDefaults(); })) .AddAzureQueueStreams(AZURE_QUEUE_STREAM_PROVIDER_NAME, ob => ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); })) .AddAzureQueueStreams("AzureQueueProvider2", ob => ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames($"{dep.Value.ClusterId}2", queueCount); })); } } public StreamReliabilityTests(ITestOutputHelper output) { this.output = output; #if DELETE_AFTER_TEST _usedGrains = new HashSet<IStreamReliabilityTestGrain>(); #endif } public override async Task InitializeAsync() { await base.InitializeAsync(); CheckSilosRunning("Initially", numExpectedSilos); } public override async Task DisposeAsync() { #if DELETE_AFTER_TEST List<Task> promises = new List<Task>(); foreach (var g in _usedGrains) { promises.Add(g.ClearGrain()); } await Task.WhenAll(promises); #endif await base.DisposeAsync(); if (!string.IsNullOrWhiteSpace(TestDefaultConfiguration.DataConnectionString)) { await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount), new AzureQueueOptions().ConfigureTestDefaults()); await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount), new AzureQueueOptions().ConfigureTestDefaults()); } } [SkippableFact, TestCategory("Functional")] public void Baseline_StreamRel() { // This test case is just a sanity-check that the silo test config is OK. const string testName = "Baseline_StreamRel"; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); StreamTestUtils.LogEndTest(testName, logger); } [SkippableFact, TestCategory("Functional")] public async Task Baseline_StreamRel_RestartSilos() { // This test case is just a sanity-check that the silo test config is OK. const string testName = "Baseline_StreamRel_RestartSilos"; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); CheckSilosRunning("Before Restart", numExpectedSilos); var silos = this.HostedCluster.Silos; await RestartAllSilos(); CheckSilosRunning("After Restart", numExpectedSilos); Assert.NotEqual(silos, this.HostedCluster.Silos); // Should be different silos after restart StreamTestUtils.LogEndTest(testName, logger); } [SkippableFact, TestCategory("Functional")] public async Task SMS_Baseline_StreamRel() { // This test case is just a sanity-check that the SMS test config is OK. const string testName = "SMS_Baseline_StreamRel"; _streamId = Guid.NewGuid(); _streamProviderName = SMS_STREAM_PROVIDER_NAME; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); // Grain Producer -> Grain Consumer long consumerGrainId = random.Next(); long producerGrainId = random.Next(); await Do_BaselineTest(consumerGrainId, producerGrainId); StreamTestUtils.LogEndTest(testName, logger); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure")] public async Task AQ_Baseline_StreamRel() { // This test case is just a sanity-check that the AzureQueue test config is OK. const string testName = "AQ_Baseline_StreamRel"; _streamId = Guid.NewGuid(); _streamProviderName = AZURE_QUEUE_STREAM_PROVIDER_NAME; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); await Do_BaselineTest(consumerGrainId, producerGrainId); StreamTestUtils.LogEndTest(testName, logger); } [SkippableFact(Skip ="Ignore"), TestCategory("Failures"), TestCategory("Streaming"), TestCategory("Reliability")] public async Task SMS_AddMany_Consumers() { const string testName = "SMS_AddMany_Consumers"; await Test_AddMany_Consumers(testName, SMS_STREAM_PROVIDER_NAME); } [SkippableFact(Skip = "Ignore"), TestCategory("Failures"), TestCategory("Streaming"), TestCategory("Reliability"), TestCategory("Azure")] public async Task AQ_AddMany_Consumers() { const string testName = "AQ_AddMany_Consumers"; await Test_AddMany_Consumers(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional")] public async Task SMS_PubSub_MultiConsumerSameGrain() { const string testName = "SMS_PubSub_MultiConsumerSameGrain"; await Test_PubSub_MultiConsumerSameGrain(testName, SMS_STREAM_PROVIDER_NAME); } // AQ_PubSub_MultiConsumerSameGrain not required - does not use PubSub [SkippableFact, TestCategory("Functional")] public async Task SMS_PubSub_MultiProducerSameGrain() { const string testName = "SMS_PubSub_MultiProducerSameGrain"; await Test_PubSub_MultiProducerSameGrain(testName, SMS_STREAM_PROVIDER_NAME); } // AQ_PubSub_MultiProducerSameGrain not required - does not use PubSub [SkippableFact, TestCategory("Functional")] public async Task SMS_PubSub_Unsubscribe() { const string testName = "SMS_PubSub_Unsubscribe"; await Test_PubSub_Unsubscribe(testName, SMS_STREAM_PROVIDER_NAME); } // AQ_PubSub_Unsubscribe not required - does not use PubSub //TODO: This test fails because the resubscribe to streams after restart creates a new subscription, losing the events on the previous subscription. Should be fixed when 'renew' subscription feature is added. - jbragg [SkippableFact, TestCategory("Functional"), TestCategory("Failures")] public async Task SMS_StreamRel_AllSilosRestart_PubSubCounts() { const string testName = "SMS_StreamRel_AllSilosRestart_PubSubCounts"; await Test_AllSilosRestart_PubSubCounts(testName, SMS_STREAM_PROVIDER_NAME); } // AQ_StreamRel_AllSilosRestart_PubSubCounts not required - does not use PubSub [SkippableFact, TestCategory("Functional")] public async Task SMS_StreamRel_AllSilosRestart() { const string testName = "SMS_StreamRel_AllSilosRestart"; await Test_AllSilosRestart(testName, SMS_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")] public async Task AQ_StreamRel_AllSilosRestart() { const string testName = "AQ_StreamRel_AllSilosRestart"; await Test_AllSilosRestart(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional")] public async Task SMS_StreamRel_SiloJoins() { const string testName = "SMS_StreamRel_SiloJoins"; await Test_SiloJoins(testName, SMS_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")] public async Task AQ_StreamRel_SiloJoins() { const string testName = "AQ_StreamRel_SiloJoins"; await Test_SiloJoins(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional")] public async Task SMS_StreamRel_SiloDies_Consumer() { const string testName = "SMS_StreamRel_SiloDies_Consumer"; await Test_SiloDies_Consumer(testName, SMS_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")] public async Task AQ_StreamRel_SiloDies_Consumer() { const string testName = "AQ_StreamRel_SiloDies_Consumer"; await Test_SiloDies_Consumer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional")] public async Task SMS_StreamRel_SiloDies_Producer() { const string testName = "SMS_StreamRel_SiloDies_Producer"; await Test_SiloDies_Producer(testName, SMS_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")] public async Task AQ_StreamRel_SiloDies_Producer() { const string testName = "AQ_StreamRel_SiloDies_Producer"; await Test_SiloDies_Producer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional")] public async Task SMS_StreamRel_SiloRestarts_Consumer() { const string testName = "SMS_StreamRel_SiloRestarts_Consumer"; await Test_SiloRestarts_Consumer(testName, SMS_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")] public async Task AQ_StreamRel_SiloRestarts_Consumer() { const string testName = "AQ_StreamRel_SiloRestarts_Consumer"; await Test_SiloRestarts_Consumer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional")] public async Task SMS_StreamRel_SiloRestarts_Producer() { const string testName = "SMS_StreamRel_SiloRestarts_Producer"; await Test_SiloRestarts_Producer(testName, SMS_STREAM_PROVIDER_NAME); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")] public async Task AQ_StreamRel_SiloRestarts_Producer() { const string testName = "AQ_StreamRel_SiloRestarts_Producer"; await Test_SiloRestarts_Producer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME); } // ------------------- // Test helper methods #if USE_GENERICS private async Task<IStreamReliabilityTestGrain<int>> Do_BaselineTest(long consumerGrainId, long producerGrainId) #else private async Task<IStreamReliabilityTestGrain> Do_BaselineTest(long consumerGrainId, long producerGrainId) #endif { logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId); var consumerGrain = GetGrain(consumerGrainId); var producerGrain = GetGrain(producerGrainId); #if DELETE_AFTER_TEST _usedGrains.Add(producerGrain); _usedGrains.Add(producerGrain); #endif await producerGrain.Ping(); string when = "Before subscribe"; await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, false, false); logger.Info("AddConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await consumerGrain.AddConsumer(_streamId, _streamProviderName); logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await producerGrain.BecomeProducer(_streamId, _streamProviderName); when = "After subscribe"; await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); when = "Ping"; await producerGrain.Ping(); await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); when = "SendItem"; await producerGrain.SendItem(1); await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); return producerGrain; } #if USE_GENERICS private async Task<IStreamReliabilityTestGrain<int>[]> Do_AddConsumerGrains(long baseId, int numGrains) #else private async Task<IStreamReliabilityTestGrain[]> Do_AddConsumerGrains(long baseId, int numGrains) #endif { logger.Info("Initializing: BaseId={0} NumGrains={1}", baseId, numGrains); #if USE_GENERICS var grains = new IStreamReliabilityTestGrain<int>[numGrains]; #else var grains = new IStreamReliabilityTestGrain[numGrains]; #endif List<Task> promises = new List<Task>(numGrains); for (int i = 0; i < numGrains; i++) { grains[i] = GetGrain(i + baseId); promises.Add(grains[i].Ping()); #if DELETE_AFTER_TEST _usedGrains.Add(grains[i]); #endif } await Task.WhenAll(promises); logger.Info("AddConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await Task.WhenAll(grains.Select(g => g.AddConsumer(_streamId, _streamProviderName))); return grains; } private static int baseConsumerId = 0; private async Task Test_AddMany_Consumers(string testName, string streamProviderName) { const int numLoops = 100; const int numGrains = 10; _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); var producerGrain = GetGrain(producerGrainId); var consumerGrain = GetGrain(consumerGrainId); #if DELETE_AFTER_TEST _usedGrains.Add(producerGrain); _usedGrains.Add(consumerGrain); #endif // Note: This does first SendItem await Do_BaselineTest(consumerGrainId, producerGrainId); int baseId = 10000 * ++baseConsumerId; var grains1 = await Do_AddConsumerGrains(baseId, numGrains); for (int i = 0; i < numLoops; i++) { await producerGrain.SendItem(2); } string when1 = "AddConsumers-Send-2"; // Messages received by original consumer grain await CheckReceivedCounts(when1, consumerGrain, numLoops + 1, 0); // Messages received by new consumer grains // ReSharper disable once AccessToModifiedClosure await Task.WhenAll(grains1.Select(async g => { await CheckReceivedCounts(when1, g, numLoops, 0); #if DELETE_AFTER_TEST _usedGrains.Add(g); #endif })); string when2 = "AddConsumers-Send-3"; baseId = 10000 * ++baseConsumerId; var grains2 = await Do_AddConsumerGrains(baseId, numGrains); for (int i = 0; i < numLoops; i++) { await producerGrain.SendItem(3); } ////Thread.Sleep(TimeSpan.FromSeconds(2)); // Messages received by original consumer grain await CheckReceivedCounts(when2, consumerGrain, numLoops*2 + 1, 0); // Messages received by new consumer grains await Task.WhenAll(grains2.Select(g => CheckReceivedCounts(when2, g, numLoops, 0))); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_PubSub_MultiConsumerSameGrain(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); // Grain Producer -> Grain 2 x Consumer long consumerGrainId = random.Next(); long producerGrainId = random.Next(); string when; logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId); var consumerGrain = GetGrain(consumerGrainId); var producerGrain = GetGrain(producerGrainId); logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await producerGrain.BecomeProducer(_streamId, _streamProviderName); when = "After BecomeProducer"; // Note: Only semantics guarenteed for producer is that they will have been registered by time that first msg is sent. await producerGrain.SendItem(0); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); logger.Info("AddConsumer x 2 : StreamId={0} Provider={1}", _streamId, _streamProviderName); await consumerGrain.AddConsumer(_streamId, _streamProviderName); when = "After first AddConsumer"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); await consumerGrain.AddConsumer(_streamId, _streamProviderName); when = "After second AddConsumer"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 2, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_PubSub_MultiProducerSameGrain(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); // Grain Producer -> Grain 2 x Consumer long consumerGrainId = random.Next(); long producerGrainId = random.Next(); string when; logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId); var consumerGrain = GetGrain(consumerGrainId); var producerGrain = GetGrain(producerGrainId); logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await producerGrain.BecomeProducer(_streamId, _streamProviderName); when = "After first BecomeProducer"; // Note: Only semantics guarenteed for producer is that they will have been registered by time that first msg is sent. await producerGrain.SendItem(0); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); await producerGrain.BecomeProducer(_streamId, _streamProviderName); when = "After second BecomeProducer"; await producerGrain.SendItem(0); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); logger.Info("AddConsumer x 2 : StreamId={0} Provider={1}", _streamId, _streamProviderName); await consumerGrain.AddConsumer(_streamId, _streamProviderName); when = "After first AddConsumer"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); await consumerGrain.AddConsumer(_streamId, _streamProviderName); when = "After second AddConsumer"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 2, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_PubSub_Unsubscribe(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); // Grain Producer -> Grain 2 x Consumer // Note: PubSub should only count distinct grains, even if a grain has multiple consumer handles long consumerGrainId = random.Next(); long producerGrainId = random.Next(); string when; logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId); var consumerGrain = GetGrain(consumerGrainId); var producerGrain = GetGrain(producerGrainId); logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await producerGrain.BecomeProducer(_streamId, _streamProviderName); await producerGrain.BecomeProducer(_streamId, _streamProviderName); when = "After BecomeProducer"; // Note: Only semantics guarenteed are that producer will have been registered by time that first msg is sent. await producerGrain.SendItem(0); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); logger.Info("AddConsumer x 2 : StreamId={0} Provider={1}", _streamId, _streamProviderName); var c1 = await consumerGrain.AddConsumer(_streamId, _streamProviderName); when = "After first AddConsumer"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); await CheckConsumerCounts(when, consumerGrain, 1); var c2 = await consumerGrain.AddConsumer(_streamId, _streamProviderName); when = "After second AddConsumer"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 2, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); await CheckConsumerCounts(when, consumerGrain, 2); logger.Info("RemoveConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await consumerGrain.RemoveConsumer(_streamId, _streamProviderName, c1); when = "After first RemoveConsumer"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); await CheckConsumerCounts(when, consumerGrain, 1); #if REMOVE_PRODUCER logger.Info("RemoveProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await producerGrain.RemoveProducer(_streamId, _streamProviderName); when = "After RemoveProducer"; await CheckPubSubCounts(when, 0, 1); await CheckConsumerCounts(when, consumerGrain, 1); #endif logger.Info("RemoveConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName); await consumerGrain.RemoveConsumer(_streamId, _streamProviderName, c2); when = "After second RemoveConsumer"; #if REMOVE_PRODUCER await CheckPubSubCounts(when, 0, 0); #else await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); #endif await CheckConsumerCounts(when, consumerGrain, 0); StreamTestUtils.LogEndTest(testName, logger); } [SkippableFact, TestCategory("Functional")] public async Task SMS_AllSilosRestart_UnsubscribeConsumer() { const string testName = "SMS_AllSilosRestart_UnsubscribeConsumer"; _streamId = Guid.NewGuid(); _streamProviderName = SMS_STREAM_PROVIDER_NAME; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); var consumerGrain = this.GrainFactory.GetGrain<IStreamUnsubscribeTestGrain>(consumerGrainId); logger.Info("Subscribe: StreamId={0} Provider={1}", _streamId, _streamProviderName); await consumerGrain.Subscribe(_streamId, _streamProviderName); // Restart silos await RestartAllSilos(); string when = "After restart all silos"; CheckSilosRunning(when, numExpectedSilos); // Since we restart all silos, the client might not haave had enough // time to reconnect to the new gateways. Let's retry the call if it // is the case for (int i = 0; i < 3; i++) { try { await consumerGrain.UnSubscribeFromAllStreams(); break; } catch (OrleansMessageRejectionException ex) { if (!ex.Message.Contains("No gateways available")) throw; } await Task.Delay(100); } StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_AllSilosRestart(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); await Do_BaselineTest(consumerGrainId, producerGrainId); // Restart silos await RestartAllSilos(); string when = "After restart all silos"; CheckSilosRunning(when, numExpectedSilos); when = "SendItem"; var producerGrain = GetGrain(producerGrainId); await producerGrain.SendItem(1); await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_AllSilosRestart_PubSubCounts(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); #if USE_GENERICS IStreamReliabilityTestGrain<int> producerGrain = #else IStreamReliabilityTestGrain producerGrain = #endif await Do_BaselineTest(consumerGrainId, producerGrainId); string when = "Before restart all silos"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); // Restart silos //RestartDefaultSilosButKeepCurrentClient(testName); await RestartAllSilos(); when = "After restart all silos"; CheckSilosRunning(when, numExpectedSilos); // Note: It is not guaranteed that the list of producers will not get modified / cleaned up during silo shutdown, so can't assume count will be 1 here. // Expected == -1 means don't care. await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, -1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); await producerGrain.SendItem(1); when = "After SendItem"; await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace); var consumerGrain = GetGrain(consumerGrainId); await CheckReceivedCounts(when, consumerGrain, 1, 0); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_SiloDies_Consumer(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; string when; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId); when = "Before kill one silo"; CheckSilosRunning(when, numExpectedSilos); bool sameSilo = await CheckGrainCounts(); // Find which silo the consumer grain is located on var consumerGrain = GetGrain(consumerGrainId); SiloAddress siloAddress = await consumerGrain.GetLocation(); output.WriteLine("Consumer grain is located on silo {0} ; Producer on same silo = {1}", siloAddress, sameSilo); // Kill the silo containing the consumer grain SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress)); await StopSilo(siloToKill, true, false); // Note: Don't restart failed silo for this test case // Note: Don't reinitialize client when = "After kill one silo"; CheckSilosRunning(when, numExpectedSilos - 1); when = "SendItem"; await producerGrain.SendItem(1); await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_SiloDies_Producer(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; string when; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId); when = "Before kill one silo"; CheckSilosRunning(when, numExpectedSilos); bool sameSilo = await CheckGrainCounts(); // Find which silo the producer grain is located on SiloAddress siloAddress = await producerGrain.GetLocation(); output.WriteLine("Producer grain is located on silo {0} ; Consumer on same silo = {1}", siloAddress, sameSilo); // Kill the silo containing the producer grain SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress)); await StopSilo(siloToKill, true, false); // Note: Don't restart failed silo for this test case // Note: Don't reinitialize client when = "After kill one silo"; CheckSilosRunning(when, numExpectedSilos - 1); when = "SendItem"; await producerGrain.SendItem(1); await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_SiloRestarts_Consumer(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; string when; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId); when = "Before restart one silo"; CheckSilosRunning(when, numExpectedSilos); bool sameSilo = await CheckGrainCounts(); // Find which silo the consumer grain is located on var consumerGrain = GetGrain(consumerGrainId); SiloAddress siloAddress = await consumerGrain.GetLocation(); output.WriteLine("Consumer grain is located on silo {0} ; Producer on same silo = {1}", siloAddress, sameSilo); // Restart the silo containing the consumer grain SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress)); await StopSilo(siloToKill, true, true); // Note: Don't reinitialize client when = "After restart one silo"; CheckSilosRunning(when, numExpectedSilos); when = "SendItem"; await producerGrain.SendItem(1); await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_SiloRestarts_Producer(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; string when; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId); when = "Before restart one silo"; CheckSilosRunning(when, numExpectedSilos); bool sameSilo = await CheckGrainCounts(); // Find which silo the producer grain is located on SiloAddress siloAddress = await producerGrain.GetLocation(); output.WriteLine("Producer grain is located on silo {0} ; Consumer on same silo = {1}", siloAddress, sameSilo); // Restart the silo containing the consumer grain SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress)); await StopSilo(siloToKill, true, true); // Note: Don't reinitialize client when = "After restart one silo"; CheckSilosRunning(when, numExpectedSilos); when = "SendItem"; await producerGrain.SendItem(1); await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); StreamTestUtils.LogEndTest(testName, logger); } private async Task Test_SiloJoins(string testName, string streamProviderName) { _streamId = Guid.NewGuid(); _streamProviderName = streamProviderName; const int numLoops = 3; StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster); long consumerGrainId = random.Next(); long producerGrainId = random.Next(); var producerGrain = GetGrain(producerGrainId); SiloAddress producerLocation = await producerGrain.GetLocation(); var consumerGrain = GetGrain(consumerGrainId); SiloAddress consumerLocation = await consumerGrain.GetLocation(); output.WriteLine("Grain silo locations: Producer={0} Consumer={1}", producerLocation, consumerLocation); // Note: This does first SendItem await Do_BaselineTest(consumerGrainId, producerGrainId); int expectedReceived = 1; string when = "SendItem-2"; for (int i = 0; i < numLoops; i++) { await producerGrain.SendItem(2); } expectedReceived += numLoops; await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); await CheckReceivedCounts(when, consumerGrain, expectedReceived, 0); // Add new silo //SiloHandle newSilo = StartAdditionalOrleans(); //WaitForLivenessToStabilize(); SiloHandle newSilo = await this.HostedCluster.StartAdditionalSiloAsync(); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); when = "After starting additional silo " + newSilo; output.WriteLine(when); CheckSilosRunning(when, numExpectedSilos + 1); //when = "SendItem-3"; //output.WriteLine(when); //for (int i = 0; i < numLoops; i++) //{ // await producerGrain.SendItem(3); //} //expectedReceived += numLoops; //await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true); //await CheckReceivedCounts(when, consumerGrain, expectedReceived, 0); // Find a Consumer Grain on the new silo IStreamReliabilityTestGrain newConsumer = CreateGrainOnSilo(newSilo.SiloAddress); await newConsumer.AddConsumer(_streamId, _streamProviderName); output.WriteLine("Grain silo locations: Producer={0} OldConsumer={1} NewConsumer={2}", producerLocation, consumerLocation, newSilo.SiloAddress); ////Thread.Sleep(TimeSpan.FromSeconds(2)); when = "SendItem-4"; output.WriteLine(when); for (int i = 0; i < numLoops; i++) { await producerGrain.SendItem(4); } expectedReceived += numLoops; // Old consumer received the newly published messages await CheckReceivedCounts(when+"-Old", consumerGrain, expectedReceived, 0); // New consumer received the newly published messages await CheckReceivedCounts(when+"-New", newConsumer, numLoops, 0); StreamTestUtils.LogEndTest(testName, logger); } // ---------- Utility Functions ---------- private async Task RestartAllSilos() { output.WriteLine("\n\n\n\n-----------------------------------------------------\n" + "Restarting all silos - Old Primary={0} Secondary={1}" + "\n-----------------------------------------------------\n\n\n", this.HostedCluster.Primary?.SiloAddress, this.HostedCluster.SecondarySilos.FirstOrDefault()?.SiloAddress); foreach (var silo in this.HostedCluster.GetActiveSilos().ToList()) { await this.HostedCluster.RestartSiloAsync(silo); } // Note: Needed to reinitialize client in this test case to connect to new silos // this.HostedCluster.InitializeClient(); output.WriteLine("\n\n\n\n-----------------------------------------------------\n" + "Restarted new silos - New Primary={0} Secondary={1}" + "\n-----------------------------------------------------\n\n\n", this.HostedCluster.Primary?.SiloAddress, this.HostedCluster.SecondarySilos.FirstOrDefault()?.SiloAddress); } private async Task StopSilo(SiloHandle silo, bool kill, bool restart) { SiloAddress oldSilo = silo.SiloAddress; bool isPrimary = oldSilo.Equals(this.HostedCluster.Primary?.SiloAddress); string siloType = isPrimary ? "Primary" : "Secondary"; string action; if (restart) action = kill ? "Kill+Restart" : "Stop+Restart"; else action = kill ? "Kill" : "Stop"; logger.Warn(2, "{0} {1} silo {2}", action, siloType, oldSilo); if (restart) { //RestartRuntime(silo, kill); SiloHandle newSilo = await this.HostedCluster.RestartSiloAsync(silo); logger.Info("Restarted new {0} silo {1}", siloType, newSilo.SiloAddress); Assert.NotEqual(oldSilo, newSilo.SiloAddress); //"Should be different silo address after Restart" } else if (kill) { await this.HostedCluster.KillSiloAsync(silo); Assert.False(silo.IsActive); } else { await this.HostedCluster.StopSiloAsync(silo); Assert.False(silo.IsActive); } // WaitForLivenessToStabilize(!kill); this.HostedCluster.WaitForLivenessToStabilizeAsync(kill).Wait(); } #if USE_GENERICS protected IStreamReliabilityTestGrain<int> GetGrain(long grainId) #else protected IStreamReliabilityTestGrain GetGrain(long grainId) #endif { #if USE_GENERICS return StreamReliabilityTestGrainFactory<int>.GetGrain(grainId); #else return this.GrainFactory.GetGrain<IStreamReliabilityTestGrain>(grainId); #endif } #if USE_GENERICS private IStreamReliabilityTestGrain<int> CreateGrainOnSilo(SiloHandle silo) #else private IStreamReliabilityTestGrain CreateGrainOnSilo(SiloAddress silo) #endif { // Find a Grain to use which is located on the specified silo IStreamReliabilityTestGrain newGrain; long kp = random.Next(); while (true) { newGrain = GetGrain(++kp); SiloAddress loc = newGrain.GetLocation().Result; if (loc.Equals(silo)) break; } output.WriteLine("Using Grain {0} located on silo {1}", kp, silo); return newGrain; } protected async Task CheckConsumerProducerStatus(string when, long producerGrainId, long consumerGrainId, bool expectIsProducer, bool expectIsConsumer) { await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, expectIsProducer ? 1 : 0, expectIsConsumer ? 1 : 0); } protected async Task CheckConsumerProducerStatus(string when, long producerGrainId, long consumerGrainId, int expectedNumProducers, int expectedNumConsumers) { var producerGrain = GetGrain(producerGrainId); var consumerGrain = GetGrain(consumerGrainId); bool isProducer = await producerGrain.IsProducer(); output.WriteLine("Grain {0} IsProducer={1}", producerGrainId, isProducer); Assert.Equal(expectedNumProducers > 0, isProducer); bool isConsumer = await consumerGrain.IsConsumer(); output.WriteLine("Grain {0} IsConsumer={1}", consumerGrainId, isConsumer); Assert.Equal(expectedNumConsumers > 0, isConsumer); int consumerHandleCount = await consumerGrain.GetConsumerHandlesCount(); int consumerObserverCount = await consumerGrain.GetConsumerHandlesCount(); output.WriteLine("Grain {0} HandleCount={1} ObserverCount={2}", consumerGrainId, consumerHandleCount, consumerObserverCount); Assert.Equal(expectedNumConsumers, consumerHandleCount); Assert.Equal(expectedNumConsumers, consumerObserverCount); } private void CheckSilosRunning(string when, int expectedNumSilos) { Assert.Equal(expectedNumSilos, this.HostedCluster.GetActiveSilos().Count()); } protected async Task<bool> CheckGrainCounts() { #if USE_GENERICS string grainType = typeof(StreamReliabilityTestGrain<int>).FullName; #else string grainType = typeof(StreamReliabilityTestGrain).FullName; #endif IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0); SimpleGrainStatistic[] grainStats = await mgmtGrain.GetSimpleGrainStatistics(); output.WriteLine("Found grains " + Utils.EnumerableToString(grainStats)); var grainLocs = grainStats.Where(gs => gs.GrainType == grainType).ToArray(); Assert.True(grainLocs.Length > 0, "Found too few grains"); Assert.True(grainLocs.Length <= 2, "Found too many grains " + grainLocs.Length); bool sameSilo = grainLocs.Length == 1; if (sameSilo) { StreamTestUtils.Assert_AreEqual(output, 2, grainLocs[0].ActivationCount, "Num grains on same Silo " + grainLocs[0].SiloAddress); } else { StreamTestUtils.Assert_AreEqual(output, 1, grainLocs[0].ActivationCount, "Num grains on Silo " + grainLocs[0].SiloAddress); StreamTestUtils.Assert_AreEqual(output, 1, grainLocs[1].ActivationCount, "Num grains on Silo " + grainLocs[1].SiloAddress); } return sameSilo; } #if USE_GENERICS protected async Task CheckReceivedCounts<T>(string when, IStreamReliabilityTestGrain<T> consumerGrain, int expectedReceivedCount, int expectedErrorsCount) #else protected async Task CheckReceivedCounts(string when, IStreamReliabilityTestGrain consumerGrain, int expectedReceivedCount, int expectedErrorsCount) #endif { long pk = consumerGrain.GetPrimaryKeyLong(); int receivedCount = 0; for (int i = 0; i < 20; i++) { receivedCount = await consumerGrain.GetReceivedCount(); output.WriteLine("After {0}s ReceivedCount={1} for grain {2}", i, receivedCount, pk); if (receivedCount == expectedReceivedCount) break; Thread.Sleep(TimeSpan.FromSeconds(1)); } StreamTestUtils.Assert_AreEqual(output, expectedReceivedCount, receivedCount, "ReceivedCount for stream {0} for grain {1} {2}", _streamId, pk, when); int errorsCount = await consumerGrain.GetErrorsCount(); StreamTestUtils.Assert_AreEqual(output, expectedErrorsCount, errorsCount, "ErrorsCount for stream {0} for grain {1} {2}", _streamId, pk, when); } #if USE_GENERICS protected async Task CheckConsumerCounts<T>(string when, IStreamReliabilityTestGrain<T> consumerGrain, int expectedConsumerCount) #else protected async Task CheckConsumerCounts(string when, IStreamReliabilityTestGrain consumerGrain, int expectedConsumerCount) #endif { int consumerCount = await consumerGrain.GetConsumerCount(); StreamTestUtils.Assert_AreEqual(output, expectedConsumerCount, consumerCount, "ConsumerCount for stream {0} {1}", _streamId, when); } } }
/* * 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 OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { public struct WearableItem { public UUID ItemID; public UUID AssetID; public WearableItem(UUID itemID, UUID assetID) { ItemID = itemID; AssetID = assetID; } } public class AvatarWearable { // these are guessed at by the list here - // http://wiki.secondlife.com/wiki/Avatar_Appearance. We'll // correct them over time for when were are wrong. public static readonly int BODY = 0; public static readonly int SKIN = 1; public static readonly int HAIR = 2; public static readonly int EYES = 3; public static readonly int SHIRT = 4; public static readonly int PANTS = 5; public static readonly int SHOES = 6; public static readonly int SOCKS = 7; public static readonly int JACKET = 8; public static readonly int GLOVES = 9; public static readonly int UNDERSHIRT = 10; public static readonly int UNDERPANTS = 11; public static readonly int SKIRT = 12; public static readonly int MAX_BASICWEARABLES = 13; public static readonly int ALPHA = 13; public static readonly int TATTOO = 14; public static readonly int LEGACY_VERSION_MAX_WEARABLES = 15; // public static readonly int PHYSICS = 15; // public static int MAX_WEARABLES = 16; public static readonly UUID DEFAULT_BODY_ITEM = new UUID("66c41e39-38f9-f75a-024e-585989bfaba9"); public static readonly UUID DEFAULT_BODY_ASSET = new UUID("66c41e39-38f9-f75a-024e-585989bfab73"); public static readonly UUID DEFAULT_HAIR_ITEM = new UUID("d342e6c1-b9d2-11dc-95ff-0800200c9a66"); public static readonly UUID DEFAULT_HAIR_ASSET = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66"); public static readonly UUID DEFAULT_SKIN_ITEM = new UUID("77c41e39-38f9-f75a-024e-585989bfabc9"); public static readonly UUID DEFAULT_SKIN_ASSET = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb"); public static readonly UUID DEFAULT_EYES_ITEM = new UUID("cdc31054-eed8-4021-994f-4e0c6e861b50"); public static readonly UUID DEFAULT_EYES_ASSET = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7"); public static readonly UUID DEFAULT_SHIRT_ITEM = new UUID("77c41e39-38f9-f75a-0000-585989bf0000"); public static readonly UUID DEFAULT_SHIRT_ASSET = new UUID("00000000-38f9-1111-024e-222222111110"); public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111"); public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120"); // public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8"); // public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594"); // public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1"); // public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007"); protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>(); protected List<UUID> m_ids = new List<UUID>(); public AvatarWearable() { } public AvatarWearable(UUID itemID, UUID assetID) { Wear(itemID, assetID); } public AvatarWearable(OSDArray args) { Unpack(args); } public OSD Pack() { OSDArray wearlist = new OSDArray(); foreach (UUID id in m_ids) { OSDMap weardata = new OSDMap(); weardata["item"] = OSD.FromUUID(id); weardata["asset"] = OSD.FromUUID(m_items[id]); wearlist.Add(weardata); } return wearlist; } public void Unpack(OSDArray args) { Clear(); foreach (OSDMap weardata in args) { Add(weardata["item"].AsUUID(), weardata["asset"].AsUUID()); } } public int Count { get { return m_ids.Count; } } public void Add(UUID itemID, UUID assetID) { if (itemID == UUID.Zero) return; if (m_items.ContainsKey(itemID)) { m_items[itemID] = assetID; return; } if (m_ids.Count >= 5) return; m_ids.Add(itemID); m_items[itemID] = assetID; } public void Wear(WearableItem item) { Wear(item.ItemID, item.AssetID); } public void Wear(UUID itemID, UUID assetID) { Clear(); Add(itemID, assetID); } public void Clear() { m_ids.Clear(); m_items.Clear(); } public void RemoveItem(UUID itemID) { if (m_items.ContainsKey(itemID)) { m_ids.Remove(itemID); m_items.Remove(itemID); } } public void RemoveAsset(UUID assetID) { UUID itemID = UUID.Zero; foreach (KeyValuePair<UUID, UUID> kvp in m_items) { if (kvp.Value == assetID) { itemID = kvp.Key; break; } } if (itemID != UUID.Zero) { m_ids.Remove(itemID); m_items.Remove(itemID); } } public WearableItem this [int idx] { get { if (idx >= m_ids.Count || idx < 0) return new WearableItem(UUID.Zero, UUID.Zero); return new WearableItem(m_ids[idx], m_items[m_ids[idx]]); } } public UUID GetAsset(UUID itemID) { if (!m_items.ContainsKey(itemID)) return UUID.Zero; return m_items[itemID]; } public static AvatarWearable[] DefaultWearables { get { // We use the legacy count here because this is just a fallback anyway AvatarWearable[] defaultWearables = new AvatarWearable[LEGACY_VERSION_MAX_WEARABLES]; for (int i = 0; i < LEGACY_VERSION_MAX_WEARABLES; i++) { defaultWearables[i] = new AvatarWearable(); } // Body defaultWearables[BODY].Add(DEFAULT_BODY_ITEM, DEFAULT_BODY_ASSET); // Hair defaultWearables[HAIR].Add(DEFAULT_HAIR_ITEM, DEFAULT_HAIR_ASSET); // Skin defaultWearables[SKIN].Add(DEFAULT_SKIN_ITEM, DEFAULT_SKIN_ASSET); // Eyes defaultWearables[EYES].Add(DEFAULT_EYES_ITEM, DEFAULT_EYES_ASSET); // Shirt defaultWearables[SHIRT].Add(DEFAULT_SHIRT_ITEM, DEFAULT_SHIRT_ASSET); // Pants defaultWearables[PANTS].Add(DEFAULT_PANTS_ITEM, DEFAULT_PANTS_ASSET); // // Alpha // defaultWearables[ALPHA].Add(DEFAULT_ALPHA_ITEM, DEFAULT_ALPHA_ASSET); // // Tattoo // defaultWearables[TATTOO].Add(DEFAULT_TATTOO_ITEM, DEFAULT_TATTOO_ASSET); // // Physics // defaultWearables[PHYSICS].Add(DEFAULT_TATTOO_ITEM, DEFAULT_TATTOO_ASSET); return defaultWearables; } } } }
namespace Nancy.ModelBinding { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Nancy.Extensions; using System.Collections; /// <summary> /// Default binder - used as a fallback when a specific modelbinder /// is not available. /// </summary> public class DefaultBinder : IBinder { private readonly IEnumerable<ITypeConverter> typeConverters; private readonly IEnumerable<IBodyDeserializer> bodyDeserializers; private readonly IFieldNameConverter fieldNameConverter; private readonly BindingDefaults defaults; private readonly static MethodInfo ToListMethodInfo = typeof(Enumerable).GetMethod("ToList", BindingFlags.Public | BindingFlags.Static); private readonly static MethodInfo ToArrayMethodInfo = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Public | BindingFlags.Static); private static readonly Regex BracketRegex = new Regex(@"\[(\d+)\]\z", RegexOptions.Compiled); private static readonly Regex UnderscoreRegex = new Regex(@"_(\d+)\z", RegexOptions.Compiled); public DefaultBinder(IEnumerable<ITypeConverter> typeConverters, IEnumerable<IBodyDeserializer> bodyDeserializers, IFieldNameConverter fieldNameConverter, BindingDefaults defaults) { if (typeConverters == null) { throw new ArgumentNullException("typeConverters"); } if (bodyDeserializers == null) { throw new ArgumentNullException("bodyDeserializers"); } if (fieldNameConverter == null) { throw new ArgumentNullException("fieldNameConverter"); } if (defaults == null) { throw new ArgumentNullException("defaults"); } this.typeConverters = typeConverters; this.bodyDeserializers = bodyDeserializers; this.fieldNameConverter = fieldNameConverter; this.defaults = defaults; } /// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted binding property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { Type genericType = null; if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure it has a generic type if (modelType.IsGenericType()) { genericType = modelType.GetGenericArguments().FirstOrDefault(); } else { var ienumerable = modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault( i => i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault(); } if (genericType == null) { throw new ArgumentException("When modelType is an enumerable it must specify the type.", "modelType"); } } var bindingContext = this.CreateBindingContext(context, modelType, instance, configuration, blackList, genericType); try { var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext); if (bodyDeserializedModel != null) { UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext); } } catch (Exception exception) { if (!bindingContext.Configuration.IgnoreErrors) { throw new ModelBindingException(modelType, innerException: exception); } } var bindingExceptions = new List<PropertyBindingException>(); if (!bindingContext.Configuration.BodyOnly) { if (bindingContext.DestinationType.IsCollection() || bindingContext.DestinationType.IsArray() ||bindingContext.DestinationType.IsEnumerable()) { var loopCount = this.GetBindingListInstanceCount(context); var model = (IList)bindingContext.Model; for (var i = 0; i < loopCount; i++) { object genericinstance; if (model.Count > i) { genericinstance = model[i]; } else { genericinstance = Activator.CreateInstance(bindingContext.GenericType); model.Add(genericinstance); } foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingCollectionValue = modelProperty.GetValue(genericinstance); var collectionStringValue = GetValue(modelProperty.Name, bindingContext, i); if (this.BindingValueIsValid(collectionStringValue, existingCollectionValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, collectionStringValue, bindingContext, genericinstance); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } } else { foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(bindingContext.Model); var stringValue = GetValue(modelProperty.Name, bindingContext); if (this.BindingValueIsValid(stringValue, existingValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, stringValue, bindingContext); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } if (bindingExceptions.Any() && !bindingContext.Configuration.IgnoreErrors) { throw new ModelBindingException(modelType, bindingExceptions); } } if (modelType.IsArray()) { var generictoArrayMethod = ToArrayMethodInfo.MakeGenericMethod(new[] { genericType }); return generictoArrayMethod.Invoke(null, new[] { bindingContext.Model }); } return bindingContext.Model; } private bool BindingValueIsValid(string bindingValue, object existingValue, BindingMemberInfo modelProperty, BindingContext bindingContext) { return (!string.IsNullOrEmpty(bindingValue) && (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite)); } /// <summary> /// Gets the number of distinct indexes from context: /// /// i.e: /// IntProperty_5 /// StringProperty_5 /// IntProperty_7 /// StringProperty_8 /// You'll end up with a list of 3 matches: 5,7,8 /// /// </summary> /// <param name="context">Current Context </param> /// <returns>An int containing the number of elements</returns> private int GetBindingListInstanceCount(NancyContext context) { var dictionary = context.Request.Form as IDictionary<string, object>; if (dictionary == null) { return 0; } return dictionary.Keys.Select(IsMatch).Where(x => x != -1).Distinct().ToArray().Length; } private static int IsMatch(string item) { var bracketMatch = BracketRegex.Match(item); if (bracketMatch.Success) { return int.Parse(bracketMatch.Groups[1].Value); } var underscoreMatch = UnderscoreRegex.Match(item); if (underscoreMatch.Success) { return int.Parse(underscoreMatch.Groups[1].Value); } return -1; } private static void UpdateModelWithDeserializedModel(object bodyDeserializedModel, BindingContext bindingContext) { var bodyDeserializedModelType = bodyDeserializedModel.GetType(); if (bodyDeserializedModelType.IsValueType) { bindingContext.Model = bodyDeserializedModel; return; } if (bodyDeserializedModelType.IsCollection() || bodyDeserializedModelType.IsEnumerable() || bodyDeserializedModelType.IsArray()) { var count = 0; foreach (var o in (IEnumerable)bodyDeserializedModel) { var model = (IList)bindingContext.Model; if (o.GetType().IsValueType || o is string) { HandleValueTypeCollectionElement(model, count, o); } else { HandleReferenceTypeCollectionElement(bindingContext, model, count, o); } count++; } } else { foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(bindingContext.Model); if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite) { CopyValue(modelProperty, bodyDeserializedModel, bindingContext.Model); } } } } private static void HandleValueTypeCollectionElement(IList model, int count, object o) { // If the instance specified in the binder contains the n-th element use that if (model.Count > count) { return; } model.Add(o); } private static void HandleReferenceTypeCollectionElement(BindingContext bindingContext, IList model, int count, object o) { // If the instance specified in the binder contains the n-th element use that otherwise make a new one. object genericTypeInstance; if (model.Count > count) { genericTypeInstance = model[count]; } else { genericTypeInstance = Activator.CreateInstance(bindingContext.GenericType); model.Add(genericTypeInstance); } foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(genericTypeInstance); if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite) { CopyValue(modelProperty, o, genericTypeInstance); } } } private static void CopyValue(BindingMemberInfo modelProperty, object source, object destination) { var newValue = modelProperty.GetValue(source); modelProperty.SetValue(destination, newValue); } private static bool IsDefaultValue(object existingValue, Type propertyType) { return propertyType.IsValueType ? Equals(existingValue, Activator.CreateInstance(propertyType)) : existingValue == null; } private BindingContext CreateBindingContext(NancyContext context, Type modelType, object instance, BindingConfig configuration, IEnumerable<string> blackList, Type genericType) { return new BindingContext { Configuration = configuration, Context = context, DestinationType = modelType, Model = CreateModel(modelType, genericType, instance), ValidModelBindingMembers = GetBindingMembers(modelType, genericType, blackList).ToList(), RequestData = this.GetDataFields(context), GenericType = genericType, TypeConverters = this.typeConverters.Concat(this.defaults.DefaultTypeConverters), }; } private IDictionary<string, string> GetDataFields(NancyContext context) { var dictionaries = new IDictionary<string, string>[] { ConvertDynamicDictionary(context.Request.Form), ConvertDynamicDictionary(context.Request.Query), ConvertDynamicDictionary(context.Parameters) }; return dictionaries.Merge(); } private IDictionary<string, string> ConvertDynamicDictionary(DynamicDictionary dictionary) { if (dictionary == null) { return null; } return dictionary.GetDynamicMemberNames().ToDictionary( memberName => this.fieldNameConverter.Convert(memberName), memberName => (string)dictionary[memberName]); } private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context) { BindValue(modelProperty, stringValue, context, context.Model); } private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context, object targetInstance) { var destinationType = modelProperty.PropertyType; var typeConverter = context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(destinationType, context)); if (typeConverter != null) { try { SetBindingMemberValue(modelProperty, targetInstance, typeConverter.Convert(stringValue, destinationType, context)); } catch (Exception e) { throw new PropertyBindingException(modelProperty.Name, stringValue, e); } } else if (destinationType == typeof(string)) { SetBindingMemberValue(modelProperty, targetInstance, stringValue); } } private static void SetBindingMemberValue(BindingMemberInfo modelProperty, object model, object value) { // TODO - catch reflection exceptions? modelProperty.SetValue(model, value); } private static IEnumerable<BindingMemberInfo> GetBindingMembers(Type modelType, Type genericType, IEnumerable<string> blackList) { var blackListHash = new HashSet<string>(blackList, StringComparer.Ordinal); return BindingMemberInfo.Collect(genericType ?? modelType) .Where(member => !blackListHash.Contains(member.Name)); } private static object CreateModel(Type modelType, Type genericType, object instance) { if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure instance has a Add method. Otherwise call `.ToList` if (instance != null && modelType.IsInstanceOfType(instance)) { var addMethod = modelType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance); if (addMethod != null) { return instance; } var genericMethod = ToListMethodInfo.MakeGenericMethod(genericType); return genericMethod.Invoke(null, new[] { instance }); } //else just make a list var listType = typeof(List<>).MakeGenericType(genericType); return Activator.CreateInstance(listType); } if (instance == null) { return Activator.CreateInstance(modelType, true); } return !modelType.IsInstanceOfType(instance) ? Activator.CreateInstance(modelType, true) : instance; } private static string GetValue(string propertyName, BindingContext context, int index = -1) { if (index != -1) { var indexindexes = context.RequestData.Keys.Select(IsMatch) .Where(i => i != -1) .OrderBy(i => i) .Distinct() .Select((k, i) => new KeyValuePair<int, int>(i, k)) .ToDictionary(k => k.Key, v => v.Value); if (indexindexes.ContainsKey(index)) { var propertyValue = context.RequestData.Where(c => { var indexId = IsMatch(c.Key); return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexindexes[index]; }) .Select(k => k.Value) .FirstOrDefault(); return propertyValue ?? string.Empty; } return string.Empty; } return context.RequestData.ContainsKey(propertyName) ? context.RequestData[propertyName] : string.Empty; } private object DeserializeRequestBody(BindingContext context) { if (context.Context == null || context.Context.Request == null) { return null; } var contentType = GetRequestContentType(context.Context); var bodyDeserializer = this.bodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context)) ?? this.defaults.DefaultBodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context)); return bodyDeserializer != null ? bodyDeserializer.Deserialize(contentType, context.Context.Request.Body, context) : null; } private static string GetRequestContentType(NancyContext context) { if (context == null || context.Request == null) { return string.Empty; } var contentType = context.Request.Headers.ContentType; return (string.IsNullOrEmpty(contentType)) ? string.Empty : contentType; } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace RemoteTimerJob.Console { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
/*************************************************************************** * MiniModeWindow.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> * Felipe Almeida Lessa ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using Gtk; using Glade; using Mono.Unix; using Hyena.Widgets; using Hyena.Gui; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.Gui; using Banshee.Gui.Widgets; using Banshee.Sources.Gui; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Widgets; namespace Banshee.MiniMode { public class MiniMode : Banshee.Gui.BaseClientWindow { [Widget] private Gtk.Box SeekContainer; [Widget] private Gtk.Box VolumeContainer; [Widget] private Gtk.Box InfoBox; [Widget] private Gtk.Box SourceBox; [Widget] private Gtk.Box CoverBox; [Widget] private Gtk.Box PlaybackBox; [Widget] private Gtk.Box LowerButtonsBox; [Widget] private Gtk.Button fullmode_button; private TrackInfoDisplay track_info_display; private ConnectedVolumeButton volume_button; private SourceComboBox source_combo_box; private ConnectedSeekSlider seek_slider; private object tooltip_host; private BaseClientWindow default_main_window; private Glade.XML glade; public MiniMode (BaseClientWindow defaultMainWindow) : base (Catalog.GetString ("Banshee Media Player"), "minimode", 0, 0) { default_main_window = defaultMainWindow; glade = new Glade.XML (System.Reflection.Assembly.GetExecutingAssembly (), "minimode.glade", "MiniModeWindow", null); glade.Autoconnect (this); Widget child = glade["mini_mode_contents"]; (child.Parent as Container).Remove (child); Add (child); BorderWidth = 12; Resizable = false; // Playback Buttons Widget previous_button = ActionService.PlaybackActions["PreviousAction"].CreateToolItem (); Widget playpause_button = ActionService.PlaybackActions["PlayPauseAction"].CreateToolItem (); Widget button = ActionService.PlaybackActions["NextAction"].CreateToolItem (); Menu menu = ActionService.PlaybackActions.ShuffleActions.CreateMenu (); MenuButton next_button = new MenuButton (button, menu, true); PlaybackBox.PackStart (previous_button, false, false, 0); PlaybackBox.PackStart (playpause_button, false, false, 0); PlaybackBox.PackStart (next_button, false, false, 0); PlaybackBox.ShowAll (); // Seek Slider/Position Label seek_slider = new ConnectedSeekSlider (); SeekContainer.PackStart (seek_slider, false, false, 0); SeekContainer.ShowAll (); // Volume button volume_button = new ConnectedVolumeButton (); VolumeContainer.PackStart (volume_button, false, false, 0); volume_button.Show (); // Source combobox source_combo_box = new SourceComboBox (); SourceBox.PackStart (source_combo_box, true, true, 0); source_combo_box.Show (); // Track info track_info_display = new ClassicTrackInfoDisplay (); track_info_display.Show (); CoverBox.PackStart (track_info_display, true, true, 0); // Repeat button RepeatActionButton repeat_toggle_button = new RepeatActionButton (); LowerButtonsBox.PackEnd (repeat_toggle_button, false, false, 0); LowerButtonsBox.ShowAll (); tooltip_host = TooltipSetter.CreateHost (); SetTip (fullmode_button, Catalog.GetString ("Switch back to full mode")); SetTip (repeat_toggle_button, Catalog.GetString ("Change repeat playback mode")); // Hook up everything ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.Error | PlayerEvent.StateChange | PlayerEvent.TrackInfoUpdated); SetHeightLimit (); } protected override void Initialize () { } private void SetTip (Widget widget, string tip) { TooltipSetter.Set (tooltip_host, widget, tip); } private void SetHeightLimit () { Gdk.Geometry limits = new Gdk.Geometry (); limits.MinHeight = -1; limits.MaxHeight = -1; limits.MinWidth = SizeRequest ().Width; limits.MaxWidth = Gdk.Screen.Default.Width; SetGeometryHints (this, limits, Gdk.WindowHints.MaxSize | Gdk.WindowHints.MinSize); } public void Enable () { source_combo_box.UpdateActiveSource (); UpdateMetaDisplay (); default_main_window.Hide (); OverrideFullscreen (); Show (); } public void Disable () { Hide (); RelinquishFullscreen (); default_main_window.Show (); } // Called when the user clicks the fullmode_button public void Hide (object o, EventArgs a) { ElementsService.PrimaryWindow = default_main_window; Disable (); } // ---- Player Event Handlers ---- private void OnPlayerEvent (PlayerEventArgs args) { switch (args.Event) { case PlayerEvent.Error: case PlayerEvent.TrackInfoUpdated: UpdateMetaDisplay (); break; case PlayerEvent.StateChange: switch (((PlayerEventStateChangeArgs)args).Current) { case PlayerState.Loaded: UpdateMetaDisplay (); break; case PlayerState.Idle: InfoBox.Visible = false; UpdateMetaDisplay (); break; } break; } } protected void UpdateMetaDisplay () { TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack; if (track == null) { InfoBox.Visible = false; return; } InfoBox.Visible = true; try { SetHeightLimit (); } catch (Exception) { } } #region Mini-mode Fullscreen Override private ViewActions.FullscreenHandler previous_fullscreen_handler; private void OverrideFullscreen () { InterfaceActionService service = ServiceManager.Get<InterfaceActionService> (); if (service == null || service.ViewActions == null) { return; } previous_fullscreen_handler = service.ViewActions.Fullscreen; service.ViewActions.Fullscreen = FullscreenHandler; } private void RelinquishFullscreen () { InterfaceActionService service = ServiceManager.Get<InterfaceActionService> (); if (service == null || service.ViewActions == null) { return; } service.ViewActions.Fullscreen = previous_fullscreen_handler; } private void FullscreenHandler (bool fullscreen) { // Do nothing, we don't want full-screen while in mini-mode. } #endregion } }
// // ServiceManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-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.Linq; using System.IO; using System.Collections.Generic; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.MediaProfiles; using Banshee.Sources; using Banshee.Database; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Library; using Banshee.Hardware; using System.Collections.Concurrent; namespace Banshee.ServiceStack { public static class ServiceManager { private static ConcurrentDictionary<string, IService> _services = new ConcurrentDictionary<string, IService> (); private static ConcurrentDictionary<string, IExtensionService> _extensions = new ConcurrentDictionary<string, IExtensionService> (); private static Stack<IService> dispose_services = new Stack<IService> (); private static List<Type> service_types = new List<Type> (); private static ExtensionNodeList extension_nodes; private static bool is_initialized = false; public static event EventHandler StartupBegin; public static event EventHandler StartupFinished; public static event ServiceStartedHandler ServiceStarted; public static void Initialize () { Application.ClientStarted += OnClientStarted; } public static void InitializeAddins () { AddinManager.Initialize (ApplicationContext.CommandLine.Contains ("uninstalled") ? "." : Paths.ApplicationData); IProgressStatus monitor = ApplicationContext.CommandLine.Contains ("debug-addins") ? new ConsoleProgressStatus (true) : null; AddinManager.AddinLoadError += (o, a) => { try { AddinManager.Registry.DisableAddin (a.AddinId); } catch {} Log.Error (a.Message, a.Exception); }; if (ApplicationContext.Debugging) { AddinManager.Registry.Rebuild (monitor); } else { AddinManager.Registry.Update (monitor); } } public static void RegisterAddinServices () { extension_nodes = AddinManager.GetExtensionNodes ("/Banshee/ServiceManager/Service"); } public static void RegisterDefaultServices () { RegisterService<DBusServiceManager> (); RegisterService<DBusCommandService> (); RegisterService<BansheeDbConnection> (); RegisterService<Banshee.Preferences.PreferenceService> (); RegisterService<SourceManager> (); RegisterService<MediaProfileManager> (); RegisterService<PlayerEngineService> (); RegisterService<PlaybackControllerService> (); RegisterService<JobScheduler> (); RegisterService<Banshee.Hardware.HardwareManager> (); RegisterService<Banshee.Collection.Indexer.CollectionIndexerService> (); RegisterService<Banshee.Metadata.SaveTrackMetadataService> (); } public static void DefaultInitialize () { Initialize (); InitializeAddins (); RegisterDefaultServices (); RegisterAddinServices (); } private static void OnClientStarted (Client client) { DelayedInitialize (); } public static void Run() { OnStartupBegin (); uint cumulative_timer_id = Log.InformationTimerStart (); System.Net.ServicePointManager.DefaultConnectionLimit = 6; foreach (Type type in service_types) { RegisterService (type); } if (extension_nodes != null) { foreach (TypeExtensionNode node in extension_nodes) { StartExtension (node); } } if (AddinManager.IsInitialized) { AddinManager.AddExtensionNodeHandler ("/Banshee/ServiceManager/Service", OnExtensionChanged); } is_initialized = true; Log.InformationTimerPrint (cumulative_timer_id, "All services are started {0}"); OnStartupFinished (); } private static IService RegisterService (Type type) { IService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IService)Activator.CreateInstance (type); RegisterService (service); Log.DebugTimerPrint (timer_id, String.Format ( "Core service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); if (service is IDisposable) { dispose_services.Push (service); } if (service is IInitializeService) { ((IInitializeService)service).Initialize (); } return service; } catch (Exception e) { if (typeof (IRequiredService).IsAssignableFrom (type)) { Log.ErrorFormat ("Error initializing required service {0}", service == null ? type.ToString () : service.ServiceName, false); throw; } Log.Warning (String.Format ("Service `{0}' not started: {1}", type.FullName, e.InnerException != null ? e.InnerException.Message : e.Message)); Log.Error (e.InnerException ?? e); } return null; } private static void StartExtension (TypeExtensionNode node) { if (_extensions.ContainsKey (node.Path)) { return; } IExtensionService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IExtensionService)node.CreateInstance (typeof (IExtensionService)); service.Initialize (); RegisterService (service); DelayedInitialize (service); Log.DebugTimerPrint (timer_id, String.Format ( "Extension service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); _extensions.TryAdd (node.Path, service); dispose_services.Push (service); } catch (Exception e) { Log.Error (e.InnerException ?? e); Log.Warning (String.Format ("Extension `{0}' not started: {1}", service == null ? node.Path : service.GetType ().FullName, e.Message)); } } private static void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add) { StartExtension (node); } else if (args.Change == ExtensionChange.Remove && _extensions.ContainsKey (node.Path)) { IExtensionService service; _extensions.TryRemove (node.Path, out service); Remove (service); ((IDisposable)service).Dispose (); Log.DebugFormat ("Extension service disposed ({0})", service.ServiceName); // Rebuild the dispose stack excluding the extension service IService [] tmp_services = new IService[dispose_services.Count - 1]; int count = tmp_services.Length; foreach (IService tmp_service in dispose_services) { if (tmp_service != service) { tmp_services[--count] = tmp_service; } } dispose_services = new Stack<IService> (tmp_services); } } private static bool delayed_initialized, have_client; private static void DelayedInitialize () { if (!delayed_initialized) { have_client = true; var initialized = new HashSet <string> (); var to_initialize = _services.Values.ToList (); foreach (IService service in to_initialize) { if (!initialized.Contains (service.ServiceName)) { DelayedInitialize (service); initialized.Add (service.ServiceName); } } delayed_initialized = true; } } private static void DelayedInitialize (IService service) { try { if (have_client && service is IDelayedInitializeService) { Log.DebugFormat ("Delayed Initializating {0}", service); ((IDelayedInitializeService)service).DelayedInitialize (); } } catch (Exception e) { Log.Error (e.InnerException ?? e); Log.Warning (String.Format ("Service `{0}' not initialized: {1}", service.GetType ().FullName, e.Message)); } } public static void Shutdown () { while (dispose_services.Count > 0) { IService service = dispose_services.Pop (); try { ((IDisposable)service).Dispose (); Log.DebugFormat ("Service disposed ({0})", service.ServiceName); } catch (Exception e) { Log.Error (String.Format ("Service disposal ({0}) threw an exception", service.ServiceName), e); } } _services.Clear (); } public static void RegisterService (IService service) { Add (service); if(service is IDBusExportable) { DBusServiceManager.RegisterObject ((IDBusExportable)service); } } public static void RegisterService<T> () where T : IService { if (is_initialized) { RegisterService (Activator.CreateInstance <T> ()); } else { service_types.Add (typeof (T)); } } public static bool Contains (string serviceName) { return _services.ContainsKey (serviceName); } public static bool Contains<T> () where T : class, IService { return Contains (typeof (T).Name); } public static IService Get (string serviceName) { IService svc; return _services.TryGetValue (serviceName, out svc) ? svc : null; } public static T Get<T> () where T : class, IService { var type = typeof (T); var key = type.Name; if (typeof (IRegisterOnDemandService).IsAssignableFrom (typeof (T))) { return (T) _services.GetOrAdd (key, k => RegisterService (type)); } else { return (T) Get (key); } } private static void Add (IService service) { _services.TryAdd (service.ServiceName, service); _services.TryAdd (service.GetType ().Name, service); } private static void Remove (IService service) { IService svc; _services.TryRemove (service.ServiceName, out svc); _services.TryRemove (service.GetType ().Name, out svc); } private static void OnStartupBegin () { EventHandler handler = StartupBegin; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnStartupFinished () { EventHandler handler = StartupFinished; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnServiceStarted (IService service) { ServiceStartedHandler handler = ServiceStarted; if (handler != null) { handler (new ServiceStartedArgs (service)); } } public static int StartupServiceCount { get { return service_types.Count + (extension_nodes == null ? 0 : extension_nodes.Count) + 1; } } public static bool IsInitialized { get { return is_initialized; } } public static DBusServiceManager DBusServiceManager { get { return Get<DBusServiceManager> (); } } public static BansheeDbConnection DbConnection { get { return (BansheeDbConnection)Get ("DbConnection"); } } public static MediaProfileManager MediaProfileManager { get { return Get<MediaProfileManager> (); } } public static SourceManager SourceManager { get { return (SourceManager)Get ("SourceManager"); } } public static JobScheduler JobScheduler { get { return (JobScheduler)Get ("JobScheduler"); } } public static PlayerEngineService PlayerEngine { get { return (PlayerEngineService)Get ("PlayerEngine"); } } public static PlaybackControllerService PlaybackController { get { return (PlaybackControllerService)Get ("PlaybackController"); } } public static HardwareManager HardwareManager { get { return Get<HardwareManager> (); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // Copyright (C) 2004 Novell, Inc (http://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. using Xunit; using System.Xml; using System.Data.SqlTypes; using System.Globalization; namespace System.Data.Tests.SqlTypes { public class SqlDateTimeTest { private long[] _myTicks = { 631501920000000000L, // 25 Feb 2002 - 00:00:00 631502475130080000L, // 25 Feb 2002 - 15:25:13,8 631502115130080000L, // 25 Feb 2002 - 05:25:13,8 631502115000000000L, // 25 Feb 2002 - 05:25:00 631502115130000000L, // 25 Feb 2002 - 05:25:13 631502079130000000L, // 25 Feb 2002 - 04:25:13 629197085770000000L // 06 Nov 1994 - 08:49:37 }; private SqlDateTime _test1; private SqlDateTime _test2; private SqlDateTime _test3; public SqlDateTimeTest() { CultureInfo.CurrentCulture = new CultureInfo("en-US"); _test1 = new SqlDateTime(2002, 10, 19, 9, 40, 0); _test2 = new SqlDateTime(2003, 11, 20, 10, 50, 1); _test3 = new SqlDateTime(2003, 11, 20, 10, 50, 1); } // Test constructor [Fact] public void Create() { // SqlDateTime (DateTime) SqlDateTime CTest = new SqlDateTime( new DateTime(2002, 5, 19, 3, 34, 0)); Assert.Equal(2002, CTest.Value.Year); // SqlDateTime (int, int) CTest = new SqlDateTime(0, 0); // SqlDateTime (int, int, int) Assert.Equal(1900, CTest.Value.Year); Assert.Equal(1, CTest.Value.Month); Assert.Equal(1, CTest.Value.Day); Assert.Equal(0, CTest.Value.Hour); // SqlDateTime (int, int, int, int, int, int) CTest = new SqlDateTime(5000, 12, 31); Assert.Equal(5000, CTest.Value.Year); Assert.Equal(12, CTest.Value.Month); Assert.Equal(31, CTest.Value.Day); // SqlDateTime (int, int, int, int, int, int, double) CTest = new SqlDateTime(1978, 5, 19, 3, 34, 0); Assert.Equal(1978, CTest.Value.Year); Assert.Equal(5, CTest.Value.Month); Assert.Equal(19, CTest.Value.Day); Assert.Equal(3, CTest.Value.Hour); Assert.Equal(34, CTest.Value.Minute); Assert.Equal(0, CTest.Value.Second); try { CTest = new SqlDateTime(10000, 12, 31); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlTypeException), e.GetType()); } // SqlDateTime (int, int, int, int, int, int, int) CTest = new SqlDateTime(1978, 5, 19, 3, 34, 0, 12); Assert.Equal(1978, CTest.Value.Year); Assert.Equal(5, CTest.Value.Month); Assert.Equal(19, CTest.Value.Day); Assert.Equal(3, CTest.Value.Hour); Assert.Equal(34, CTest.Value.Minute); Assert.Equal(0, CTest.Value.Second); Assert.Equal(0, CTest.Value.Millisecond); } // Test public fields [Fact] public void PublicFields() { // MaxValue Assert.Equal(9999, SqlDateTime.MaxValue.Value.Year); Assert.Equal(12, SqlDateTime.MaxValue.Value.Month); Assert.Equal(31, SqlDateTime.MaxValue.Value.Day); Assert.Equal(23, SqlDateTime.MaxValue.Value.Hour); Assert.Equal(59, SqlDateTime.MaxValue.Value.Minute); Assert.Equal(59, SqlDateTime.MaxValue.Value.Second); // MinValue Assert.Equal(1753, SqlDateTime.MinValue.Value.Year); Assert.Equal(1, SqlDateTime.MinValue.Value.Month); Assert.Equal(1, SqlDateTime.MinValue.Value.Day); Assert.Equal(0, SqlDateTime.MinValue.Value.Hour); Assert.Equal(0, SqlDateTime.MinValue.Value.Minute); Assert.Equal(0, SqlDateTime.MinValue.Value.Second); // Null Assert.True(SqlDateTime.Null.IsNull); // SQLTicksPerHour Assert.Equal(1080000, SqlDateTime.SQLTicksPerHour); // SQLTicksPerMinute Assert.Equal(18000, SqlDateTime.SQLTicksPerMinute); // SQLTicksPerSecond Assert.Equal(300, SqlDateTime.SQLTicksPerSecond); } // Test properties [Fact] public void Properties() { // DayTicks Assert.Equal(37546, _test1.DayTicks); try { int test = SqlDateTime.Null.DayTicks; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlNullValueException), e.GetType()); } // IsNull Assert.True(SqlDateTime.Null.IsNull); Assert.True(!_test2.IsNull); // TimeTicks Assert.Equal(10440000, _test1.TimeTicks); try { int test = SqlDateTime.Null.TimeTicks; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlNullValueException), e.GetType()); } // Value Assert.Equal(2003, _test2.Value.Year); Assert.Equal(2002, _test1.Value.Year); } // PUBLIC METHODS [Fact] public void CompareTo() { SqlString TestString = new SqlString("This is a test"); Assert.True(_test1.CompareTo(_test3) < 0); Assert.True(_test2.CompareTo(_test1) > 0); Assert.True(_test2.CompareTo(_test3) == 0); Assert.True(_test1.CompareTo(SqlDateTime.Null) > 0); try { _test1.CompareTo(TestString); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentException), e.GetType()); } } [Fact] public void EqualsMethods() { Assert.True(!_test1.Equals(_test2)); Assert.True(!_test2.Equals(new SqlString("TEST"))); Assert.True(_test2.Equals(_test3)); // Static Equals()-method Assert.True(SqlDateTime.Equals(_test2, _test3).Value); Assert.True(!SqlDateTime.Equals(_test1, _test2).Value); } [Fact] public void GetHashCodeTest() { // FIXME: Better way to test HashCode Assert.Equal(_test1.GetHashCode(), _test1.GetHashCode()); Assert.True(_test2.GetHashCode() != _test1.GetHashCode()); } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)] public void GetTypeTest() { Assert.Equal("System.Data.SqlTypes.SqlDateTime", _test1.GetType().ToString()); Assert.Equal("System.DateTime", _test1.Value.GetType().ToString()); } [Fact] public void Greaters() { // GreateThan () Assert.True(!SqlDateTime.GreaterThan(_test1, _test2).Value); Assert.True(SqlDateTime.GreaterThan(_test2, _test1).Value); Assert.True(!SqlDateTime.GreaterThan(_test2, _test3).Value); // GreaterTharOrEqual () Assert.True(!SqlDateTime.GreaterThanOrEqual(_test1, _test2).Value); Assert.True(SqlDateTime.GreaterThanOrEqual(_test2, _test1).Value); Assert.True(SqlDateTime.GreaterThanOrEqual(_test2, _test3).Value); } [Fact] public void Lessers() { // LessThan() Assert.True(!SqlDateTime.LessThan(_test2, _test3).Value); Assert.True(!SqlDateTime.LessThan(_test2, _test1).Value); Assert.True(SqlDateTime.LessThan(_test1, _test3).Value); // LessThanOrEqual () Assert.True(SqlDateTime.LessThanOrEqual(_test1, _test2).Value); Assert.True(!SqlDateTime.LessThanOrEqual(_test2, _test1).Value); Assert.True(SqlDateTime.LessThanOrEqual(_test3, _test2).Value); Assert.True(SqlDateTime.LessThanOrEqual(_test1, SqlDateTime.Null).IsNull); } [Fact] public void NotEquals() { Assert.True(SqlDateTime.NotEquals(_test1, _test2).Value); Assert.True(SqlDateTime.NotEquals(_test3, _test1).Value); Assert.True(!SqlDateTime.NotEquals(_test2, _test3).Value); Assert.True(SqlDateTime.NotEquals(SqlDateTime.Null, _test2).IsNull); } [Fact] public void Parse() { try { SqlDateTime.Parse(null); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentNullException), e.GetType()); } try { SqlDateTime.Parse("not-a-number"); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(FormatException), e.GetType()); } SqlDateTime t1 = SqlDateTime.Parse("02/25/2002"); Assert.Equal(_myTicks[0], t1.Value.Ticks); try { t1 = SqlDateTime.Parse("2002-02-25"); } catch (Exception e) { Assert.False(true); } // Thanks for Martin Baulig for these (DateTimeTest.cs) Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = SqlDateTime.Parse("Monday, 25 February 2002"); Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = SqlDateTime.Parse("Monday, 25 February 2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = SqlDateTime.Parse("Monday, 25 February 2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = SqlDateTime.Parse("02/25/2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = SqlDateTime.Parse("02/25/2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = SqlDateTime.Parse("2002-02-25 04:25:13Z"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); SqlDateTime t2 = new SqlDateTime(DateTime.Today.Year, 2, 25); t1 = SqlDateTime.Parse("February 25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = SqlDateTime.Parse("February 08"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t1 = SqlDateTime.Parse("Mon, 25 Feb 2002 04:25:13 GMT"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); t1 = SqlDateTime.Parse("2002-02-25T05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 0); t1 = SqlDateTime.Parse("05:25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 13); t1 = SqlDateTime.Parse("05:25:13"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = SqlDateTime.Parse("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = SqlDateTime.Parse("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = SqlDateTime.Parse("February 8"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); } // OPERATORS [Fact] public void ArithmeticOperators() { TimeSpan TestSpan = new TimeSpan(20, 1, 20, 20); SqlDateTime ResultDateTime; // "+"-operator ResultDateTime = _test1 + TestSpan; Assert.Equal(2002, ResultDateTime.Value.Year); Assert.Equal(8, ResultDateTime.Value.Day); Assert.Equal(11, ResultDateTime.Value.Hour); Assert.Equal(0, ResultDateTime.Value.Minute); Assert.Equal(20, ResultDateTime.Value.Second); Assert.True((SqlDateTime.Null + TestSpan).IsNull); try { ResultDateTime = SqlDateTime.MaxValue + TestSpan; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentOutOfRangeException), e.GetType()); } // "-"-operator ResultDateTime = _test1 - TestSpan; Assert.Equal(2002, ResultDateTime.Value.Year); Assert.Equal(29, ResultDateTime.Value.Day); Assert.Equal(8, ResultDateTime.Value.Hour); Assert.Equal(19, ResultDateTime.Value.Minute); Assert.Equal(40, ResultDateTime.Value.Second); Assert.True((SqlDateTime.Null - TestSpan).IsNull); try { ResultDateTime = SqlDateTime.MinValue - TestSpan; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlTypeException), e.GetType()); } } [Fact] public void ThanOrEqualOperators() { // == -operator Assert.True((_test2 == _test3).Value); Assert.True(!(_test1 == _test2).Value); Assert.True((_test1 == SqlDateTime.Null).IsNull); // != -operator Assert.True(!(_test2 != _test3).Value); Assert.True((_test1 != _test3).Value); Assert.True((_test1 != SqlDateTime.Null).IsNull); // > -operator Assert.True((_test2 > _test1).Value); Assert.True(!(_test3 > _test2).Value); Assert.True((_test1 > SqlDateTime.Null).IsNull); // >= -operator Assert.True(!(_test1 >= _test3).Value); Assert.True((_test3 >= _test1).Value); Assert.True((_test2 >= _test3).Value); Assert.True((_test1 >= SqlDateTime.Null).IsNull); // < -operator Assert.True(!(_test2 < _test1).Value); Assert.True((_test1 < _test3).Value); Assert.True(!(_test2 < _test3).Value); Assert.True((_test1 < SqlDateTime.Null).IsNull); // <= -operator Assert.True((_test1 <= _test3).Value); Assert.True(!(_test3 <= _test1).Value); Assert.True((_test2 <= _test3).Value); Assert.True((_test1 <= SqlDateTime.Null).IsNull); } [Fact] public void SqlDateTimeToDateTime() { Assert.Equal(2002, ((DateTime)_test1).Year); Assert.Equal(2003, ((DateTime)_test2).Year); Assert.Equal(10, ((DateTime)_test1).Month); Assert.Equal(19, ((DateTime)_test1).Day); Assert.Equal(9, ((DateTime)_test1).Hour); Assert.Equal(40, ((DateTime)_test1).Minute); Assert.Equal(0, ((DateTime)_test1).Second); } [Fact] public void SqlStringToSqlDateTime() { SqlString TestString = new SqlString("02/25/2002"); SqlDateTime t1 = (SqlDateTime)TestString; Assert.Equal(_myTicks[0], t1.Value.Ticks); // Thanks for Martin Baulig for these (DateTimeTest.cs) Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Monday, 25 February 2002"); Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Monday, 25 February 2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Monday, 25 February 2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("02/25/2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("02/25/2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("2002-02-25 04:25:13Z"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); SqlDateTime t2 = new SqlDateTime(DateTime.Today.Year, 2, 25); t1 = (SqlDateTime)new SqlString("February 25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = (SqlDateTime)new SqlString("February 08"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Mon, 25 Feb 2002 04:25:13 GMT"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); t1 = (SqlDateTime)new SqlString("2002-02-25T05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 0); t1 = (SqlDateTime)new SqlString("05:25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 13); t1 = (SqlDateTime)new SqlString("05:25:13"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = (SqlDateTime)new SqlString("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = (SqlDateTime)new SqlString("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = (SqlDateTime)new SqlString("February 8"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); } [Fact] public void DateTimeToSqlDateTime() { DateTime DateTimeTest = new DateTime(2002, 10, 19, 11, 53, 4); SqlDateTime Result = DateTimeTest; Assert.Equal(2002, Result.Value.Year); Assert.Equal(10, Result.Value.Month); Assert.Equal(19, Result.Value.Day); Assert.Equal(11, Result.Value.Hour); Assert.Equal(53, Result.Value.Minute); Assert.Equal(4, Result.Value.Second); } [Fact] public void TicksRoundTrip() { SqlDateTime d1 = new SqlDateTime(2007, 05, 04, 18, 02, 40, 398.25); SqlDateTime d2 = new SqlDateTime(d1.DayTicks, d1.TimeTicks); Assert.Equal(39204, d1.DayTicks); Assert.Equal(19488119, d1.TimeTicks); Assert.Equal(633138985603970000, d1.Value.Ticks); Assert.Equal(d1.DayTicks, d2.DayTicks); Assert.Equal(d1.TimeTicks, d2.TimeTicks); Assert.Equal(d1.Value.Ticks, d2.Value.Ticks); Assert.Equal(d1, d2); } [Fact] public void EffingBilisecond() { SqlDateTime d1 = new SqlDateTime(2007, 05, 04, 18, 02, 40, 398252); Assert.Equal(39204, d1.DayTicks); Assert.Equal(19488119, d1.TimeTicks); Assert.Equal(633138985603970000, d1.Value.Ticks); } [Fact] public void GetXsdTypeTest() { XmlQualifiedName qualifiedName = SqlDateTime.GetXsdType(null); Assert.Equal("dateTime", qualifiedName.Name); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using WinHttpHandlerTests; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; internal static partial class Interop { internal static partial class Crypt32 { public static bool CertFreeCertificateContext(IntPtr certContext) { return true; } public static bool CertVerifyCertificateChainPolicy( IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus) { return true; } } internal static partial class mincore { public static string GetMessage(IntPtr moduleName, int error) { string messageFormat = "Fake error message, error code: {0}"; return string.Format(messageFormat, error); } public static IntPtr GetModuleHandle(string moduleName) { return IntPtr.Zero; } } internal static partial class WinHttp { public static SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, uint flags) { if (accessType == Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY && !TestControl.WinHttpAutomaticProxySupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_PARAMETER; return new FakeSafeWinHttpHandle(false); } APICallHistory.ProxyInfo proxyInfo; proxyInfo.AccessType = accessType; proxyInfo.Proxy = proxyName; proxyInfo.ProxyBypass = proxyBypass; APICallHistory.SessionProxySettings = proxyInfo; return new FakeSafeWinHttpHandle(true); } public static bool WinHttpCloseHandle(IntPtr sessionHandle) { return true; } public static SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, uint modifiers) { return true; } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers) { return true; } public static SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context) { return true; } public static bool WinHttpReceiveResponse(SafeWinHttpHandle requestHandle, IntPtr reserved) { if (TestControl.ResponseDelayTime > 0) { TestControl.ResponseDelayCompletedEvent.Reset(); Thread.Sleep(TestControl.ResponseDelayTime); TestControl.ResponseDelayCompletedEvent.Set(); } return true; } public static bool WinHttpQueryDataAvailable(SafeWinHttpHandle requestHandle, out uint bytesAvailable) { bytesAvailable = 0; return true; } public static bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, out uint bytesRead) { bytesRead = 0; if (TestControl.WinHttpAPIFail) { return false; } TestServer.ReadFromResponseBody(buffer, bufferSize, out bytesRead); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, StringBuilder buffer, ref uint bufferLength, IntPtr index) { string httpVersion = "HTTP/1.1"; string statusText = "OK"; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_VERSION) { if (buffer == null) { bufferLength = ((uint)httpVersion.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(httpVersion); return true; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT) { if (buffer == null) { bufferLength = ((uint)statusText.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(statusText); return true; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING) { string compression = null; if (TestServer.ResponseHeaders.Contains("Content-Encoding: deflate")) { compression = "deflate"; } else if (TestServer.ResponseHeaders.Contains("Content-Encoding: gzip")) { compression = "gzip"; } if (compression == null) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } if (buffer == null) { bufferLength = ((uint)compression.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(compression); return true; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF) { if (buffer == null) { bufferLength = ((uint)TestServer.ResponseHeaders.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(TestServer.ResponseHeaders); return true; } return false; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index) { infoLevel &= ~Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE) { number = (uint)HttpStatusCode.OK; return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, StringBuilder buffer, ref uint bufferSize) { string uri = "http://www.contoso.com/"; if (option == Interop.WinHttp.WINHTTP_OPTION_URL) { if (buffer == null) { bufferSize = ((uint)uri.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(uri); return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, out uint bytesWritten) { if (TestControl.WinHttpAPIFail) { bytesWritten = 0; return false; } TestServer.WriteToRequestBody(buffer, bufferSize); bytesWritten = bufferSize; return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)) { if (option == Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION & !TestControl.WinHttpDecompressionSupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION; return false; } if (option == Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_DISABLE_COOKIES) { APICallHistory.WinHttpOptionDisableCookies = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION) { APICallHistory.WinHttpOptionEnableSslRevocation = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS) { APICallHistory.WinHttpOptionSecureProtocols = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS) { APICallHistory.WinHttpOptionSecurityFlags = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS) { APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY) { APICallHistory.WinHttpOptionRedirectPolicy = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, string optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_USERNAME) { APICallHistory.ProxyUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_PASSWORD) { APICallHistory.ProxyPassword = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_USERNAME) { APICallHistory.ServerUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PASSWORD) { APICallHistory.ServerPassword = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY) { var proxyInfo = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_PROXY_INFO>(optionData); var proxyInfoHistory = new APICallHistory.ProxyInfo(); proxyInfoHistory.AccessType = proxyInfo.AccessType; proxyInfoHistory.Proxy = Marshal.PtrToStringUni(proxyInfo.Proxy); proxyInfoHistory.ProxyBypass = Marshal.PtrToStringUni(proxyInfo.ProxyBypass); APICallHistory.RequestProxySettings = proxyInfoHistory; } else if (option == Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT) { APICallHistory.WinHttpOptionClientCertContext.Add(optionData); } return true; } public static bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved) { return true; } public static bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget) { supportedSchemes = 0; firstScheme = 0; authTarget = 0; return true; } public static bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout) { return true; } public static bool WinHttpGetIEProxyConfigForCurrentUser( out Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig) { if (FakeRegistry.WinInetProxySettings.RegistryKeyMissing) { proxyConfig.AutoDetect = false; proxyConfig.AutoConfigUrl = IntPtr.Zero; proxyConfig.Proxy = IntPtr.Zero; proxyConfig.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_FILE_NOT_FOUND; return false; } proxyConfig.AutoDetect = FakeRegistry.WinInetProxySettings.AutoDetect; proxyConfig.AutoConfigUrl = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.AutoConfigUrl); proxyConfig.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyConfig.ProxyBypass = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.ProxyBypass); return true; } public static bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo) { if (TestControl.PACFileNotDetectedOnNetwork) { proxyInfo.AccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.Proxy = IntPtr.Zero; proxyInfo.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED; return false; } proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyInfo.ProxyBypass = IntPtr.Zero; return true; } public static IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved) { return IntPtr.Zero; } } }
// // 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.UnitTests.Layouts { using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; using NLog.Layouts; using NLog.Targets; using Xunit; public class SimpleLayoutParserTests : NLogTestBase { [Fact] public void SimpleTest() { SimpleLayout l = "${message}"; Assert.Equal(1, l.Renderers.Count); Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]); } [Fact] public void UnclosedTest() { new SimpleLayout("${message"); } [Fact] public void SingleParamTest() { SimpleLayout l = "${mdc:item=AAA}"; Assert.Equal(1, l.Renderers.Count); MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer; Assert.NotNull(mdc); Assert.Equal("AAA", mdc.Item); } [Fact] public void ValueWithColonTest() { SimpleLayout l = "${mdc:item=AAA\\:}"; Assert.Equal(1, l.Renderers.Count); MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer; Assert.NotNull(mdc); Assert.Equal("AAA:", mdc.Item); } [Fact] public void ValueWithBracketTest() { SimpleLayout l = "${mdc:item=AAA\\}\\:}"; Assert.Equal("${mdc:item=AAA\\}\\:}", l.Text); //Assert.Equal(1, l.Renderers.Count); MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer; Assert.NotNull(mdc); Assert.Equal("AAA}:", mdc.Item); } [Fact] public void DefaultValueTest() { SimpleLayout l = "${mdc:BBB}"; //Assert.Equal(1, l.Renderers.Count); MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer; Assert.NotNull(mdc); Assert.Equal("BBB", mdc.Item); } [Fact] public void DefaultValueWithBracketTest() { SimpleLayout l = "${mdc:AAA\\}\\:}"; Assert.Equal(l.Text, "${mdc:AAA\\}\\:}"); Assert.Equal(1, l.Renderers.Count); MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer; Assert.NotNull(mdc); Assert.Equal("AAA}:", mdc.Item); } [Fact] public void DefaultValueWithOtherParametersTest() { SimpleLayout l = "${exception:message,type:separator=x}"; Assert.Equal(1, l.Renderers.Count); ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer; Assert.NotNull(elr); Assert.Equal("message,type", elr.Format); Assert.Equal("x", elr.Separator); } [Fact] public void EmptyValueTest() { SimpleLayout l = "${mdc:item=}"; Assert.Equal(1, l.Renderers.Count); MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer; Assert.NotNull(mdc); Assert.Equal("", mdc.Item); } [Fact] public void NestedLayoutTest() { SimpleLayout l = "${rot13:inner=${ndc:topFrames=3:separator=x}}"; Assert.Equal(1, l.Renderers.Count); var lr = l.Renderers[0] as Rot13LayoutRendererWrapper; Assert.NotNull(lr); var nestedLayout = lr.Inner as SimpleLayout; Assert.NotNull(nestedLayout); Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text); Assert.Equal(1, nestedLayout.Renderers.Count); var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer; Assert.NotNull(ndcLayoutRenderer); Assert.Equal(3, ndcLayoutRenderer.TopFrames); Assert.Equal("x", ndcLayoutRenderer.Separator); } [Fact] public void DoubleNestedLayoutTest() { SimpleLayout l = "${rot13:inner=${rot13:inner=${ndc:topFrames=3:separator=x}}}"; Assert.Equal(1, l.Renderers.Count); var lr = l.Renderers[0] as Rot13LayoutRendererWrapper; Assert.NotNull(lr); var nestedLayout0 = lr.Inner as SimpleLayout; Assert.NotNull(nestedLayout0); Assert.Equal("${rot13:inner=${ndc:topFrames=3:separator=x}}", nestedLayout0.Text); var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper; var nestedLayout = innerRot13.Inner as SimpleLayout; Assert.NotNull(nestedLayout); Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text); Assert.Equal(1, nestedLayout.Renderers.Count); var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer; Assert.NotNull(ndcLayoutRenderer); Assert.Equal(3, ndcLayoutRenderer.TopFrames); Assert.Equal("x", ndcLayoutRenderer.Separator); } [Fact] public void DoubleNestedLayoutWithDefaultLayoutParametersTest() { SimpleLayout l = "${rot13:${rot13:${ndc:topFrames=3:separator=x}}}"; Assert.Equal(1, l.Renderers.Count); var lr = l.Renderers[0] as Rot13LayoutRendererWrapper; Assert.NotNull(lr); var nestedLayout0 = lr.Inner as SimpleLayout; Assert.NotNull(nestedLayout0); Assert.Equal("${rot13:${ndc:topFrames=3:separator=x}}", nestedLayout0.Text); var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper; var nestedLayout = innerRot13.Inner as SimpleLayout; Assert.NotNull(nestedLayout); Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text); Assert.Equal(1, nestedLayout.Renderers.Count); var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer; Assert.NotNull(ndcLayoutRenderer); Assert.Equal(3, ndcLayoutRenderer.TopFrames); Assert.Equal("x", ndcLayoutRenderer.Separator); } [Fact] public void AmbientPropertyTest() { SimpleLayout l = "${message:padding=10}"; Assert.Equal(1, l.Renderers.Count); var pad = l.Renderers[0] as PaddingLayoutRendererWrapper; Assert.NotNull(pad); var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer; Assert.NotNull(message); } [Fact] public void MissingLayoutRendererTest() { Assert.Throws<NLogConfigurationException>(() => { SimpleLayout l = "${rot13:${foobar}}"; }); } [Fact] public void DoubleAmbientPropertyTest() { SimpleLayout l = "${message:uppercase=true:padding=10}"; Assert.Equal(1, l.Renderers.Count); var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper; Assert.NotNull(upperCase); var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper; Assert.NotNull(pad); var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer; Assert.NotNull(message); } [Fact] public void ReverseDoubleAmbientPropertyTest() { SimpleLayout l = "${message:padding=10:uppercase=true}"; Assert.Equal(1, l.Renderers.Count); var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper; Assert.NotNull(pad); var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper; Assert.NotNull(upperCase); var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer; Assert.NotNull(message); } [Fact] public void EscapeTest() { AssertEscapeRoundTrips(string.Empty); AssertEscapeRoundTrips("hello ${${}} world!"); AssertEscapeRoundTrips("hello $"); AssertEscapeRoundTrips("hello ${"); AssertEscapeRoundTrips("hello $${{"); AssertEscapeRoundTrips("hello ${message}"); AssertEscapeRoundTrips("hello ${${level}}"); AssertEscapeRoundTrips("hello ${${level}${message}}"); } [Fact] public void EvaluateTest() { var logEventInfo = LogEventInfo.CreateNullEvent(); logEventInfo.Level = LogLevel.Warn; Assert.Equal("Warn", SimpleLayout.Evaluate("${level}", logEventInfo)); } [Fact] public void EvaluateTest2() { Assert.Equal("Off", SimpleLayout.Evaluate("${level}")); Assert.Equal(string.Empty, SimpleLayout.Evaluate("${message}")); Assert.Equal(string.Empty, SimpleLayout.Evaluate("${logger}")); } private static void AssertEscapeRoundTrips(string originalString) { string escapedString = SimpleLayout.Escape(originalString); SimpleLayout l = escapedString; string renderedString = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(originalString, renderedString); } [Fact] public void LayoutParserEscapeCodesForRegExTestV1() { MappedDiagnosticsContext.Clear(); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?&lt;!\\d[ -]*)(?\u003a(?&lt;digits&gt;\\d)[ -]*)\u007b8,16\u007d(?=(\\d[ -]*)\u007b3\u007d(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var c = layout.Renderers.Count; Assert.Equal(1, c); var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper; Assert.NotNull(l1); Assert.Equal(true, l1.Regex); Assert.Equal(true, l1.IgnoreCase); Assert.Equal(@"::", l1.ReplaceWith); Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor); } [Fact] public void LayoutParserEscapeCodesForRegExTestV2() { MappedDiagnosticsContext.Clear(); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?&lt;!\\d[ -]*)(?\:(?&lt;digits&gt;\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var c = layout.Renderers.Count; Assert.Equal(1, c); var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper; Assert.NotNull(l1); Assert.Equal(true, l1.Regex); Assert.Equal(true, l1.IgnoreCase); Assert.Equal(@"::", l1.ReplaceWith); Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor); } [Fact] public void InnerLayoutWithColonTest_with_workaround() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test${literal:text=\:} Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test: Hello", l.Render(le)); } [Fact] public void InnerLayoutWithColonTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test\: Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test: Hello", l.Render(le)); } [Fact] public void InnerLayoutWithSlashSingleTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test\\Hello", l.Render(le)); } [Fact] public void InnerLayoutWithSlashTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test\\Hello", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\}}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test{Hello}", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest2() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\\}}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal(@"Test{Hello\}", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_reverse() { SimpleLayout l = @"${when:Inner=Test{Hello\}:when=1 == 1}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test{Hello}", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_no_escape() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello}}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test{Hello}", l.Render(le)); } [Fact] public void InnerLayoutWithHashTest() { SimpleLayout l = @"${when:when=1 == 1:inner=Log_{#\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Log_{#}.log", l.Render(le)); } [Fact] public void InnerLayoutWithHashTest_need_escape() { SimpleLayout l = @"${when:when=1 == 1:inner=L\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("L}.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape() { SimpleLayout l = @"${when:when=1 == 1:inner=\}{.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("}{.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape2() { SimpleLayout l = @"${when:when=1 == 1:inner={\}\}{.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("{}}{.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape3() { SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("{}}}.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape4() { SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("{}}}.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape5() { SimpleLayout l = @"${when:when=1 == 1:inner=\}{a\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("}{a}.log", l.Render(le)); } [Fact] public void InnerLayoutWithHashTest_and_layoutrender() { SimpleLayout l = @"${when:when=1 == 1:inner=${counter}/Log_{#\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("1/Log_{#}.log", l.Render(le)); } } }
namespace Zu.ChromeDevTools.Debugger { using System; using System.Threading; using System.Threading.Tasks; /// <summary> /// Represents an adapter for the Debugger domain to simplify the command interface. /// </summary> public class DebuggerAdapter { private readonly ChromeSession m_session; public DebuggerAdapter(ChromeSession session) { m_session = session ?? throw new ArgumentNullException(nameof(session)); } /// <summary> /// Gets the ChromeSession associated with the adapter. /// </summary> public ChromeSession Session { get { return m_session; } } /// <summary> /// Continues execution until specific location is reached. /// </summary> public async Task<ContinueToLocationCommandResponse> ContinueToLocation(ContinueToLocationCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ContinueToLocationCommand, ContinueToLocationCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Disables debugger for given page. /// </summary> public async Task<DisableCommandResponse> Disable(DisableCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<DisableCommand, DisableCommandResponse>(command ?? new DisableCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Enables debugger for the given page. Clients should not assume that the debugging has been /// enabled until the result for this command is received. /// </summary> public async Task<EnableCommandResponse> Enable(EnableCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<EnableCommand, EnableCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Evaluates expression on a given call frame. /// </summary> public async Task<EvaluateOnCallFrameCommandResponse> EvaluateOnCallFrame(EvaluateOnCallFrameCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<EvaluateOnCallFrameCommand, EvaluateOnCallFrameCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns possible locations for breakpoint. scriptId in start and end range locations should be /// the same. /// </summary> public async Task<GetPossibleBreakpointsCommandResponse> GetPossibleBreakpoints(GetPossibleBreakpointsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetPossibleBreakpointsCommand, GetPossibleBreakpointsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns source for the script with given id. /// </summary> public async Task<GetScriptSourceCommandResponse> GetScriptSource(GetScriptSourceCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetScriptSourceCommand, GetScriptSourceCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// This command is deprecated. Use getScriptSource instead. /// </summary> public async Task<GetWasmBytecodeCommandResponse> GetWasmBytecode(GetWasmBytecodeCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetWasmBytecodeCommand, GetWasmBytecodeCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns stack trace with given `stackTraceId`. /// </summary> public async Task<GetStackTraceCommandResponse> GetStackTrace(GetStackTraceCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetStackTraceCommand, GetStackTraceCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Stops on the next JavaScript statement. /// </summary> public async Task<PauseCommandResponse> Pause(PauseCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<PauseCommand, PauseCommandResponse>(command ?? new PauseCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// /// </summary> public async Task<PauseOnAsyncCallCommandResponse> PauseOnAsyncCall(PauseOnAsyncCallCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<PauseOnAsyncCallCommand, PauseOnAsyncCallCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Removes JavaScript breakpoint. /// </summary> public async Task<RemoveBreakpointCommandResponse> RemoveBreakpoint(RemoveBreakpointCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<RemoveBreakpointCommand, RemoveBreakpointCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Restarts particular call frame from the beginning. /// </summary> public async Task<RestartFrameCommandResponse> RestartFrame(RestartFrameCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<RestartFrameCommand, RestartFrameCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Resumes JavaScript execution. /// </summary> public async Task<ResumeCommandResponse> Resume(ResumeCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ResumeCommand, ResumeCommandResponse>(command ?? new ResumeCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Searches for given string in script content. /// </summary> public async Task<SearchInContentCommandResponse> SearchInContent(SearchInContentCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SearchInContentCommand, SearchInContentCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Enables or disables async call stacks tracking. /// </summary> public async Task<SetAsyncCallStackDepthCommandResponse> SetAsyncCallStackDepth(SetAsyncCallStackDepthCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetAsyncCallStackDepthCommand, SetAsyncCallStackDepthCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in /// scripts with url matching one of the patterns. VM will try to leave blackboxed script by /// performing 'step in' several times, finally resorting to 'step out' if unsuccessful. /// </summary> public async Task<SetBlackboxPatternsCommandResponse> SetBlackboxPatterns(SetBlackboxPatternsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBlackboxPatternsCommand, SetBlackboxPatternsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted /// scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. /// Positions array contains positions where blackbox state is changed. First interval isn't /// blackboxed. Array should be sorted. /// </summary> public async Task<SetBlackboxedRangesCommandResponse> SetBlackboxedRanges(SetBlackboxedRangesCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBlackboxedRangesCommand, SetBlackboxedRangesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets JavaScript breakpoint at a given location. /// </summary> public async Task<SetBreakpointCommandResponse> SetBreakpoint(SetBreakpointCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBreakpointCommand, SetBreakpointCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets instrumentation breakpoint. /// </summary> public async Task<SetInstrumentationBreakpointCommandResponse> SetInstrumentationBreakpoint(SetInstrumentationBreakpointCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetInstrumentationBreakpointCommand, SetInstrumentationBreakpointCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this /// command is issued, all existing parsed scripts will have breakpoints resolved and returned in /// `locations` property. Further matching script parsing will result in subsequent /// `breakpointResolved` events issued. This logical breakpoint will survive page reloads. /// </summary> public async Task<SetBreakpointByUrlCommandResponse> SetBreakpointByUrl(SetBreakpointByUrlCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBreakpointByUrlCommand, SetBreakpointByUrlCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets JavaScript breakpoint before each call to the given function. /// If another function was created from the same source as a given one, /// calling it will also trigger the breakpoint. /// </summary> public async Task<SetBreakpointOnFunctionCallCommandResponse> SetBreakpointOnFunctionCall(SetBreakpointOnFunctionCallCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBreakpointOnFunctionCallCommand, SetBreakpointOnFunctionCallCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Activates / deactivates all breakpoints on the page. /// </summary> public async Task<SetBreakpointsActiveCommandResponse> SetBreakpointsActive(SetBreakpointsActiveCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetBreakpointsActiveCommand, SetBreakpointsActiveCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or /// no exceptions. Initial pause on exceptions state is `none`. /// </summary> public async Task<SetPauseOnExceptionsCommandResponse> SetPauseOnExceptions(SetPauseOnExceptionsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetPauseOnExceptionsCommand, SetPauseOnExceptionsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Changes return value in top frame. Available only at return break position. /// </summary> public async Task<SetReturnValueCommandResponse> SetReturnValue(SetReturnValueCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetReturnValueCommand, SetReturnValueCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Edits JavaScript source live. /// </summary> public async Task<SetScriptSourceCommandResponse> SetScriptSource(SetScriptSourceCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetScriptSourceCommand, SetScriptSourceCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). /// </summary> public async Task<SetSkipAllPausesCommandResponse> SetSkipAllPauses(SetSkipAllPausesCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetSkipAllPausesCommand, SetSkipAllPausesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Changes value of variable in a callframe. Object-based scopes are not supported and must be /// mutated manually. /// </summary> public async Task<SetVariableValueCommandResponse> SetVariableValue(SetVariableValueCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetVariableValueCommand, SetVariableValueCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Steps into the function call. /// </summary> public async Task<StepIntoCommandResponse> StepInto(StepIntoCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<StepIntoCommand, StepIntoCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Steps out of the function call. /// </summary> public async Task<StepOutCommandResponse> StepOut(StepOutCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<StepOutCommand, StepOutCommandResponse>(command ?? new StepOutCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Steps over the statement. /// </summary> public async Task<StepOverCommandResponse> StepOver(StepOverCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<StepOverCommand, StepOverCommandResponse>(command ?? new StepOverCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Fired when breakpoint is resolved to an actual script and location. /// </summary> public void SubscribeToBreakpointResolvedEvent(Action<BreakpointResolvedEvent> eventCallback) { m_session.Subscribe(eventCallback); } /// <summary> /// Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. /// </summary> public void SubscribeToPausedEvent(Action<PausedEvent> eventCallback) { m_session.Subscribe(eventCallback); } /// <summary> /// Fired when the virtual machine resumed execution. /// </summary> public void SubscribeToResumedEvent(Action<ResumedEvent> eventCallback) { m_session.Subscribe(eventCallback); } /// <summary> /// Fired when virtual machine fails to parse the script. /// </summary> public void SubscribeToScriptFailedToParseEvent(Action<ScriptFailedToParseEvent> eventCallback) { m_session.Subscribe(eventCallback); } /// <summary> /// Fired when virtual machine parses script. This event is also fired for all known and uncollected /// scripts upon enabling debugger. /// </summary> public void SubscribeToScriptParsedEvent(Action<ScriptParsedEvent> eventCallback) { m_session.Subscribe(eventCallback); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeAccessTokenHandle : System.Runtime.InteropServices.SafeHandle { public SafeAccessTokenHandle(System.IntPtr handle) : base(default(System.IntPtr), default(bool)) { } public static Microsoft.Win32.SafeHandles.SafeAccessTokenHandle InvalidHandle { get { throw null; } } public override bool IsInvalid { get { throw null; } } protected override bool ReleaseHandle() { throw null; } } } namespace System.Security.Principal { public sealed partial class IdentityNotMappedException : System.SystemException { public IdentityNotMappedException() { } public IdentityNotMappedException(string message) { } public IdentityNotMappedException(string message, System.Exception inner) { } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public System.Security.Principal.IdentityReferenceCollection UnmappedIdentities { get { throw null; } } } public abstract partial class IdentityReference { internal IdentityReference() { } public abstract string Value { get; } public abstract override bool Equals(object o); public abstract override int GetHashCode(); public abstract bool IsValidTargetType(System.Type targetType); public static bool operator ==(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { throw null; } public static bool operator !=(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { throw null; } public abstract override string ToString(); public abstract System.Security.Principal.IdentityReference Translate(System.Type targetType); } public partial class IdentityReferenceCollection : System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>, System.Collections.Generic.IEnumerable<System.Security.Principal.IdentityReference>, System.Collections.IEnumerable { public IdentityReferenceCollection() { } public IdentityReferenceCollection(int capacity) { } public int Count { get { throw null; } } public System.Security.Principal.IdentityReference this[int index] { get { throw null; } set { } } bool System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>.IsReadOnly { get { throw null; } } public void Add(System.Security.Principal.IdentityReference identity) { } public void Clear() { } public bool Contains(System.Security.Principal.IdentityReference identity) { throw null; } public void CopyTo(System.Security.Principal.IdentityReference[] array, int offset) { } public System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference> GetEnumerator() { throw null; } public bool Remove(System.Security.Principal.IdentityReference identity) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType) { throw null; } public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType, bool forceSuccess) { throw null; } } public sealed partial class NTAccount : System.Security.Principal.IdentityReference { public NTAccount(string name) { } public NTAccount(string domainName, string accountName) { } public override string Value { get { throw null; } } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public override bool IsValidTargetType(System.Type targetType) { throw null; } public static bool operator ==(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { throw null; } public static bool operator !=(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { throw null; } public override string ToString() { throw null; } public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { throw null; } } public sealed partial class SecurityIdentifier : System.Security.Principal.IdentityReference, System.IComparable<System.Security.Principal.SecurityIdentifier> { public static readonly int MaxBinaryLength; public static readonly int MinBinaryLength; public SecurityIdentifier(byte[] binaryForm, int offset) { } public SecurityIdentifier(System.IntPtr binaryForm) { } public SecurityIdentifier(System.Security.Principal.WellKnownSidType sidType, System.Security.Principal.SecurityIdentifier domainSid) { } public SecurityIdentifier(string sddlForm) { } public System.Security.Principal.SecurityIdentifier AccountDomainSid { get { throw null; } } public int BinaryLength { get { throw null; } } public override string Value { get { throw null; } } public int CompareTo(System.Security.Principal.SecurityIdentifier sid) { throw null; } public override bool Equals(object o) { throw null; } public bool Equals(System.Security.Principal.SecurityIdentifier sid) { throw null; } public void GetBinaryForm(byte[] binaryForm, int offset) { } public override int GetHashCode() { throw null; } public bool IsAccountSid() { throw null; } public bool IsEqualDomainSid(System.Security.Principal.SecurityIdentifier sid) { throw null; } public override bool IsValidTargetType(System.Type targetType) { throw null; } public bool IsWellKnown(System.Security.Principal.WellKnownSidType type) { throw null; } public static bool operator ==(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { throw null; } public static bool operator !=(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { throw null; } public override string ToString() { throw null; } public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { throw null; } } [System.FlagsAttribute] public enum TokenAccessLevels { AdjustDefault = 128, AdjustGroups = 64, AdjustPrivileges = 32, AdjustSessionId = 256, AllAccess = 983551, AssignPrimary = 1, Duplicate = 2, Impersonate = 4, MaximumAllowed = 33554432, Query = 8, QuerySource = 16, Read = 131080, Write = 131296, } public enum WellKnownSidType { /// <summary>Indicates a null SID.</summary> NullSid = 0, /// <summary>Indicates a SID that matches everyone.</summary> WorldSid = 1, /// <summary>Indicates a local SID.</summary> LocalSid = 2, /// <summary>Indicates a SID that matches the owner or creator of an object.</summary> CreatorOwnerSid = 3, /// <summary>Indicates a SID that matches the creator group of an object.</summary> CreatorGroupSid = 4, /// <summary>Indicates a creator owner server SID.</summary> CreatorOwnerServerSid = 5, /// <summary>Indicates a creator group server SID.</summary> CreatorGroupServerSid = 6, /// <summary>Indicates a SID for the Windows NT authority account.</summary> NTAuthoritySid = 7, /// <summary>Indicates a SID for a dial-up account.</summary> DialupSid = 8, /// <summary>Indicates a SID for a network account. This SID is added to the process of a token when it logs on across a network.</summary> NetworkSid = 9, /// <summary>Indicates a SID for a batch process. This SID is added to the process of a token when it logs on as a batch job.</summary> BatchSid = 10, /// <summary>Indicates a SID for an interactive account. This SID is added to the process of a token when it logs on interactively.</summary> InteractiveSid = 11, /// <summary>Indicates a SID for a service. This SID is added to the process of a token when it logs on as a service.</summary> ServiceSid = 12, /// <summary>Indicates a SID for the anonymous account.</summary> AnonymousSid = 13, /// <summary>Indicates a proxy SID.</summary> ProxySid = 14, /// <summary>Indicates a SID for an enterprise controller.</summary> EnterpriseControllersSid = 15, /// <summary>Indicates a SID for self.</summary> SelfSid = 16, /// <summary>Indicates a SID that matches any authenticated user.</summary> AuthenticatedUserSid = 17, /// <summary>Indicates a SID for restricted code.</summary> RestrictedCodeSid = 18, /// <summary>Indicates a SID that matches a terminal server account.</summary> TerminalServerSid = 19, /// <summary>Indicates a SID that matches remote logons.</summary> RemoteLogonIdSid = 20, /// <summary>Indicates a SID that matches logon IDs.</summary> LogonIdsSid = 21, /// <summary>Indicates a SID that matches the local system.</summary> LocalSystemSid = 22, /// <summary>Indicates a SID that matches a local service.</summary> LocalServiceSid = 23, /// <summary>Indicates a SID that matches a network service.</summary> NetworkServiceSid = 24, /// <summary>Indicates a SID that matches the domain account.</summary> BuiltinDomainSid = 25, /// <summary>Indicates a SID that matches the administrator group.</summary> BuiltinAdministratorsSid = 26, /// <summary>Indicates a SID that matches built-in user accounts.</summary> BuiltinUsersSid = 27, /// <summary>Indicates a SID that matches the guest account.</summary> BuiltinGuestsSid = 28, /// <summary>Indicates a SID that matches the power users group.</summary> BuiltinPowerUsersSid = 29, /// <summary>Indicates a SID that matches the account operators account.</summary> BuiltinAccountOperatorsSid = 30, /// <summary>Indicates a SID that matches the system operators group.</summary> BuiltinSystemOperatorsSid = 31, /// <summary>Indicates a SID that matches the print operators group.</summary> BuiltinPrintOperatorsSid = 32, /// <summary>Indicates a SID that matches the backup operators group.</summary> BuiltinBackupOperatorsSid = 33, /// <summary>Indicates a SID that matches the replicator account.</summary> BuiltinReplicatorSid = 34, /// <summary>Indicates a SID that matches pre-Windows 2000 compatible accounts.</summary> BuiltinPreWindows2000CompatibleAccessSid = 35, /// <summary>Indicates a SID that matches remote desktop users.</summary> BuiltinRemoteDesktopUsersSid = 36, /// <summary>Indicates a SID that matches the network operators group.</summary> BuiltinNetworkConfigurationOperatorsSid = 37, /// <summary>Indicates a SID that matches the account administrator's account.</summary> AccountAdministratorSid = 38, /// <summary>Indicates a SID that matches the account guest group.</summary> AccountGuestSid = 39, /// <summary>Indicates a SID that matches account Kerberos target group.</summary> AccountKrbtgtSid = 40, /// <summary>Indicates a SID that matches the account domain administrator group.</summary> AccountDomainAdminsSid = 41, /// <summary>Indicates a SID that matches the account domain users group.</summary> AccountDomainUsersSid = 42, /// <summary>Indicates a SID that matches the account domain guests group.</summary> AccountDomainGuestsSid = 43, /// <summary>Indicates a SID that matches the account computer group.</summary> AccountComputersSid = 44, /// <summary>Indicates a SID that matches the account controller group.</summary> AccountControllersSid = 45, /// <summary>Indicates a SID that matches the certificate administrators group.</summary> AccountCertAdminsSid = 46, /// <summary>Indicates a SID that matches the schema administrators group.</summary> AccountSchemaAdminsSid = 47, /// <summary>Indicates a SID that matches the enterprise administrators group.</summary> AccountEnterpriseAdminsSid = 48, /// <summary>Indicates a SID that matches the policy administrators group.</summary> AccountPolicyAdminsSid = 49, /// <summary>Indicates a SID that matches the RAS and IAS server account.</summary> AccountRasAndIasServersSid = 50, /// <summary>Indicates a SID present when the Microsoft NTLM authentication package authenticated the client.</summary> NtlmAuthenticationSid = 51, /// <summary>Indicates a SID present when the Microsoft Digest authentication package authenticated the client.</summary> DigestAuthenticationSid = 52, /// <summary>Indicates a SID present when the Secure Channel (SSL/TLS) authentication package authenticated the client.</summary> SChannelAuthenticationSid = 53, /// <summary>Indicates a SID present when the user authenticated from within the forest or across a trust that does not have the selective authentication option enabled. If this SID is present, then <see cref="WinOtherOrganizationSid"/> cannot be present.</summary> ThisOrganizationSid = 54, /// <summary>Indicates a SID present when the user authenticated across a forest with the selective authentication option enabled. If this SID is present, then <see cref="WinThisOrganizationSid"/> cannot be present.</summary> OtherOrganizationSid = 55, /// <summary>Indicates a SID that allows a user to create incoming forest trusts. It is added to the token of users who are a member of the Incoming Forest Trust Builders built-in group in the root domain of the forest.</summary> BuiltinIncomingForestTrustBuildersSid = 56, /// <summary>Indicates a SID that matches the performance monitor user group.</summary> BuiltinPerformanceMonitoringUsersSid = 57, /// <summary>Indicates a SID that matches the performance log user group.</summary> BuiltinPerformanceLoggingUsersSid = 58, /// <summary>Indicates a SID that matches the Windows Authorization Access group.</summary> BuiltinAuthorizationAccessSid = 59, /// <summary>Indicates a SID is present in a server that can issue terminal server licenses.</summary> WinBuiltinTerminalServerLicenseServersSid = 60, [System.ObsoleteAttribute("This member has been depcreated and is only maintained for backwards compatability. WellKnownSidType values greater than MaxDefined may be defined in future releases.")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] MaxDefined = WinBuiltinTerminalServerLicenseServersSid, /// <summary>Indicates a SID that matches the distributed COM user group.</summary> WinBuiltinDCOMUsersSid = 61, /// <summary>Indicates a SID that matches the Internet built-in user group.</summary> WinBuiltinIUsersSid = 62, /// <summary>Indicates a SID that matches the Internet user group.</summary> WinIUserSid = 63, /// <summary>Indicates a SID that allows a user to use cryptographic operations. It is added to the token of users who are a member of the CryptoOperators built-in group. </summary> WinBuiltinCryptoOperatorsSid = 64, /// <summary>Indicates a SID that matches an untrusted label.</summary> WinUntrustedLabelSid = 65, /// <summary>Indicates a SID that matches an low level of trust label.</summary> WinLowLabelSid = 66, /// <summary>Indicates a SID that matches an medium level of trust label.</summary> WinMediumLabelSid = 67, /// <summary>Indicates a SID that matches a high level of trust label.</summary> WinHighLabelSid = 68, /// <summary>Indicates a SID that matches a system label.</summary> WinSystemLabelSid = 69, /// <summary>Indicates a SID that matches a write restricted code group.</summary> WinWriteRestrictedCodeSid = 70, /// <summary>Indicates a SID that matches a creator and owner rights group.</summary> WinCreatorOwnerRightsSid = 71, /// <summary>Indicates a SID that matches a cacheable principals group.</summary> WinCacheablePrincipalsGroupSid = 72, /// <summary>Indicates a SID that matches a non-cacheable principals group.</summary> WinNonCacheablePrincipalsGroupSid = 73, /// <summary>Indicates a SID that matches an enterprise wide read-only controllers group.</summary> WinEnterpriseReadonlyControllersSid = 74, /// <summary>Indicates a SID that matches an account read-only controllers group.</summary> WinAccountReadonlyControllersSid = 75, /// <summary>Indicates a SID that matches an event log readers group.</summary> WinBuiltinEventLogReadersGroup = 76, /// <summary>Indicates a SID that matches a read-only enterprise domain controller.</summary> WinNewEnterpriseReadonlyControllersSid = 77, /// <summary>Indicates a SID that matches the built-in DCOM certification services access group.</summary> WinBuiltinCertSvcDComAccessGroup = 78, /// <summary>Indicates a SID that matches the medium plus integrity label.</summary> WinMediumPlusLabelSid = 79, /// <summary>Indicates a SID that matches a local logon group.</summary> WinLocalLogonSid = 80, /// <summary>Indicates a SID that matches a console logon group.</summary> WinConsoleLogonSid = 81, /// <summary>Indicates a SID that matches a certificate for the given organization.</summary> WinThisOrganizationCertificateSid = 82, /// <summary>Indicates a SID that matches the application package authority.</summary> WinApplicationPackageAuthoritySid = 83, /// <summary>Indicates a SID that applies to all app containers.</summary> WinBuiltinAnyPackageSid = 84, /// <summary>Indicates a SID of Internet client capability for app containers.</summary> WinCapabilityInternetClientSid = 85, /// <summary>Indicates a SID of Internet client and server capability for app containers.</summary> WinCapabilityInternetClientServerSid = 86, /// <summary>Indicates a SID of private network client and server capability for app containers.</summary> WinCapabilityPrivateNetworkClientServerSid = 87, /// <summary>Indicates a SID for pictures library capability for app containers.</summary> WinCapabilityPicturesLibrarySid = 88, /// <summary>Indicates a SID for videos library capability for app containers.</summary> WinCapabilityVideosLibrarySid = 89, /// <summary>Indicates a SID for music library capability for app containers.</summary> WinCapabilityMusicLibrarySid = 90, /// <summary>Indicates a SID for documents library capability for app containers.</summary> WinCapabilityDocumentsLibrarySid = 91, /// <summary>Indicates a SID for shared user certificates capability for app containers.</summary> WinCapabilitySharedUserCertificatesSid = 92, /// <summary>Indicates a SID for Windows credentials capability for app containers.</summary> WinCapabilityEnterpriseAuthenticationSid = 93, /// <summary>Indicates a SID for removable storage capability for app containers.</summary> WinCapabilityRemovableStorageSid = 94 } public enum WindowsBuiltInRole { AccountOperator = 548, Administrator = 544, BackupOperator = 551, Guest = 546, PowerUser = 547, PrintOperator = 550, Replicator = 552, SystemOperator = 549, User = 545, } public partial class WindowsIdentity : System.Security.Claims.ClaimsIdentity, System.IDisposable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback { public new const string DefaultIssuer = "AD AUTHORITY"; public WindowsIdentity(System.IntPtr userToken) { } public WindowsIdentity(System.IntPtr userToken, string type) { } public WindowsIdentity(string sUserPrincipalName) { } public WindowsIdentity(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public Microsoft.Win32.SafeHandles.SafeAccessTokenHandle AccessToken { get { throw null; } } public sealed override string AuthenticationType { get { throw null; } } public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } } public System.Security.Principal.IdentityReferenceCollection Groups { get { throw null; } } public System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { throw null; } } public virtual bool IsAnonymous { get { throw null; } } public override bool IsAuthenticated { get { throw null; } } public virtual bool IsGuest { get { throw null; } } public virtual bool IsSystem { get { throw null; } } public override string Name { get { throw null; } } public System.Security.Principal.SecurityIdentifier Owner { get { throw null; } } public virtual IntPtr Token { get { throw null; } } public System.Security.Principal.SecurityIdentifier User { get { throw null; } } public override System.Security.Claims.ClaimsIdentity Clone() { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public static System.Security.Principal.WindowsIdentity GetAnonymous() { throw null; } public static System.Security.Principal.WindowsIdentity GetCurrent() { throw null; } public static System.Security.Principal.WindowsIdentity GetCurrent(bool ifImpersonating) { throw null; } public static System.Security.Principal.WindowsIdentity GetCurrent(System.Security.Principal.TokenAccessLevels desiredAccess) { throw null; } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } public static void RunImpersonated(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Action action) { } public static T RunImpersonated<T>(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Func<T> func) { throw null; } } public partial class WindowsPrincipal : System.Security.Claims.ClaimsPrincipal { public WindowsPrincipal(System.Security.Principal.WindowsIdentity ntIdentity) { } public override System.Security.Principal.IIdentity Identity { get { throw null; } } public virtual bool IsInRole(int rid) { throw null; } public virtual bool IsInRole(System.Security.Principal.SecurityIdentifier sid) { throw null; } public virtual bool IsInRole(System.Security.Principal.WindowsBuiltInRole role) { throw null; } public override bool IsInRole(string role) { throw null; } } }
using System; using System.Text; using PalmeralGenNHibernate.CEN.Default_; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Exceptions; using PalmeralGenNHibernate.EN.Default_; using PalmeralGenNHibernate.Exceptions; namespace PalmeralGenNHibernate.CAD.Default_ { public partial class JornadaFechaCAD : BasicCAD, IJornadaFechaCAD { public JornadaFechaCAD() : base () { } public JornadaFechaCAD(ISession sessionAux) : base (sessionAux) { } public JornadaFechaEN ReadOIDDefault (int id) { JornadaFechaEN jornadaFechaEN = null; try { SessionInitializeTransaction (); jornadaFechaEN = (JornadaFechaEN)session.Get (typeof(JornadaFechaEN), id); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } return jornadaFechaEN; } public int Crear (JornadaFechaEN jornadaFecha) { try { SessionInitializeTransaction (); if (jornadaFecha.Instalacion != null) { jornadaFecha.Instalacion = (PalmeralGenNHibernate.EN.Default_.InstalacionEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.InstalacionEN), jornadaFecha.Instalacion.Id); jornadaFecha.Instalacion.Jornadas.Add (jornadaFecha); } session.Save (jornadaFecha); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } return jornadaFecha.Id; } public void Editar (JornadaFechaEN jornadaFecha) { try { SessionInitializeTransaction (); JornadaFechaEN jornadaFechaEN = (JornadaFechaEN)session.Load (typeof(JornadaFechaEN), jornadaFecha.Id); jornadaFechaEN.Fecha = jornadaFecha.Fecha; session.Update (jornadaFechaEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } } public void Eliminar (int id) { try { SessionInitializeTransaction (); JornadaFechaEN jornadaFechaEN = (JornadaFechaEN)session.Load (typeof(JornadaFechaEN), id); session.Delete (jornadaFechaEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } } public JornadaFechaEN ObtenerJornada (int id) { JornadaFechaEN jornadaFechaEN = null; try { SessionInitializeTransaction (); jornadaFechaEN = (JornadaFechaEN)session.Get (typeof(JornadaFechaEN), id); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } return jornadaFechaEN; } public System.Collections.Generic.IList<JornadaFechaEN> ObtenerTodas (int first, int size) { System.Collections.Generic.IList<JornadaFechaEN> result = null; try { SessionInitializeTransaction (); if (size > 0) result = session.CreateCriteria (typeof(JornadaFechaEN)). SetFirstResult (first).SetMaxResults (size).List<JornadaFechaEN>(); else result = session.CreateCriteria (typeof(JornadaFechaEN)).List<JornadaFechaEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } return result; } public void Relationer_instalacion (int p_jornadafecha, string p_instalacion) { PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadaFechaEN = null; try { SessionInitializeTransaction (); jornadaFechaEN = (JornadaFechaEN)session.Load (typeof(JornadaFechaEN), p_jornadafecha); jornadaFechaEN.Instalacion = (PalmeralGenNHibernate.EN.Default_.InstalacionEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.InstalacionEN), p_instalacion); jornadaFechaEN.Instalacion.Jornadas.Add (jornadaFechaEN); session.Update (jornadaFechaEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } } public void Relationer_trabajadores (int p_jornadafecha, System.Collections.Generic.IList<string> p_trabajador) { PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadaFechaEN = null; try { SessionInitializeTransaction (); jornadaFechaEN = (JornadaFechaEN)session.Load (typeof(JornadaFechaEN), p_jornadafecha); PalmeralGenNHibernate.EN.Default_.TrabajadorEN trabajadoresENAux = null; if (jornadaFechaEN.Trabajadores == null) { jornadaFechaEN.Trabajadores = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.TrabajadorEN>(); } foreach (string item in p_trabajador) { trabajadoresENAux = new PalmeralGenNHibernate.EN.Default_.TrabajadorEN (); trabajadoresENAux = (PalmeralGenNHibernate.EN.Default_.TrabajadorEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.TrabajadorEN), item); trabajadoresENAux.Jornadas.Add (jornadaFechaEN); jornadaFechaEN.Trabajadores.Add (trabajadoresENAux); } session.Update (jornadaFechaEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } } public void Unrelationer_instalacion (int p_jornadafecha, string p_instalacion) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadaFechaEN = null; jornadaFechaEN = (JornadaFechaEN)session.Load (typeof(JornadaFechaEN), p_jornadafecha); if (jornadaFechaEN.Instalacion.Id == p_instalacion) { jornadaFechaEN.Instalacion = null; } else throw new ModelException ("The identifier " + p_instalacion + " in p_instalacion you are trying to unrelationer, doesn't exist in JornadaFechaEN"); session.Update (jornadaFechaEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } } public void Unrelationer_trabajadores (int p_jornadafecha, System.Collections.Generic.IList<string> p_trabajador) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadaFechaEN = null; jornadaFechaEN = (JornadaFechaEN)session.Load (typeof(JornadaFechaEN), p_jornadafecha); PalmeralGenNHibernate.EN.Default_.TrabajadorEN trabajadoresENAux = null; if (jornadaFechaEN.Trabajadores != null) { foreach (string item in p_trabajador) { trabajadoresENAux = (PalmeralGenNHibernate.EN.Default_.TrabajadorEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.TrabajadorEN), item); if (jornadaFechaEN.Trabajadores.Contains (trabajadoresENAux) == true) { jornadaFechaEN.Trabajadores.Remove (trabajadoresENAux); trabajadoresENAux.Jornadas.Remove (jornadaFechaEN); } else throw new ModelException ("The identifier " + item + " in p_trabajador you are trying to unrelationer, doesn't exist in JornadaFechaEN"); } } session.Update (jornadaFechaEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in JornadaFechaCAD.", ex); } finally { SessionClose (); } } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; using IRTaktiks.Input; using IRTaktiks.Components.Debug; using IRTaktiks.Components.Screen; using IRTaktiks.Components.Manager; using IRTaktiks.Components.Playable; using IRTaktiks.Components.Logic; using IRTaktiks.Components.Scenario; namespace IRTaktiks { /// <summary> /// This is the main type for your game /// </summary> public class IRTGame : Game { #region GameScreens /// <summary> /// The screens of the Game. /// </summary> public enum GameScreens { TitleScreen, ConfigScreen, GameScreen, EndScreen } #endregion #region Debug /// <summary> /// The console component. /// </summary> private IRTaktiks.Components.Debug.Console ConsoleField; /// <summary> /// The console component. /// </summary> public IRTaktiks.Components.Debug.Console Console { get { return ConsoleField; } } /// <summary> /// The FPS component. /// </summary> private FPS FPSField; /// <summary> /// The FPS component. /// </summary> public FPS FPS { get { return FPSField; } } /// <summary> /// The touch debug component. /// </summary> private TouchDebug TouchDebugField; /// <summary> /// The touch debug component. /// </summary> public TouchDebug TouchDebug { get { return TouchDebugField; } } #endregion #region Game Properties /// <summary> /// The player one of the game. /// </summary> private Player PlayerOneField; /// <summary> /// The player one of the game. /// </summary> public Player PlayerOne { get { return PlayerOneField; } set { PlayerOneField = value; } } /// <summary> /// The player two of the game. /// </summary> private Player PlayerTwoField; /// <summary> /// The player two of the game. /// </summary> public Player PlayerTwo { get { return PlayerTwoField; } set { PlayerTwoField = value; } } #endregion #region Graphic Properties /// <summary> /// The instance of the camera. /// </summary> private Camera CameraField; /// <summary> /// The instance of the camera. /// </summary> public Camera Camera { get { return CameraField; } } /// <summary> /// Handles the configuration and management of the graphics device. /// </summary> private GraphicsDeviceManager GraphicsDeviceManagerField; /// <summary> /// Handles the configuration and management of the graphics device. /// </summary> public GraphicsDeviceManager GraphicsDeviceManager { get { return GraphicsDeviceManagerField; } } /// <summary> /// Manager of the map. /// </summary> private MapManager MapManagerField; /// <summary> /// Manager of the map. /// </summary> public MapManager MapManager { get { return MapManagerField; } } /// <summary> /// Manager of sprites. /// </summary> private SpriteManager SpriteManagerField; /// <summary> /// Manager of sprites. /// </summary> public SpriteManager SpriteManager { get { return SpriteManagerField; } } /// <summary> /// Manager of areas. /// </summary> private AreaManager AreaManagerField; /// <summary> /// Manager of areas. /// </summary> public AreaManager AreaManager { get { return AreaManagerField; } } /// <summary> /// Manager of particle effects. /// </summary> private ParticleManager ParticleManagerField; /// <summary> /// Manager of particle effects. /// </summary> public ParticleManager ParticleManager { get { return ParticleManagerField; } } /// <summary> /// Manager of damages. /// </summary> private DamageManager DamageManagerField; /// <summary> /// Manager of damages. /// </summary> public DamageManager DamageManager { get { return DamageManagerField; } } #endregion #region Screens /// <summary> /// The screen manager component of the game. /// </summary> private ScreenManager ScreenManagerField; /// <summary> /// The screen manager component of the game. /// </summary> public ScreenManager ScreenManager { get { return ScreenManagerField; } set { ScreenManagerField = value; } } /// <summary> /// The title screen of the game. /// </summary> private TitleScreen TitleScreenField; /// <summary> /// The title screen of the game. /// </summary> public TitleScreen TitleScreen { get { return TitleScreenField; } } /// <summary> /// The config screen of the game. /// </summary> private ConfigScreen ConfigScreenField; /// <summary> /// The config screen of the game. /// </summary> public ConfigScreen ConfigScreen { get { return ConfigScreenField; } } /// <summary> /// The game screen of the game. /// </summary> private GameScreen GameScreenField; /// <summary> /// The game screen of the game. /// </summary> public GameScreen GameScreen { get { return GameScreenField; } } /// <summary> /// The end screen of the game. /// </summary> private EndScreen EndScreenField; /// <summary> /// The end screen of the game. /// </summary> public EndScreen EndScreen { get { return EndScreenField; } } #endregion #region Constructor /// <summary> /// Constructor of class. /// </summary> public IRTGame() { this.GraphicsDeviceManagerField = new GraphicsDeviceManager(this); this.Content.RootDirectory = "Content"; this.Window.Title = "IRTaktiks - Tactical RPG for multi-touch interfaces"; this.IsMouseVisible = true; this.GraphicsDeviceManager.PreferredBackBufferWidth = IRTSettings.Default.Width; this.GraphicsDeviceManager.PreferredBackBufferHeight = IRTSettings.Default.Height; this.GraphicsDeviceManager.IsFullScreen = IRTSettings.Default.FullScreen; this.GraphicsDeviceManager.SynchronizeWithVerticalRetrace = true; this.GraphicsDeviceManager.PreferMultiSampling = true; this.GraphicsDeviceManager.ApplyChanges(); } #endregion #region Game Methods /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // Resources loading. TextureManager.Instance.Initialize(this); EffectManager.Instance.Initialize(this); FontManager.Instance.Initialize(this); // Components creation. this.CameraField = new Camera(this); this.MapManagerField = new MapManager(this); this.SpriteManagerField = new SpriteManager(this); this.AreaManagerField = new AreaManager(this.GraphicsDevice, this.Camera); this.ParticleManagerField = new ParticleManager(new Vector3(0, 0, -100), this.GraphicsDevice, this.Camera); this.DamageManagerField = new DamageManager(this); // Debug this.ConsoleField = new IRTaktiks.Components.Debug.Console(this); this.FPSField = new FPS(this); this.TouchDebugField = new TouchDebug(this); AnimationManager.Instance.Initialize(this); // Screen construction. this.TitleScreenField = new TitleScreen(this, 0); this.ConfigScreenField = new ConfigScreen(this, 0); this.GameScreenField = new GameScreen(this, 0); this.EndScreenField = new EndScreen(this, 0); this.ScreenManagerField = new ScreenManager(this); // Map addicition. this.MapManager.Enabled = false; this.MapManager.Visible = false; this.Components.Add(this.MapManager); // Screen addiction. this.ScreenManager.Screens.Add(this.TitleScreen); this.ScreenManager.Screens.Add(this.ConfigScreen); this.ScreenManager.Screens.Add(this.GameScreen); this.ScreenManager.Screens.Add(this.EndScreen); // Components addiction. this.Components.Add(this.Camera); this.Components.Add(this.ScreenManager); // Debug this.Components.Add(this.Console); this.Components.Add(this.FPS); this.Components.Add(this.TouchDebug); // Change the game to its first status. this.ChangeScreen(GameScreens.TitleScreen); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load all of your content. /// </summary> protected override void LoadContent() { base.LoadContent(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload all content. /// </summary> protected override void UnloadContent() { base.UnloadContent(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> private bool mouseIsPressed; protected override void Update(GameTime gameTime) { // Exits the game. if (Keyboard.GetState().IsKeyDown(Keys.Escape)) { this.Exit(); } // Check for mouse injection if (IRTSettings.Default.ListenMouse) { MouseState mouseState = Mouse.GetState(); if (!mouseIsPressed) { if (mouseState.LeftButton == ButtonState.Pressed) { mouseIsPressed = true; InputManager.Instance.RaiseCursorDown(0, new Vector2(mouseState.X, mouseState.Y)); } } else { if (mouseState.LeftButton == ButtonState.Pressed) { mouseIsPressed = true; InputManager.Instance.RaiseCursorUpdate(0, new Vector2(mouseState.X, mouseState.Y)); } else { mouseIsPressed = false; InputManager.Instance.RaiseCursorUp(0, new Vector2(mouseState.X, mouseState.Y)); } } } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { this.GraphicsDeviceManager.GraphicsDevice.Clear(new Color(64, 64, 64)); this.GraphicsDeviceManager.GraphicsDevice.RenderState.CullMode = CullMode.None; base.Draw(gameTime); } #endregion #region Methods /// <summary> /// Change the status of the game. /// </summary> /// <param name="newStatus">The new status of the game.</param> public void ChangeScreen(GameScreens newScreen) { // Make all screen invisibles and disabled. this.TitleScreen.Enabled = false; this.TitleScreen.Visible = false; this.ConfigScreen.Enabled = false; this.ConfigScreen.Visible = false; this.GameScreen.Enabled = false; this.GameScreen.Visible = false; this.EndScreen.Enabled = false; this.EndScreen.Visible = false; switch (newScreen) { case GameScreens.TitleScreen: this.TitleScreen.Enabled = true; this.TitleScreen.Visible = true; this.TitleScreen.Initialize(); return; case GameScreens.ConfigScreen: this.ConfigScreen.Enabled = true; this.ConfigScreen.Visible = true; this.ConfigScreen.Initialize(); return; case GameScreens.GameScreen: this.GameScreen.Enabled = true; this.GameScreen.Visible = true; this.GameScreen.Initialize(); return; case GameScreens.EndScreen: this.EndScreen.Enabled = true; this.EndScreen.Visible = true; this.EndScreen.Initialize(); return; } } #endregion } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NExpect; using NUnit.Framework; using PeanutButter.RandomGenerators; using static NExpect.Expectations; namespace PeanutButter.TinyEventAggregator.Tests { [TestFixture] public class Demo { const int WAIT_TO_PROVE_SUSPEND_WORKS = 1000; [Test] public async Task DemonstrateUsage() { // Arrange // you could use the singleton EventAggregator.Instance if you like // or have an instance provided by DI, or even use multiple instances // in your application if that makes sense for the usage var eventAggregator = new EventAggregator(); var loggedInUsers = new List<User>(); // Act // somewhere in the system, we'd like to know when a user logs in... eventAggregator.GetEvent<LoginEvent>() .Subscribe(user => loggedInUsers.Add(user)); eventAggregator.GetEvent<LogoutEvent>() .Subscribe(user => loggedInUsers.Remove(user)); // elsewhere, logins are happening var karen = new User() { Id = 1, Name = "Karen" }; var bob = new User() { Id = 2, Name = "Bob" }; // GetEvent<T> always returns the same event instance, // so if you're going to use it a lot, you can var it // off var loginEvent = eventAggregator.GetEvent<LoginEvent>(); loginEvent.Publish(karen); Expect(loggedInUsers) .To.Contain(karen); loginEvent.Publish(bob); Expect(loggedInUsers) .To.Contain(bob); // we can suspend messaging: eventAggregator.Suspend(); // now, messages are not processed... // note that publisher threads which use the `Publish` method will suspend too! // -> so for the test, we put this in a task var beforeBarrier = new Barrier(2); var afterBarrier = new Barrier(2); var sam = new User() { Id = 3, Name = "Sam" }; #pragma warning disable 4014 Task.Run(() => { beforeBarrier.SignalAndWait(); loginEvent.Publish(sam); afterBarrier.SignalAndWait(); }); #pragma warning restore 4014 beforeBarrier.SignalAndWait(); Thread.Sleep(100); // wait a little to let the Publish call kick off Expect(loggedInUsers) .Not.To.Contain(sam); // we can unsuspend eventAggregator.Unsuspend(); afterBarrier.SignalAndWait(); Expect(loggedInUsers) .To.Contain(sam); // there's an async publish which won't block up the publisher: eventAggregator.Suspend(); var task = eventAggregator.GetEvent<LogoutEvent>() .PublishAsync(sam); var waited = task.Wait(WAIT_TO_PROVE_SUSPEND_WORKS); Expect(waited) .To.Be.False(); Expect(loggedInUsers) .To.Contain(sam); eventAggregator.Unsuspend(); await task; Expect(loggedInUsers) .Not.To.Contain(sam); // when to use Publish vs PublishAsync // - Publish is useful when you'd like to use your event aggregator // from, eg, a WPF application, since handlers will get called // on the same thread (most likely your UI thread, if Publish was // called, eg, from a button click event handler), so you won't have to // marshall to the UI thread. However, you'll still have to consider // what your consumer code is doing to ensure that the UI doesn't // lock up, of course! // Since Publish will BLOCK when the event aggregator (or single event // type) is suspended, it's a bad idea to use Publish from your UI handlers // if you ever plan on suspending pub/sub as suspension will likely cause // your app to hang (UI thread will go unresponsive and you'll get a white // app window // On the other hand, the blocking nature of Publish means that you are // guaranteed of message delivery order // - PublishAsync can be used as "fire and forget" for background // handling, but of course this means that you're not guaranteed of // message delivery order (chances are good they'll come in order, but // this is really up to the TPL and how the task is scheduled) and you'll // have to marshal back to the UI thread if that makes sense for your // application // Naturally, receivers are invoked on the final thread that the publish // happened on -- if you're using PublishAsync, that means it's quite // likely to _not_ be the same thread as the caller // we can also suspend / resume for specific events var logoutEvent = eventAggregator.GetEvent<LogoutEvent>(); logoutEvent.Suspend(); var logoutTask = logoutEvent.PublishAsync(bob); waited = logoutTask.Wait(WAIT_TO_PROVE_SUSPEND_WORKS); Expect(waited) .To.Be.False(); Expect(loggedInUsers) .To.Contain(bob); // logout messages were suspended! await loginEvent.PublishAsync(sam); Expect(loggedInUsers) .To.Contain(sam); logoutEvent.Unsuspend(); waited = logoutTask.Wait(WAIT_TO_PROVE_SUSPEND_WORKS); Expect(waited) .To.Be.True(); Expect(loggedInUsers) .Not.To.Contain(bob); // we can also have limited subscriptions var onceOffUser = null as User; var limitedUsers = new List<User>(); var resubscribe = false; eventAggregator.GetEvent<OnceOffEvent>() .SubscribeOnce(OnceOffSubscription); var limit = RandomValueGen.GetRandomInt(3, 5); eventAggregator.GetEvent<LimitedEvent>() .LimitedSubscription(user => limitedUsers.Add(user), limit); for (var i = 0; i < 10; i++) { eventAggregator.GetEvent<OnceOffEvent>() .Publish(RandomValueGen.GetRandom<User>()); eventAggregator.GetEvent<LimitedEvent>() .Publish(RandomValueGen.GetRandom<User>()); } Expect(onceOffUser) .Not.To.Be.Null(); Expect(limitedUsers) .To.Contain.Only(limit).Items(); onceOffUser = null; resubscribe = true; eventAggregator.GetEvent<OnceOffEvent>() .SubscribeOnce(OnceOffSubscription); eventAggregator.GetEvent<OnceOffEvent>() .Publish(sam); Expect(onceOffUser) .To.Be(sam); // since we should have resubscribed, this publish // will now throw Expect(() => eventAggregator.GetEvent<OnceOffEvent>() .Publish(sam) ).To.Throw<InvalidOperationException>(); // Assert void OnceOffSubscription(User user) { if (onceOffUser != null) { throw new InvalidOperationException( $"Once-off subscription should limit to one callback!" ); } onceOffUser = user; // sometimes it's useful to re-subscribe here, depending // on your app requirements (: if (resubscribe) { eventAggregator.GetEvent<OnceOffEvent>() .SubscribeOnce(OnceOffSubscription); } } } public class User { public int Id { get; set; } public string Name { get; set; } } public class LoginEvent : EventBase<User> { } public class LogoutEvent : EventBase<User> { } public class OnceOffEvent : EventBase<User> { } public class LimitedEvent : EventBase<User> { } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using SubSonic.Sugar; using SubSonic.Utilities; namespace SubSonic { /// <summary> /// Summary for the QuickTable class /// </summary> [DefaultProperty("TableName")] [ToolboxData("<{0}:QuickTable runat=server></{0}:QuickTable>")] public class QuickTable : WebControl, INamingContainer { #region props private const string headerLinkStyle = "text-decoration:none;color:black;font-size:12pt;font-family:arial;"; private const string pagerButtonStyle = "border:1px solid #cccccc;background-color:whitesmoke;font-family:helvetica;font-size:10pt"; private const string pagerStyle = "alignment:center; font-size:10pt;font-family:arial;border-top:1px solid #666666;margin-top:5px"; private const string tableAlternatingStyle = "padding:3px;background-color:whitesmoke;font-family:arial;font-size:10pt;"; private const string tableCellStyle = "padding:3px;background-color:white;font-family:arial;font-size:10pt;"; private const string tableHeaderStyle = "font-weight:bold; text-align:center;font-family:arial;font-size:12pt;border-bottom:1px solid #666666;"; private readonly string tableStyle = String.Empty; private string buttonFirstText = " << "; private string buttonLastText = " >> "; private string buttonNextText = " > "; private string buttonPreviousText = " < "; private string columnList = String.Empty; private string headerLinkCSSClass = String.Empty; private string linkOnColumn = String.Empty; private string linkToPage = String.Empty; private int pageIndex = 1; private string pagerButtonCSS = String.Empty; private string pagerCSS = String.Empty; private int pageSize; private string providerName = String.Empty; private bool showSort = true; private string tableAlternatingCSSClass = String.Empty; private string tableCellCSSClass = String.Empty; private string tableCSSClass = String.Empty; private string tableHeaderCSSClass = String.Empty; private string tableName = String.Empty; private int totalPages; private int totalRecords; private List<Where> whereCollection = new List<Where>(); private string whereExpression = String.Empty; /// <summary> /// Gets or sets a value indicating whether [show sort]. /// </summary> /// <value><c>true</c> if [show sort]; otherwise, <c>false</c>.</value> public bool ShowSort { get { return showSort; } set { showSort = value; } } /// <summary> /// Gets or sets the column list. /// </summary> /// <value>The column list.</value> public string ColumnList { get { return columnList; } set { columnList = value; } } /// <summary> /// Gets or sets the name of the provider. /// </summary> /// <value>The name of the provider.</value> public string ProviderName { get { if(String.IsNullOrEmpty(providerName)) providerName = DataService.Provider.Name; return providerName; } set { providerName = value; } } /// <summary> /// Gets or sets the name of the table. /// </summary> /// <value>The name of the table.</value> public string TableName { get { return tableName; } set { tableName = value; } } /// <summary> /// Gets or sets the size of the page. /// </summary> /// <value>The size of the page.</value> public int PageSize { get { return pageSize; } set { pageSize = value; } } /// <summary> /// Gets or sets the index of the page. /// </summary> /// <value>The index of the page.</value> public int PageIndex { get { return pageIndex; } set { pageIndex = value; } } /// <summary> /// Gets or sets the link to page. /// </summary> /// <value>The link to page.</value> public string LinkToPage { get { return linkToPage; } set { linkToPage = value; } } /// <summary> /// Gets or sets the link on column. /// </summary> /// <value>The link on column.</value> public string LinkOnColumn { get { return linkOnColumn; } set { linkOnColumn = value; } } /// <summary> /// Gets or sets the where collection. /// </summary> /// <value>The where collection.</value> public List<Where> WhereCollection { get { return whereCollection; } set { whereCollection = value; } } /// <summary> /// Gets or sets the where expression. /// </summary> /// <value>The where expression.</value> public string WhereExpression { get { return whereExpression; } set { whereExpression = value; } } /// <summary> /// Gets or sets the header link CSS class. /// </summary> /// <value>The header link CSS class.</value> public string HeaderLinkCSSClass { get { return headerLinkCSSClass; } set { headerLinkCSSClass = value; } } /// <summary> /// Gets or sets the table CSS class. /// </summary> /// <value>The table CSS class.</value> public string TableCSSClass { get { return tableCSSClass; } set { tableCSSClass = value; } } /// <summary> /// Gets or sets the table header CSS class. /// </summary> /// <value>The table header CSS class.</value> public string TableHeaderCSSClass { get { return tableHeaderCSSClass; } set { tableHeaderCSSClass = value; } } /// <summary> /// Gets or sets the table cell CSS class. /// </summary> /// <value>The table cell CSS class.</value> public string TableCellCSSClass { get { return tableCellCSSClass; } set { tableCellCSSClass = value; } } /// <summary> /// Gets or sets the table alternating CSS class. /// </summary> /// <value>The table alternating CSS class.</value> public string TableAlternatingCSSClass { get { return tableAlternatingCSSClass; } set { tableAlternatingCSSClass = value; } } /// <summary> /// Gets or sets the pager CSS. /// </summary> /// <value>The pager CSS.</value> public string PagerCSS { get { return pagerCSS; } set { pagerCSS = value; } } /// <summary> /// Gets or sets the page button CSS class. /// </summary> /// <value>The page button CSS class.</value> public string PageButtonCSSClass { get { return pagerButtonCSS; } set { pagerButtonCSS = value; } } /// <summary> /// Gets or sets the total records. /// </summary> /// <value>The total records.</value> public int TotalRecords { get { return totalRecords; } set { totalRecords = value; } } /// <summary> /// Gets or sets the total pages. /// </summary> /// <value>The total pages.</value> public int TotalPages { get { return totalPages; } set { totalPages = value; } } /// <summary> /// Gets or sets the button first text. /// </summary> /// <value>The button first text.</value> public string ButtonFirstText { get { return buttonFirstText; } set { buttonFirstText = value; } } /// <summary> /// Gets or sets the button previous text. /// </summary> /// <value>The button previous text.</value> public string ButtonPreviousText { get { return buttonPreviousText; } set { buttonPreviousText = value; } } /// <summary> /// Gets or sets the button next text. /// </summary> /// <value>The button next text.</value> public string ButtonNextText { get { return buttonNextText; } set { buttonNextText = value; } } /// <summary> /// Gets or sets the button last text. /// </summary> /// <value>The button last text.</value> public string ButtonLastText { get { return buttonLastText; } set { buttonLastText = value; } } #endregion //The "wrapper" table that holds the data //and the pager private const string CENTER = "center"; private const string CLASS = "class"; private const string CURRENT_PAGE = "currentPage"; private const string LEFT = "left"; private const string RIGHT = "right"; private const string SORT_BY = "sortBy"; private const string STYLE = "style"; private const string TOTAL_RECORDS = "totalRecords"; private readonly Button btnFirst = new Button(); private readonly Button btnLast = new Button(); private readonly Button btnNext = new Button(); private readonly Button btnPrev = new Button(); private readonly ArrayList colList = new ArrayList(); private readonly DropDownList ddlPages = new DropDownList(); private readonly Label lblRecordCount = new Label(); private readonly Literal litPagerLabel = new Literal(); private readonly HtmlTable tbl = new HtmlTable(); private readonly HtmlTable tblPage = new HtmlTable(); private readonly HtmlTable tblWrap = new HtmlTable(); private readonly HtmlTableCell tdBottom = new HtmlTableCell(); private readonly HtmlTableCell tdTop = new HtmlTableCell(); private readonly HtmlTableRow trBottom = new HtmlTableRow(); private readonly HtmlTableRow trTop = new HtmlTableRow(); private DataTable dataSource; private TableSchema.Table schema; private string sortBy; private string sortDirection = "ASC"; private HtmlTableCell td; private HtmlTableRow tr; /// <summary> /// Gets or sets the sort by. /// </summary> /// <value>The sort by.</value> public string SortBy { get { return sortBy; } set { sortBy = value; } } /// <summary> /// Gets or sets the sort direction. /// </summary> /// <value>The sort direction.</value> public string SortDirection { get { return sortDirection; } set { sortDirection = value; } } /// <summary> /// Adds the header text. /// </summary> /// <param name="tableColumn">The table column.</param> /// <param name="tdHeaderCell">The td header cell.</param> /// <param name="overrideText">The override text.</param> private void AddHeaderText(TableSchema.TableColumn tableColumn, HtmlTableCell tdHeaderCell, string overrideText) { if(showSort) { LinkButton btn = new LinkButton { ID = "btn" + tableColumn.ColumnName, CommandArgument = tableColumn.ColumnName, Text = String.IsNullOrEmpty(overrideText) ? tableColumn.DisplayName : overrideText }; if(!String.IsNullOrEmpty(headerLinkCSSClass)) btn.CssClass = headerLinkCSSClass; else btn.Attributes.Add(STYLE, headerLinkStyle); tdHeaderCell.Controls.Add(btn); if(tableColumn.IsNumeric) tdHeaderCell.Align = RIGHT; else if(tableColumn.IsDateTime) tdHeaderCell.Align = CENTER; btn.Click += Sort_Click; } else tdHeaderCell.InnerHtml = String.IsNullOrEmpty(overrideText) ? overrideText : tableColumn.DisplayName; } /// <summary> /// Ensures the totals. /// </summary> /// <param name="qry">The qry.</param> private void EnsureTotals(SqlQuery qry) { //if there's paging, we have to run an initial query to figure out //how many records we have //we should only do this once... if(pageSize > 0) { if(ViewState[TOTAL_RECORDS] == null) { //set it int originalPageSize = qry.PageSize; qry.PageSize = 0; TotalRecords = qry.GetRecordCount(); qry.PageSize = originalPageSize; ViewState[TOTAL_RECORDS] = TotalRecords; } else TotalRecords = (int)ViewState[TOTAL_RECORDS]; //the pages are the records/pageSize+1 //totalPages = (totalPages % pageSize == 0) ? totalRecords / pageSize : totalRecords / pageSize + 1; totalPages = (totalRecords % pageSize == 0) ? totalRecords / pageSize : totalRecords / pageSize + 1; lblRecordCount.Text = " of " + totalPages + " (" + totalRecords + " total) "; if(ddlPages.Items.Count == 0) { //set up the dropDown for(int i = 1; i <= totalPages; i++) ddlPages.Items.Add(new ListItem(i.ToString(), i.ToString())); } } } /// <summary> /// Loads the grid. /// </summary> private void LoadGrid() { if(String.IsNullOrEmpty(tableName)) throw new ArgumentException("No tableName property set - please be sure to set the name of the table or view you'd like to see", tableName); DecideSortDirection(); //load the data DataProvider provider = DataService.GetInstance(ProviderName); SqlQuery q = new Select(provider).From(tableName); //set the select list StringBuilder selectList = new StringBuilder("*"); if(!String.IsNullOrEmpty(columnList)) { selectList = new StringBuilder(); for(int i = 0; i < colList.Count; i++) { selectList.Append(colList[i].ToString().Trim()); if(i + 1 < colList.Count) selectList.Append(","); } } q.SelectColumnList = selectList.ToString().Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); //sorting if(!String.IsNullOrEmpty(sortBy)) { TableSchema.TableColumn col = provider.GetTableSchema(tableName, TableType.Table).GetColumn(sortBy); if(col != null && col.MaxLength < 2048 && col.DataType != DbType.Binary && col.DataType != DbType.Byte) { if(String.IsNullOrEmpty(sortDirection) || sortDirection.Trim() == SqlFragment.ASC.Trim()) q.OrderAsc(sortBy); else q.OrderDesc(sortBy); } } //paging if(pageSize > 0) { q.Paged(pageIndex, pageSize); ddlPages.SelectedValue = pageIndex.ToString(); } //honor logical deletes q.CheckLogicalDelete(); //where if(!String.IsNullOrEmpty(whereExpression)) q.WhereExpression(whereExpression); SqlQueryBridge.AddLegacyWhereCollection(q, whereCollection); DataSet ds = q.ExecuteDataSet(); if(ds.Tables.Count > 0) dataSource = ds.Tables[0]; else throw new Exception("Bad query - no data returned. Did you set the correct provider?"); EnsureTotals(q); //set the buttons SetPagingButtonState(); //create a table BuildRows(); } /// <summary> /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); tbl.CellPadding = 3; tbl.CellSpacing = 0; tbl.Width = "100%"; tblPage.Width = "100%"; //add three rows to this table //i know this might seem sort of strange //but given that we're dealing with eventing of buttons //.NET is a bit clumsy about it - these controls //need to exist in the control bag in order for the //event to be recognize. So we add them up front trTop.Cells.Add(tdTop); tblWrap.Rows.Add(trTop); trBottom.Cells.Add(tdBottom); tblWrap.Rows.Add(trBottom); tdTop.Controls.Add(tbl); tdBottom.Controls.Add(tblPage); Controls.Add(tblWrap); //set CSS if(!String.IsNullOrEmpty(tableCSSClass)) tbl.Attributes.Add(CLASS, tableCSSClass); else tbl.Attributes.Add(STYLE, tableStyle); if(!String.IsNullOrEmpty(pagerButtonCSS)) { btnFirst.Attributes.Add(CLASS, pagerButtonCSS); btnPrev.Attributes.Add(CLASS, pagerButtonCSS); btnNext.Attributes.Add(CLASS, pagerButtonCSS); btnLast.Attributes.Add(CLASS, pagerButtonCSS); ddlPages.Attributes.Add(CLASS, pagerButtonCSS); } else { btnFirst.Attributes.Add(STYLE, pagerButtonStyle); btnPrev.Attributes.Add(STYLE, pagerButtonStyle); btnNext.Attributes.Add(STYLE, pagerButtonStyle); btnLast.Attributes.Add(STYLE, pagerButtonStyle); ddlPages.Attributes.Add(STYLE, pagerButtonStyle); } //have to load up the pager buttons to the control set so we recognize them on //postback //load the schema schema = DataService.GetSchema(tableName, ProviderName, TableType.Table) ?? DataService.GetSchema(tableName, ProviderName, TableType.View); if(schema == null) throw new Exception("Can't find a table names " + tableName + ". Did you set the correct providerName?"); //load the headers BuildHeader(); BuildPager(); //if(!Page.IsPostBack) //{ LoadGrid(); trBottom.Visible = !(pageSize >= totalRecords); //} } #region Sorting /// <summary> /// Handles the Click event of the Sort control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Sort_Click(object sender, EventArgs e) { //the sort event. use a view to sort the table data LinkButton btn = (LinkButton)sender; SortBy = btn.CommandArgument; LoadGrid(); } /// <summary> /// Decides the sort direction. /// </summary> private void DecideSortDirection() { //string sortDir = "ASC"; if(ViewState[SORT_BY] != null) { string selectedSort = ViewState[SORT_BY].ToString(); if(String.IsNullOrEmpty(SortBy)) { //sort wasn't clicked - a postback //has reset the property to null //so set the sort to what's in the viewState SortBy = selectedSort; } else { if(selectedSort == SortBy) { //the direction should be desc SortDirection = SqlFragment.DESC; //reset the sorter to null ViewState[SORT_BY] = null; } else { //this is the first sort for this row //put it to the ViewState ViewState[SORT_BY] = SortBy; } } } else { //if this is the first sort, store it in the ViewState ViewState[SORT_BY] = SortBy; } } #endregion #region Table Builders /// <summary> /// Builds the header. /// </summary> private void BuildHeader() { tr = new HtmlTableRow(); string[] customCols = columnList.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); if(customCols.Length != 0) { foreach(string s in customCols) { td = new HtmlTableCell(); if(!String.IsNullOrEmpty(tableHeaderCSSClass)) td.Attributes.Add(CLASS, tableHeaderCSSClass); else td.Attributes.Add(STYLE, tableHeaderStyle); if(s.Contains(":")) { //it's a cast in the form of "productID:ID" string[] castedList = s.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries); try { TableSchema.TableColumn col = schema.GetColumn(castedList[0].Trim()) ?? schema.GetColumn(castedList[1].Trim()); if(col == null) throw new Exception("Can't find a column for this table named " + castedList[0] + " or " + castedList[1]); colList.Add(col.ColumnName.ToLower()); AddHeaderText(col, td, castedList[1]); } catch { throw new Exception("Invalid Custom Columns. If you want to pass in a custom colum, it should be in the form 'columnName:Replacement Name'"); } } else { TableSchema.TableColumn col = schema.GetColumn(s.Trim()); if(col == null) throw new Exception("Can't find a column for this table named " + s); colList.Add(col.ColumnName.ToLower()); AddHeaderText(col, td, String.Empty); } tr.Cells.Add(td); } } else { //loop the schema foreach(TableSchema.TableColumn col in schema.Columns) { td = new HtmlTableCell(); td.Attributes.Add(STYLE, tableHeaderStyle); AddHeaderText(col, td, String.Empty); tr.Cells.Add(td); colList.Add(col.ColumnName.ToLower()); } } tbl.Rows.Add(tr); } /// <summary> /// Builds the rows. /// </summary> private void BuildRows() { //pull the data //bool isEven = false; for(int i = tbl.Rows.Count - 1; i > 0; i--) tbl.Rows.RemoveAt(i); //tbl.Rows.Clear(); string cellAttribute = String.IsNullOrEmpty(tableCellCSSClass) ? STYLE : CLASS; string cellAttributeValue = String.IsNullOrEmpty(tableCellCSSClass) ? tableCellStyle : tableCellCSSClass; string cellAttributeAltValue = String.IsNullOrEmpty(tableCellCSSClass) ? tableAlternatingStyle : tableAlternatingCSSClass; int rowCount = dataSource.Rows.Count; for(int r = 0; r < rowCount; r++) { DataRow dr = dataSource.Rows[r]; tr = new HtmlTableRow(); if(Numbers.IsEven(r)) tr.Attributes.Add(cellAttribute, cellAttributeValue); else tr.Attributes.Add(cellAttribute, cellAttributeAltValue); int colCounter = 0; for(int i = 0; i < colList.Count; i++) { string colName = colList[i].ToString(); TableSchema.TableColumn schemaColumn = schema.GetColumn(colName); td = new HtmlTableCell(); if(schemaColumn.IsDateTime) { DateTime dt; td.InnerHtml = DateTime.TryParse(dr[colName].ToString(), out dt) ? dt.ToShortDateString() : dr[colName].ToString(); td.Align = CENTER; } else if(schemaColumn.DataType == DbType.Currency) { decimal dCurr; decimal.TryParse(dr[colName].ToString(), out dCurr); td.InnerHtml = dCurr.ToString("c"); td.Align = RIGHT; } else if(schemaColumn.IsNumeric) { td.InnerHtml = dr[colName].ToString(); td.Align = RIGHT; } else td.InnerHtml = dr[colName].ToString(); //check the linkTo if(!String.IsNullOrEmpty(linkToPage)) { string link; if(schema.PrimaryKey != null && linkToPage.Contains("{0}")) link = "<a href=\"" + linkToPage.Replace("{0}", dr[schema.PrimaryKey.ColumnName].ToString()) + "\">" + td.InnerHtml + "</a>"; else if(schema.PrimaryKey != null) link = "<a href=\"" + linkToPage + "?id=" + dr[schema.PrimaryKey.ColumnName] + "\">" + td.InnerHtml + "</a>"; else if(!String.IsNullOrEmpty(linkOnColumn) && linkToPage.Contains("{0}")) link = "<a href=\"" + linkToPage.Replace("{0}", dr[linkOnColumn].ToString()) + "\">" + td.InnerHtml + "</a>"; else if(!String.IsNullOrEmpty(linkOnColumn)) link = "<a href=\"" + linkToPage + "?id=" + dr[linkOnColumn] + "\">" + td.InnerHtml + "</a>"; else link = "<a href=\"" + linkToPage + "\">" + td.InnerHtml + "</a>"; if((!String.IsNullOrEmpty(linkOnColumn) && Utility.IsMatch(linkOnColumn, colName)) || colCounter == 0) td.InnerHtml = link; } tr.Cells.Add(td); colCounter++; } tbl.Rows.Add(tr); } } /// <summary> /// Builds the pager. /// </summary> private void BuildPager() { if(pageSize > 0) { HtmlTableRow trPage = new HtmlTableRow(); tblPage.Rows.Add(trPage); HtmlTableCell tdPage = new HtmlTableCell(); trPage.Cells.Add(tdPage); litPagerLabel.Text = " Page "; //add the pager buttons tdPage.Controls.Add(btnFirst); tdPage.Controls.Add(btnPrev); tdPage.Controls.Add(litPagerLabel); tdPage.Controls.Add(ddlPages); tdPage.Controls.Add(lblRecordCount); tdPage.Controls.Add(btnNext); tdPage.Controls.Add(btnLast); //set the text btnFirst.Text = buttonFirstText; btnLast.Text = buttonLastText; btnPrev.Text = buttonPreviousText; btnNext.Text = buttonNextText; //always the same btnFirst.CommandArgument = "1"; //handle the page event btnFirst.Click += Paging_Click; btnLast.Click += Paging_Click; btnPrev.Click += Paging_Click; btnNext.Click += Paging_Click; ddlPages.SelectedIndexChanged += ddlPages_SelectedIndexChanged; ddlPages.AutoPostBack = true; tdPage.ColSpan = colList.Count; tdPage.Align = CENTER; if(!String.IsNullOrEmpty(pagerCSS)) tdPage.Attributes.Add(CLASS, pagerCSS); else tdPage.Attributes.Add(STYLE, pagerStyle); //add to the pager table tblPage.Rows.Add(trPage); } } #endregion #region Paging /// <summary> /// Handles the SelectedIndexChanged event of the ddlPages control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void ddlPages_SelectedIndexChanged(object sender, EventArgs e) { pageIndex = int.Parse(ddlPages.SelectedValue); //put it to the ViewState so we know what //page we're on if sorting is clicked ViewState[CURRENT_PAGE] = pageIndex; LoadGrid(); } /// <summary> /// Handles the Click event of the Paging control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Paging_Click(object sender, EventArgs e) { Button btn = (Button)sender; int pIndex; int.TryParse(btn.CommandArgument, out pIndex); PageIndex = pIndex; //put it to the ViewState so we know what //page we're on if sorting is clicked ViewState[CURRENT_PAGE] = pIndex; LoadGrid(); } /// <summary> /// Sets the state of the paging button. /// </summary> private void SetPagingButtonState() { if(ViewState[CURRENT_PAGE] != null) pageIndex = (int)ViewState[CURRENT_PAGE]; else { pageIndex = 1; ViewState[CURRENT_PAGE] = 1; } if(totalPages > 0 && totalRecords > 0) { //this is always the same if(pageIndex == 0) pageIndex = 1; int nextPage = pageIndex + 1; int prevPage = pageIndex - 1; //command args btnNext.CommandArgument = nextPage.ToString(); btnPrev.CommandArgument = prevPage.ToString(); btnLast.CommandArgument = totalPages.ToString(); //use btnPrev.Enabled = true; btnNext.Enabled = true; btnLast.Enabled = true; btnFirst.Enabled = true; if(pageIndex == totalPages) { btnNext.Enabled = false; btnLast.Enabled = false; } else if(pageIndex == 1) { btnPrev.Enabled = false; btnFirst.Enabled = false; } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using XNodeEditor.Internal; namespace XNodeEditor { public partial class NodeEditorWindow { public enum NodeActivity { Idle, HoldNode, DragNode, HoldGrid, DragGrid } public static NodeActivity currentActivity = NodeActivity.Idle; public static bool isPanning { get; private set; } public static Vector2[] dragOffset; public static XNode.Node[] copyBuffer = null; private bool IsDraggingPort { get { return draggedOutput != null; } } private bool IsHoveringPort { get { return hoveredPort != null; } } private bool IsHoveringNode { get { return hoveredNode != null; } } private bool IsHoveringReroute { get { return hoveredReroute.port != null; } } private XNode.Node hoveredNode = null; [NonSerialized] public XNode.NodePort hoveredPort = null; [NonSerialized] private XNode.NodePort draggedOutput = null; [NonSerialized] private XNode.NodePort draggedOutputTarget = null; [NonSerialized] private XNode.NodePort autoConnectOutput = null; [NonSerialized] private List<Vector2> draggedOutputReroutes = new List<Vector2>(); private RerouteReference hoveredReroute = new RerouteReference(); public List<RerouteReference> selectedReroutes = new List<RerouteReference>(); private Vector2 dragBoxStart; private UnityEngine.Object[] preBoxSelection; private RerouteReference[] preBoxSelectionReroute; private Rect selectionBox; private bool isDoubleClick = false; private Vector2 lastMousePosition; private float dragThreshold = 1f; public void Controls() { wantsMouseMove = true; Event e = Event.current; switch (e.type) { case EventType.DragUpdated: case EventType.DragPerform: DragAndDrop.visualMode = DragAndDropVisualMode.Generic; if (e.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); graphEditor.OnDropObjects(DragAndDrop.objectReferences); } break; case EventType.MouseMove: //Keyboard commands will not get correct mouse position from Event lastMousePosition = e.mousePosition; break; case EventType.ScrollWheel: float oldZoom = zoom; if (e.delta.y > 0) zoom += 0.1f * zoom; else zoom -= 0.1f * zoom; if (NodeEditorPreferences.GetSettings().zoomToMouse) panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset); break; case EventType.MouseDrag: if (e.button == 0) { if (IsDraggingPort) { // Set target even if we can't connect, so as to prevent auto-conn menu from opening erroneously if (IsHoveringPort && hoveredPort.IsInput && !draggedOutput.IsConnectedTo(hoveredPort)) { draggedOutputTarget = hoveredPort; } else { draggedOutputTarget = null; } Repaint(); } else if (currentActivity == NodeActivity.HoldNode) { RecalculateDragOffsets(e); currentActivity = NodeActivity.DragNode; Repaint(); } if (currentActivity == NodeActivity.DragNode) { // Holding ctrl inverts grid snap bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap; if (e.control) gridSnap = !gridSnap; Vector2 mousePos = WindowToGridPosition(e.mousePosition); // Move selected nodes with offset for (int i = 0; i < Selection.objects.Length; i++) { if (Selection.objects[i] is XNode.Node) { XNode.Node node = Selection.objects[i] as XNode.Node; Undo.RecordObject(node, "Moved Node"); Vector2 initial = node.position; node.position = mousePos + dragOffset[i]; if (gridSnap) { node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8; node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8; } // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame. Vector2 offset = node.position - initial; if (offset.sqrMagnitude > 0) { foreach (XNode.NodePort output in node.Outputs) { Rect rect; if (portConnectionPoints.TryGetValue(output, out rect)) { rect.position += offset; portConnectionPoints[output] = rect; } } foreach (XNode.NodePort input in node.Inputs) { Rect rect; if (portConnectionPoints.TryGetValue(input, out rect)) { rect.position += offset; portConnectionPoints[input] = rect; } } } } } // Move selected reroutes with offset for (int i = 0; i < selectedReroutes.Count; i++) { Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i]; if (gridSnap) { pos.x = (Mathf.Round(pos.x / 16) * 16); pos.y = (Mathf.Round(pos.y / 16) * 16); } selectedReroutes[i].SetPoint(pos); } Repaint(); } else if (currentActivity == NodeActivity.HoldGrid) { currentActivity = NodeActivity.DragGrid; preBoxSelection = Selection.objects; preBoxSelectionReroute = selectedReroutes.ToArray(); dragBoxStart = WindowToGridPosition(e.mousePosition); Repaint(); } else if (currentActivity == NodeActivity.DragGrid) { Vector2 boxStartPos = GridToWindowPosition(dragBoxStart); Vector2 boxSize = e.mousePosition - boxStartPos; if (boxSize.x < 0) { boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x); } if (boxSize.y < 0) { boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y); } selectionBox = new Rect(boxStartPos, boxSize); Repaint(); } } else if (e.button == 1 || e.button == 2) { //check drag threshold for larger screens if (e.delta.magnitude > dragThreshold) { panOffset += e.delta * zoom; isPanning = true; } } break; case EventType.MouseDown: Repaint(); if (e.button == 0) { draggedOutputReroutes.Clear(); if (IsHoveringPort) { if (hoveredPort.IsOutput) { draggedOutput = hoveredPort; autoConnectOutput = hoveredPort; } else { hoveredPort.VerifyConnections(); autoConnectOutput = null; if (hoveredPort.IsConnected) { XNode.Node node = hoveredPort.node; XNode.NodePort output = hoveredPort.Connection; int outputConnectionIndex = output.GetConnectionIndex(hoveredPort); draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex); hoveredPort.Disconnect(output); draggedOutput = output; draggedOutputTarget = hoveredPort; if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node); } } } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { // If mousedown on node header, select or deselect if (!Selection.Contains(hoveredNode)) { SelectNode(hoveredNode, e.control || e.shift); if (!e.control && !e.shift) selectedReroutes.Clear(); } else if (e.control || e.shift) DeselectNode(hoveredNode); // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown. isDoubleClick = (e.clickCount == 2); e.Use(); currentActivity = NodeActivity.HoldNode; } else if (IsHoveringReroute) { // If reroute isn't selected if (!selectedReroutes.Contains(hoveredReroute)) { // Add it if (e.control || e.shift) selectedReroutes.Add(hoveredReroute); // Select it else { selectedReroutes = new List<RerouteReference>() { hoveredReroute }; Selection.activeObject = null; } } // Deselect else if (e.control || e.shift) selectedReroutes.Remove(hoveredReroute); e.Use(); currentActivity = NodeActivity.HoldNode; } // If mousedown on grid background, deselect all else if (!IsHoveringNode) { currentActivity = NodeActivity.HoldGrid; if (!e.control && !e.shift) { selectedReroutes.Clear(); Selection.activeObject = null; } } } break; case EventType.MouseUp: if (e.button == 0) { //Port drag release if (IsDraggingPort) { // If connection is valid, save it if (draggedOutputTarget != null && draggedOutput.CanConnectTo(draggedOutputTarget)) { XNode.Node node = draggedOutputTarget.node; if (graph.nodes.Count != 0) draggedOutput.Connect(draggedOutputTarget); // ConnectionIndex can be -1 if the connection is removed instantly after creation int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget); if (connectionIndex != -1) { draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes); if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node); EditorUtility.SetDirty(graph); } } // Open context menu for auto-connection if there is no target node else if (draggedOutputTarget == null && NodeEditorPreferences.GetSettings().dragToCreate && autoConnectOutput != null) { GenericMenu menu = new GenericMenu(); graphEditor.AddContextMenuItems(menu); menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); } //Release dragged connection draggedOutput = null; draggedOutputTarget = null; EditorUtility.SetDirty(graph); if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } else if (currentActivity == NodeActivity.DragNode) { IEnumerable<XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node); foreach (XNode.Node node in nodes) EditorUtility.SetDirty(node); if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } else if (!IsHoveringNode) { // If click outside node, release field focus if (!isPanning) { EditorGUI.FocusTextInControl(null); EditorGUIUtility.editingTextField = false; } if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } // If click node header, select it. if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift)) { selectedReroutes.Clear(); SelectNode(hoveredNode, false); // Double click to center node if (isDoubleClick) { Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero; panOffset = -hoveredNode.position - nodeDimension; } } // If click reroute, select it. if (IsHoveringReroute && !(e.control || e.shift)) { selectedReroutes = new List<RerouteReference>() { hoveredReroute }; Selection.activeObject = null; } Repaint(); currentActivity = NodeActivity.Idle; } else if (e.button == 1 || e.button == 2) { if (!isPanning) { if (IsDraggingPort) { draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition)); } else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1) { selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint()); selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1); } else if (IsHoveringReroute) { ShowRerouteContextMenu(hoveredReroute); } else if (IsHoveringPort) { ShowPortContextMenu(hoveredPort); } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { if (!Selection.Contains(hoveredNode)) SelectNode(hoveredNode, false); autoConnectOutput = null; GenericMenu menu = new GenericMenu(); NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu); menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places. } else if (!IsHoveringNode) { autoConnectOutput = null; GenericMenu menu = new GenericMenu(); graphEditor.AddContextMenuItems(menu); menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); } } isPanning = false; } // Reset DoubleClick isDoubleClick = false; break; case EventType.KeyDown: if (EditorGUIUtility.editingTextField) break; else if (e.keyCode == KeyCode.F) Home(); if (NodeEditorUtilities.IsMac()) { if (e.keyCode == KeyCode.Return) RenameSelectedNode(); } else { if (e.keyCode == KeyCode.F2) RenameSelectedNode(); } if (e.keyCode == KeyCode.A) { if (Selection.objects.Any(x => graph.nodes.Contains(x as XNode.Node))) { foreach (XNode.Node node in graph.nodes) { DeselectNode(node); } } else { foreach (XNode.Node node in graph.nodes) { SelectNode(node, true); } } Repaint(); } break; case EventType.ValidateCommand: case EventType.ExecuteCommand: if (e.commandName == "SoftDelete") { if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); e.Use(); } else if (NodeEditorUtilities.IsMac() && e.commandName == "Delete") { if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); e.Use(); } else if (e.commandName == "Duplicate") { if (e.type == EventType.ExecuteCommand) DuplicateSelectedNodes(); e.Use(); } else if (e.commandName == "Copy") { if (e.type == EventType.ExecuteCommand) CopySelectedNodes(); e.Use(); } else if (e.commandName == "Paste") { if (e.type == EventType.ExecuteCommand) PasteNodes(WindowToGridPosition(lastMousePosition)); e.Use(); } Repaint(); break; case EventType.Ignore: // If release mouse outside window if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid) { Repaint(); currentActivity = NodeActivity.Idle; } break; } } private void RecalculateDragOffsets(Event current) { dragOffset = new Vector2[Selection.objects.Length + selectedReroutes.Count]; // Selected nodes for (int i = 0; i < Selection.objects.Length; i++) { if (Selection.objects[i] is XNode.Node) { XNode.Node node = Selection.objects[i] as XNode.Node; dragOffset[i] = node.position - WindowToGridPosition(current.mousePosition); } } // Selected reroutes for (int i = 0; i < selectedReroutes.Count; i++) { dragOffset[Selection.objects.Length + i] = selectedReroutes[i].GetPoint() - WindowToGridPosition(current.mousePosition); } } /// <summary> Puts all selected nodes in focus. If no nodes are present, resets view and zoom to to origin </summary> public void Home() { var nodes = Selection.objects.Where(o => o is XNode.Node).Cast<XNode.Node>().ToList(); if (nodes.Count > 0) { Vector2 minPos = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); Vector2 maxPos = nodes.Select(x => x.position + (nodeSizes.ContainsKey(x) ? nodeSizes[x] : Vector2.zero)).Aggregate((x, y) => new Vector2(Mathf.Max(x.x, y.x), Mathf.Max(x.y, y.y))); panOffset = -(minPos + (maxPos - minPos) / 2f); } else { zoom = 2; panOffset = Vector2.zero; } } /// <summary> Remove nodes in the graph in Selection.objects</summary> public void RemoveSelectedNodes() { // We need to delete reroutes starting at the highest point index to avoid shifting indices selectedReroutes = selectedReroutes.OrderByDescending(x => x.pointIndex).ToList(); for (int i = 0; i < selectedReroutes.Count; i++) { selectedReroutes[i].RemovePoint(); } selectedReroutes.Clear(); foreach (UnityEngine.Object item in Selection.objects) { if (item is XNode.Node) { XNode.Node node = item as XNode.Node; graphEditor.RemoveNode(node); } } } /// <summary> Initiate a rename on the currently selected node </summary> public void RenameSelectedNode() { if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { XNode.Node node = Selection.activeObject as XNode.Node; Vector2 size; if (nodeSizes.TryGetValue(node, out size)) { RenamePopup.Show(Selection.activeObject, size.x); } else { RenamePopup.Show(Selection.activeObject); } } } /// <summary> Draw this node on top of other nodes by placing it last in the graph.nodes list </summary> public void MoveNodeToTop(XNode.Node node) { int index; while ((index = graph.nodes.IndexOf(node)) != graph.nodes.Count - 1) { graph.nodes[index] = graph.nodes[index + 1]; graph.nodes[index + 1] = node; } } /// <summary> Duplicate selected nodes and select the duplicates </summary> public void DuplicateSelectedNodes() { // Get selected nodes which are part of this graph XNode.Node[] selectedNodes = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray(); if (selectedNodes == null || selectedNodes.Length == 0) return; // Get top left node position Vector2 topLeftNode = selectedNodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); InsertDuplicateNodes(selectedNodes, topLeftNode + new Vector2(30, 30)); } public void CopySelectedNodes() { copyBuffer = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray(); } public void PasteNodes(Vector2 pos) { InsertDuplicateNodes(copyBuffer, pos); } private void InsertDuplicateNodes(XNode.Node[] nodes, Vector2 topLeft) { if (nodes == null || nodes.Length == 0) return; // Get top-left node Vector2 topLeftNode = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); Vector2 offset = topLeft - topLeftNode; UnityEngine.Object[] newNodes = new UnityEngine.Object[nodes.Length]; Dictionary<XNode.Node, XNode.Node> substitutes = new Dictionary<XNode.Node, XNode.Node>(); for (int i = 0; i < nodes.Length; i++) { XNode.Node srcNode = nodes[i]; if (srcNode == null) continue; // Check if user is allowed to add more of given node type XNode.Node.DisallowMultipleNodesAttribute disallowAttrib; Type nodeType = srcNode.GetType(); if (NodeEditorUtilities.GetAttrib(nodeType, out disallowAttrib)) { int typeCount = graph.nodes.Count(x => x.GetType() == nodeType); if (typeCount >= disallowAttrib.max) continue; } XNode.Node newNode = graphEditor.CopyNode(srcNode); substitutes.Add(srcNode, newNode); newNode.position = srcNode.position + offset; newNodes[i] = newNode; } // Walk through the selected nodes again, recreate connections, using the new nodes for (int i = 0; i < nodes.Length; i++) { XNode.Node srcNode = nodes[i]; if (srcNode == null) continue; foreach (XNode.NodePort port in srcNode.Ports) { for (int c = 0; c < port.ConnectionCount; c++) { XNode.NodePort inputPort = port.direction == XNode.NodePort.IO.Input ? port : port.GetConnection(c); XNode.NodePort outputPort = port.direction == XNode.NodePort.IO.Output ? port : port.GetConnection(c); XNode.Node newNodeIn, newNodeOut; if (substitutes.TryGetValue(inputPort.node, out newNodeIn) && substitutes.TryGetValue(outputPort.node, out newNodeOut)) { newNodeIn.UpdatePorts(); newNodeOut.UpdatePorts(); inputPort = newNodeIn.GetInputPort(inputPort.fieldName); outputPort = newNodeOut.GetOutputPort(outputPort.fieldName); } if (!inputPort.IsConnectedTo(outputPort)) inputPort.Connect(outputPort); } } } // Select the new nodes Selection.objects = newNodes; } /// <summary> Draw a connection as we are dragging it </summary> public void DrawDraggedConnection() { if (IsDraggingPort) { Gradient gradient = graphEditor.GetNoodleGradient(draggedOutput, null); float thickness = graphEditor.GetNoodleThickness(draggedOutput, null); NoodlePath path = graphEditor.GetNoodlePath(draggedOutput, null); NoodleStroke stroke = graphEditor.GetNoodleStroke(draggedOutput, null); Rect fromRect; if (!_portConnectionPoints.TryGetValue(draggedOutput, out fromRect)) return; List<Vector2> gridPoints = new List<Vector2>(); gridPoints.Add(fromRect.center); for (int i = 0; i < draggedOutputReroutes.Count; i++) { gridPoints.Add(draggedOutputReroutes[i]); } if (draggedOutputTarget != null) gridPoints.Add(portConnectionPoints[draggedOutputTarget].center); else gridPoints.Add(WindowToGridPosition(Event.current.mousePosition)); DrawNoodle(gradient, path, stroke, thickness, gridPoints); Color bgcol = Color.black; Color frcol = gradient.colorKeys[0].color; bgcol.a = 0.6f; frcol.a = 0.6f; // Loop through reroute points again and draw the points for (int i = 0; i < draggedOutputReroutes.Count; i++) { // Draw reroute point at position Rect rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16)); rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8); rect = GridToWindowRect(rect); NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol); } } } bool IsHoveringTitle(XNode.Node node) { Vector2 mousePos = Event.current.mousePosition; //Get node position Vector2 nodePos = GridToWindowPosition(node.position); float width; Vector2 size; if (nodeSizes.TryGetValue(node, out size)) width = size.x; else width = 200; Rect windowRect = new Rect(nodePos, new Vector2(width / zoom, 30 / zoom)); return windowRect.Contains(mousePos); } /// <summary> Attempt to connect dragged output to target node </summary> public void AutoConnect(XNode.Node node) { if (autoConnectOutput == null) return; // Find input port of same type XNode.NodePort inputPort = node.Ports.FirstOrDefault(x => x.IsInput && x.ValueType == autoConnectOutput.ValueType); // Fallback to input port if (inputPort == null) inputPort = node.Ports.FirstOrDefault(x => x.IsInput); // Autoconnect if connection is compatible if (inputPort != null && inputPort.CanConnectTo(autoConnectOutput)) autoConnectOutput.Connect(inputPort); // Save changes EditorUtility.SetDirty(graph); if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); autoConnectOutput = null; } } }
namespace Boxed.Mapping.Test { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; public class AsyncMapperTest : Disposable { private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); [Fact] public Task MapAsync_Null_ThrowsArgumentNullExceptionAsync() { var mapper = new AsyncMapper(); return Assert.ThrowsAsync<ArgumentNullException>( "source", () => mapper.MapAsync(null, this.cancellationTokenSource.Token)); } [Fact] public async Task MapAsync_ToNewObject_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapAsync(new MapFrom() { Property = 1 }, this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.Equal(this.cancellationTokenSource.Token, mapper.CancellationToken); Assert.Equal(1, to.Property); } [Fact] public async Task MapArrayAsync_Empty_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapArrayAsync(Array.Empty<MapFrom>(), this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.IsType<MapTo[]>(to); Assert.Empty(to); } [Fact] public async Task MapArrayAsync_ToNewObject_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapArrayAsync( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 }, }, this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.Equal(this.cancellationTokenSource.Token, mapper.CancellationToken); Assert.IsType<MapTo[]>(to); Assert.Equal(2, to.Length); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public async Task MapTypedCollectionAsync_Empty_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapCollectionAsync(Array.Empty<MapFrom>(), new List<MapTo>(), this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.IsType<List<MapTo>>(to); Assert.Empty(to); } [Fact] public async Task MapTypedCollectionAsync_ToNewObject_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapCollectionAsync( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 }, }, new List<MapTo>(), this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.Equal(this.cancellationTokenSource.Token, mapper.CancellationToken); Assert.IsType<List<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public async Task MapCollectionAsync_Empty_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapCollectionAsync(Array.Empty<MapFrom>(), this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.IsType<Collection<MapTo>>(to); Assert.Empty(to); } [Fact] public async Task MapCollectionAsync_ToNewObject_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapCollectionAsync( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 }, }, this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.Equal(this.cancellationTokenSource.Token, mapper.CancellationToken); Assert.IsType<Collection<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public async Task MapListAsync_Empty_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapListAsync(Array.Empty<MapFrom>(), this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.IsType<List<MapTo>>(to); Assert.Empty(to); } [Fact] public async Task MapListAsync_ToNewObject_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapListAsync( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 }, }, this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.Equal(this.cancellationTokenSource.Token, mapper.CancellationToken); Assert.IsType<List<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public async Task MapObservableCollectionAsync_Empty_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapObservableCollectionAsync(Array.Empty<MapFrom>(), this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.IsType<ObservableCollection<MapTo>>(to); Assert.Empty(to); } [Fact] public async Task MapObservableCollectionAsync_ToNewObject_MappedAsync() { var mapper = new AsyncMapper(); var to = await mapper .MapObservableCollectionAsync( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 }, }, this.cancellationTokenSource.Token) .ConfigureAwait(false); Assert.Equal(this.cancellationTokenSource.Token, mapper.CancellationToken); Assert.IsType<ObservableCollection<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public async Task MapEnumerableAsync_ToNewObject_MappedAsync() { var mapper = new AsyncMapper(); var source = new TestAsyncEnumerable<MapFrom>( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 }, }); var to = mapper.MapEnumerableAsync(source, this.cancellationTokenSource.Token); var list = await to.ToListAsync().ConfigureAwait(false); Assert.Equal(this.cancellationTokenSource.Token, mapper.CancellationToken); Assert.IsType<List<MapTo>>(list); Assert.Equal(2, list.Count); Assert.Equal(1, list[0].Property); Assert.Equal(2, list[1].Property); } protected override void DisposeManaged() => this.cancellationTokenSource.Dispose(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 CompareScalarNotGreaterThanDouble() { var test = new SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.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 (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble testClass) { var result = Sse2.CompareScalarNotGreaterThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareScalarNotGreaterThan( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.CompareScalarNotGreaterThan( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.CompareScalarNotGreaterThan( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.CompareScalarNotGreaterThan( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.CompareScalarNotGreaterThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.CompareScalarNotGreaterThan( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareScalarNotGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareScalarNotGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareScalarNotGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble(); var result = Sse2.CompareScalarNotGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareScalarNotGreaterThanDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.CompareScalarNotGreaterThan( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.CompareScalarNotGreaterThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareScalarNotGreaterThan( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.CompareScalarNotGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.CompareScalarNotGreaterThan( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] > right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareScalarNotGreaterThan)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Configuration; using Orleans.LeaseProviders; using Orleans.Runtime; using Orleans.Timers; namespace Orleans.Streams { /// <summary> /// LeaseBasedQueueBalancer. This balancer supports queue balancing in cluster auto-scale scenarios, /// unexpected server failure scenarios, and tries to support ideal distribution as much as possible. /// </summary> public class LeaseBasedQueueBalancer : QueueBalancerBase, IStreamQueueBalancer { private class AcquiredQueue { public int LeaseOrder { get; set; } public QueueId QueueId { get; set; } public AcquiredLease AcquiredLease { get; set; } public AcquiredQueue(int order, QueueId queueId, AcquiredLease lease) { this.LeaseOrder = order; this.QueueId = queueId; this.AcquiredLease = lease; } } private readonly LeaseBasedQueueBalancerOptions options; private readonly ILeaseProvider leaseProvider; private readonly ITimerRegistry timerRegistry; private readonly AsyncSerialExecutor executor = new AsyncSerialExecutor(); private int allQueuesCount; private readonly List<AcquiredQueue> myQueues = new List<AcquiredQueue>(); private IDisposable leaseMaintenanceTimer; private IDisposable leaseAquisitionTimer; private RoundRobinSelector<QueueId> queueSelector; private int responsibility; private int leaseOrder; /// <summary> /// Initializes a new instance of the <see cref="LeaseBasedQueueBalancer"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="options">The options.</param> /// <param name="leaseProvider">The lease provider.</param> /// <param name="timerRegistry">The timer registry.</param> /// <param name="services">The services.</param> /// <param name="loggerFactory">The logger factory.</param> public LeaseBasedQueueBalancer( string name, LeaseBasedQueueBalancerOptions options, ILeaseProvider leaseProvider, ITimerRegistry timerRegistry, IServiceProvider services, ILoggerFactory loggerFactory) : base(services, loggerFactory.CreateLogger($"{typeof(LeaseBasedQueueBalancer).FullName}.{name}")) { this.options = options; this.leaseProvider = leaseProvider; this.timerRegistry = timerRegistry; } /// <summary> /// Creates a new <see cref="LeaseBasedQueueBalancer"/> instance. /// </summary> /// <param name="services">The services.</param> /// <param name="name">The name.</param> /// <returns>The new <see cref="LeaseBasedQueueBalancer"/> instance.</returns> public static IStreamQueueBalancer Create(IServiceProvider services, string name) { var options = services.GetOptionsByName<LeaseBasedQueueBalancerOptions>(name); var leaseProvider = services.GetServiceByName<ILeaseProvider>(name) ?? services.GetRequiredService<ILeaseProvider>(); return ActivatorUtilities.CreateInstance<LeaseBasedQueueBalancer>(services, name, options, leaseProvider); } /// <inheritdoc/> public override Task Initialize(IStreamQueueMapper queueMapper) { if (base.Cancellation.IsCancellationRequested) throw new InvalidOperationException("Cannot initialize a terminated balancer."); if (queueMapper == null) { throw new ArgumentNullException("queueMapper"); } var allQueues = queueMapper.GetAllQueues().ToList(); this.allQueuesCount = allQueues.Count; //Selector default to round robin selector now, but we can make a further change to make selector configurable if needed. Selector algorithm could //be affecting queue balancing stablization time in cluster initializing and auto-scaling this.queueSelector = new RoundRobinSelector<QueueId>(allQueues); return base.Initialize(queueMapper); } /// <inheritdoc/> public override async Task Shutdown() { if (base.Cancellation.IsCancellationRequested) return; this.myQueues.Clear(); this.responsibility = 0; this.leaseMaintenanceTimer?.Dispose(); this.leaseMaintenanceTimer = null; this.leaseAquisitionTimer?.Dispose(); this.leaseAquisitionTimer = null; await base.Shutdown(); //release all owned leases await this.executor.AddNext(this.ReleaseLeasesToMeetResponsibility); } /// <inheritdoc/> public override IEnumerable<QueueId> GetMyQueues() { if (base.Cancellation.IsCancellationRequested) throw new InvalidOperationException("Cannot aquire queues from a terminated balancer."); return this.myQueues.Select(queue => queue.QueueId); } private async Task MaintainLeases(object state) { try { await this.executor.AddNext(this.MaintainLeases); } catch (Exception ex) { this.Logger.LogError(ex, "Maintaining leases failed"); } } private async Task MaintainLeases() { if (base.Cancellation.IsCancellationRequested) return; var oldQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId)); try { bool allLeasesRenewed = await this.RenewLeases(); // if we lost some leases during renew after leaseAquisitionTimer stopped, restart it if (!allLeasesRenewed && this.leaseAquisitionTimer == null && !base.Cancellation.IsCancellationRequested) { this.leaseAquisitionTimer = this.timerRegistry.RegisterTimer(null, this.AcquireLeasesToMeetResponsibility, null, TimeSpan.Zero, this.options.LeaseAquisitionPeriod); } } finally { await this.NotifyOnChange(oldQueues); } } private async Task AcquireLeasesToMeetResponsibility(object state) { try { await this.executor.AddNext(this.AcquireLeasesToMeetResponsibility); } catch (Exception ex) { this.Logger.LogError(ex, "Acquiring min leases failed"); } } private async Task AcquireLeasesToMeetResponsibility() { if (base.Cancellation.IsCancellationRequested) return; var oldQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId)); try { if (this.myQueues.Count < this.responsibility) { await this.AcquireLeasesToMeetExpectation(this.responsibility, this.options.LeaseLength.Divide(10)); } else if (this.myQueues.Count > this.responsibility) { await this.ReleaseLeasesToMeetResponsibility(); } } finally { await this.NotifyOnChange(oldQueues); if (this.myQueues.Count == this.responsibility) { this.leaseAquisitionTimer?.Dispose(); this.leaseAquisitionTimer = null; } } } private async Task ReleaseLeasesToMeetResponsibility() { if (base.Cancellation.IsCancellationRequested) return; if (this.Logger.IsEnabled(LogLevel.Trace)) { this.Logger.LogTrace("ReleaseLeasesToMeetResponsibility. QueueCount: {QueueCount}, Responsibility: {Responsibility}", this.myQueues.Count, this.responsibility); } var queueCountToRelease = this.myQueues.Count - this.responsibility; if (queueCountToRelease <= 0) return; // Remove oldest acquired queues first, this provides max recovery time for the queues // being moved. // TODO: Consider making this behavior configurable/plugable - jbragg AcquiredLease[] queuesToGiveUp = this.myQueues .OrderBy(queue => queue.LeaseOrder) .Take(queueCountToRelease) .Select(queue => queue.AcquiredLease) .ToArray(); // Remove queues from list even if release fails, since we can let the lease expire // TODO: mark for removal instead so we don't renew, and only remove leases that have not expired. - jbragg for(int index = this.myQueues.Count-1; index >= 0; index--) { if(queuesToGiveUp.Contains(this.myQueues[index].AcquiredLease)) { this.myQueues.RemoveAt(index); } } await this.leaseProvider.Release(this.options.LeaseCategory, queuesToGiveUp); //remove queuesToGiveUp from myQueue list after the balancer released the leases on them this.Logger.LogInformation("Released leases for {QueueCount} queues", queueCountToRelease); this.Logger.LogInformation("Holding leases for {QueueCount} of an expected {MinQueueCount} queues.", this.myQueues.Count, this.responsibility); } private async Task AcquireLeasesToMeetExpectation(int expectedTotalLeaseCount, TimeSpan timeout) { if (base.Cancellation.IsCancellationRequested) return; if (this.Logger.IsEnabled(LogLevel.Trace)) { this.Logger.LogTrace("AcquireLeasesToMeetExpectation. QueueCount: {QueueCount}, ExpectedTotalLeaseCount: {ExpectedTotalLeaseCount}", this.myQueues.Count, expectedTotalLeaseCount); } var leasesToAquire = expectedTotalLeaseCount - this.myQueues.Count; if (leasesToAquire <= 0) return; // tracks how many remaining possible leases there are. var possibleLeaseCount = this.queueSelector.Count - this.myQueues.Count; if (this.Logger.IsEnabled(LogLevel.Debug)) { this.Logger.LogDebug("Holding leased for {QueueCount} queues. Trying to acquire {AquireQueueCount} queues to reach {TargetQueueCount} of a possible {PossibleLeaseCount}", this.myQueues.Count, leasesToAquire, expectedTotalLeaseCount, possibleLeaseCount); } ValueStopwatch sw = ValueStopwatch.StartNew(); // try to acquire leases until we have no more to aquire or no more possible while (!base.Cancellation.IsCancellationRequested && leasesToAquire > 0 && possibleLeaseCount > 0) { //select new queues to acquire List<QueueId> expectedQueues = this.queueSelector.NextSelection(leasesToAquire, this.myQueues.Select(queue=>queue.QueueId).ToList()); // build lease request from each queue LeaseRequest[] leaseRequests = expectedQueues .Select(queue => new LeaseRequest() { ResourceKey = queue.ToString(), Duration = this.options.LeaseLength }) .ToArray(); AcquireLeaseResult[] results = await this.leaseProvider.Acquire(this.options.LeaseCategory, leaseRequests); //add successfully acquired queue to myQueues list for (var i = 0; i < results.Length; i++) { AcquireLeaseResult result = results[i]; switch (result.StatusCode) { case ResponseCode.OK: { this.myQueues.Add(new AcquiredQueue(this.leaseOrder++, expectedQueues[i], result.AcquiredLease)); break; } case ResponseCode.TransientFailure: { this.Logger.LogWarning(result.FailureException, "Failed to acquire lease {LeaseKey} due to transient error.", result.AcquiredLease.ResourceKey); break; } // this is expected much of the time case ResponseCode.LeaseNotAvailable: { if (this.Logger.IsEnabled(LogLevel.Debug)) { this.Logger.LogDebug(result.FailureException, "Failed to acquire lease {LeaseKey} due to {Reason}.", result.AcquiredLease.ResourceKey, result.StatusCode); } break; } // An acquire call should not return this code, so log as error case ResponseCode.InvalidToken: { this.Logger.LogError(result.FailureException, "Failed to aquire acquire {LeaseKey} unexpected invalid token.", result.AcquiredLease.ResourceKey); break; } default: { this.Logger.LogError(result.FailureException, "Unexpected response to acquire request of lease {LeaseKey}. StatusCode {StatusCode}.", result.AcquiredLease.ResourceKey, result.StatusCode); break; } } } possibleLeaseCount -= expectedQueues.Count; leasesToAquire = expectedTotalLeaseCount - this.myQueues.Count; if (this.Logger.IsEnabled(LogLevel.Debug)) { this.Logger.LogDebug("Holding leased for {QueueCount} queues. Trying to acquire {AquireQueueCount} queues to reach {TargetQueueCount} of a possible {PossibleLeaseCount} lease", this.myQueues.Count, leasesToAquire, expectedTotalLeaseCount, possibleLeaseCount); } if (sw.Elapsed > timeout) { // blown our alotted time, try again next period break; } } this.Logger.LogInformation("Holding leases for {QueueCount} of an expected {MinQueueCount} queues.", this.myQueues.Count, this.responsibility); } /// <summary> /// Renew leases /// </summary> /// <returns>bool - false if we failed to renew all leases</returns> private async Task<bool> RenewLeases() { bool allRenewed = true; if (base.Cancellation.IsCancellationRequested) return false; if (this.Logger.IsEnabled(LogLevel.Trace)) { this.Logger.LogTrace("RenewLeases. QueueCount: {QueueCount}", this.myQueues.Count); } if (this.myQueues.Count <= 0) return allRenewed; var results = await this.leaseProvider.Renew(this.options.LeaseCategory, this.myQueues.Select(queue => queue.AcquiredLease).ToArray()); //update myQueues list with successfully renewed leases for (var i = 0; i < results.Length; i++) { AcquireLeaseResult result = results[i]; switch (result.StatusCode) { case ResponseCode.OK: { this.myQueues[i].AcquiredLease = result.AcquiredLease; break; } case ResponseCode.TransientFailure: { this.myQueues.RemoveAt(i); allRenewed &= false; this.Logger.LogWarning(result.FailureException, "Failed to renew lease {LeaseKey} due to transient error.", result.AcquiredLease.ResourceKey); break; } // these can occure if lease has expired and/or someone else has taken it case ResponseCode.InvalidToken: case ResponseCode.LeaseNotAvailable: { this.myQueues.RemoveAt(i); allRenewed &= false; this.Logger.LogWarning(result.FailureException, "Failed to renew lease {LeaseKey} due to {Reason}.", result.AcquiredLease.ResourceKey, result.StatusCode); break; } default: { this.myQueues.RemoveAt(i); allRenewed &= false; this.Logger.LogError(result.FailureException, "Unexpected response to renew of lease {LeaseKey}. StatusCode {StatusCode}.", result.AcquiredLease.ResourceKey, result.StatusCode); break; } } } this.Logger.LogInformation("Renewed leases for {QueueCount} queues.", this.myQueues.Count); return allRenewed; } private Task NotifyOnChange(HashSet<QueueId> oldQueues) { if (base.Cancellation.IsCancellationRequested) return Task.CompletedTask; var newQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId)); //if queue changed, notify listeners return !oldQueues.SetEquals(newQueues) ? this.NotifyListeners() : Task.CompletedTask; } /// <inheritdoc/> protected override void OnClusterMembershipChange(HashSet<SiloAddress> activeSilos) { if (base.Cancellation.IsCancellationRequested) return; this.ScheduleUpdateResponsibilities(activeSilos).Ignore(); } private async Task ScheduleUpdateResponsibilities(HashSet<SiloAddress> activeSilos) { if (base.Cancellation.IsCancellationRequested) return; try { await this.executor.AddNext(() => UpdateResponsibilities(activeSilos)); } catch (Exception ex) { this.Logger.LogError(ex, "Updating Responsibilities"); } } /// <summary> /// Checks to see if this balancer should be greedy, which means it attempts to grab one /// more queue than the non-greedy balancers. /// </summary> /// <param name="overflow">number of free queues, assuming all balancers meet their minimum responsibilities</param> /// <param name="activeSilos">number of active silos hosting queues</param> /// <returns>bool - true indicates that the balancer should try to acquire one /// more queue than the non-greedy balancers</returns> private bool AmGreedy(int overflow, HashSet<SiloAddress> activeSilos) { // If using multiple stream providers, this will select the same silos to be greedy for // all providers, aggravating inbalance as stream provider count increases. // TODO: consider making this behavior configurable/plugable - jbragg // TODO: use heap? - jbragg return activeSilos.OrderBy(silo => silo) .Take(overflow) .Contains(base.SiloAddress); } private async Task UpdateResponsibilities(HashSet<SiloAddress> activeSilos) { if (base.Cancellation.IsCancellationRequested) return; var activeSiloCount = Math.Max(1, activeSilos.Count); this.responsibility = this.allQueuesCount / activeSiloCount; var overflow = this.allQueuesCount % activeSiloCount; if(overflow != 0 && this.AmGreedy(overflow, activeSilos)) { this.responsibility++; } if (this.Logger.IsEnabled(LogLevel.Debug)) { this.Logger.LogDebug("Updating Responsibilities for {QueueCount} queue over {SiloCount} silos. Need {MinQueueCount} queues, have {MyQueueCount}", this.allQueuesCount, activeSiloCount, this.responsibility, this.myQueues.Count); } if (this.myQueues.Count < this.responsibility && this.leaseAquisitionTimer == null) { this.leaseAquisitionTimer = this.timerRegistry.RegisterTimer( null, this.AcquireLeasesToMeetResponsibility, null, this.options.LeaseAquisitionPeriod, this.options.LeaseAquisitionPeriod); } if (this.leaseMaintenanceTimer == null) { this.leaseMaintenanceTimer = this.timerRegistry.RegisterTimer( null, this.MaintainLeases, null, this.options.LeaseRenewPeriod, this.options.LeaseRenewPeriod); } await this.AcquireLeasesToMeetResponsibility(); } } }
// 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. #if USE_MDT_EVENTSOURCE using Microsoft.Diagnostics.Tracing; #else using System.Diagnostics.Tracing; #endif #if USE_ETW using Microsoft.Diagnostics.Tracing.Session; #endif using Xunit; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BasicEventSourceTests { public class TestEventCounter { #if USE_ETW // Specifies whether the process is elevated or not. private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated()); private static bool IsProcessElevated => s_isElevated.Value; #endif // USE_ETW private sealed class MyEventSource : EventSource { private EventCounter _requestCounter; private EventCounter _errorCounter; public MyEventSource() { _requestCounter = new EventCounter("Request", this); _errorCounter = new EventCounter("Error", this); } public void Request(float elapsed) { _requestCounter.WriteMetric(elapsed); } public void Error() { _errorCounter.WriteMetric(1); } } [Fact] #if !USE_MDT_EVENTSOURCE [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, reason: "https://github.com/dotnet/corefx/issues/23661")] #endif [ActiveIssue("https://github.com/dotnet/corefx/issues/22791", TargetFrameworkMonikers.UapAot)] [ActiveIssue("https://github.com/dotnet/corefx/issues/25029")] public void Test_Write_Metric_EventListener() { using (var listener = new EventListenerListener()) { Test_Write_Metric(listener); } } #if USE_ETW [ConditionalFact(nameof(IsProcessElevated))] [ActiveIssue("https://github.com/dotnet/corefx/issues/27106")] public void Test_Write_Metric_ETW() { using (var listener = new EtwListener()) { Test_Write_Metric(listener); } } #endif private void Test_Write_Metric(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new MyEventSource()) { var tests = new List<SubTest>(); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 1 event, explicit poll at end", delegate () { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); listener.EnableTimer(logger, 0); }, delegate (List<Event> evts) { // There will be two events (request and error) for time 0 and 2 more at 1 second and 2 more when we shut it off. Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 1, 5, 0, 5, 5); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 2 events, explicit poll at end", delegate () { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); logger.Request(10); listener.EnableTimer(logger, 0); // poll }, delegate (List<Event> evts) { Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 3 events in two polling periods (explicit polling)", delegate () { listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(5); logger.Request(10); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(8); logger.Error(); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate (List<Event> evts) { Assert.Equal(6, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 1, 1, 0, 1, 1); ValidateSingleEventCounter(evts[4], "Request", 1, 8, 0, 8, 8); ValidateSingleEventCounter(evts[5], "Error", 2, 1, 0, 1, 1); })); /*************************************************************************/ int num100msecTimerTicks = 0; tests.Add(new SubTest("EventCounter: Log multiple events in multiple periods", delegate () { // We have had problems with timer ticks not being called back 100% reliably. // However timers really don't have a strong guarentee (only that the happen eventually) // So what we do is create a timer callback that simply counts the number of callbacks. // This acts as a marker to show whether the timer callbacks are happening promptly. // If we don't get enough of these tick callbacks then we don't require EventCounter to // be sending periodic callbacks either. num100msecTimerTicks = 0; using (var timer = new System.Threading.Timer(delegate(object state) { num100msecTimerTicks++; EventTestHarness.LogWriteLine("Tick"); }, null, 100, 100)) { listener.EnableTimer(logger, .1); /* Poll every .1 s */ // logs at 0 seconds because of EnableTimer command Sleep(100); logger.Request(1); Sleep(100); logger.Request(2); logger.Error(); Sleep(100); logger.Request(4); Sleep(100); logger.Request(8); logger.Error(); Sleep(100); logger.Request(16); Sleep(220); listener.EnableTimer(logger, 0); } }, delegate (List<Event> evts) { int requestCount = 0; float requestSum = 0; float requestMin = float.MaxValue; float requestMax = float.MinValue; int errorCount = 0; float errorSum = 0; float errorMin = float.MaxValue; float errorMax = float.MinValue; float timeSum = 0; for (int j = 0; j < evts.Count; j += 2) { var requestPayload = ValidateEventHeaderAndGetPayload(evts[j]); Assert.Equal("Request", requestPayload["Name"]); var count = (int)requestPayload["Count"]; requestCount += count; if (count > 0) requestSum += (float)requestPayload["Mean"] * count; requestMin = Math.Min(requestMin, (float)requestPayload["Min"]); requestMax = Math.Max(requestMax, (float)requestPayload["Max"]); float requestIntevalSec = (float)requestPayload["IntervalSec"]; var errorPayload = ValidateEventHeaderAndGetPayload(evts[j + 1]); Assert.Equal("Error", errorPayload["Name"]); count = (int)errorPayload["Count"]; errorCount += count; if (count > 0) errorSum += (float)errorPayload["Mean"] * count; errorMin = Math.Min(errorMin, (float)errorPayload["Min"]); errorMax = Math.Max(errorMax, (float)errorPayload["Max"]); float errorIntevalSec = (float)requestPayload["IntervalSec"]; Assert.Equal(requestIntevalSec, errorIntevalSec); timeSum += requestIntevalSec; } EventTestHarness.LogWriteLine("Validating: Count={0} RequestSum={1:n3} TimeSum={2:n3} ", evts.Count, requestSum, timeSum); Assert.Equal(requestCount, 5); Assert.Equal(requestSum, 31); Assert.Equal(requestMin, 1); Assert.Equal(requestMax, 16); Assert.Equal(errorCount, 2); Assert.Equal(errorSum, 2); Assert.Equal(errorMin, 1); Assert.Equal(errorMax, 1); Assert.True(.4 < timeSum, $"FAILURE: .4 < {timeSum}"); // We should have at least 400 msec Assert.True(timeSum < 2, $"FAILURE: {timeSum} < 2"); // But well under 2 sec. // Do all the things that depend on the count of events last so we know everything else is sane Assert.True(4 <= evts.Count, "We expect two metrics at the beginning trigger and two at the end trigger. evts.Count = " + evts.Count); Assert.True(evts.Count % 2 == 0, "We expect two metrics for every trigger. evts.Count = " + evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); // We shoudl always get the unconditional callback at the start and end of the trace. Assert.True(4 <= evts.Count, $"FAILURE EventCounter Multi-event: 4 <= {evts.Count} ticks: {num100msecTimerTicks} thread: {Thread.CurrentThread.ManagedThreadId}"); // We expect the timer to have gone off at least twice, plus the explicit poll at the begining and end. // Each one fires two events (one for requests, one for errors). so that is (2 + 2)*2 = 8 // We expect about 7 timer requests, but we don't get picky about the exact count // Putting in a generous buffer, we double 7 to say we don't expect more than 14 timer fires // so that is (2 + 14) * 2 = 32 if (num100msecTimerTicks > 3) // We seem to have problems with timer events going off 100% reliably. To avoid failures here we only check if in the 700 msec test we get at least 3 100 msec ticks. Assert.True(8 <= evts.Count, $"FAILURE: 8 <= {evts.Count}"); Assert.True(evts.Count <= 32, $"FAILURE: {evts.Count} <= 32"); })); /*************************************************************************/ #if FEATURE_EVENTCOUNTER_DISPOSE tests.Add(new SubTest("EventCounter: Dispose()", delegate () { // Creating and destroying var myCounter = new EventCounter("counter for a transient object", logger); myCounter.WriteMetric(10); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ myCounter.Dispose(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate (List<Event> evts) { // The static counters (Request and Error), should not log any counts and stay at zero. // The new counter will exist for the first poll but will not exist for the second. Assert.Equal(5, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "counter for a transient object", 1, 10, 0, 10, 10); ValidateSingleEventCounter(evts[3], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[4], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); #endif /*************************************************************************/ EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); } // Thread.Sleep has proven unreliable, sometime sleeping much shorter than it should. // This makes sure it at least sleeps 'msec' at a miniumum. private static void Sleep(int minMSec) { var startTime = DateTime.UtcNow; for (; ; ) { DateTime endTime = DateTime.UtcNow; double delta = (endTime - startTime).TotalMilliseconds; if (delta >= minMSec) break; Thread.Sleep(1); } } private static void ValidateSingleEventCounter(Event evt, string counterName, int count, float mean, float standardDeviation, float min, float max) { ValidateEventCounter(counterName, count, mean, standardDeviation, min, max, ValidateEventHeaderAndGetPayload(evt)); } private static IDictionary<string, object> ValidateEventHeaderAndGetPayload(Event evt) { Assert.Equal("EventCounters", evt.EventName); Assert.Equal(1, evt.PayloadCount); Assert.NotNull(evt.PayloadNames); Assert.Equal(1, evt.PayloadNames.Count); Assert.Equal("Payload", evt.PayloadNames[0]); var ret = (IDictionary<string, object>)evt.PayloadValue(0, "Payload"); Assert.NotNull(ret); return ret; } private static void ValidateEventCounter(string counterName, int count, float mean, float standardDeviation, float min, float max, IDictionary<string, object> payloadContent) { Assert.Equal(counterName, (string)payloadContent["Name"]); Assert.Equal(count, (int)payloadContent["Count"]); if (count != 0) { Assert.Equal(mean, (float)payloadContent["Mean"]); Assert.Equal(standardDeviation, (float)payloadContent["StandardDeviation"]); } Assert.Equal(min, (float)payloadContent["Min"]); Assert.Equal(max, (float)payloadContent["Max"]); } } }
/* ==================================================================== This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Drawing; using System.Drawing.Drawing2D; using fyiReporting.RDL; namespace fyiReporting.RDL { //takes the record data and returns the instructions for drawing...I guess. internal class DrawString : DrawBase { internal DrawString(Single Xin, Single Yin, Single WidthIn, Single HeightIn,System.Collections.Hashtable ObjectTableIn) { X = Xin; Y = Yin; Width = WidthIn; Height = HeightIn; ObjectTable = ObjectTableIn; items = new List<PageItem>(); } public List<PageItem> Process(int Flags, byte[] RecordData) { MemoryStream _ms = null; BinaryReader _br = null; MemoryStream _fs = null; BinaryReader _fr = null; try { _fs = new MemoryStream(BitConverter.GetBytes(Flags)); _fr = new BinaryReader(_fs); //Byte 1 will be ObjectID - a font in the object table byte ObjectID = _fr.ReadByte(); //Byte 2 is the real flags byte RealFlags = _fr.ReadByte(); // 0 1 2 3 4 5 6 7 // X X X X X X X S // if S = type of brush - if S then ARGB, else a brush object in object table _ms = new MemoryStream(RecordData); _br = new BinaryReader(_ms); bool BrushIsARGB = ((RealFlags & (int)Math.Pow(2, 7)) == (int)Math.Pow(2, 7)); Brush b; if (BrushIsARGB) { byte A, R, G, B; B = _br.ReadByte(); G = _br.ReadByte(); R = _br.ReadByte(); A = _br.ReadByte(); b = new SolidBrush(Color.FromArgb(A, R, G, B)); } else { UInt32 BrushID = _br.ReadUInt32(); EMFBrush EMFb = (EMFBrush)ObjectTable[(byte)BrushID]; b = EMFb.myBrush; } UInt32 FormatID = _br.ReadUInt32(); // Index of Optional stringFormatobject in Object Table... UInt32 StringLength = _br.ReadUInt32(); //bounding of string... Single recX = _br.ReadSingle(); Single recY = _br.ReadSingle(); Single recWidth = _br.ReadSingle(); Single recHeight = _br.ReadSingle(); //Array of Chars... char[] StringData = new char[StringLength]; System.Text.UnicodeEncoding d = new System.Text.UnicodeEncoding(); d.GetChars(_br.ReadBytes((int)StringLength * 2), 0, (int)StringLength * 2, StringData, 0); EMFFont EF = (EMFFont)ObjectTable[(byte)ObjectID]; Font f = EF.myFont; StringFormat sf; if (ObjectTable.Contains((byte)FormatID)) { EMFStringFormat ESF = (EMFStringFormat)ObjectTable[(byte)FormatID]; sf = ESF.myStringFormat; } else { sf = new StringFormat(); } DoInstructions(f, sf, b, recX, recY, recWidth, recHeight, new String(StringData)); return items; } finally { if (_br != null) _br.Close(); if (_ms != null) _ms.Dispose(); if (_fr != null) _fr.Close(); if (_fs != null) _fs.Dispose(); } } private void DoInstructions(Font f, StringFormat sf, Brush br, Single recX, Single recY, Single recWidth, Single recHeight, String Text) { Color Col = Color.Black; if (br.GetType().Name.Equals("SolidBrush")) { SolidBrush sb = (SolidBrush)br; Col = sb.Color; } PageText pt = new PageText(Text); pt.X = X + recX * SCALEFACTOR; pt.Y = Y + recY * SCALEFACTOR; pt.W = recWidth * SCALEFACTOR; pt.H = recHeight * SCALEFACTOR; StyleInfo SI = new StyleInfo(); SI.Color = Col; SI.Direction = DirectionEnum.LTR; SI.FontFamily = f.Name; SI.FontSize = f.Size * SCALEFACTOR; if (f.Italic) {SI.FontStyle = FontStyleEnum.Italic;} if (f.Bold) { SI.FontWeight = FontWeightEnum.Bold; } if (f.Underline) { SI.TextDecoration = TextDecorationEnum.Underline; } if (sf.LineAlignment == StringAlignment.Center) { SI.TextAlign = TextAlignEnum.Center; } else if (sf.LineAlignment == StringAlignment.Far) { SI.TextAlign = TextAlignEnum.Right; } if (sf.Alignment == StringAlignment.Center) { SI.VerticalAlign = VerticalAlignEnum.Middle; } else if (sf.Alignment == StringAlignment.Far) { SI.VerticalAlign = VerticalAlignEnum.Bottom; } if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) == StringFormatFlags.DirectionVertical) { SI.WritingMode = WritingModeEnum.tb_rl; } else { SI.WritingMode = WritingModeEnum.lr_tb; } pt.SI = SI; items.Add(pt); //r = Math.Round((r / 255), 3); //g = Math.Round((g / 255), 3); //b = Math.Round((b / 255), 3); //string pdfFont = fonts.GetPdfFont(f.Name); ////need a graphics object... //Bitmap bm = new Bitmap(1, 1); //Graphics gr = Graphics.FromImage(bm); //Font scaleFont = new Font(f.Name, (f.Size * ScaleY) * 1.5f, f.Style, f.Unit); //SizeF TextSize = gr.MeasureString(Text.Substring(0, Text.Length), scaleFont, (int)(recWidth * ScaleX), sf); //float textwidth = TextSize.Width; //float textHeight = TextSize.Height; //float startX = X + recX * ScaleX; //float startY = Y + Height - recY * ScaleY - (scaleFont.Size); //if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) != StringFormatFlags.DirectionVertical) //{ // if (sf.LineAlignment == StringAlignment.Center) // { // startX = (startX + (recWidth * ScaleX) / 2) - (textwidth / 4); // } // else if (sf.LineAlignment == StringAlignment.Far) // { // startX = (startX + recWidth * ScaleX) - (textwidth / 1.8f); // } //} //else //{ // startX += textwidth / 4; // if (sf.LineAlignment == StringAlignment.Center) // { // startY = (startY - (recHeight * ScaleY) / 2) + (textHeight / 4); // } // else if (sf.LineAlignment == StringAlignment.Far) // { // startY = (startY - recHeight * ScaleY) + (textHeight / 1.8f); // } //} //Lines.Append("\r\nq\t"); //string newtext = PdfUtility.UTF16StringQuoter(Text); //if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) != StringFormatFlags.DirectionVertical) //{ // Lines.AppendFormat(System.Globalization.NumberFormatInfo.InvariantInfo, // "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{2} {3} Td \t({4}) Tj\tET\tQ\t", // pdfFont, scaleFont.SizeInPoints, startX, startY, newtext, r, g, b); //} //else //{ // double rads = -283.0 / 180.0; // double radsCos = Math.Cos(rads); // double radsSin = Math.Sin(rads); // Lines.AppendFormat(System.Globalization.NumberFormatInfo.InvariantInfo, // "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{8} {9} {10} {11} {2} {3} Tm \t({4}) Tj\tET\tQ\t", // pdfFont, scaleFont.SizeInPoints, startX, startY, newtext, r, g, b, // radsCos, radsSin, -radsSin, radsCos); //} } } }
using System; using System.Collections.Generic; using EventStore.ClientAPI.Common.Utils; using Newtonsoft.Json.Linq; namespace EventStore.ClientAPI { /// <summary> /// Builder for <see cref="StreamMetadata"/>. /// </summary> public class StreamMetadataBuilder { private int? _maxCount; private TimeSpan? _maxAge; private int? _truncateBefore; private TimeSpan? _cacheControl; private string[] _aclRead; private string[] _aclWrite; private string[] _aclDelete; private string[] _aclMetaRead; private string[] _aclMetaWrite; private readonly IDictionary<string, JToken> _customMetadata = new Dictionary<string, JToken>(); internal StreamMetadataBuilder() { } /// <summary> /// Builds a <see cref="StreamMetadata"/> from a <see cref="StreamMetadataBuilder"/>. /// </summary> /// <param name="builder">A <see cref="StreamMetadataBuilder"/>.</param> /// <returns>A <see cref="StreamMetadata"/>.</returns> public static implicit operator StreamMetadata(StreamMetadataBuilder builder) { var acl = builder._aclRead == null && builder._aclWrite == null && builder._aclDelete == null && builder._aclMetaRead == null && builder._aclMetaWrite == null ? null : new StreamAcl(builder._aclRead, builder._aclWrite, builder._aclDelete, builder._aclMetaRead, builder._aclMetaWrite); return new StreamMetadata(builder._maxCount, builder._maxAge, builder._truncateBefore, builder._cacheControl, acl, builder._customMetadata); } /// <summary> /// Sets the maximum number of events allowed in the stream. /// </summary> /// <param name="maxCount">The maximum number of events allowed in the stream.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetMaxCount(int maxCount) { Ensure.Positive(maxCount, "maxCount"); _maxCount = maxCount; return this; } /// <summary> /// Sets the maximum age of events allowed in the stream. /// </summary> /// <param name="maxAge">The maximum age of events allowed in the stream.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetMaxAge(TimeSpan maxAge) { Ensure.Positive(maxAge.Ticks, "maxAge"); _maxAge = maxAge; return this; } /// <summary> /// Sets the event number from which previous events can be scavenged. /// </summary> /// <param name="truncateBefore">The event number from which previous events can be scavenged.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetTruncateBefore(int truncateBefore) { Ensure.Nonnegative(truncateBefore, "truncateBefore"); _truncateBefore = truncateBefore; return this; } /// <summary> /// Sets the amount of time for which the stream head is cachable. /// </summary> /// <param name="cacheControl">The amount of time for which the stream head is cachable.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCacheControl(TimeSpan cacheControl) { Ensure.Positive(cacheControl.Ticks, "cacheControl"); _cacheControl = cacheControl; return this; } /// <summary> /// Sets a single role name with read permission for the stream. /// </summary> /// <param name="role">Role name.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetReadRole(string role) { _aclRead = role == null ? null : new[] { role }; return this; } /// <summary> /// Sets role names with read permission for the stream. /// </summary> /// <param name="roles">Role names.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetReadRoles(string[] roles) { _aclRead = roles; return this; } /// <summary> /// Sets a single role name with write permission for the stream. /// </summary> /// <param name="role">Role name.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetWriteRole(string role) { _aclWrite = role == null ? null : new[] { role }; return this; } /// <summary> /// Sets role names with write permission for the stream. /// </summary> /// <param name="roles">Role names.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetWriteRoles(string[] roles) { _aclWrite = roles; return this; } /// <summary> /// Sets a single role name with delete permission for the stream. /// </summary> /// <param name="role">Role name.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetDeleteRole(string role) { _aclDelete = role == null ? null : new[] { role }; return this; } /// <summary> /// Sets role names with delete permission for the stream. /// </summary> /// <param name="roles">Role names.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetDeleteRoles(string[] roles) { _aclDelete = roles; return this; } /// <summary> /// Sets a single role name with metadata read permission for the stream. /// </summary> /// <param name="role">Role name.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetMetadataReadRole(string role) { _aclMetaRead = role == null ? null : new[] { role }; return this; } /// <summary> /// Sets role names with metadata read permission for the stream. /// </summary> /// <param name="roles">Role names.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetMetadataReadRoles(string[] roles) { _aclMetaRead = roles; return this; } /// <summary> /// Sets a single role name with metadata write permission for the stream. /// </summary> /// <param name="role">Role name.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetMetadataWriteRole(string role) { _aclMetaWrite = role == null ? null : new[] { role }; return this; } /// <summary> /// Sets role names with metadata write permission for the stream. /// </summary> /// <param name="roles">Role names.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetMetadataWriteRoles(string[] roles) { _aclMetaWrite = roles; return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, string value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, int value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, int? value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, long value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, long? value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, float value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, float? value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, double value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, double? value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, decimal value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, decimal? value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, bool value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomProperty(string key, bool? value) { _customMetadata.Add(key, value); return this; } /// <summary> /// Sets a custom metadata property to a string of raw JSON. /// </summary> /// <param name="key">The key.</param> /// <param name="rawJson">The value.</param> /// <returns>The builder.</returns> public StreamMetadataBuilder SetCustomPropertyWithValueAsRawJsonString(string key, string rawJson) { _customMetadata.Add(key, JToken.Parse(rawJson)); return this; } } }
// 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.IO; using System.Xml; using System.Security; using System.Reflection; using System.Collections; using System.Diagnostics; using System.Globalization; using Microsoft.Build.BuildEngine.Shared; using Microsoft.Build.Framework; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class is used to track tasks used by a project. Tasks are declared in project files with the &lt;UsingTask&gt; tag. /// Task and assembly names must be specified per .NET guidelines, however, the names do not need to be fully qualified if /// they provide enough information to locate the tasks they refer to. Assemblies can also be referred to using file paths -- /// this is useful when it is not possible/desirable to place task assemblies in the GAC, or in the same directory as MSBuild. /// </summary> /// <remarks> /// 1) specifying a task assembly using BOTH its assembly name (strong or weak) AND its file path is not allowed /// 2) when specifying the assembly name, the file extension (usually ".dll") must NOT be specified /// 3) when specifying the assembly file, the file extension MUST be specified /// </remarks> /// <example> /// &lt;UsingTask TaskName="Microsoft.Build.Tasks.Csc" ==> look for the "Csc" task in the /// AssemblyName="Microsoft.Build.Tasks"/&gt; weakly-named "Microsoft.Build.Tasks" assembly /// /// &lt;UsingTask TaskName="t1" ==> look for the "t1" task in the /// AssemblyName="mytasks, Culture=en, Version=1.0.0.0"/&gt; strongly-named "mytasks" assembly /// /// &lt;UsingTask TaskName="foo" ==> look for the "foo" task in the /// AssemblyFile="$(MyDownloadedTasks)\utiltasks.dll"/&gt; "utiltasks" assembly file /// /// &lt;UsingTask TaskName="UtilTasks.Bar" ==> invalid task declaration /// AssemblyName="utiltasks.dll" /// AssemblyFile="$(MyDownloadedTasks)\"/&gt; /// </example> /// <owner>SumedhK</owner> internal sealed class TaskRegistry : ITaskRegistry { #region Constructors /// <summary> /// Default constructor does no work because the tables are initialized lazily when a task is registered /// </summary> internal TaskRegistry() { registeredTasks = null; } #endregion #region Properties /// <summary> /// Gets the collection of task declarations created by parsing the &lt;UsingTask&gt; XML. /// Used for unit tests only. /// </summary> internal Hashtable AllTaskDeclarations { get { return registeredTasks; } } #endregion #region Methods /// <summary> /// Removes all entries from the registry. /// </summary> public void Clear() { // The hashtables are lazily allocated if they are needed if (registeredTasks != null) { cachedTaskClassesWithExactMatch.Clear(); cachedTaskClassesWithFuzzyMatch.Clear(); registeredTasks.Clear(); } } /// <summary> /// Given a task name, this method retrieves the task class. If the task has been requested before, it will be found in /// the class cache; otherwise, &lt;UsingTask&gt; declarations will be used to search the appropriate assemblies. /// </summary> /// <param name="taskName"></param> /// <param name="taskProjectFile"></param> /// <param name="taskNode"></param> /// <param name="exactMatchRequired"></param> /// <param name="loggingServices"></param> /// <param name="buildEventContext"></param> /// <param name="taskClass"></param> /// <returns>true, if task is found</returns> public bool GetRegisteredTask ( string taskName, string taskProjectFile, XmlNode taskNode, bool exactMatchRequired, EngineLoggingServices loggingServices, BuildEventContext buildEventContext, out LoadedType taskClass ) { taskClass = null; // If there are no using tags in the project don't bother caching or looking for tasks if (registeredTasks == null) { return false; } Hashtable cachedTaskClasses = exactMatchRequired ? this.cachedTaskClassesWithExactMatch : this.cachedTaskClassesWithFuzzyMatch; if (cachedTaskClasses.Contains(taskName)) { // Caller has asked us before for this same task name, and for the same value of "bool exactMatchRequired". // Return whatever the previous result was, even if it was null. Why would the result be different than // it was before? NOTE: Hash tables CAN have "null" as their value, and this still returns "true" for Contains(...). taskClass = (LoadedType) cachedTaskClasses[taskName]; } else { Hashtable registeredTasksFound; // look for the given task name in the registry; if not found, gather all registered task names that partially // match the given name if (FindRegisteredTasks(taskName, exactMatchRequired, out registeredTasksFound)) { foreach (DictionaryEntry registeredTaskFound in registeredTasksFound) { string mostSpecificTaskName = (string)registeredTaskFound.Key; // if the given task name is longer than the registered task name if (taskName.Length > ((string)registeredTaskFound.Key).Length) { // we will use the longer name to help disambiguate between multiple matches mostSpecificTaskName = taskName; } if (GetTaskFromAssembly(mostSpecificTaskName, (ArrayList)registeredTaskFound.Value, taskProjectFile, taskNode, loggingServices, buildEventContext, out taskClass)) { // Whilst we are within the processing of the task, we haven't actually started executing it, so // our using task message needs to be in the context of the target. However any errors should be reported // at the point where the task appears in the project. BuildEventContext usingTaskContext = new BuildEventContext(buildEventContext.NodeId, buildEventContext.TargetId, buildEventContext.ProjectContextId, BuildEventContext.InvalidTaskId); loggingServices.LogComment(usingTaskContext, "TaskFound", taskName, taskClass.Assembly.ToString()); break; } } } // Cache the result, even if it is null. We should never again do the work we just did, for this task name. cachedTaskClasses[taskName] = taskClass; } return (taskClass != null); } /// <summary> /// Searches all task declarations for the given task name. If no exact match is found, looks for partial matches. /// </summary> /// <remarks> /// It is possible to get multiple partial matches for a task name that is not fully qualified. /// NOTE: this method is marked internal for unit testing purposes only. /// </remarks> /// <param name="taskName"></param> /// <param name="exactMatchRequired"></param> /// <param name="registeredTasksFound"></param> /// <returns>true, if given task name matches one or more task declarations</returns> internal bool FindRegisteredTasks(string taskName, bool exactMatchRequired, out Hashtable registeredTasksFound) { registeredTasksFound = new Hashtable(StringComparer.OrdinalIgnoreCase); ArrayList taskAssemblies = registeredTasks != null ? (ArrayList)registeredTasks[taskName] : null; // if we find an exact match if (taskAssemblies != null) { // we're done registeredTasksFound[taskName] = taskAssemblies; } else if (!exactMatchRequired) { // look through all task declarations for partial matches foreach (DictionaryEntry registeredTask in registeredTasks) { if (TypeLoader.IsPartialTypeNameMatch(taskName, (string)registeredTask.Key)) { registeredTasksFound[registeredTask.Key] = registeredTask.Value; } } } return (registeredTasksFound.Count > 0); } /// <summary> /// Given a task name and a list of assemblies, this helper method checks if the task exists in any of the assemblies. /// </summary> /// <remarks> /// If the task name is fully qualified, then a match (if any) is unambiguous; otherwise, if there are multiple tasks with /// the same name in different namespaces/assemblies, the first task found will be returned. /// </remarks> /// <param name="taskName"></param> /// <param name="taskAssemblies"></param> /// <param name="taskProjectFile"></param> /// <param name="taskNode"></param> /// <param name="loggingServices"></param> /// <param name="buildEventContext"></param> /// <param name="taskClass"></param> /// <returns>true, if task is successfully loaded</returns> private bool GetTaskFromAssembly ( string taskName, ArrayList taskAssemblies, string taskProjectFile, XmlNode taskNode, EngineLoggingServices loggingServices, BuildEventContext buildEventContext, out LoadedType taskClass ) { taskClass = null; foreach (AssemblyLoadInfo assembly in taskAssemblies) { try { taskClass = typeLoader.Load(taskName, assembly); } catch (TargetInvocationException e) { // Exception thrown by the called code itself // Log the stack, so the task vendor can fix their code ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskLoadFailure", taskName, assembly.ToString(), Environment.NewLine + e.InnerException.ToString()); } catch (ReflectionTypeLoadException e) { // ReflectionTypeLoadException.LoaderExceptions may contain nulls foreach (Exception exception in e.LoaderExceptions) { if (exception != null) { loggingServices.LogError(buildEventContext, new BuildEventFileInfo(taskProjectFile), "TaskLoadFailure", taskName, assembly.ToString(), exception.Message); } } ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskLoadFailure", taskName, assembly.ToString(), e.Message); } catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) throw; ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskLoadFailure", taskName, assembly.ToString(), e.Message); } if (taskClass != null) { return true; } } return false; } /// <summary> /// Reads the given &lt;UsingTask&gt; tag and saves the task information specified in it. /// </summary> /// <param name="usingTask"></param> /// <param name="expander"></param> /// <param name="loggingServices"></param> /// <param name="buildEventContext"></param> public void RegisterTask(UsingTask usingTask, Expander expander, EngineLoggingServices loggingServices, BuildEventContext buildEventContext) { if ( // if the <UsingTask> tag doesn't have a condition on it (usingTask.Condition == null) || // or if the condition holds Utilities.EvaluateCondition(usingTask.Condition, usingTask.ConditionAttribute, expander, null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists, loggingServices, buildEventContext) ) { // Lazily allocate the hashtables if they are needed if (registeredTasks == null) { cachedTaskClassesWithExactMatch = new Hashtable(StringComparer.OrdinalIgnoreCase); cachedTaskClassesWithFuzzyMatch = new Hashtable(StringComparer.OrdinalIgnoreCase); registeredTasks = new Hashtable(StringComparer.OrdinalIgnoreCase); } string assemblyName = null; string assemblyFile = null; if (usingTask.AssemblyName != null) { // expand out all embedded properties and items in the assembly name assemblyName = expander.ExpandAllIntoString(usingTask.AssemblyName, usingTask.AssemblyNameAttribute); ProjectErrorUtilities.VerifyThrowInvalidProject(assemblyName.Length > 0, usingTask.AssemblyNameAttribute, "InvalidEvaluatedAttributeValue", assemblyName, usingTask.AssemblyName, XMakeAttributes.assemblyName, XMakeElements.usingTask); } else { // expand out all embedded properties and items in the assembly file/path assemblyFile = expander.ExpandAllIntoString(usingTask.AssemblyFile, usingTask.AssemblyFileAttribute); ProjectErrorUtilities.VerifyThrowInvalidProject(assemblyFile.Length > 0, usingTask.AssemblyFileAttribute, "InvalidEvaluatedAttributeValue", assemblyFile, usingTask.AssemblyFile, XMakeAttributes.assemblyFile, XMakeElements.usingTask); // figure out the directory of the project in which this <UsingTask> node was defined string projectFile = XmlUtilities.GetXmlNodeFile(usingTask.TaskNameAttribute.OwnerElement, String.Empty); string projectDir = (projectFile.Length > 0) ? Path.GetDirectoryName(projectFile) : String.Empty; // ensure the assembly file/path is relative to the project in which this <UsingTask> node was defined -- we // don't want paths from imported projects being interpreted relative to the main project file try { assemblyFile = Path.Combine(projectDir, assemblyFile); } catch (ArgumentException ex) { // Invalid chars in AssemblyFile path ProjectErrorUtilities.VerifyThrowInvalidProject(false, usingTask.AssemblyFileAttribute, "InvalidAttributeValueWithException", assemblyFile, XMakeAttributes.assemblyFile, XMakeElements.usingTask, ex.Message); } } AssemblyLoadInfo taskAssembly = new AssemblyLoadInfo(assemblyName, assemblyFile); // expand out all embedded properties and items string taskName = expander.ExpandAllIntoString(usingTask.TaskName, usingTask.TaskNameAttribute); ProjectErrorUtilities.VerifyThrowInvalidProject(taskName.Length > 0, usingTask.TaskNameAttribute, "InvalidEvaluatedAttributeValue", taskName, usingTask.TaskName, XMakeAttributes.taskName, XMakeElements.usingTask); // since more than one task can have the same name, we want to keep track of all assemblies that are declared to // contain tasks with a given name... ArrayList taskAssemblies = (ArrayList)registeredTasks[taskName]; if (taskAssemblies == null) { taskAssemblies = new ArrayList(); registeredTasks[taskName] = taskAssemblies; } taskAssemblies.Add(taskAssembly); } } /// <summary> /// Checks if the given type is a task class. /// </summary> /// <remarks>This method is used as a TypeFilter delegate.</remarks> /// <owner>SumedhK</owner> /// <param name="type"></param> /// <param name="unused"></param> /// <returns>true, if specified type is a task</returns> private static bool IsTaskClass(Type type, object unused) { return (type.IsClass && !type.IsAbstract && (type.GetInterface("ITask") != null)); } #endregion #region Data // cache of tasks that have been verified to exist in their respective assemblies private Hashtable cachedTaskClassesWithExactMatch; private Hashtable cachedTaskClassesWithFuzzyMatch; /// <summary> /// Cache of task declarations i.e. the &lt;UsingTask&gt; tags fed to this registry. /// </summary> private Hashtable registeredTasks; // used for finding tasks when reflecting through assemblies private readonly TypeLoader typeLoader = new TypeLoader(new TypeFilter(IsTaskClass)); #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.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM March 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. [Serializable] public abstract class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; private int _currentEraValue = -1; private bool _isReadOnly = false; // The minimum supported DateTime range for the calendar. public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual CalendarId ID { get { return CalendarId.UNINITIALIZED_VALUE; } } /// // Return the Base calendar ID for calendars that didn't have defined data in calendarData // internal virtual CalendarId BaseCalendarID { get { return ID; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// public bool IsReadOnly { get { return (_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of ICloneable. // //////////////////////////////////////////////////////////////////////// public virtual object Clone() { object o = MemberwiseClone(); ((Calendar)o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState(true); return (clonedCalendar); } internal void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { _isReadOnly = readOnly; } /*=================================CurrentEraValue========================== **Action: This is used to convert CurretEra(0) to an appropriate era value. **Returns: **Arguments: **Exceptions: **Notes: ** The value is from calendar.nlp. ============================================================================*/ internal virtual int CurrentEraValue { get { // The following code assumes that the current era value can not be -1. if (_currentEraValue == -1) { Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID"); _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (_currentEraValue); } } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange, minValue, maxValue))); } Contract.EndContractBlock(); } internal DateTime Add(DateTime time, double value, int scale) { // From ECMA CLI spec, Partition III, section 3.27: // // If overflow occurs converting a floating-point type to an integer, or if the floating-point value // being converted to an integer is a NaN, the value returned is unspecified. // // Based upon this, this method should be performing the comparison against the double // before attempting a cast. Otherwise, the result is undefined. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue); } long millis = (long)tempMillis; long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return (Add(time, milliseconds, 1)); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays(DateTime time, int days) { return (Add(time, days, MillisPerDay)); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours(DateTime time, int hours) { return (Add(time, hours, MillisPerHour)); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes(DateTime time, int minutes) { return (Add(time, minutes, MillisPerMinute)); } // 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 abstract DateTime AddMonths(DateTime time, int months); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, MillisPerSecond); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks(DateTime time, int weeks) { return (AddDays(time, weeks * 7)); } // 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 abstract DateTime AddYears(DateTime time, int years); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth(DateTime time); // 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 abstract DayOfWeek GetDayOfWeek(DateTime time); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear(DateTime time); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth(int year, int month) { return (GetDaysInMonth(year, month, CurrentEra)); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth(int year, int month, int era); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear(int year) { return (GetDaysInYear(year, CurrentEra)); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear(int year, int era); // Returns the era for the specified DateTime value. public abstract int GetEra(DateTime time); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour(DateTime time) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds(DateTime time) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute(DateTime time) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth(DateTime time); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear(int year) { return (GetMonthsInYear(year, CurrentEra)); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear(int year, int era); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond(DateTime time) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day / 7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7; // Calculate the offset (how many days from the start of the year to the start of the week) int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7; if (offset == 0 || offset >= minimumDaysInFirstWeek) { // First of year falls in the first week of the year return 1; } int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7); // starting from first day of the year, how many days do you have to go forward // before getting to the first day of the week? int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7; int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek; if (daysInInitialPartialWeek >= minimumDaysInFirstWeek) { // If the offset is greater than the minimum Days in the first week, it means that // First of year is part of the first week of the year even though it is only a partial week // add another week day += 7; } return (day / 7 + 1); } // it would be nice to make this abstract but we can't since that would break previous implementations protected virtual int DaysInYearBeforeMinSupportedYear { get { return 365; } } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear(DateTime time); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay(int year, int month, int day) { return (IsLeapDay(year, month, day, CurrentEra)); } // 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 abstract bool IsLeapDay(int year, int month, int day, int era); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth(int year, int month) { return (IsLeapMonth(year, month, CurrentEra)); } // 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 abstract bool IsLeapMonth(int year, int month, int era); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth(int year) { return (GetLeapMonth(year, CurrentEra)); } // 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 virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) return 0; int monthsCount = GetMonthsInYear(year, era); for (int month = 1; month <= monthsCount; month++) { if (IsLeapMonth(year, month, era)) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear(int year) { return (IsLeapYear(year, CurrentEra)); } // 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 abstract bool IsLeapYear(int year, int era); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime)); } internal virtual bool IsValidMonth(int year, int month, int era) { return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era)); } internal virtual bool IsValidDay(int year, int month, int day, int era) { return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era)); } // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.InvariantCulture, SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1))); } return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue) { // Call nativeGetTwoDigitYearMax int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID); if (twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } }
// Copyright 2010 Chris Patterson // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Stact.Workflow { using System; using System.Linq.Expressions; using Configuration; using Magnum.Extensions; public static class StateMachineConfiguratorExtensions { static void DoNothing<T>(T configurator) { } /// <summary> /// Selects a state to which events can be added /// </summary> /// <typeparam name="TWorkflow"></typeparam> /// <typeparam name="TInstance"></typeparam> /// <param name="stateMachineConfigurator"></param> /// <param name="stateExpression"></param> /// <returns></returns> public static StateConfigurator<TWorkflow, TInstance> During<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator, Expression<Func<TWorkflow, State>> stateExpression) where TWorkflow : class where TInstance : class { return stateMachineConfigurator.During(stateExpression, DoNothing); } public static StateConfigurator<TWorkflow, TInstance> During<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator, Expression<Func<TWorkflow, State>> stateExpression, Action<StateConfigurator<TWorkflow, TInstance>> configurationAction) where TWorkflow : class where TInstance : class { var configurator = new StateConfiguratorImpl<TWorkflow, TInstance>(stateMachineConfigurator, stateExpression); stateMachineConfigurator.AddConfigurator(configurator); configurationAction(configurator); return configurator; } /// <summary> /// The initial state for a workflow (named Initial) to which events can be attached /// </summary> /// <typeparam name="TWorkflow"></typeparam> /// <typeparam name="TInstance"></typeparam> /// <param name="stateMachineConfigurator"></param> /// <returns></returns> public static StateConfigurator<TWorkflow, TInstance> Initially<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator) where TWorkflow : class where TInstance : class { return stateMachineConfigurator.Initially(DoNothing); } public static StateConfigurator<TWorkflow, TInstance> Initially<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator, Action<StateConfigurator<TWorkflow, TInstance>> configurationAction) where TWorkflow : class where TInstance : class { var configurator = new StateConfiguratorImpl<TWorkflow, TInstance>(stateMachineConfigurator, StateMachineWorkflow.InitialStateName); stateMachineConfigurator.AddConfigurator(configurator); configurationAction(configurator); return configurator; } /// <summary> /// Finally is triggered upon entry to the Final state /// </summary> /// <typeparam name="TWorkflow"></typeparam> /// <typeparam name="TInstance"></typeparam> /// <param name="stateMachineConfigurator"></param> /// <returns></returns> public static ActivityConfigurator<TWorkflow, TInstance> Finally<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator) where TWorkflow : class where TInstance : class { return stateMachineConfigurator.Finally(DoNothing); } /// <summary> /// Finally is triggered upon entry to the Final state /// </summary> /// <typeparam name="TWorkflow"></typeparam> /// <typeparam name="TInstance"></typeparam> /// <param name="stateMachineConfigurator"></param> /// <param name="configurationAction"></param> /// <returns></returns> public static ActivityConfigurator<TWorkflow, TInstance> Finally<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator, Action<ActivityConfigurator<TWorkflow, TInstance>> configurationAction) where TWorkflow : class where TInstance : class { var stateConfigurator = stateMachineConfigurator.DuringAny(); Expression<Func<State, Event>> selector = x => x.Entry; string eventName = StateMachineWorkflow.FinalStateName + "." + selector.MemberName(); var activityConfigurator = new SimpleActivityConfigurator<TWorkflow, TInstance>(stateConfigurator, eventName); stateConfigurator.AddConfigurator(activityConfigurator); configurationAction(activityConfigurator); return activityConfigurator; } public static StateConfigurator<TWorkflow, TInstance> DuringAny<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator, Action<StateConfigurator<TWorkflow, TInstance>> configurationAction) where TWorkflow : class where TInstance : class { var stateConfigurator = new AnyStateConfigurator<TWorkflow, TInstance>(); stateMachineConfigurator.AddConfigurator(stateConfigurator); configurationAction(stateConfigurator); return stateConfigurator; } public static StateConfigurator<TWorkflow, TInstance> DuringAny<TWorkflow, TInstance>( this StateMachineConfigurator<TWorkflow, TInstance> stateMachineConfigurator) where TWorkflow : class where TInstance : class { var stateConfigurator = new AnyStateConfigurator<TWorkflow, TInstance>(); stateMachineConfigurator.AddConfigurator(stateConfigurator); return stateConfigurator; } /// <summary> /// Selects an event that is accepted during the specified state /// </summary> /// <typeparam name="TWorkflow"></typeparam> /// <typeparam name="TInstance"></typeparam> /// <param name="stateConfigurator"></param> /// <param name="eventExpression"></param> /// <returns></returns> public static ActivityConfigurator<TWorkflow, TInstance> When<TWorkflow, TInstance>( this StateConfigurator<TWorkflow, TInstance> stateConfigurator, Expression<Func<TWorkflow, Event>> eventExpression) where TWorkflow : class where TInstance : class { return stateConfigurator.When(eventExpression, DoNothing); } public static ActivityConfigurator<TWorkflow, TInstance> When<TWorkflow, TInstance>( this StateConfigurator<TWorkflow, TInstance> stateConfigurator, Expression<Func<TWorkflow, Event>> eventExpression, Action<ActivityConfigurator<TWorkflow, TInstance>> configurationAction) where TWorkflow : class where TInstance : class { var configurator = new SimpleActivityConfigurator<TWorkflow, TInstance>(stateConfigurator, eventExpression); stateConfigurator.AddConfigurator(configurator); configurationAction(configurator); return configurator; } /// <summary> /// Selects an event that is accepted during the specified state /// </summary> /// <typeparam name="TWorkflow"></typeparam> /// <typeparam name="TInstance"></typeparam> /// <typeparam name="TBody"></typeparam> /// <param name="stateConfigurator"></param> /// <param name="eventExpression"></param> /// <returns></returns> public static ActivityConfigurator<TWorkflow, TInstance, TBody> When<TWorkflow, TInstance, TBody>( this StateConfigurator<TWorkflow, TInstance> stateConfigurator, Expression<Func<TWorkflow, Event<TBody>>> eventExpression) where TWorkflow : class where TInstance : class { return stateConfigurator.When(eventExpression, DoNothing); } public static ActivityConfigurator<TWorkflow, TInstance, TBody> When<TWorkflow, TInstance, TBody>( this StateConfigurator<TWorkflow, TInstance> stateConfigurator, Expression<Func<TWorkflow, Event<TBody>>> eventExpression, Action<ActivityConfigurator<TWorkflow, TInstance, TBody>> configurationAction) where TWorkflow : class where TInstance : class { var configurator = new MessageActivityConfigurator<TWorkflow, TInstance, TBody>(stateConfigurator, eventExpression); stateConfigurator.AddConfigurator(configurator); configurationAction(configurator); return configurator; } /// <summary> /// Transition the state machine workflow to the Final state /// </summary> /// <typeparam name="TWorkflow"></typeparam> /// <typeparam name="TInstance"></typeparam> /// <param name="activityConfigurator"></param> /// <returns></returns> public static ActivityConfigurator<TWorkflow, TInstance> Finalize<TWorkflow, TInstance>( this ActivityConfigurator<TWorkflow, TInstance> activityConfigurator) where TWorkflow : class where TInstance : class { var configurator = new TransitionConfigurator<TWorkflow, TInstance>(StateMachineWorkflow.FinalStateName); activityConfigurator.AddConfigurator(configurator); return activityConfigurator; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Linq; namespace Python.Runtime { /// <summary> /// Common base class for all objects that are implemented in managed /// code. It defines the common fields that associate CLR and Python /// objects and common utilities to convert between those identities. /// </summary> [Serializable] internal abstract class ManagedType { /// <summary> /// Given a Python object, return the associated managed object or null. /// </summary> internal static ManagedType? GetManagedObject(BorrowedReference ob) { if (ob != null) { BorrowedReference tp = Runtime.PyObject_TYPE(ob); var flags = PyType.GetFlags(tp); if ((flags & TypeFlags.HasClrInstance) != 0) { var gc = TryGetGCHandle(ob, tp); return (ManagedType?)gc?.Target; } } return null; } internal static bool IsInstanceOfManagedType(BorrowedReference ob) { if (ob != null) { BorrowedReference tp = Runtime.PyObject_TYPE(ob); if (tp == Runtime.PyTypeType || tp == Runtime.PyCLRMetaType) { tp = ob; } return IsManagedType(tp); } return false; } internal static bool IsManagedType(BorrowedReference type) { var flags = PyType.GetFlags(type); return (flags & TypeFlags.HasClrInstance) != 0; } internal static BorrowedReference GetUnmanagedBaseType(BorrowedReference managedType) { Debug.Assert(managedType != null && IsManagedType(managedType)); do { managedType = PyType.GetBase(managedType); Debug.Assert(managedType != null); } while (IsManagedType(managedType)); return managedType; } internal unsafe static int PyVisit(BorrowedReference ob, IntPtr visit, IntPtr arg) { if (ob == null) { return 0; } var visitFunc = (delegate* unmanaged[Cdecl]<BorrowedReference, IntPtr, int>)(visit); return visitFunc(ob, arg); } internal static unsafe void DecrefTypeAndFree(StolenReference ob) { if (ob == null) throw new ArgumentNullException(nameof(ob)); var borrowed = new BorrowedReference(ob.DangerousGetAddress()); var type = Runtime.PyObject_TYPE(borrowed); var freePtr = Util.ReadIntPtr(type, TypeOffset.tp_free); Debug.Assert(freePtr != IntPtr.Zero); var free = (delegate* unmanaged[Cdecl]<StolenReference, void>)freePtr; free(ob); Runtime.XDecref(StolenReference.DangerousFromPointer(type.DangerousGetAddress())); } internal static int CallClear(BorrowedReference ob) => CallTypeClear(ob, Runtime.PyObject_TYPE(ob)); /// <summary> /// Wrapper for calling tp_clear /// </summary> internal static unsafe int CallTypeClear(BorrowedReference ob, BorrowedReference tp) { if (ob == null) throw new ArgumentNullException(nameof(ob)); if (tp == null) throw new ArgumentNullException(nameof(tp)); var clearPtr = Util.ReadIntPtr(tp, TypeOffset.tp_clear); if (clearPtr == IntPtr.Zero) { return 0; } var clearFunc = (delegate* unmanaged[Cdecl]<BorrowedReference, int>)clearPtr; return clearFunc(ob); } internal Dictionary<string, object?>? Save(BorrowedReference ob) { return OnSave(ob); } internal void Load(BorrowedReference ob, Dictionary<string, object?>? context) { OnLoad(ob, context); } protected virtual Dictionary<string, object?>? OnSave(BorrowedReference ob) => null; protected virtual void OnLoad(BorrowedReference ob, Dictionary<string, object?>? context) { } /// <summary> /// Initializes given object, or returns <c>false</c> and sets Python error on failure /// </summary> public virtual bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) { // this just calls obj.__init__(*args, **kw) using var init = Runtime.PyObject_GetAttr(obj, PyIdentifier.__init__); Runtime.PyErr_Clear(); if (!init.IsNull()) { using var result = Runtime.PyObject_Call(init.Borrow(), args, kw); if (result.IsNull()) { return false; } } return true; } protected static void ClearObjectDict(BorrowedReference ob) { BorrowedReference type = Runtime.PyObject_TYPE(ob); int instanceDictOffset = Util.ReadInt32(type, TypeOffset.tp_dictoffset); Debug.Assert(instanceDictOffset > 0); Runtime.Py_CLEAR(ob, instanceDictOffset); } protected static BorrowedReference GetObjectDict(BorrowedReference ob) { BorrowedReference type = Runtime.PyObject_TYPE(ob); int instanceDictOffset = Util.ReadInt32(type, TypeOffset.tp_dictoffset); Debug.Assert(instanceDictOffset > 0); return Util.ReadRef(ob, instanceDictOffset); } protected static void SetObjectDict(BorrowedReference ob, StolenReference value) { if (value.Pointer == IntPtr.Zero) throw new ArgumentNullException(nameof(value)); SetObjectDictNullable(ob, value.AnalyzerWorkaround()); } protected static void SetObjectDictNullable(BorrowedReference ob, StolenReference value) { BorrowedReference type = Runtime.PyObject_TYPE(ob); int instanceDictOffset = Util.ReadInt32(type, TypeOffset.tp_dictoffset); Debug.Assert(instanceDictOffset > 0); Runtime.ReplaceReference(ob, instanceDictOffset, value.AnalyzerWorkaround()); } internal static void GetGCHandle(BorrowedReference reflectedClrObject, BorrowedReference type, out IntPtr handle) { Debug.Assert(reflectedClrObject != null); Debug.Assert(IsManagedType(type) || IsManagedType(reflectedClrObject)); Debug.Assert(Runtime.PyObject_TypeCheck(reflectedClrObject, type)); int gcHandleOffset = Util.ReadInt32(type, Offsets.tp_clr_inst_offset); Debug.Assert(gcHandleOffset > 0); handle = Util.ReadIntPtr(reflectedClrObject, gcHandleOffset); } internal static GCHandle? TryGetGCHandle(BorrowedReference reflectedClrObject, BorrowedReference type) { GetGCHandle(reflectedClrObject, type, out IntPtr handle); return handle == IntPtr.Zero ? null : (GCHandle)handle; } internal static GCHandle? TryGetGCHandle(BorrowedReference reflectedClrObject) { BorrowedReference reflectedType = Runtime.PyObject_TYPE(reflectedClrObject); return TryGetGCHandle(reflectedClrObject, reflectedType); } internal static GCHandle GetGCHandle(BorrowedReference reflectedClrObject) => TryGetGCHandle(reflectedClrObject) ?? throw new InvalidOperationException(); internal static GCHandle GetGCHandle(BorrowedReference reflectedClrObject, BorrowedReference type) => TryGetGCHandle(reflectedClrObject, type) ?? throw new InvalidOperationException(); internal static void InitGCHandle(BorrowedReference reflectedClrObject, BorrowedReference type, GCHandle handle) { Debug.Assert(TryGetGCHandle(reflectedClrObject) == null); SetGCHandle(reflectedClrObject, type: type, handle); } internal static void InitGCHandle(BorrowedReference reflectedClrObject, GCHandle handle) => InitGCHandle(reflectedClrObject, Runtime.PyObject_TYPE(reflectedClrObject), handle); internal static void SetGCHandle(BorrowedReference reflectedClrObject, BorrowedReference type, GCHandle newHandle) { Debug.Assert(type != null); Debug.Assert(reflectedClrObject != null); Debug.Assert(IsManagedType(type) || IsManagedType(reflectedClrObject)); Debug.Assert(Runtime.PyObject_TypeCheck(reflectedClrObject, type)); int offset = Util.ReadInt32(type, Offsets.tp_clr_inst_offset); Debug.Assert(offset > 0); Util.WriteIntPtr(reflectedClrObject, offset, (IntPtr)newHandle); } internal static void SetGCHandle(BorrowedReference reflectedClrObject, GCHandle newHandle) => SetGCHandle(reflectedClrObject, Runtime.PyObject_TYPE(reflectedClrObject), newHandle); internal static bool TryFreeGCHandle(BorrowedReference reflectedClrObject) => TryFreeGCHandle(reflectedClrObject, Runtime.PyObject_TYPE(reflectedClrObject)); internal static bool TryFreeGCHandle(BorrowedReference reflectedClrObject, BorrowedReference type) { Debug.Assert(type != null); Debug.Assert(reflectedClrObject != null); Debug.Assert(IsManagedType(type) || IsManagedType(reflectedClrObject)); Debug.Assert(Runtime.PyObject_TypeCheck(reflectedClrObject, type)); int offset = Util.ReadInt32(type, Offsets.tp_clr_inst_offset); Debug.Assert(offset > 0); IntPtr raw = Util.ReadIntPtr(reflectedClrObject, offset); if (raw == IntPtr.Zero) return false; var handle = (GCHandle)raw; handle.Free(); Util.WriteIntPtr(reflectedClrObject, offset, IntPtr.Zero); return true; } internal static class Offsets { static Offsets() { int pyTypeSize = Util.ReadInt32(Runtime.PyTypeType, TypeOffset.tp_basicsize); if (pyTypeSize < 0) throw new InvalidOperationException(); tp_clr_inst_offset = pyTypeSize; tp_clr_inst = tp_clr_inst_offset + IntPtr.Size; } public static int tp_clr_inst_offset { get; } public static int tp_clr_inst { get; } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Diagnostics; namespace m { public class LevelFrame : System.Windows.Forms.Form, ICommandTarget { private System.ComponentModel.Container components = null; private System.Windows.Forms.Splitter splitter; Document m_doc; LevelViewParent m_viewTop; LevelViewParent m_viewBottom; float m_nSplitRatio; static ArrayList s_alsFrames = new ArrayList(); bool m_fNoRecurse = false; public LevelFrame(Form frmParent, Document doc, Type typeView) { InitializeComponent(); LevelDocTemplate doct = (LevelDocTemplate)DocManager.FindDocTemplate(typeof(LevelDoc)); doct.DocActive += new LevelDocTemplate.DocActiveHandler(LevelDocTemplate_DocActive); m_doc = doc; doc.PathChanged += new Document.PathChangedHandler(Document_PathChanged); doc.ModifiedChanged += new Document.ModifiedChangedHandler(Document_ModifiedChanged); doc.OpenCountChanged += new Document.OpenCountChangedHandler(Document_OpenCountChanged); ((LevelDoc)doc).NameChanged += new LevelDoc.NameChangedHandler(LevelDoc_NameChanged); // Parent this and create panes MdiParent = frmParent; ChangePanes(2); // See if the top most mdi frame is maximized. If so, maximize this too // If no window around, maximize bool fMaximize = true; if (frmParent.ActiveMdiChild != null) { if (frmParent.ActiveMdiChild.WindowState != FormWindowState.Maximized) fMaximize = false; } if (fMaximize) WindowState = FormWindowState.Maximized; // Set Title s_alsFrames.Add(this); SetTitle(); // If this doc is active, this is the new command target if (m_doc == DocManager.GetActiveDocument(typeof(LevelDoc))) DocManager.SetCommandTarget(this); // Show Show(); } public void DispatchCommand(Command cmd) { if (m_viewTop.ContainsFocus) { m_viewTop.DispatchCommand(cmd); } if (m_viewBottom.ContainsFocus) { m_viewBottom.DispatchCommand(cmd); } } void Document_ModifiedChanged(Document doc, bool fModified) { SetTitle(); } void LevelDoc_NameChanged(LevelDoc lvld) { SetTitle(); } void Document_PathChanged(Document doc) { SetTitle(); } void Document_OpenCountChanged(Document doc) { SetTitle(); } void SetTitle() { // Set the window title string strTitle = m_doc.GetName(); string strPath = m_doc.GetPath(); if (strPath != null) strTitle += " (" + strPath + ")"; if (m_doc.GetOpenCount() > 1) strTitle += ":" + (s_alsFrames.IndexOf(this) + 1); if (m_doc.IsModified()) strTitle += "*"; Text = strTitle; } protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.splitter = new System.Windows.Forms.Splitter(); this.SuspendLayout(); // // splitter // this.splitter.BackColor = System.Drawing.Color.PapayaWhip; this.splitter.Dock = System.Windows.Forms.DockStyle.Top; this.splitter.MinExtra = 17; this.splitter.MinSize = 0; this.splitter.Name = "splitter"; this.splitter.Size = new System.Drawing.Size(634, 5); this.splitter.TabIndex = 1; this.splitter.TabStop = false; this.splitter.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.splitter_SplitterMoved); this.splitter.DoubleClick += new System.EventHandler(this.splitter_DoubleClick); // // LevelFrame // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.SystemColors.AppWorkspace; this.ClientSize = new System.Drawing.Size(634, 360); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.splitter}); this.Name = "LevelFrame"; this.Text = "LevelFrame"; this.Closing += new System.ComponentModel.CancelEventHandler(this.LevelFrame_Closing); this.SizeChanged += new System.EventHandler(this.LevelFrame_SizeChanged); this.ResumeLayout(false); } #endregion public Document GetDocument() { return m_doc; } void ChangePanes(int nPaneStateNew) { // If starting, create panes and views if (m_viewTop == null && m_viewBottom == null) { // Bottom full size m_viewBottom = new LevelViewParent(); m_viewBottom.SetDocument(m_doc); m_viewBottom.Dock = DockStyle.Fill; Controls.Add(m_viewBottom); // Top m_viewTop = new LevelViewParent(); m_viewTop.SetDocument(m_doc); m_viewTop.Dock = DockStyle.Top; Controls.Add(m_viewTop); // Set right order for auto formatting Controls.SetChildIndex(m_viewBottom, 0); Controls.SetChildIndex(splitter, 1); Controls.SetChildIndex(m_viewTop, 2); // If state 2 then top pane is zero height if (nPaneStateNew == 2) splitter.SplitPosition = 0; return; } // If closing remove panes and views if (nPaneStateNew == 0) { m_viewTop.Dispose(); Controls.Remove(m_viewTop); m_viewTop = null; m_viewBottom.Dispose(); Controls.Remove(m_viewBottom); m_viewBottom = null; return; } // Have both panes. switch (nPaneStateNew) { case -2: // Expand the top pane: Make top pane the bottom pane, // then make top pane size 0 LevelViewParent viewT = m_viewTop; m_viewTop = m_viewBottom; m_viewBottom = viewT; // Set right order for auto formatting m_viewTop.Dock = DockStyle.Top; m_viewTop.Height = 0; m_viewBottom.Dock = DockStyle.Fill; splitter.SplitPosition = 0; Controls.SetChildIndex(m_viewBottom, 0); Controls.SetChildIndex(splitter, 1); Controls.SetChildIndex(m_viewTop, 2); break; case 2: // Expand the bottom pane: Make top pane 0 size splitter.SplitPosition = 0; break; case 3: // Expand the top pane splitter.SplitPosition = ClientSize.Height / 2; break; } } private void splitter_DoubleClick(object sender, System.EventArgs e) { if (splitter.SplitPosition == 0) { ChangePanes(3); } else { ChangePanes(2); } } private void splitter_SplitterMoved(object sender, System.Windows.Forms.SplitterEventArgs e) { // If splitter at bottom, exchange top pane with bottom and close // out top. if (ClientSize.Height - splitter.SplitPosition <= splitter.MinExtra + 10) { if (!m_fNoRecurse) { m_fNoRecurse = true; ChangePanes(-2); m_fNoRecurse = false; } } // Save away size ratio m_nSplitRatio = (float)splitter.SplitPosition / (float)ClientSize.Height; } private void LevelFrame_Closing(object sender, System.ComponentModel.CancelEventArgs e) { s_alsFrames.Remove(this); if (!m_doc.Close()) { e.Cancel = true; return; } ChangePanes(0); } private void LevelFrame_SizeChanged(object sender, System.EventArgs e) { splitter.SplitPosition = (int)((float)ClientSize.Height * m_nSplitRatio); } // For zorder control when another doc closes void LevelDocTemplate_DocActive(Document doc) { if (m_doc == doc) BringToFront(); } // For z order control when this doc gets clicked on. // Activated event doesn't work consistently // MdiChildActivate on parent doesn't give details about the activation // and is before the activation // This is the resulting hack: public struct WINDOWPOS { public IntPtr hwnd; public IntPtr hwndInsertAfter; public int x; public int y; public int cx; public int cy; public uint flags; } protected unsafe override void WndProc(ref Message m) { switch (m.Msg) { // #define WM_WINDOWPOSCHANGED 0x0047 // #define SWP_NOZORDER 0x0004 case 0x47: WINDOWPOS *ppos = (WINDOWPOS *)m.LParam; if (ppos == null || (ppos->flags & 4) == 0) { DocManager.SetActiveDocument(typeof(LevelDoc), m_doc); DocManager.SetCommandTarget(this); } break; // #define WM_NCACTIVATE 0x0086 case 0x86: if (((ushort)m.WParam) != 0) DocManager.SetCommandTarget(this); break; } base.WndProc(ref m); } } }
namespace PokerTell.PokerHandParsers.Tests.Base { using System.Linq; using NUnit.Framework; using PokerTell.Infrastructure.Enumerations.PokerHand; using PokerTell.Infrastructure.Interfaces.PokerHand; using PokerTell.PokerHand.Aquisition; using PokerTell.PokerHandParsers.Base; using PokerTell.UnitTests.Tools; public abstract class PlayerActionsParserTests { protected PlayerActionsParser _parser; const string PlayerName = "Hero"; [SetUp] public void _Init() { _parser = GetPlayerActionsParser(); } [Test] public void Parse_EmptyString_PlayerActionsAreEmpty() { _parser.Parse(string.Empty, PlayerName); Assert.That(_parser.PlayerActions.Count, Is.EqualTo(0)); } [Test] public void Parse_NoActions_PlayerActionsAreEmpty() { _parser.Parse("noActionsInThis", PlayerName); Assert.That(_parser.PlayerActions.Count, Is.EqualTo(0)); } [Test] [Sequential] public void Parse_PlayerHasOneBetOrCallAction_AddsActionWithRatioToPlayerActions( [Values(ActionTypes.B, ActionTypes.C)] ActionTypes actionType) { const double someRatio = 1.0; var aquiredPokerAction = new AquiredPokerAction(actionType, someRatio); string streetHistory = OneBetOrCallActionFor(PlayerName, aquiredPokerAction); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.First()).IsEqualTo(aquiredPokerAction); } [Test] [Sequential] public void Parse_PlayerHasOnePostingAction_AddsActionWithRatioToPlayerActions( [Values(PostingTypes.Ante, PostingTypes.BigBlind, PostingTypes.SmallBlind)] PostingTypes postingType) { const double someRatio = 1.0; const ActionTypes actionType = ActionTypes.P; var aquiredPokerAction = new AquiredPokerAction(actionType, someRatio); string streetHistory = PostingActionFor(PlayerName, postingType, someRatio); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.First()).IsEqualTo(aquiredPokerAction); } [Test] [Sequential] public void Parse_PlayerHasOneActionWithoutRatio_AddsActionWithoutRatioToPlayerActions( [Values(ActionTypes.F, ActionTypes.X)] ActionTypes actionType) { var aquiredPokerAction = new AquiredPokerAction(actionType, 0); string streetHistory = OneNonRatioActionFor(PlayerName, aquiredPokerAction); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.First().What).IsEqualTo(aquiredPokerAction.What); } [Test] public void Parse_TwoActions_AddsFirstActionAsFirstToPlayerActions() { var action1 = new AquiredPokerAction(ActionTypes.B, 1.0); var action2 = new AquiredPokerAction(ActionTypes.R, 2.0); string streetHistory = OneBetOrCallActionFor(PlayerName, action1) + " \n" + OneRaiseActionFor(PlayerName, action2); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.First()).IsEqualTo(action1); } [Test] public void Parse_TwoActions_AddsSecondActionAsLastToPlayerActions() { var action1 = new AquiredPokerAction(ActionTypes.B, 1.0); var action2 = new AquiredPokerAction(ActionTypes.R, 2.0); string streetHistory = OneBetOrCallActionFor(PlayerName, action1) + " \n" + OneRaiseActionFor(PlayerName, action2); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.Last()).IsEqualTo(action2); } [Test] public void Parse_ContainsActionForOtherPlayers_DoesNotAddAnyActionToPlayerActions() { var action = new AquiredPokerAction(ActionTypes.B, 1.0); string streetHistory = OneBetOrCallActionFor("OtherPlayer", action); _parser.Parse(streetHistory, PlayerName); Assert.That(_parser.PlayerActions.Count, Is.EqualTo(0)); } [Test] public void Parse_PlayerSomeActionAndUncalledBetAction_AddsUncalledBetActionAsLastToPlayerActions() { const double ratio = 1.0; var someAction = new AquiredPokerAction(ActionTypes.B, 1.0); var uncalledBetAction = new AquiredPokerAction(ActionTypes.U, ratio); string streetHistory = OneBetOrCallActionFor(PlayerName, someAction) + " \n" + UncalledBetActionFor(PlayerName, ratio); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.Last()).IsEqualTo(uncalledBetAction); } [Test] public void Parse_PlayerUncalledBetActionAndAllinBetAction_AddsAllinActionAsLastToPlayerActions() { const double ratio = 1.0; var allinAction = new AquiredPokerAction(ActionTypes.A, ratio); string streetHistory = UncalledBetActionFor(PlayerName, ratio) + " \n" + AllinBetActionFor(PlayerName, ratio); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.Last()).IsEqualTo(allinAction); } [Test] public void Parse_PlayerAllinActionAndWinningAction_AddsWinningActionAsLastToPlayerActions() { const double ratio = 1.0; var winningAction = new AquiredPokerAction(ActionTypes.W, ratio); string streetHistory = AllinBetActionFor(PlayerName, ratio) + " \n" + ShowedAndWonFor(PlayerName, ratio); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.Last()).IsEqualTo(winningAction); } [Test] public void Parse_PlayerDidNotShowAndCollected_AddsWinningActionAsLastToPlayerActions() { const double ratio = 1.0; var winningAction = new AquiredPokerAction(ActionTypes.W, ratio); string streetHistory = DidNotShowAndCollectedFor(PlayerName, ratio); _parser.Parse(streetHistory, PlayerName); Affirm.That(_parser.PlayerActions.Last()).IsEqualTo(winningAction); } protected abstract PlayerActionsParser GetPlayerActionsParser(); protected abstract string OneRaiseActionFor(string playerName, IAquiredPokerAction action); protected abstract string OneBetOrCallActionFor(string playerName, IAquiredPokerAction action); protected abstract string PostingActionFor(string playerName, PostingTypes postingType, double ratio); protected abstract string OneNonRatioActionFor(string playerName, IAquiredPokerAction action); protected abstract string UncalledBetActionFor(string playerName, double ratio); protected abstract string AllinBetActionFor(string playerName, double ratio); protected abstract string ShowedAndWonFor(string playerName, double ratio); protected abstract string DidNotShowAndCollectedFor(string playerName, double ratio); public enum PostingTypes { Ante, BigBlind, SmallBlind } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D07_Country_Child (editable child object).<br/> /// This is a generated base class of <see cref="D07_Country_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D06_Country"/> collection. /// </remarks> [Serializable] public partial class D07_Country_Child : BusinessBase<D07_Country_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D07_Country_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="D07_Country_Child"/> object.</returns> internal static D07_Country_Child NewD07_Country_Child() { return DataPortal.CreateChild<D07_Country_Child>(); } /// <summary> /// Factory method. Loads a <see cref="D07_Country_Child"/> object, based on given parameters. /// </summary> /// <param name="country_ID1">The Country_ID1 parameter of the D07_Country_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="D07_Country_Child"/> object.</returns> internal static D07_Country_Child GetD07_Country_Child(int country_ID1) { return DataPortal.FetchChild<D07_Country_Child>(country_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D07_Country_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D07_Country_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D07_Country_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D07_Country_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="country_ID1">The Country ID1.</param> protected void Child_Fetch(int country_ID1) { var args = new DataPortalHookArgs(country_ID1); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<ID07_Country_ChildDal>(); var data = dal.Fetch(country_ID1); Fetch(data); } OnFetchPost(args); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="D07_Country_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D07_Country_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D06_Country parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<ID07_Country_ChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.Country_ID, Country_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="D07_Country_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(D06_Country parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<ID07_Country_ChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.Country_ID, Country_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="D07_Country_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(D06_Country parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<ID07_Country_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Country_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
namespace Fixtures.SwaggerBatBodyDate { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class DateExtensions { /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetNull(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetNullAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetInvalidDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetInvalidDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetInvalidDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetInvalidDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetOverflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetOverflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetOverflowDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetOverflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetUnderflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetUnderflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetUnderflowDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUnderflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='dateBody'> /// </param> public static void PutMaxDate(this IDate operations, DateTime? dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMaxDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutMaxDateAsync( this IDate operations, DateTime? dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMaxDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetMaxDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMaxDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetMaxDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetMaxDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='dateBody'> /// </param> public static void PutMinDate(this IDate operations, DateTime? dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMinDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutMinDateAsync( this IDate operations, DateTime? dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMinDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetMinDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMinDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetMinDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetMinDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } } }