context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using NuPattern.VisualStudio.Properties; using NuPattern.VisualStudio.Solution.Hierarchy.Design; namespace NuPattern.VisualStudio.Solution.Hierarchy { /// <summary> /// Node in the solution explorer /// </summary> [TypeConverter(typeof(HierarchyNodeConverter))] internal class HierarchyNode : IDisposable, IHierarchyNode { #region NativeMethods class private sealed class NativeMethods { private NativeMethods() { } [StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO { public IntPtr hIcon; public IntPtr iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; // use passed dwFileAttribute public const uint SHGFI_ICON = 0x100; public const uint SHGFI_LARGEICON = 0x0; // 'Large icon public const uint SHGFI_SMALLICON = 0x1; // 'Small icon [DllImport(@"shell32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); [DllImport(@"comctl32.dll")] public extern static IntPtr ImageList_GetIcon(IntPtr himl, int i, uint flags); } #endregion /// <summary> /// Constructs a HierarchyNode at the solution root /// </summary> /// <param name="vsSolution"></param> [SecurityCritical] public HierarchyNode(IVsSolution vsSolution) : this(vsSolution, Guid.Empty) { } /// <summary> /// Constructs a HierarchyNode given the unique string identifier /// </summary> /// <param name="vsSolution"></param> /// <param name="projectUniqueName"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsSolution.GetProjectOfUniqueName(System.String,Microsoft.VisualStudio.Shell.Interop.IVsHierarchy@)")] [SecurityCritical] public HierarchyNode(IVsSolution vsSolution, string projectUniqueName) { Guard.NotNull(() => vsSolution, vsSolution); Guard.NotNullOrEmpty(() => projectUniqueName, projectUniqueName); IVsHierarchy rootHierarchy = null; if (projectUniqueName.StartsWith(@"{", StringComparison.OrdinalIgnoreCase) && projectUniqueName.EndsWith(@"}", StringComparison.OrdinalIgnoreCase)) { projectUniqueName = projectUniqueName.Substring(1, projectUniqueName.Length - 2); } if (projectUniqueName.Length == Guid.Empty.ToString().Length && projectUniqueName.Split('-').Length == 5) { Guid projectGuid = new Guid(projectUniqueName); int hr = vsSolution.GetProjectOfGuid(ref projectGuid, out rootHierarchy); Marshal.ThrowExceptionForHR(hr); } else { int hr = vsSolution.GetProjectOfUniqueName(projectUniqueName, out rootHierarchy); if (rootHierarchy == null) { //Thrown if Project doesn't exist on solution throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Properties.Resources.ProjectNode_InvalidProjectUniqueName, projectUniqueName)); } } Init(vsSolution, rootHierarchy, VSConstants.VSITEMID_ROOT); } /// <summary> /// Constructs a HierarchyNode given the projectGuid /// </summary> /// <param name="vsSolution"></param> /// <param name="projectGuid"></param> // FXCOP: False positive [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SecurityCritical] public HierarchyNode(IVsSolution vsSolution, Guid projectGuid) { Guard.NotNull(() => vsSolution, vsSolution); IVsHierarchy rootHierarchy = null; int hr = vsSolution.GetProjectOfGuid(ref projectGuid, out rootHierarchy); if (rootHierarchy == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.HierarchyNode_ProjectDoesNotExist, projectGuid.ToString("b")), Marshal.GetExceptionForHR(hr)); } Init(vsSolution, rootHierarchy, VSConstants.VSITEMID_ROOT); } /// <summary> /// Constructs a hierarchy node at the root level of hierarchy /// </summary> /// <param name="vsSolution"></param> /// <param name="hierarchy"></param> [SecurityCritical] public HierarchyNode(IVsSolution vsSolution, IVsHierarchy hierarchy) { Guard.NotNull(() => vsSolution, vsSolution); Init(vsSolution, hierarchy, VSConstants.VSITEMID_ROOT); } /// <summary> /// Builds a child HierarchyNode from the parent node /// </summary> /// <param name="parent"></param> /// <param name="childId"></param> [SecurityCritical] public HierarchyNode(HierarchyNode parent, uint childId) { Guard.NotNull(() => parent, parent); Init(parent.solution, parent.hierarchy, childId); } /// <summary> /// Queries the type T to the internal hierarchy object /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] public T GetObject<T>() where T : class { return (hierarchy as T); } /// <summary> /// Returns true if this a root node of another node /// </summary> public bool IsRoot { get { return (VSConstants.VSITEMID_ROOT == itemId); } } /// <summary> /// Name of this node /// </summary> public string Name { get { return GetProperty<string>(__VSHPROPID.VSHPROPID_Name); } } /// <summary> /// Document cookie /// </summary> public uint DocCookie { get { return GetProperty<uint>(__VSHPROPID.VSHPROPID_ItemDocCookie); } } /// <summary> /// Name of this node /// </summary> public string CanonicalName { [SecurityCritical] get { string name = string.Empty; int hr = hierarchy.GetCanonicalName(itemId, out name); Marshal.ThrowExceptionForHR(hr); if (name != null) { return name; } return string.Empty; } } /// <summary> /// Returns the unique string that identifies this node in the solution /// </summary> public string UniqueName { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] get { string uniqueName = string.Empty; int hr = solution.GetUniqueNameOfProject(hierarchy, out uniqueName); Marshal.ThrowExceptionForHR(hr); return uniqueName; } } /// <summary> /// Returns the Project GUID /// </summary> public Guid ProjectGuid { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] get { return GetGuidProperty(__VSHPROPID.VSHPROPID_ProjectIDGuid); } } /// <summary> /// Returns true if the current node is the solution root /// </summary> public bool IsSolution { get { return (Parent == null); } } /// <summary> /// Returns the TypeGUID /// </summary> public Guid TypeGuid { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] get { // If the root node is a solution, then there is no TypeGuid if (IsSolution) { return Guid.Empty; } else { return GetGuidProperty(__VSHPROPID.VSHPROPID_TypeGuid, this.ItemId); } } } /// <summary> /// Icon handle of the node /// </summary> public IntPtr IconHandle { get { return new IntPtr(GetProperty<int>(__VSHPROPID.VSHPROPID_IconHandle)); } } /// <summary> /// Icon index of the node /// </summary> public int IconIndex { get { return GetProperty<int>(__VSHPROPID.VSHPROPID_IconIndex); } } /// <summary> /// True if the Icon index of the node is valid /// </summary> public bool HasIconIndex { get { return HasProperty(__VSHPROPID.VSHPROPID_IconIndex); } } /// <summary> /// StateIcon index of the node /// </summary> public int StateIconIndex { get { return GetProperty<int>(__VSHPROPID.VSHPROPID_StateIconIndex); } } /// <summary> /// OverlayIcon index of the node /// </summary> public int OverlayIconIndex { get { return GetProperty<int>(__VSHPROPID.VSHPROPID_OverlayIconIndex); } } /// <summary> /// Imagelist Handle /// </summary> public IntPtr ImageListHandle { get { return new IntPtr(GetProperty<int>(__VSHPROPID.VSHPROPID_IconImgList)); } } private string iconKey; /// <summary> /// Returns the Key to index icons in an image collection /// </summary> public string IconKey { get { if (iconKey == null) { if (HasIconIndex) { iconKey = TypeGuid.ToString(@"b", CultureInfo.InvariantCulture) + @"." + IconIndex.ToString(CultureInfo.InvariantCulture); } else if (IsValidFullPathName(SaveName)) { iconKey = new FileInfo(SaveName).Extension; } else { iconKey = string.Empty; } } return iconKey; } } /// <summary> /// item id /// </summary> private uint itemId; public uint ItemId { get { return itemId; } } /// <summary> /// hierarchy object /// </summary> private IVsHierarchy hierarchy; protected IVsHierarchy Hierarchy { get { return hierarchy; } } /// <summary> /// Solution service /// </summary> private IVsSolution solution; protected IVsSolution Solution { get { return solution; } } protected static bool IsValidFullPathName(string fileName) { Debug.Assert(fileName != null); if (string.IsNullOrEmpty(fileName)) { return false; } int i = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar); if (i == -1) { return IsValidFileName(fileName); } else { string pathPart = fileName.Substring(0, i + 1); if (IsValidPath(pathPart)) { string filePart = fileName.Substring(i + 1); return IsValidFileName(filePart); } } return false; } protected static bool IsValidPath(string pathPart) { Debug.Assert(pathPart != null); if (string.IsNullOrEmpty(pathPart)) { return true; } foreach (char c in System.IO.Path.GetInvalidPathChars()) { if (pathPart.IndexOf(c) != -1) { return false; } } return true; } protected static bool IsValidFileName(string filePart) { Debug.Assert(filePart != null); if (string.IsNullOrEmpty(filePart)) { return false; } foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { if (filePart.IndexOf(c) != -1) { return false; } } return true; } private Icon icon; /// <summary> /// Returns the icon of the node /// </summary> public Icon Icon { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] get { if (icon == null) { if (ImageListHandle != IntPtr.Zero && HasIconIndex) { IntPtr hIcon = NativeMethods.ImageList_GetIcon(ImageListHandle, IconIndex, 0); icon = Icon.FromHandle(hIcon); } else if (IconHandle != IntPtr.Zero) { icon = Icon.FromHandle(IconHandle); } else if (IsValidFullPathName(SaveName)) { // The following comes from kb 319350 NativeMethods.SHFILEINFO shinfo = new NativeMethods.SHFILEINFO(); NativeMethods.SHGetFileInfo( new FileInfo(SaveName).Extension, NativeMethods.FILE_ATTRIBUTE_NORMAL, ref shinfo, (uint)Marshal.SizeOf(shinfo), NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_SMALLICON); if (shinfo.hIcon != IntPtr.Zero) { icon = System.Drawing.Icon.FromHandle(shinfo.hIcon); } } } return icon; } } /// <summary> /// Returns true is there is al least one child under this node /// </summary> public bool HasChildren { get { return (FirstChildId != VSConstants.VSITEMID_NIL); } } /// <summary> /// Returns the item id of the first child /// </summary> public uint FirstChildId { get { //Get the first child node of the current hierarchy being walked // NOTE: to work around a bug with the Solution implementation of VSHPROPID_FirstChild, // we keep track of the recursion level. If we are asking for the first child under // the Solution, we use VSHPROPID_FirstVisibleChild instead of _FirstChild. // In VS 2005 and earlier, the Solution improperly enumerates all nested projects // in the Solution (at any depth) as if they are immediate children of the Solution. // Its implementation _FirstVisibleChild is correct however, and given that there is // not a feature to hide a SolutionFolder or a Project, thus _FirstVisibleChild is // expected to return the identical results as _FirstChild. return GetItemId(GetProperty<object>(IsSolution ? __VSHPROPID.VSHPROPID_FirstVisibleChild : __VSHPROPID.VSHPROPID_FirstChild)); } } /// <summary> /// Gets the next child id from the passed childId /// </summary> /// <param name="childId"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsHierarchy.GetProperty(System.UInt32,System.Int32,System.Object@)")] [SecurityCritical] public uint GetNextChildId(uint childId) { object nextChild = null; // NOTE: to work around a bug with the Solution implementation of VSHPROPID_NextSibling, // we keep track of the recursion level. If we are asking for the next sibling under // the Solution, we use VSHPROPID_NextVisibleSibling instead of _NextSibling. // In VS 2005 and earlier, the Solution improperly enumerates all nested projects // in the Solution (at any depth) as if they are immediate children of the Solution. // Its implementation _NextVisibleSibling is correct however, and given that there is // not a feature to hide a SolutionFolder or a Project, thus _NextVisibleSibling is // expected to return the identical results as _NextSibling. hierarchy.GetProperty(childId, (int)(IsSolution ? __VSHPROPID.VSHPROPID_NextVisibleSibling : __VSHPROPID.VSHPROPID_NextSibling), out nextChild); return GetItemId(nextChild); } /// <summary> /// Returns the file name of the hierarcynode /// </summary> public string SaveName { get { return GetProperty<string>(__VSHPROPID.VSHPROPID_SaveName); } } /// <summary> /// Returns the project directory /// </summary> public string ProjectDir { get { return GetProperty<string>(__VSHPROPID.VSHPROPID_ProjectDir); } } /// <summary> /// Returns the full path /// </summary> /// <returns></returns> public string Path { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] get { string path = string.Empty; if (hierarchy is IVsProject) { int hr = ((IVsProject)hierarchy).GetMkDocument(itemId, out path); Marshal.ThrowExceptionForHR(hr); return path; } else { return string.Empty; } } } public string RelativePath { get { if (IsRoot) { return ProjectDir; } else if (ParentNode != null) { return System.IO.Path.Combine(ParentNode.RelativePath, Name); } else { return Name; } } } /// <summary> /// Returns the extensibility object /// </summary> public object ExtObject { get { return GetProperty<object>(__VSHPROPID.VSHPROPID_ExtObject); } } [SecurityCritical] private Guid GetGuidProperty(__VSHPROPID propId, uint itemid) { Guid guid = Guid.Empty; int hr = hierarchy.GetGuidProperty(itemid, (int)propId, out guid); // in case of failure, we simply trace the error and return silently with an empty guid // so the caller can resolve what to do without blowing out execution with an exception if (hr != 0) Trace.TraceError(Marshal.GetExceptionForHR(hr).ToString()); return guid; } [SecurityCritical] private Guid GetGuidProperty(__VSHPROPID propId) { return GetGuidProperty(propId, VSConstants.VSITEMID_ROOT); } private bool HasProperty(__VSHPROPID propId) { object value = null; int hr = hierarchy.GetProperty(this.itemId, (int)propId, out value); if (hr != VSConstants.S_OK || value == null) { return false; } return true; } private T GetProperty<T>(__VSHPROPID propId, uint itemid) { object value = null; int hr = hierarchy.GetProperty(itemid, (int)propId, out value); if (hr != VSConstants.S_OK || value == null) { return default(T); } return (T)value; } private T GetProperty<T>(__VSHPROPID propId) { return GetProperty<T>(propId, this.itemId); } private static uint GetItemId(object pvar) { if (pvar == null) return VSConstants.VSITEMID_NIL; if (pvar is int) return (uint)(int)pvar; if (pvar is uint) return (uint)pvar; if (pvar is short) return (uint)(short)pvar; if (pvar is ushort) return (uint)(ushort)pvar; if (pvar is long) return (uint)(long)pvar; return VSConstants.VSITEMID_NIL; } [SecurityCritical] public HierarchyNode CreateSolutionFolder(string folderName) { Guard.NotNullOrEmpty(() => folderName, folderName); IntPtr ptr = IntPtr.Zero; Guid solutionFolderGuid = new Guid(Constants.SolutionFolderType); Guid iidProject = typeof(IVsHierarchy).GUID; int hr = solution.CreateProject( ref solutionFolderGuid, null, null, folderName, 0, ref iidProject, out ptr); if (hr == VSConstants.S_OK && ptr != IntPtr.Zero) { IVsHierarchy vsHierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(ptr); Debug.Assert(vsHierarchy != null); return new HierarchyNode(solution, vsHierarchy); } return null; } public HierarchyNode Find(Predicate<HierarchyNode> func) { foreach (HierarchyNode child in this.Children) { if (func(child)) { return child; } } return null; } // FXCOP: False positive [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "child")] public void ForEach(Action<HierarchyNode> func) { foreach (HierarchyNode child in this.Children) { func(child); } } public void RecursiveForEach(Action<HierarchyNode> func) { func(this); foreach (HierarchyNode child in this.Children) { child.RecursiveForEach(func); } } public HierarchyNode RecursiveFind(Predicate<HierarchyNode> func) { if (func(this)) { return this; } foreach (HierarchyNode child in this.Children) { HierarchyNode found = child.RecursiveFind(func); if (found != null) { return found; } } return null; } public HierarchyNode FindByName(string name) { return Find(delegate(HierarchyNode node) { return (node.Name != null && node.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); }); } public HierarchyNode RecursiveFindByName(string name) { if (name.IndexOf(System.IO.Path.DirectorySeparatorChar) == -1) { return RecursiveFind(delegate(HierarchyNode node) { return (node.Name != null && node.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); }); } HierarchyNode folder = null; foreach (string part in name.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)) { folder = folder == null ? this.FindByName(part) : folder.FindByName(part); if (folder == null) { break; } } return folder; } [SecurityCritical] public HierarchyNode FindOrCreateSolutionFolder(string name) { HierarchyNode folder = FindByName(name); if (folder == null) { folder = CreateSolutionFolder(name); } return folder; } public HierarchyNode Parent { get { if (!IsRoot) { return new HierarchyNode(solution, hierarchy); } else { IVsHierarchy vsHierarchy = GetProperty<IVsHierarchy>(__VSHPROPID.VSHPROPID_ParentHierarchy, VSConstants.VSITEMID_ROOT); if (vsHierarchy == null) { return null; } return new HierarchyNode(solution, vsHierarchy); } } } public void Remove() { Debug.Assert(Parent != null); Parent.RemoveItem(itemId); } private bool RemoveItem(uint vsItemId) { IVsProject2 vsProject = hierarchy as IVsProject2; if (vsProject == null) { return false; } int result = 0; int hr = vsProject.RemoveItem(0, vsItemId, out result); return (hr == VSConstants.S_OK && result == 1); } #region IDisposable Members private bool disposed; // Do not make this method virtual. // A derived class should not be able to override this method. public void Dispose() { Dispose(true); // Take yourself off the Finalization queue // to prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } // Dispose(bool disposing) executes in two distinct scenarios. // If disposing equals true, the method has been called directly // or indirectly by a user's code. Managed and unmanaged resources // can be disposed. // If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { // Dispose managed resources. } // Release unmanaged resources. If disposing is false, // only the following code is executed. // Note that this is not thread safe. // Another thread could start disposing the object // after the managed resources are disposed, // but before the disposed flag is set to true. // If thread safety is necessary, it must be // implemented by the client. } disposed = true; } // Use C# destructor syntax for finalization code. // This destructor will run only if the Dispose method // does not get called. // It gives your base class the opportunity to finalize. // Do not provide destructors in types derived from this class. ~HierarchyNode() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } #endregion public IEnumerable<IHierarchyNode> Children { get { return new HierarchyNodeCollection(this); } } [SecurityCritical] private void Init(IVsSolution vsSolution, IVsHierarchy vsHierarchy, uint vsItemId) { this.solution = vsSolution; int hr = VSConstants.E_FAIL; if (vsHierarchy == null) { Guid emptyGuid = Guid.Empty; hr = this.solution.GetProjectOfGuid(ref emptyGuid, out this.hierarchy); Marshal.ThrowExceptionForHR(hr); } else { this.hierarchy = vsHierarchy; } this.itemId = vsItemId; IntPtr nestedHierarchyObj; uint nestedItemId; Guid hierGuid = typeof(IVsHierarchy).GUID; // Check first if this node has a nested hierarchy. If so, then there really are two // identities for this node: 1. hierarchy/itemid 2. nestedHierarchy/nestedItemId. // We will convert this node using the inner nestedHierarchy/nestedItemId identity. hr = this.hierarchy.GetNestedHierarchy(this.itemId, ref hierGuid, out nestedHierarchyObj, out nestedItemId); if (VSConstants.S_OK == hr && IntPtr.Zero != nestedHierarchyObj) { IVsHierarchy nestedHierarchy = Marshal.GetObjectForIUnknown(nestedHierarchyObj) as IVsHierarchy; Marshal.Release(nestedHierarchyObj); // we are responsible to release the refcount on the out IntPtr parameter if (nestedHierarchy != null) { this.hierarchy = nestedHierarchy; this.itemId = nestedItemId; } } } public HierarchyNode ParentNode { get { HierarchyNode parent = this.Parent; if (parent == this) return parent; parent = parent.RecursiveFind(x => x.Children.FirstOrDefault(child => child.ItemId == this.ItemId) != null); return parent; } } public string SolutionRelativeName { get { if (IsSolution) { return string.Empty; } else if (ParentNode != null) { string parentRelativeName = ParentNode.SolutionRelativeName; if (!String.IsNullOrEmpty(parentRelativeName)) return parentRelativeName + System.IO.Path.DirectorySeparatorChar + Name; } return Name; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02.extension02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02.extension02; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a an Extension method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public static class Extension { public static int Foo(this Parent p, dynamic x = null) { return 0; } } public class Parent { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02a.extension02a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02a.extension02a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a an Extension method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public static class Extension { public static int Foo(this Parent p, int? x = 1) { return 0; } } public class Parent { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); try { p.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, e.Message, "Parent", "Foo"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02b.extension02b { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02b.extension02b; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a an Extension method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public static class Extension { public static int Foo(this Parent p, int? x = 1) { return x == null ? 0 : 1; } } public class Parent { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = null; try { p.Foo(d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, e.Message, "Parent", "Foo"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.partial04b.partial04b { public partial class Parent { partial void Foo(int? i = 0); } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.partial04b.partial04b { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a Partial class with OPs</Description> // <Expects status=success></Expects> // <Code> public partial class Parent { public Parent() { TestOk = false; } public bool TestOk { get; set; } public void FooTest() { Foo(); } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); p.FooTest(); if (p.TestOk) return 1; return 0; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01.array01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01.array01; // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic[] i = null) { if (i == null) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01a.array01a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01a.array01a; // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i == null) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01b.array01b { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01b.array01b; // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i[0] == null && i[1] == 1) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new int?[] { null, 1 } ; dynamic p = new Parent(); return p.Foo(d); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array03.array03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array03.array03; // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(new object[] { 1, 2, 3 } ); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array03a.array03a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array03a.array03a; // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = new int?[] { 1, 2, 3 } ; return p.Foo(d); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array04.array04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array04.array04; // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(i: new object[] { 1, 2, 3 } ); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array04a.array04a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array04a.array04a; // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = new int?[] { 1, 2, null } ; return p.Foo(i: d); } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using System.Text; using System.IO; using System.Xml; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { internal enum ReadType { Read, ReadAsInt32, ReadAsBytes, ReadAsString, ReadAsDecimal, ReadAsDateTime, ReadAsDateTimeOffset } /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to JSON text data. /// </summary> public class JsonTextReader : JsonReader, IJsonLineInfo { private const char UnicodeReplacementChar = '\uFFFD'; private readonly TextReader _reader; private char[] _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; private int _lineNumber; private bool _isEndOfFile; private StringBuffer _buffer; private StringReference _stringReference; /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param> public JsonTextReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; _lineNumber = 1; _chars = new char[1025]; } #if DEBUG internal void SetCharBuffer(char[] chars) { _chars = chars; } #endif private StringBuffer GetBuffer() { if (_buffer == null) { _buffer = new StringBuffer(1025); } else { _buffer.Position = 0; } return _buffer; } private void OnNewLine(int pos) { _lineNumber++; _lineStartPos = pos - 1; } private void ParseString(char quote) { _charPos++; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quote); if (_readType == ReadType.ReadAsBytes) { byte[] data; if (_stringReference.Length == 0) { data = new byte[0]; } else { data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); } SetToken(JsonToken.Bytes, data); } else if (_readType == ReadType.ReadAsString) { string text = _stringReference.ToString(); SetToken(JsonToken.String, text); _quoteChar = quote; } else { string text = _stringReference.ToString(); if (_dateParseHandling != DateParseHandling.None) { DateParseHandling dateParseHandling; if (_readType == ReadType.ReadAsDateTime) dateParseHandling = DateParseHandling.DateTime; else if (_readType == ReadType.ReadAsDateTimeOffset) dateParseHandling = DateParseHandling.DateTimeOffset; else dateParseHandling = _dateParseHandling; object dt; if (DateTimeUtils.TryParseDateTime(text, dateParseHandling, DateTimeZoneHandling, out dt)) { SetToken(JsonToken.Date, dt); return; } } SetToken(JsonToken.String, text); _quoteChar = quote; } } private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { const int charByteCount = 2; Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount); } private void ShiftBufferIfNeeded() { // once in the last 10% of the buffer shift the remainling content to the start to avoid // unnessesarly increasing the buffer size when reading numbers/strings int length = _chars.Length; if (length - _charPos <= length * 0.1) { int count = _charsUsed - _charPos; if (count > 0) BlockCopyChars(_chars, _charPos, _chars, 0, count); _lineStartPos -= _charPos; _charPos = 0; _charsUsed = count; _chars[_charsUsed] = '\0'; } } private int ReadData(bool append) { return ReadData(append, 0); } private int ReadData(bool append, int charsRequired) { if (_isEndOfFile) return 0; // char buffer is full if (_charsUsed + charsRequired >= _chars.Length - 1) { if (append) { // copy to new array either double the size of the current or big enough to fit required content int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1); // increase the size of the buffer char[] dst = new char[newArrayLength]; BlockCopyChars(_chars, 0, dst, 0, _chars.Length); _chars = dst; } else { int remainingCharCount = _charsUsed - _charPos; if (remainingCharCount + charsRequired + 1 >= _chars.Length) { // the remaining count plus the required is bigger than the current buffer size char[] dst = new char[remainingCharCount + charsRequired + 1]; if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount); _chars = dst; } else { // copy any remaining data to the beginning of the buffer if needed and reset positions if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = remainingCharCount; } } int attemptCharReadCount = _chars.Length - _charsUsed - 1; int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount); _charsUsed += charsRead; if (charsRead == 0) _isEndOfFile = true; _chars[_charsUsed] = '\0'; return charsRead; } private bool EnsureChars(int relativePosition, bool append) { if (_charPos + relativePosition >= _charsUsed) return ReadChars(relativePosition, append); return true; } private bool ReadChars(int relativePosition, bool append) { if (_isEndOfFile) return false; int charsRequired = _charPos + relativePosition - _charsUsed + 1; int totalCharsRead = 0; // it is possible that the TextReader doesn't return all data at once // repeat read until the required text is returned or the reader is out of content do { int charsRead = ReadData(append, charsRequired - totalCharsRead); // no more content if (charsRead == 0) break; totalCharsRead += charsRead; } while (totalCharsRead < charsRequired); if (totalCharsRead < charsRequired) return false; return true; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> [DebuggerStepThrough] public override bool Read() { _readType = ReadType.Read; if (!ReadInternal()) { SetToken(JsonToken.None); return false; } return true; } /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns> /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array. /// </returns> public override byte[] ReadAsBytes() { return ReadAsBytesInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public override decimal? ReadAsDecimal() { return ReadAsDecimalInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public override int? ReadAsInt32() { return ReadAsInt32Internal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override string ReadAsString() { return ReadAsStringInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTime? ReadAsDateTime() { return ReadAsDateTimeInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { return ReadAsDateTimeOffsetInternal(); } internal override bool ReadInternal() { while (true) { switch (_currentState) { case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: return ParseValue(); case State.Complete: break; case State.Object: case State.ObjectStart: return ParseObject(); case State.PostValue: // returns true if it hits // end of object or array if (ParsePostValue()) return true; break; case State.Finished: if (EnsureChars(0, false)) { EatWhitespace(false); if (_isEndOfFile) { return false; } if (_chars[_charPos] == '/') { ParseComment(); return true; } else { throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } } return false; case State.Closed: break; case State.Error: break; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } } private void ReadStringIntoBuffer(char quote) { int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; StringBuffer buffer = null; while (true) { switch (_chars[charPos++]) { case '\0': if (_charsUsed == charPos - 1) { charPos--; if (ReadData(true) == 0) { _charPos = charPos; throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } } break; case '\\': _charPos = charPos; if (!EnsureChars(0, true)) { _charPos = charPos; throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } // start of escape sequence int escapeStartPos = charPos - 1; char currentChar = _chars[charPos]; char writeChar; switch (currentChar) { case 'b': charPos++; writeChar = '\b'; break; case 't': charPos++; writeChar = '\t'; break; case 'n': charPos++; writeChar = '\n'; break; case 'f': charPos++; writeChar = '\f'; break; case 'r': charPos++; writeChar = '\r'; break; case '\\': charPos++; writeChar = '\\'; break; case '"': case '\'': case '/': writeChar = currentChar; charPos++; break; case 'u': charPos++; _charPos = charPos; writeChar = ParseUnicode(); if (StringUtils.IsLowSurrogate(writeChar)) { // low surrogate with no preceding high surrogate; this char is replaced writeChar = UnicodeReplacementChar; } else if (StringUtils.IsHighSurrogate(writeChar)) { bool anotherHighSurrogate; // loop for handling situations where there are multiple consecutive high surrogates do { anotherHighSurrogate = false; // potential start of a surrogate pair if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u') { char highSurrogate = writeChar; _charPos += 2; writeChar = ParseUnicode(); if (StringUtils.IsLowSurrogate(writeChar)) { // a valid surrogate pair! } else if (StringUtils.IsHighSurrogate(writeChar)) { // another high surrogate; replace current and start check over highSurrogate = UnicodeReplacementChar; anotherHighSurrogate = true; } else { // high surrogate not followed by low surrogate; original char is replaced highSurrogate = UnicodeReplacementChar; } if (buffer == null) buffer = GetBuffer(); WriteCharToBuffer(buffer, highSurrogate, lastWritePosition, escapeStartPos); lastWritePosition = _charPos; } else { // there are not enough remaining chars for the low surrogate or is not follow by unicode sequence // replace high surrogate and continue on as usual writeChar = UnicodeReplacementChar; } } while (anotherHighSurrogate); } charPos = _charPos; break; default: charPos++; _charPos = charPos; throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); } if (buffer == null) buffer = GetBuffer(); WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos); lastWritePosition = charPos; break; case StringUtils.CarriageReturn: _charPos = charPos - 1; ProcessCarriageReturn(true); charPos = _charPos; break; case StringUtils.LineFeed: _charPos = charPos - 1; ProcessLineFeed(); charPos = _charPos; break; case '"': case '\'': if (_chars[charPos - 1] == quote) { charPos--; if (initialPosition == lastWritePosition) { _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition); } else { if (buffer == null) buffer = GetBuffer(); if (charPos > lastWritePosition) buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition); _stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position); } charPos++; _charPos = charPos; return; } break; } } } private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition) { if (writeToPosition > lastWritePosition) { buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition); } buffer.Append(writeChar); } private char ParseUnicode() { char writeChar; if (EnsureChars(4, true)) { string hexValues = new string(_chars, _charPos, 4); char hexChar = Convert.ToChar(int.Parse(hexValues, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo)); writeChar = hexChar; _charPos += 4; } else { throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character."); } return writeChar; } private void ReadNumberIntoBuffer() { int charPos = _charPos; while (true) { switch (_chars[charPos++]) { case '\0': if (_charsUsed == charPos - 1) { charPos--; _charPos = charPos; if (ReadData(true) == 0) return; } else { _charPos = charPos - 1; return; } break; case '-': case '+': case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': case 'x': case 'X': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: _charPos = charPos - 1; return; } } } private void ClearRecentString() { if (_buffer != null) _buffer.Position = 0; _stringReference = new StringReference(); } private bool ParsePostValue() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) { _currentState = State.Finished; return false; } } else { _charPos++; } break; case '}': _charPos++; SetToken(JsonToken.EndObject); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case '/': ParseComment(); return true; case ',': _charPos++; // finished parsing SetStateBasedOnCurrent(); return false; case ' ': case StringUtils.Tab: // eat _charPos++; break; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } break; } } } private bool ParseObject() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) return false; } else { _charPos++; } break; case '}': SetToken(JsonToken.EndObject); _charPos++; return true; case '/': ParseComment(); return true; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { return ParseProperty(); } break; } } } private bool ParseProperty() { char firstChar = _chars[_charPos]; char quoteChar; if (firstChar == '"' || firstChar == '\'') { _charPos++; quoteChar = firstChar; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quoteChar); } else if (ValidIdentifierChar(firstChar)) { quoteChar = '\0'; ShiftBufferIfNeeded(); ParseUnquotedProperty(); } else { throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } string propertyName = _stringReference.ToString(); EatWhitespace(false); if (_chars[_charPos] != ':') throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; SetToken(JsonToken.PropertyName, propertyName); _quoteChar = quoteChar; ClearRecentString(); return true; } private bool ValidIdentifierChar(char value) { return (char.IsLetterOrDigit(value) || value == '_' || value == '$'); } private void ParseUnquotedProperty() { int initialPosition = _charPos; // parse unquoted property name until whitespace or colon while (true) { switch (_chars[_charPos]) { case '\0': if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name."); break; } _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); return; default: char currentChar = _chars[_charPos]; if (ValidIdentifierChar(currentChar)) { _charPos++; break; } else if (char.IsWhiteSpace(currentChar) || currentChar == ':') { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); return; } throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } private bool ParseValue() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) return false; } else { _charPos++; } break; case '"': case '\'': ParseString(currentChar); return true; case 't': ParseTrue(); return true; case 'f': ParseFalse(); return true; case 'n': if (EnsureChars(1, true)) { char next = _chars[_charPos + 1]; if (next == 'u') ParseNull(); else if (next == 'e') ParseConstructor(); else throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } else { throw JsonReaderException.Create(this, "Unexpected end."); } return true; case 'N': ParseNumberNaN(); return true; case 'I': ParseNumberPositiveInfinity(); return true; case '-': if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I') ParseNumberNegativeInfinity(); else ParseNumber(); return true; case '/': ParseComment(); return true; case 'u': ParseUndefined(); return true; case '{': _charPos++; SetToken(JsonToken.StartObject); return true; case '[': _charPos++; SetToken(JsonToken.StartArray); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ',': // don't increment position, the next call to read will handle comma // this is done to handle multiple empty comma values SetToken(JsonToken.Undefined); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; break; } else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') { ParseNumber(); return true; } else { throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } } private void ProcessLineFeed() { _charPos++; OnNewLine(_charPos); } private void ProcessCarriageReturn(bool append) { _charPos++; if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed) _charPos++; OnNewLine(_charPos); } private bool EatWhitespace(bool oneOrMore) { bool finished = false; bool ateWhitespace = false; while (!finished) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) finished = true; } else { _charPos++; } break; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (currentChar == ' ' || char.IsWhiteSpace(currentChar)) { ateWhitespace = true; _charPos++; } else { finished = true; } break; } } return (!oneOrMore || ateWhitespace); } private void ParseConstructor() { if (MatchValueWithTrailingSeperator("new")) { EatWhitespace(false); int initialPosition = _charPos; int endPosition; while (true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') { if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing constructor."); } else { endPosition = _charPos; _charPos++; break; } } else if (char.IsLetterOrDigit(currentChar)) { _charPos++; } else if (currentChar == StringUtils.CarriageReturn) { endPosition = _charPos; ProcessCarriageReturn(true); break; } else if (currentChar == StringUtils.LineFeed) { endPosition = _charPos; ProcessLineFeed(); break; } else if (char.IsWhiteSpace(currentChar)) { endPosition = _charPos; _charPos++; break; } else if (currentChar == '(') { endPosition = _charPos; break; } else { throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } _stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition); string constructorName = _stringReference.ToString(); EatWhitespace(false); if (_chars[_charPos] != '(') throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; ClearRecentString(); SetToken(JsonToken.StartConstructor, constructorName); } else { throw JsonReaderException.Create(this, "Unexpected content while parsing JSON."); } } private void ParseNumber() { ShiftBufferIfNeeded(); char firstChar = _chars[_charPos]; int initialPosition = _charPos; ReadNumberIntoBuffer(); _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); object numberValue; JsonToken numberType; bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1); bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E'); if (_readType == ReadType.ReadAsInt32) { if (singleDigit) { // digit char values start at 48 numberValue = firstChar - 48; } else if (nonBase10) { string number = _stringReference.ToString(); // decimal.Parse doesn't support parsing hexadecimal values int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8); numberValue = integer; } else { numberValue = ConvertUtils.Int32Parse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); } numberType = JsonToken.Integer; } else if (_readType == ReadType.ReadAsDecimal) { if (singleDigit) { // digit char values start at 48 numberValue = (decimal)firstChar - 48; } else if (nonBase10) { string number = _stringReference.ToString(); // decimal.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberValue = Convert.ToDecimal(integer); } else { string number = _stringReference.ToString(); numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); } numberType = JsonToken.Float; } else { if (singleDigit) { // digit char values start at 48 numberValue = (long)firstChar - 48; numberType = JsonToken.Integer; } else if (nonBase10) { string number = _stringReference.ToString(); numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberType = JsonToken.Integer; } else { long value; ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value); if (parseResult == ParseResult.Success) { numberValue = value; numberType = JsonToken.Integer; } else if (parseResult == ParseResult.Invalid) { string number = _stringReference.ToString(); if (_floatParseHandling == FloatParseHandling.Decimal) numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); else numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture); numberType = JsonToken.Float; } else if (parseResult == ParseResult.Overflow) { string number = _stringReference.ToString(); numberValue = BigInteger.Parse(number, CultureInfo.InvariantCulture); numberType = JsonToken.Integer; } else { throw JsonReaderException.Create(this, "Unknown error parsing integer."); } } } ClearRecentString(); SetToken(numberType, numberValue); } private void ParseComment() { // should have already parsed / character before reaching this method _charPos++; if (!EnsureChars(1, false) || _chars[_charPos] != '*') throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); else _charPos++; int initialPosition = _charPos; bool commentFinished = false; while (!commentFinished) { switch (_chars[_charPos]) { case '\0': if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); } else { _charPos++; } break; case '*': _charPos++; if (EnsureChars(0, true)) { if (_chars[_charPos] == '/') { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1); _charPos++; commentFinished = true; } } break; case StringUtils.CarriageReturn: ProcessCarriageReturn(true); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: _charPos++; break; } } SetToken(JsonToken.Comment, _stringReference.ToString()); ClearRecentString(); } private bool MatchValue(string value) { if (!EnsureChars(value.Length - 1, true)) return false; for (int i = 0; i < value.Length; i++) { if (_chars[_charPos + i] != value[i]) { return false; } } _charPos += value.Length; return true; } private bool MatchValueWithTrailingSeperator(string value) { // will match value and then move to the next character, checking that it is a seperator character bool match = MatchValue(value); if (!match) return false; if (!EnsureChars(0, false)) return true; return IsSeperator(_chars[_charPos]) || _chars[_charPos] == '\0'; } private bool IsSeperator(char c) { switch (c) { case '}': case ']': case ',': return true; case '/': // check next character to see if start of a comment if (!EnsureChars(1, false)) return false; return (_chars[_charPos + 1] == '*'); case ')': if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart) return true; break; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: return true; default: if (char.IsWhiteSpace(c)) return true; break; } return false; } private void ParseTrue() { // check characters equal 'true' // and that it is followed by either a seperator character // or the text ends if (MatchValueWithTrailingSeperator(JsonConvert.True)) { SetToken(JsonToken.Boolean, true); } else { throw JsonReaderException.Create(this, "Error parsing boolean value."); } } private void ParseNull() { if (MatchValueWithTrailingSeperator(JsonConvert.Null)) { SetToken(JsonToken.Null); } else { throw JsonReaderException.Create(this, "Error parsing null value."); } } private void ParseUndefined() { if (MatchValueWithTrailingSeperator(JsonConvert.Undefined)) { SetToken(JsonToken.Undefined); } else { throw JsonReaderException.Create(this, "Error parsing undefined value."); } } private void ParseFalse() { if (MatchValueWithTrailingSeperator(JsonConvert.False)) { SetToken(JsonToken.Boolean, false); } else { throw JsonReaderException.Create(this, "Error parsing boolean value."); } } private void ParseNumberNegativeInfinity() { if (MatchValueWithTrailingSeperator(JsonConvert.NegativeInfinity)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read -Infinity as a decimal."); SetToken(JsonToken.Float, double.NegativeInfinity); } else { throw JsonReaderException.Create(this, "Error parsing negative infinity value."); } } private void ParseNumberPositiveInfinity() { if (MatchValueWithTrailingSeperator(JsonConvert.PositiveInfinity)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read Infinity as a decimal."); SetToken(JsonToken.Float, double.PositiveInfinity); } else { throw JsonReaderException.Create(this, "Error parsing positive infinity value."); } } private void ParseNumberNaN() { if (MatchValueWithTrailingSeperator(JsonConvert.NaN)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read NaN as a decimal."); SetToken(JsonToken.Float, double.NaN); } else { throw JsonReaderException.Create(this, "Error parsing NaN value."); } } /// <summary> /// Changes the state to closed. /// </summary> public override void Close() { base.Close(); if (CloseInput && _reader != null) _reader.Dispose(); if (_buffer != null) _buffer.Clear(); } /// <summary> /// Gets a value indicating whether the class can return line information. /// </summary> /// <returns> /// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>. /// </returns> public bool HasLineInfo() { return true; } /// <summary> /// Gets the current line number. /// </summary> /// <value> /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LineNumber { get { if (CurrentState == State.Start && LinePosition == 0) return 0; return _lineNumber; } } /// <summary> /// Gets the current line position. /// </summary> /// <value> /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LinePosition { get { return _charPos - _lineStartPos; } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsInt16() { var test = new VectorAs__AsInt16(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsInt16 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector256<Int16> value; value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector256<Int16> value; value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<byte> byteResult = value.As<Int16, byte>(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<double> doubleResult = value.As<Int16, double>(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<short> shortResult = value.As<Int16, short>(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<int> intResult = value.As<Int16, int>(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<long> longResult = value.As<Int16, long>(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<sbyte> sbyteResult = value.As<Int16, sbyte>(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<float> floatResult = value.As<Int16, float>(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<ushort> ushortResult = value.As<Int16, ushort>(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<uint> uintResult = value.As<Int16, uint>(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); Vector256<ulong> ulongResult = value.As<Int16, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector256<Int16> value; value = Vector256.Create(TestLibrary.Generator.GetInt16()); object byteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsByte)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<byte>)(byteResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object doubleResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsDouble)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<double>)(doubleResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object shortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt16)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<short>)(shortResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object intResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt32)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<int>)(intResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object longResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt64)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<long>)(longResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object sbyteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSByte)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<sbyte>)(sbyteResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object floatResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSingle)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<float>)(floatResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object ushortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt16)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ushort>)(ushortResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object uintResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt32)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<uint>)(uintResult), value); value = Vector256.Create(TestLibrary.Generator.GetInt16()); object ulongResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt64)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector256<T> result, Vector256<Int16> value, [CallerMemberName] string method = "") where T : struct { Int16[] resultElements = new Int16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref resultElements[0]), result); Int16[] valueElements = new Int16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(Int16[] resultElements, Int16[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int16>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Utilities; using System; using System.Globalization; using System.Linq; namespace Avalonia { /// <summary> /// Describes the thickness of a frame around a rectangle. /// </summary> public struct Thickness { /// <summary> /// The thickness on the left. /// </summary> private readonly double _left; /// <summary> /// The thickness on the top. /// </summary> private readonly double _top; /// <summary> /// The thickness on the right. /// </summary> private readonly double _right; /// <summary> /// The thickness on the bottom. /// </summary> private readonly double _bottom; /// <summary> /// Initializes a new instance of the <see cref="Thickness"/> structure. /// </summary> /// <param name="uniformLength">The length that should be applied to all sides.</param> public Thickness(double uniformLength) { _left = _top = _right = _bottom = uniformLength; } /// <summary> /// Initializes a new instance of the <see cref="Thickness"/> structure. /// </summary> /// <param name="horizontal">The thickness on the left and right.</param> /// <param name="vertical">The thickness on the top and bottom.</param> public Thickness(double horizontal, double vertical) { _left = _right = horizontal; _top = _bottom = vertical; } /// <summary> /// Initializes a new instance of the <see cref="Thickness"/> structure. /// </summary> /// <param name="left">The thickness on the left.</param> /// <param name="top">The thickness on the top.</param> /// <param name="right">The thickness on the right.</param> /// <param name="bottom">The thickness on the bottom.</param> public Thickness(double left, double top, double right, double bottom) { _left = left; _top = top; _right = right; _bottom = bottom; } /// <summary> /// Gets the thickness on the left. /// </summary> public double Left => _left; /// <summary> /// Gets the thickness on the top. /// </summary> public double Top => _top; /// <summary> /// Gets the thickness on the right. /// </summary> public double Right => _right; /// <summary> /// Gets the thickness on the bottom. /// </summary> public double Bottom => _bottom; /// <summary> /// Gets a value indicating whether all sides are set to 0. /// </summary> public bool IsEmpty => Left.Equals(0) && IsUniform; /// <summary> /// Gets a value indicating whether all sides are equal. /// </summary> public bool IsUniform => Left.Equals(Right) && Top.Equals(Bottom) && Right.Equals(Bottom); /// <summary> /// Compares two Thicknesses. /// </summary> /// <param name="a">The first thickness.</param> /// <param name="b">The second thickness.</param> /// <returns>The equality.</returns> public static bool operator ==(Thickness a, Thickness b) { return a.Equals(b); } /// <summary> /// Compares two Thicknesses. /// </summary> /// <param name="a">The first thickness.</param> /// <param name="b">The second thickness.</param> /// <returns>The unequality.</returns> public static bool operator !=(Thickness a, Thickness b) { return !a.Equals(b); } /// <summary> /// Adds two Thicknesses. /// </summary> /// <param name="a">The first thickness.</param> /// <param name="b">The second thickness.</param> /// <returns>The equality.</returns> public static Thickness operator +(Thickness a, Thickness b) { return new Thickness( a.Left + b.Left, a.Top + b.Top, a.Right + b.Right, a.Bottom + b.Bottom); } /// <summary> /// Adds a Thickness to a Size. /// </summary> /// <param name="size">The size.</param> /// <param name="thickness">The thickness.</param> /// <returns>The equality.</returns> public static Size operator +(Size size, Thickness thickness) { return new Size( size.Width + thickness.Left + thickness.Right, size.Height + thickness.Top + thickness.Bottom); } /// <summary> /// Subtracts a Thickness from a Size. /// </summary> /// <param name="size">The size.</param> /// <param name="thickness">The thickness.</param> /// <returns>The equality.</returns> public static Size operator -(Size size, Thickness thickness) { return new Size( size.Width - (thickness.Left + thickness.Right), size.Height - (thickness.Top + thickness.Bottom)); } /// <summary> /// Parses a <see cref="Thickness"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The <see cref="Thickness"/>.</returns> public static Thickness Parse(string s) { using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Thickness")) { if(tokenizer.TryReadDouble(out var a)) { if (tokenizer.TryReadDouble(out var b)) { if (tokenizer.TryReadDouble(out var c)) { return new Thickness(a, b, c, tokenizer.ReadDouble()); } return new Thickness(a, b); } return new Thickness(a); } throw new FormatException("Invalid Thickness."); } } /// <summary> /// Checks for equality between a thickness and an object. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// True if <paramref name="obj"/> is a size that equals the current size. /// </returns> public override bool Equals(object obj) { if (obj is Thickness) { Thickness other = (Thickness)obj; return Left == other.Left && Top == other.Top && Right == other.Right && Bottom == other.Bottom; } return false; } /// <summary> /// Returns a hash code for a <see cref="Thickness"/>. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + Left.GetHashCode(); hash = (hash * 23) + Top.GetHashCode(); hash = (hash * 23) + Right.GetHashCode(); hash = (hash * 23) + Bottom.GetHashCode(); return hash; } } /// <summary> /// Returns the string representation of the thickness. /// </summary> /// <returns>The string representation of the thickness.</returns> public override string ToString() { return $"{_left},{_top},{_right},{_bottom}"; } } }
// 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.Http.Headers; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class HttpClientHandlerTest_Headers : HttpClientHandlerTestBase { public HttpClientHandlerTest_Headers(ITestOutputHelper output) : base(output) { } private sealed class DerivedHttpHeaders : HttpHeaders { } [Fact] public async Task SendAsync_UserAgent_CorrectlyWritten() { string userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.18 Safari/537.36"; await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) { var message = new HttpRequestMessage(HttpMethod.Get, uri) { Version = VersionFromUseHttp2 }; message.Headers.TryAddWithoutValidation("User-Agent", userAgent); (await client.SendAsync(message).ConfigureAwait(false)).Dispose(); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK); string agent = requestData.GetSingleHeaderValue("User-Agent"); Assert.Equal(userAgent, agent); }); } [Theory] [InlineData("\u05D1\u05F1")] [InlineData("jp\u30A5")] public async Task SendAsync_InvalidCharactersInHeader_Throw(string value) { await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, uri) { Version = VersionFromUseHttp2 }; Assert.True(request.Headers.TryAddWithoutValidation("bad", value)); await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request)); } }, async server => { try { // Client should abort at some point so this is going to throw. HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK).ConfigureAwait(false); } catch (IOException) { }; }); } [Theory] [InlineData("x-Special_name", "header name with underscore", true)] // underscores in header [InlineData("Date", "invaliddateformat", false)] // invalid format for header but added with TryAddWithoutValidation [InlineData("Accept-CharSet", "text/plain, text/json", false)] // invalid format for header but added with TryAddWithoutValidation [InlineData("Content-Location", "", false)] // invalid format for header but added with TryAddWithoutValidation [InlineData("Max-Forwards", "NotAnInteger", false)] // invalid format for header but added with TryAddWithoutValidation public async Task SendAsync_SpecialHeaderKeyOrValue_Success(string key, string value, bool parsable) { await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { bool contentHeader = false; using (HttpClient client = CreateHttpClient()) { var message = new HttpRequestMessage(HttpMethod.Get, uri) { Version = VersionFromUseHttp2 }; if (!message.Headers.TryAddWithoutValidation(key, value)) { message.Content = new StringContent(""); contentHeader = message.Content.Headers.TryAddWithoutValidation(key, value); } (await client.SendAsync(message).ConfigureAwait(false)).Dispose(); } // Validate our test by validating our understanding of a header's parsability. HttpHeaders headers = contentHeader ? (HttpHeaders) new StringContent("").Headers : new HttpRequestMessage().Headers; if (parsable) { headers.Add(key, value); } else { Assert.Throws<FormatException>(() => headers.Add(key, value)); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK); Assert.Equal(value, requestData.GetSingleHeaderValue(key)); }); } [Theory] [InlineData("Content-Security-Policy", 4618)] [InlineData("RandomCustomHeader", 12345)] public async Task GetAsync_LargeHeader_Success(string headerName, int headerValueLength) { var rand = new Random(42); string headerValue = string.Concat(Enumerable.Range(0, headerValueLength).Select(_ => (char)('A' + rand.Next(26)))); const string ContentString = "hello world"; await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage resp = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(headerValue, resp.Headers.GetValues(headerName).Single()); Assert.Equal(ContentString, await resp.Content.ReadAsStringAsync()); } }, async server => { var headers = new List<HttpHeaderData>(); headers.Add(new HttpHeaderData(headerName, headerValue)); await server.HandleRequestAsync(HttpStatusCode.OK, headers: headers, content: ContentString); }); } [Fact] public async Task GetAsync_EmptyResponseHeader_Success() { IList<HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData("Date", $"{DateTimeOffset.UtcNow:R}"), new HttpHeaderData("x-empty", ""), new HttpHeaderData("x-last", "bye") }; await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) { HttpResponseMessage response = await client.GetAsync(uri).ConfigureAwait(false); Assert.Equal(headers.Count, response.Headers.Count()); Assert.NotNull(response.Headers.GetValues("x-empty")); } }, async server => { await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestDataAsync(); await connection.SendResponseAsync(HttpStatusCode.OK, headers); }); }); } [Fact] public async Task GetAsync_MissingExpires_ReturnNull() { await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) { HttpResponseMessage response = await client.GetAsync(uri); Assert.Null(response.Content.Headers.Expires); } }, async server => { await server.HandleRequestAsync(HttpStatusCode.OK); }); } [Theory] [InlineData("Thu, 01 Dec 1994 16:00:00 GMT", true)] [InlineData("-1", false)] [InlineData("0", false)] public async Task SendAsync_Expires_Success(string value, bool isValid) { await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) { var message = new HttpRequestMessage(HttpMethod.Get, uri) { Version = VersionFromUseHttp2 }; HttpResponseMessage response = await client.SendAsync(message); Assert.NotNull(response.Content.Headers.Expires); // Invalid date should be converted to MinValue so everything is expired. Assert.Equal(isValid ? DateTime.Parse(value) : DateTimeOffset.MinValue, response.Content.Headers.Expires); } }, async server => { IList<HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData("Expires", value) }; HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK, headers); }); } [Theory] [InlineData("-1", false)] [InlineData("Thu, 01 Dec 1994 16:00:00 GMT", true)] public void HeadersAdd_CustomExpires_Success(string value, bool isValid) { var headers = new DerivedHttpHeaders(); if (!isValid) { Assert.Throws<FormatException>(() => headers.Add("Expires", value)); } Assert.True(headers.TryAddWithoutValidation("Expires", value)); Assert.Equal(1, Enumerable.Count(headers.GetValues("Expires"))); Assert.Equal(value, headers.GetValues("Expires").First()); } [Theory] [InlineData("Accept-Encoding", "identity,gzip")] public async Task SendAsync_RequestHeaderInResponse_Success(string name, string value) { await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClient client = CreateHttpClient()) { var message = new HttpRequestMessage(HttpMethod.Get, uri) { Version = VersionFromUseHttp2 }; HttpResponseMessage response = await client.SendAsync(message); Assert.Equal(value, response.Headers.GetValues(name).First()); } }, async server => { IList<HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData(name, value) }; HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK, headers); }); } [OuterLoop("Uses external server")] [Theory] [InlineData(false)] [InlineData(true)] public async Task SendAsync_GetWithValidHostHeader_Success(bool withPort) { var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer) { Version = VersionFromUseHttp2 }; m.Headers.Host = withPort ? Configuration.Http.SecureHost + ":443" : Configuration.Http.SecureHost; using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.SendAsync(m)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } [OuterLoop("Uses external server")] [Fact] public async Task SendAsync_GetWithInvalidHostHeader_ThrowsException() { if (PlatformDetection.IsNetCore && (!UseSocketsHttpHandler || LoopbackServerFactory.IsHttp2)) { // Only .NET Framework and SocketsHttpHandler with HTTP/1.x use the Host header to influence the SSL auth. // Host header is not used for HTTP2 return; } var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer) { Version = VersionFromUseHttp2 }; m.Headers.Host = "hostheaderthatdoesnotmatch"; using (HttpClient client = CreateHttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(m)); } } [Fact] public async Task SendAsync_WithZeroLengthHeaderName_Throws() { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using HttpClient client = CreateHttpClient(); await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri)); }, async server => { await server.HandleRequestAsync(headers: new[] { new HttpHeaderData("", "foo") }); }); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && (!NETSTANDARD || WindowsEventLogPackage) namespace NLog.Targets { using System; using System.ComponentModel; using System.Diagnostics; using Internal.Fakeables; using NLog.Common; using NLog.Config; using NLog.Layouts; /// <summary> /// Writes log message to the Event Log. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/EventLog-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" /> /// </example> [Target("EventLog")] public class EventLogTarget : TargetWithLayout, IInstallable { /// <summary> /// Max size in characters (limitation of the EventLog API). /// </summary> internal const int EventLogMaxMessageLength = 16384; private readonly IEventLogWrapper _eventLogWrapper; /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> public EventLogTarget() : this(null, null) { } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> /// <param name="name">Name of the target.</param> public EventLogTarget(string name) : this(null, null) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> /// <param name="appDomain"><see cref="IAppDomain"/>.<see cref="IAppDomain.FriendlyName"/> to be used as Source.</param> [Obsolete("This constructor will be removed in NLog 5. Marked obsolete on NLog 4.6")] public EventLogTarget(IAppDomain appDomain) : this(null, appDomain) { } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> internal EventLogTarget(IEventLogWrapper eventLogWrapper, IAppDomain appDomain) { _eventLogWrapper = eventLogWrapper ?? new EventLogWrapper(); appDomain = appDomain ?? LogFactory.CurrentAppDomain; Source = appDomain.FriendlyName; Log = "Application"; MachineName = "."; MaxMessageLength = EventLogMaxMessageLength; OptimizeBufferReuse = GetType() == typeof(EventLogTarget); // Class not sealed, reduce breaking changes } /// <summary> /// Gets or sets the name of the machine on which Event Log service is running. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(".")] public string MachineName { get; set; } /// <summary> /// Gets or sets the layout that renders event ID. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout EventId { get; set; } /// <summary> /// Gets or sets the layout that renders event Category. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout Category { get; set; } /// <summary> /// Optional entry type. When not set, or when not convertible to <see cref="EventLogEntryType"/> then determined by <see cref="NLog.LogLevel"/> /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout EntryType { get; set; } /// <summary> /// Gets or sets the value to be used as the event Source. /// </summary> /// <remarks> /// By default this is the friendly name of the current AppDomain. /// </remarks> /// <docgen category='Event Log Options' order='10' /> public Layout Source { get; set; } /// <summary> /// Gets or sets the name of the Event Log to write to. This can be System, Application or any user-defined name. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue("Application")] public string Log { get; set; } /// <summary> /// Gets or sets the message length limit to write to the Event Log. /// </summary> /// <remarks><value>MaxMessageLength</value> cannot be zero or negative</remarks> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(EventLogMaxMessageLength)] public int MaxMessageLength { get => _maxMessageLength; set { if (value <= 0) throw new ArgumentException("MaxMessageLength cannot be zero or negative."); _maxMessageLength = value; } } private int _maxMessageLength; /// <summary> /// Gets or sets the maximum Event log size in kilobytes. /// </summary> /// <remarks> /// <value>MaxKilobytes</value> cannot be less than 64 or greater than 4194240 or not a multiple of 64. /// If <c>null</c>, the value will not be specified while creating the Event log. /// </remarks> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(null)] public long? MaxKilobytes { get => _maxKilobytes; set { if (value != null && (value < 64 || value > 4194240 || (value % 64 != 0))) // Event log API restrictions throw new ArgumentException("MaxKilobytes must be a multiple of 64, and between 64 and 4194240"); _maxKilobytes = value; } } private long? _maxKilobytes; /// <summary> /// Gets or sets the action to take if the message is larger than the <see cref="MaxMessageLength"/> option. /// </summary> /// <docgen category='Event Log Overflow Action' order='10' /> [DefaultValue(EventLogTargetOverflowAction.Truncate)] public EventLogTargetOverflowAction OnOverflow { get; set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { // always throw error to keep backwards compatible behavior. CreateEventSourceIfNeeded(GetFixedSource(), true); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("EventLogTarget(Name={0}): Skipping removing of event source because it contains layout renderers", Name); } else { _eventLogWrapper.DeleteEventSource(fixedSource, MachineName); } } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (!string.IsNullOrEmpty(fixedSource)) { return _eventLogWrapper.SourceExists(fixedSource, MachineName); } InternalLogger.Debug("EventLogTarget(Name={0}): Unclear if event source exists because it contains layout renderers", Name); return null; //unclear! } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); CreateEventSourceIfNeeded(GetFixedSource(), false); } /// <summary> /// Writes the specified logging event to the event log. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { string message = RenderLogEvent(Layout, logEvent); EventLogEntryType entryType = GetEntryType(logEvent); int eventId = 0; string renderEventId = RenderLogEvent(EventId, logEvent); if (!string.IsNullOrEmpty(renderEventId) && !int.TryParse(renderEventId, out eventId)) { InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry failed to parse EventId={1}", Name, renderEventId); } short category = 0; string renderCategory = RenderLogEvent(Category, logEvent); if (!string.IsNullOrEmpty(renderCategory) && !short.TryParse(renderCategory, out category)) { InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry failed to parse Category={1}", Name, renderCategory); } var eventLogSource = RenderLogEvent(Source, logEvent); if (string.IsNullOrEmpty(eventLogSource)) { InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry discarded because Source rendered as empty string", Name); return; } // limitation of EventLog API if (message.Length > MaxMessageLength) { if (OnOverflow == EventLogTargetOverflowAction.Truncate) { message = message.Substring(0, MaxMessageLength); WriteEntry(eventLogSource, message, entryType, eventId, category); } else if (OnOverflow == EventLogTargetOverflowAction.Split) { for (int offset = 0; offset < message.Length; offset += MaxMessageLength) { string chunk = message.Substring(offset, Math.Min(MaxMessageLength, (message.Length - offset))); WriteEntry(eventLogSource, chunk, entryType, eventId, category); } } else if (OnOverflow == EventLogTargetOverflowAction.Discard) { // message should not be written InternalLogger.Debug("EventLogTarget(Name={0}): WriteEntry discarded because too big message size: {1}", Name, message.Length); } } else { WriteEntry(eventLogSource, message, entryType, eventId, category); } } private void WriteEntry(string eventLogSource, string message, EventLogEntryType entryType, int eventId, short category) { var isCacheUpToDate = _eventLogWrapper.IsEventLogAssociated && _eventLogWrapper.Log == Log && _eventLogWrapper.MachineName == MachineName && _eventLogWrapper.Source == eventLogSource; if (!isCacheUpToDate) { InternalLogger.Debug("EventLogTarget(Name={0}): Refresh EventLog Source {1} and Log {2}", Name, eventLogSource, Log); _eventLogWrapper.AssociateNewEventLog(Log, MachineName, eventLogSource); try { if (!_eventLogWrapper.SourceExists(eventLogSource, MachineName)) { InternalLogger.Warn("EventLogTarget(Name={0}): Source {1} does not exist", Name, eventLogSource); } else { var currentLogName = _eventLogWrapper.LogNameFromSourceName(eventLogSource, MachineName); if (!currentLogName.Equals(Log, StringComparison.CurrentCultureIgnoreCase)) { InternalLogger.Debug("EventLogTarget(Name={0}): Source {1} should be mapped to Log {2}, but EventLog.LogNameFromSourceName returns {3}", Name, eventLogSource, Log, currentLogName); } } } catch (Exception ex) { if (LogManager.ThrowExceptions) throw; InternalLogger.Warn(ex, "EventLogTarget(Name={0}): Exception thrown when checking if Source {1} and LogName {2} are valid", Name, eventLogSource, Log); } } _eventLogWrapper.WriteEntry(message, entryType, eventId, category); } /// <summary> /// Get the entry type for logging the message. /// </summary> /// <param name="logEvent">The logging event - for rendering the <see cref="EntryType"/></param> private EventLogEntryType GetEntryType(LogEventInfo logEvent) { string renderEntryType = RenderLogEvent(EntryType, logEvent); if (!string.IsNullOrEmpty(renderEntryType)) { // try parse, if fail, determine auto if (ConversionHelpers.TryParseEnum(renderEntryType, out EventLogEntryType eventLogEntryType)) { return eventLogEntryType; } InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry failed to parse EntryType={1}", Name, renderEntryType); } // determine auto if (logEvent.Level >= LogLevel.Error) { return EventLogEntryType.Error; } if (logEvent.Level >= LogLevel.Warn) { return EventLogEntryType.Warning; } return EventLogEntryType.Information; } /// <summary> /// Get the source, if and only if the source is fixed. /// </summary> /// <returns><c>null</c> when not <see cref="SimpleLayout.IsFixedText"/></returns> /// <remarks>Internal for unit tests</remarks> internal string GetFixedSource() { if (Source is SimpleLayout simpleLayout && simpleLayout.IsFixedText) { return simpleLayout.FixedText; } return null; } /// <summary> /// (re-)create an event source, if it isn't there. Works only with fixed source names. /// </summary> /// <param name="fixedSource">The source name. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or <see cref="string.Empty"/>.</param> /// <param name="alwaysThrowError">always throw an Exception when there is an error</param> private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError) { if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("EventLogTarget(Name={0}): Skipping creation of event source because it contains layout renderers", Name); // we can only create event sources if the source is fixed (no layout) return; } // if we throw anywhere, we remain non-operational try { if (_eventLogWrapper.SourceExists(fixedSource, MachineName)) { string currentLogName = _eventLogWrapper.LogNameFromSourceName(fixedSource, MachineName); if (!currentLogName.Equals(Log, StringComparison.CurrentCultureIgnoreCase)) { InternalLogger.Debug("EventLogTarget(Name={0}): Updating source {1} to use log {2}, instead of {3} (Computer restart is needed)", Name, fixedSource, Log, currentLogName); // re-create the association between Log and Source _eventLogWrapper.DeleteEventSource(fixedSource, MachineName); var eventSourceCreationData = new EventSourceCreationData(fixedSource, Log) { MachineName = MachineName }; _eventLogWrapper.CreateEventSource(eventSourceCreationData); } } else { InternalLogger.Debug("EventLogTarget(Name={0}): Creating source {1} to use log {2}", Name, fixedSource, Log); var eventSourceCreationData = new EventSourceCreationData(fixedSource, Log) { MachineName = MachineName }; _eventLogWrapper.CreateEventSource(eventSourceCreationData); } _eventLogWrapper.AssociateNewEventLog(Log, MachineName, fixedSource); if (MaxKilobytes.HasValue && _eventLogWrapper.MaximumKilobytes < MaxKilobytes) { _eventLogWrapper.MaximumKilobytes = MaxKilobytes.Value; } } catch (Exception exception) { InternalLogger.Error(exception, "EventLogTarget(Name={0}): Error when connecting to EventLog. Source={1} in Log={2}", Name, fixedSource, Log); if (alwaysThrowError || LogManager.ThrowExceptions) { throw; } } } /// <summary> /// A wrapper for Windows event log. /// </summary> internal interface IEventLogWrapper { #region Instance methods /// <summary> /// A wrapper for the property <see cref="EventLog.Source"/>. /// </summary> string Source { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.Log"/>. /// </summary> string Log { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.MachineName"/>. /// </summary> string MachineName { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.MaximumKilobytes"/>. /// </summary> long MaximumKilobytes { get; set; } /// <summary> /// Indicates whether an event log instance is associated. /// </summary> bool IsEventLogAssociated { get; } /// <summary> /// A wrapper for the method <see cref="EventLog.WriteEntry(string, EventLogEntryType, int, short)"/>. /// </summary> void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category); #endregion #region "Static" methods /// <summary> /// Creates a new association with an instance of the event log. /// </summary> void AssociateNewEventLog(string logName, string machineName, string source); /// <summary> /// A wrapper for the static method <see cref="EventLog.DeleteEventSource(string, string)"/>. /// </summary> void DeleteEventSource(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.SourceExists(string, string)"/>. /// </summary> bool SourceExists(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.LogNameFromSourceName(string, string)"/>. /// </summary> string LogNameFromSourceName(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.CreateEventSource(EventSourceCreationData)"/>. /// </summary> void CreateEventSource(EventSourceCreationData sourceData); #endregion } /// <summary> /// The implementation of <see cref="IEventLogWrapper"/>, that uses Windows <see cref="EventLog"/>. /// </summary> private sealed class EventLogWrapper : IEventLogWrapper { private EventLog _windowsEventLog; #region Instance methods /// <inheritdoc /> public string Source { get; private set; } /// <inheritdoc /> public string Log { get; private set; } /// <inheritdoc /> public string MachineName { get; private set; } /// <inheritdoc /> public long MaximumKilobytes { get => _windowsEventLog.MaximumKilobytes; set => _windowsEventLog.MaximumKilobytes = value; } /// <inheritdoc /> public bool IsEventLogAssociated => _windowsEventLog != null; /// <inheritdoc /> public void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category) => _windowsEventLog.WriteEntry(message, entryType, eventId, category); #endregion #region "Static" methods /// <inheritdoc /> /// <summary> /// Creates a new association with an instance of Windows <see cref="EventLog"/>. /// </summary> public void AssociateNewEventLog(string logName, string machineName, string source) { var windowsEventLog = _windowsEventLog; _windowsEventLog = new EventLog(logName, machineName, source); Source = source; Log = logName; MachineName = machineName; if (windowsEventLog != null) windowsEventLog.Dispose(); } /// <inheritdoc /> public void DeleteEventSource(string source, string machineName) => EventLog.DeleteEventSource(source, machineName); /// <inheritdoc /> public bool SourceExists(string source, string machineName) => EventLog.SourceExists(source, machineName); /// <inheritdoc /> public string LogNameFromSourceName(string source, string machineName) => EventLog.LogNameFromSourceName(source, machineName); /// <inheritdoc /> public void CreateEventSource(EventSourceCreationData sourceData) => EventLog.CreateEventSource(sourceData); #endregion } } } #endif
using J2N; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// LUCENENET specific extensions to various .NET types to make it easier to port tests /// from Java with fewer changes. /// </summary> internal static class SystemTypesHelpers { public static char[] toCharArray(this string str) { return str.ToCharArray(); } public static string toString(this object obj) // LUCENENET TODO: wrap Collections.ToString() { // LUCENENET: We compensate for the fact that // .NET doesn't have reliable results from ToString // by defaulting the behavior to return a concatenated // list of the contents of enumerables rather than the // .NET type name (similar to the way Java behaves). // Unless of course we already have a string (which // implements IEnumerable so we need skip it). if (obj is IEnumerable && !(obj is string)) { string result = obj.ToString(); // Assume that this is a default call to object.ToString() // when it starts with the same namespace as the type. if (!result.StartsWith(obj.GetType().Namespace, StringComparison.Ordinal)) { return result; } // If this is the default text, replace it with // the contents of the enumerable as Java would. IEnumerable list = obj as IEnumerable; StringBuilder sb = new StringBuilder(); bool isArray = obj.GetType().IsArray; sb.Append(isArray ? "{" : "["); foreach (object item in list) { if (sb.Length > 1) { sb.Append(", "); } sb.Append(item != null ? item.ToString() : "null"); } sb.Append(isArray ? "}" : "]"); return sb.ToString(); } return obj.ToString(); } public static bool equals(this object obj1, object obj2) { return obj1.Equals(obj2); } public static StringBuilder append(this StringBuilder sb, bool value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, byte value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static StringBuilder append(this StringBuilder sb, char value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, char[] value) { sb.Append(value); return sb; } // LUCENENET: These would only work if we copied the format from Java, // which is probably not something we want to do anyway. // Instead of calling a centralized method, we should be converting the // code on a case by case basis. //public static StringBuilder append(this StringBuilder sb, decimal value) //{ // sb.Append(value); // return sb; //} //public static StringBuilder append(this StringBuilder sb, double value) //{ // sb.Append(value); // return sb; //} //public static StringBuilder append(this StringBuilder sb, float value) //{ // sb.Append(value); // return sb; //} public static StringBuilder append(this StringBuilder sb, int value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static StringBuilder append(this StringBuilder sb, long value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static StringBuilder append(this StringBuilder sb, object value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, sbyte value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static StringBuilder append(this StringBuilder sb, short value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static StringBuilder append(this StringBuilder sb, string value) { sb.Append(value); return sb; } public static StringBuilder append(this StringBuilder sb, uint value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static StringBuilder append(this StringBuilder sb, ulong value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static StringBuilder append(this StringBuilder sb, ushort value) { // LUCENENET NOTE: .NET uses the current culture by default, and any // Java code that calls this is expecting invariant culture sb.Append(value.ToString(CultureInfo.InvariantCulture)); return sb; } public static sbyte[] getBytes(this string str, string encoding) { return (sbyte[])(Array)Encoding.GetEncoding(encoding).GetBytes(str); } public static byte[] getBytes(this string str, Encoding encoding) { return encoding.GetBytes(str); } public static int size<T>(this ICollection<T> list) { return list.Count; } public static T[] clone<T>(this T[] e) { return (T[]) e.Clone(); } public static void add<T>(this ISet<T> s, T item) { s.Add(item); } public static void addAll<T>(this ISet<T> s, IEnumerable<T> other) { s.UnionWith(other); } public static bool contains<T>(this ISet<T> s, T item) { return s.Contains(item); } public static bool containsAll<T>(this ISet<T> s, IEnumerable<T> list) { return s.IsSupersetOf(list); } public static bool remove<T>(this ISet<T> s, T item) { return s.Remove(item); } public static bool removeAll<T>(this ISet<T> s, IEnumerable<T> list) { bool modified = false; if (s.Count > list.Count()) { foreach (var item in list) modified |= s.Remove(item); } else { List<T> toRemove = new List<T>(); foreach (var item in s) { if (list.Contains(item)) { toRemove.Add(item); } } foreach (var i in toRemove) { s.Remove(i); modified = true; } } return modified; } public static void clear<T>(this ISet<T> s) { s.Clear(); } public static void retainAll<T>(this ISet<T> s, ISet<T> other) { foreach (var e in s) { if (!other.Contains(e)) s.Remove(e); } } public static void printStackTrace(this Exception e) { Console.WriteLine(e.StackTrace); } /// <summary> /// Locates resources in the same directory as this type /// </summary> public static Stream getResourceAsStream(this Type t, string name) { return t.FindAndGetManifestResourceStream(name); } public static int read(this TextReader reader, char[] buffer) { int bytesRead = reader.Read(buffer, 0, buffer.Length); // Convert the .NET 0 based bytes to the Java -1 behavior when reading is done. return bytesRead == 0 ? -1 : bytesRead; } public static string replaceFirst(this string text, string search, string replace) { var regex = new Regex(search); return regex.Replace(text, replace, 1); } public static byte[] ToByteArray(this sbyte[] arr) { var unsigned = new byte[arr.Length]; System.Buffer.BlockCopy(arr, 0, unsigned, 0, arr.Length); return unsigned; } } }
// // WindowFrame.cs // // Author: // Lluis Sanchez <[email protected]> // Konrad M. Kruczynski <[email protected]> // // Copyright (c) 2011 Xamarin Inc // Copyright (c) 2016 Antmicro Ltd // // 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. // // WindowFrame.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin 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 Xwt.Backends; using System.ComponentModel; using Xwt.Drawing; using Xwt.Motion; namespace Xwt { [BackendType (typeof(IWindowFrameBackend))] public class WindowFrame: XwtComponent, IAnimatable { EventHandler boundsChanged; EventHandler shown; EventHandler hidden; CloseRequestedHandler closeRequested; EventHandler closed; Point location; Size size; bool pendingReallocation; Image icon; WindowFrame transientFor; protected class WindowBackendHost: BackendHost<WindowFrame,IWindowFrameBackend>, IWindowFrameEventSink { protected override void OnBackendCreated () { Backend.Initialize (this); base.OnBackendCreated (); Parent.location = Backend.Bounds.Location; Parent.size = Backend.Bounds.Size; Backend.EnableEvent (WindowFrameEvent.BoundsChanged); } public void OnBoundsChanged (Rectangle bounds) { Parent.OnBoundsChanged (new BoundsChangedEventArgs () { Bounds = bounds }); } public virtual void OnShown () { Parent.OnShown (); } public virtual void OnHidden () { Parent.OnHidden (); } public virtual bool OnCloseRequested () { return Parent.OnCloseRequested (); } public virtual void OnClosed () { Parent.OnClosed (); } } static WindowFrame () { MapEvent (WindowFrameEvent.Shown, typeof(WindowFrame), "OnShown"); MapEvent (WindowFrameEvent.Hidden, typeof(WindowFrame), "OnHidden"); MapEvent (WindowFrameEvent.CloseRequested, typeof(WindowFrame), "OnCloseRequested"); MapEvent (WindowFrameEvent.Closed, typeof(WindowFrame), "OnClosed"); } public WindowFrame () { if (!(base.BackendHost is WindowBackendHost)) throw new InvalidOperationException ("CreateBackendHost for WindowFrame did not return a WindowBackendHost instance"); } public WindowFrame (string title): this () { Backend.Title = title; } protected override void Dispose (bool disposing) { base.Dispose (disposing); // Don't dispose the backend if this object is being finalized // The backend has to handle the finalizing on its own if (disposing && BackendHost.BackendCreated) Backend.Dispose (); } IWindowFrameBackend Backend { get { return (IWindowFrameBackend) BackendHost.Backend; } } protected override BackendHost CreateBackendHost () { return new WindowBackendHost (); } protected new WindowBackendHost BackendHost { get { return (WindowBackendHost) base.BackendHost; } } /// <summary> /// Gets or sets the name (not title) of this window. /// </summary> /// <value>The window name.</value> /// <remarks>The name can be used to identify this window by e.g. designers. /// The name of the window is not visible to the user. Use the Title property /// to modify the visible window title.</remarks> [DefaultValue (null)] public override string Name { get { return Backend.Name; } set { Backend.Name = value; } } public Rectangle ScreenBounds { get { return BackendBounds; } set { if (value.Width < 0) value.Width = 0; if (value.Height < 0) value.Height = 0; BackendBounds = value; if (Visible) AdjustSize (); } } public double X { get { return BackendBounds.X; } set { SetBackendLocation (value, Y); } } public double Y { get { return BackendBounds.Y; } set { SetBackendLocation (X, value); } } public double Width { get { return BackendBounds.Width; } set { if (value < 0) value = 0; SetBackendSize (value, -1); if (Visible) AdjustSize (); } } public double Height { get { return BackendBounds.Height; } set { if (value < 0) value = 0; SetBackendSize (-1, value); if (Visible) AdjustSize (); } } /// <summary> /// Size of the window, not including the decorations /// </summary> /// <value>The size.</value> public Size Size { get { return BackendBounds.Size; } set { if (value.Width < 0) value.Width = 0; if (value.Height < 0) value.Height = 0; SetBackendSize (value.Width, value.Height); if (Visible) AdjustSize (); } } public Point Location { get { return BackendBounds.Location; } set { SetBackendLocation (value.X, value.Y); } } public string Title { get { return Backend.Title; } set { Backend.Title = value; } } public Image Icon { get { return icon; } set { icon = value; Backend.SetIcon (icon != null ? icon.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null); } } public bool Decorated { get { return Backend.Decorated; } set { Backend.Decorated = value; } } public bool ShowInTaskbar { get { return Backend.ShowInTaskbar; } set { Backend.ShowInTaskbar = value; } } public WindowFrame TransientFor { get { return transientFor; } set { transientFor = value; Backend.SetTransientFor ((IWindowFrameBackend)(value as IFrontend).Backend); } } public bool Resizable { get { return Backend.Resizable; } set { Backend.Resizable = value; } } public bool Visible { get { return Backend.Visible; } set { Backend.Visible = value; } } [DefaultValue (true)] public bool Sensitive { get { return Backend.Sensitive; } set { Backend.Sensitive = value; } } public double Opacity { get { return Backend.Opacity; } set { Backend.Opacity = value; } } public bool HasFocus { get { return Backend.HasFocus; } } /// <summary> /// Gets or sets a value indicating whether this window is in full screen mode /// </summary> /// <value><c>true</c> if the window is in full screen mode; otherwise, <c>false</c>.</value> public bool FullScreen { get { return Backend.FullScreen; } set { Backend.FullScreen = value; } } /// <summary> /// Gets the screen on which most of the area of this window is placed /// </summary> /// <value>The screen.</value> public Screen Screen { get { if (!Visible) throw new InvalidOperationException ("The window is not visible"); return Desktop.GetScreen (Backend.Screen); } } public void Show () { if (!Visible) { AdjustSize (); Visible = true; } } internal virtual void AdjustSize () { } /// <summary> /// Presents a window to the user. This may mean raising the window in the stacking order, /// deiconifying it, moving it to the current desktop, and/or giving it the keyboard focus /// </summary> public void Present () { Backend.Present (); } protected virtual void OnShown () { if(shown != null) shown (this, EventArgs.Empty); } public void Hide () { Visible = false; } protected virtual void OnHidden () { if (hidden != null) hidden (this, EventArgs.Empty); } /// <summary> /// Closes the window /// </summary> /// <remarks>> /// Closes the window like if the user clicked on the close window button. /// The CloseRequested event is fired and subscribers can cancel the closing, /// so there is no guarantee that the window will actually close. /// This method doesn't dispose the window. The Dispose method has to be called. /// </remarks> public bool Close () { return Backend.Close (); } /// <summary> /// Called to check if the window can be closed /// </summary> /// <returns><c>true</c> if the window can be closed, <c>false</c> otherwise</returns> protected virtual bool OnCloseRequested () { if (closeRequested == null) return true; var eventArgs = new CloseRequestedEventArgs(); closeRequested (this, eventArgs); return eventArgs.AllowClose; } /// <summary> /// Called when the window has been closed by the user, or by a call to Close /// </summary> /// <remarks> /// This method is not called when the window is disposed, only when explicitly closed (either by code or by the user) /// </remarks> protected virtual void OnClosed () { if (closed != null) closed (this, EventArgs.Empty); } internal virtual void SetBackendSize (double width, double height) { Backend.SetSize (width, height); } internal virtual void SetBackendLocation (double x, double y) { location = new Point (x, y); Backend.Move (x, y); } internal virtual Rectangle BackendBounds { get { BackendHost.EnsureBackendLoaded (); return new Rectangle (location, size); } set { size = value.Size; location = value.Location; Backend.Bounds = value; } } protected virtual void OnBoundsChanged (BoundsChangedEventArgs a) { var bounds = new Rectangle (location, size); if (bounds != a.Bounds) { size = a.Bounds.Size; location = a.Bounds.Location; Reallocate (); if (boundsChanged != null) boundsChanged (this, a); } } internal void Reallocate () { if (!pendingReallocation) { pendingReallocation = true; BackendHost.ToolkitEngine.QueueExitAction (delegate { pendingReallocation = false; OnReallocate (); }); } } protected virtual void OnReallocate () { } void IAnimatable.BatchBegin () { } void IAnimatable.BatchCommit () { } public event EventHandler BoundsChanged { add { boundsChanged += value; } remove { boundsChanged -= value; } } public event EventHandler Shown { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.Shown, shown); shown += value; } remove { shown -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.Shown, shown); } } public event EventHandler Hidden { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.Hidden, hidden); hidden += value; } remove { hidden -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.Hidden, hidden); } } public event CloseRequestedHandler CloseRequested { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.CloseRequested, closeRequested); closeRequested += value; } remove { closeRequested -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.CloseRequested, closeRequested); } } /// <summary> /// Raised when the window has been closed by the user, or by a call to Close /// </summary> /// <remarks> /// This event is not raised when the window is disposed, only when explicitly closed (either by code or by the user) /// </remarks> public event EventHandler Closed { add { BackendHost.OnBeforeEventAdd (WindowFrameEvent.Closed, closed); closed += value; } remove { closed -= value; BackendHost.OnAfterEventRemove (WindowFrameEvent.Closed, closed); } } } public class BoundsChangedEventArgs: EventArgs { public Rectangle Bounds { get; set; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Cache.Query.Continuous { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Event; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Cache.Event; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests for continuous query. /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] [SuppressMessage("ReSharper", "PossibleNullReferenceException")] [SuppressMessage("ReSharper", "StaticMemberInGenericType")] public abstract class ContinuousQueryAbstractTest { /** Cache name: ATOMIC, backup. */ protected const string CACHE_ATOMIC_BACKUP = "atomic_backup"; /** Cache name: ATOMIC, no backup. */ protected const string CACHE_ATOMIC_NO_BACKUP = "atomic_no_backup"; /** Cache name: TRANSACTIONAL, backup. */ protected const string CACHE_TX_BACKUP = "transactional_backup"; /** Cache name: TRANSACTIONAL, no backup. */ protected const string CACHE_TX_NO_BACKUP = "transactional_no_backup"; /** Listener events. */ public static BlockingCollection<CallbackEvent> CB_EVTS = new BlockingCollection<CallbackEvent>(); /** Listener events. */ public static BlockingCollection<FilterEvent> FILTER_EVTS = new BlockingCollection<FilterEvent>(); /** First node. */ private IIgnite grid1; /** Second node. */ private IIgnite grid2; /** Cache on the first node. */ private ICache<int, BinarizableEntry> cache1; /** Cache on the second node. */ private ICache<int, BinarizableEntry> cache2; /** Cache name. */ private readonly string cacheName; /// <summary> /// Constructor. /// </summary> /// <param name="cacheName">Cache name.</param> protected ContinuousQueryAbstractTest(string cacheName) { this.cacheName = cacheName; } /// <summary> /// Set-up routine. /// </summary> [TestFixtureSetUp] public void SetUp() { GC.Collect(); TestUtils.JvmDebug = true; IgniteConfiguration cfg = new IgniteConfiguration(); BinaryConfiguration portCfg = new BinaryConfiguration(); ICollection<BinaryTypeConfiguration> portTypeCfgs = new List<BinaryTypeConfiguration>(); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableEntry))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableFilter))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(KeepBinaryFilter))); portCfg.TypeConfigurations = portTypeCfgs; cfg.BinaryConfiguration = portCfg; cfg.JvmClasspath = TestUtils.CreateTestClasspath(); cfg.JvmOptions = TestUtils.TestJavaOptions(); cfg.SpringConfigUrl = "config\\cache-query-continuous.xml"; cfg.GridName = "grid-1"; grid1 = Ignition.Start(cfg); cache1 = grid1.GetCache<int, BinarizableEntry>(cacheName); cfg.GridName = "grid-2"; grid2 = Ignition.Start(cfg); cache2 = grid2.GetCache<int, BinarizableEntry>(cacheName); } /// <summary> /// Tear-down routine. /// </summary> [TestFixtureTearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Before-test routine. /// </summary> [SetUp] public void BeforeTest() { CB_EVTS = new BlockingCollection<CallbackEvent>(); FILTER_EVTS = new BlockingCollection<FilterEvent>(); AbstractFilter<BinarizableEntry>.res = true; AbstractFilter<BinarizableEntry>.err = false; AbstractFilter<BinarizableEntry>.marshErr = false; AbstractFilter<BinarizableEntry>.unmarshErr = false; cache1.Remove(PrimaryKey(cache1)); cache1.Remove(PrimaryKey(cache2)); Assert.AreEqual(0, cache1.GetSize()); Assert.AreEqual(0, cache2.GetSize()); Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// Test arguments validation. /// </summary> [Test] public void TestValidation() { Assert.Throws<ArgumentException>(() => { cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(null)); }); } /// <summary> /// Test multiple closes. /// </summary> [Test] public void TestMultipleClose() { int key1 = PrimaryKey(cache1); int key2 = PrimaryKey(cache2); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); IDisposable qryHnd; using (qryHnd = cache1.QueryContinuous(qry)) { // Put from local node. cache1.GetAndPut(key1, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); // Put from remote node. cache2.GetAndPut(key2, Entry(key2)); CheckCallbackSingle(key2, null, Entry(key2)); } qryHnd.Dispose(); } /// <summary> /// Test regular callback operations. /// </summary> [Test] public void TestCallback() { CheckCallback(false); } /// <summary> /// Check regular callback execution. /// </summary> /// <param name="loc"></param> protected void CheckCallback(bool loc) { int key1 = PrimaryKey(cache1); int key2 = PrimaryKey(cache2); ContinuousQuery<int, BinarizableEntry> qry = loc ? new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>(), true) : new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); using (cache1.QueryContinuous(qry)) { // Put from local node. cache1.GetAndPut(key1, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); cache1.GetAndPut(key1, Entry(key1 + 1)); CheckCallbackSingle(key1, Entry(key1), Entry(key1 + 1)); cache1.Remove(key1); CheckCallbackSingle(key1, Entry(key1 + 1), null); // Put from remote node. cache2.GetAndPut(key2, Entry(key2)); if (loc) CheckNoCallback(100); else CheckCallbackSingle(key2, null, Entry(key2)); cache1.GetAndPut(key2, Entry(key2 + 1)); if (loc) CheckNoCallback(100); else CheckCallbackSingle(key2, Entry(key2), Entry(key2 + 1)); cache1.Remove(key2); if (loc) CheckNoCallback(100); else CheckCallbackSingle(key2, Entry(key2 + 1), null); } cache1.Put(key1, Entry(key1)); CheckNoCallback(100); cache1.Put(key2, Entry(key2)); CheckNoCallback(100); } /// <summary> /// Test Ignite injection into callback. /// </summary> [Test] public void TestCallbackInjection() { Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>(); Assert.IsNull(cb.ignite); using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb))) { Assert.IsNotNull(cb.ignite); } } /// <summary> /// Test binarizable filter logic. /// </summary> [Test] public void TestFilterBinarizable() { CheckFilter(true, false); } /// <summary> /// Test serializable filter logic. /// </summary> [Test] public void TestFilterSerializable() { CheckFilter(false, false); } /// <summary> /// Check filter. /// </summary> /// <param name="binarizable">Binarizable.</param> /// <param name="loc">Local cache flag.</param> protected void CheckFilter(bool binarizable, bool loc) { ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = loc ? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) : new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); using (cache1.QueryContinuous(qry)) { // Put from local node. int key1 = PrimaryKey(cache1); cache1.GetAndPut(key1, Entry(key1)); CheckFilterSingle(key1, null, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); // Put from remote node. int key2 = PrimaryKey(cache2); cache1.GetAndPut(key2, Entry(key2)); if (loc) { CheckNoFilter(key2); CheckNoCallback(key2); } else { CheckFilterSingle(key2, null, Entry(key2)); CheckCallbackSingle(key2, null, Entry(key2)); } AbstractFilter<BinarizableEntry>.res = false; // Ignored put from local node. cache1.GetAndPut(key1, Entry(key1 + 1)); CheckFilterSingle(key1, Entry(key1), Entry(key1 + 1)); CheckNoCallback(100); // Ignored put from remote node. cache1.GetAndPut(key2, Entry(key2 + 1)); if (loc) CheckNoFilter(100); else CheckFilterSingle(key2, Entry(key2), Entry(key2 + 1)); CheckNoCallback(100); } } /// <summary> /// Test binarizable filter error during invoke. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterInvokeErrorBinarizable() { CheckFilterInvokeError(true); } /// <summary> /// Test serializable filter error during invoke. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterInvokeErrorSerializable() { CheckFilterInvokeError(false); } /// <summary> /// Check filter error handling logic during invoke. /// </summary> private void CheckFilterInvokeError(bool binarizable) { AbstractFilter<BinarizableEntry>.err = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); using (cache1.QueryContinuous(qry)) { // Put from local node. try { cache1.GetAndPut(PrimaryKey(cache1), Entry(1)); Assert.Fail("Should not reach this place."); } catch (IgniteException) { // No-op. } catch (Exception) { Assert.Fail("Unexpected error."); } // Put from remote node. try { cache1.GetAndPut(PrimaryKey(cache2), Entry(1)); Assert.Fail("Should not reach this place."); } catch (IgniteException) { // No-op. } catch (Exception) { Assert.Fail("Unexpected error."); } } } /// <summary> /// Test binarizable filter marshalling error. /// </summary> [Test] public void TestFilterMarshalErrorBinarizable() { CheckFilterMarshalError(true); } /// <summary> /// Test serializable filter marshalling error. /// </summary> [Test] public void TestFilterMarshalErrorSerializable() { CheckFilterMarshalError(false); } /// <summary> /// Check filter marshal error handling. /// </summary> /// <param name="binarizable">Binarizable flag.</param> private void CheckFilterMarshalError(bool binarizable) { AbstractFilter<BinarizableEntry>.marshErr = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>)new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); Assert.Throws<Exception>(() => { using (cache1.QueryContinuous(qry)) { // No-op. } }); } /// <summary> /// Test non-serializable filter error. /// </summary> [Test] public void TestFilterNonSerializable() { CheckFilterNonSerializable(false); } /// <summary> /// Test non-serializable filter behavior. /// </summary> /// <param name="loc"></param> protected void CheckFilterNonSerializable(bool loc) { AbstractFilter<BinarizableEntry>.unmarshErr = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = new LocalFilter(); ContinuousQuery<int, BinarizableEntry> qry = loc ? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) : new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); if (loc) { using (cache1.QueryContinuous(qry)) { // Local put must be fine. int key1 = PrimaryKey(cache1); cache1.GetAndPut(key1, Entry(key1)); CheckFilterSingle(key1, null, Entry(key1)); } } else { Assert.Throws<BinaryObjectException>(() => { using (cache1.QueryContinuous(qry)) { // No-op. } }); } } /// <summary> /// Test binarizable filter unmarshalling error. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterUnmarshalErrorBinarizable() { CheckFilterUnmarshalError(true); } /// <summary> /// Test serializable filter unmarshalling error. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterUnmarshalErrorSerializable() { CheckFilterUnmarshalError(false); } /// <summary> /// Check filter unmarshal error handling. /// </summary> /// <param name="binarizable">Binarizable flag.</param> private void CheckFilterUnmarshalError(bool binarizable) { AbstractFilter<BinarizableEntry>.unmarshErr = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); using (cache1.QueryContinuous(qry)) { // Local put must be fine. int key1 = PrimaryKey(cache1); cache1.GetAndPut(key1, Entry(key1)); CheckFilterSingle(key1, null, Entry(key1)); // Remote put must fail. try { cache1.GetAndPut(PrimaryKey(cache2), Entry(1)); Assert.Fail("Should not reach this place."); } catch (IgniteException) { // No-op. } catch (Exception) { Assert.Fail("Unexpected error."); } } } /// <summary> /// Test Ignite injection into filters. /// </summary> [Test] public void TestFilterInjection() { Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>(); BinarizableFilter filter = new BinarizableFilter(); Assert.IsNull(filter.ignite); using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb, filter))) { // Local injection. Assert.IsNotNull(filter.ignite); // Remote injection. cache1.GetAndPut(PrimaryKey(cache2), Entry(1)); FilterEvent evt; Assert.IsTrue(FILTER_EVTS.TryTake(out evt, 500)); Assert.IsNotNull(evt.ignite); } } /// <summary> /// Test "keep-binary" scenario. /// </summary> [Test] public void TestKeepBinary() { var cache = cache1.WithKeepBinary<int, IBinaryObject>(); ContinuousQuery<int, IBinaryObject> qry = new ContinuousQuery<int, IBinaryObject>( new Listener<IBinaryObject>(), new KeepBinaryFilter()); using (cache.QueryContinuous(qry)) { // 1. Local put. cache1.GetAndPut(PrimaryKey(cache1), Entry(1)); CallbackEvent cbEvt; FilterEvent filterEvt; Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500)); Assert.AreEqual(PrimaryKey(cache1), filterEvt.entry.Key); Assert.AreEqual(null, filterEvt.entry.OldValue); Assert.AreEqual(Entry(1), (filterEvt.entry.Value as IBinaryObject) .Deserialize<BinarizableEntry>()); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); Assert.AreEqual(1, cbEvt.entries.Count); Assert.AreEqual(PrimaryKey(cache1), cbEvt.entries.First().Key); Assert.AreEqual(null, cbEvt.entries.First().OldValue); Assert.AreEqual(Entry(1), (cbEvt.entries.First().Value as IBinaryObject) .Deserialize<BinarizableEntry>()); // 2. Remote put. ClearEvents(); cache1.GetAndPut(PrimaryKey(cache2), Entry(2)); Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500)); Assert.AreEqual(PrimaryKey(cache2), filterEvt.entry.Key); Assert.AreEqual(null, filterEvt.entry.OldValue); Assert.AreEqual(Entry(2), (filterEvt.entry.Value as IBinaryObject) .Deserialize<BinarizableEntry>()); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); Assert.AreEqual(1, cbEvt.entries.Count); Assert.AreEqual(PrimaryKey(cache2), cbEvt.entries.First().Key); Assert.AreEqual(null, cbEvt.entries.First().OldValue); Assert.AreEqual(Entry(2), (cbEvt.entries.First().Value as IBinaryObject).Deserialize<BinarizableEntry>()); } } /// <summary> /// Test value types (special handling is required for nulls). /// </summary> [Test] public void TestValueTypes() { var cache = grid1.GetCache<int, int>(cacheName); var qry = new ContinuousQuery<int, int>(new Listener<int>()); var key = PrimaryKey(cache); using (cache.QueryContinuous(qry)) { // First update cache.Put(key, 1); CallbackEvent cbEvt; Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); var cbEntry = cbEvt.entries.Single(); Assert.IsFalse(cbEntry.HasOldValue); Assert.IsTrue(cbEntry.HasValue); Assert.AreEqual(key, cbEntry.Key); Assert.AreEqual(null, cbEntry.OldValue); Assert.AreEqual(1, cbEntry.Value); // Second update cache.Put(key, 2); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); cbEntry = cbEvt.entries.Single(); Assert.IsTrue(cbEntry.HasOldValue); Assert.IsTrue(cbEntry.HasValue); Assert.AreEqual(key, cbEntry.Key); Assert.AreEqual(1, cbEntry.OldValue); Assert.AreEqual(2, cbEntry.Value); // Remove cache.Remove(key); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); cbEntry = cbEvt.entries.Single(); Assert.IsTrue(cbEntry.HasOldValue); Assert.IsFalse(cbEntry.HasValue); Assert.AreEqual(key, cbEntry.Key); Assert.AreEqual(2, cbEntry.OldValue); Assert.AreEqual(null, cbEntry.Value); } } /// <summary> /// Test whether buffer size works fine. /// </summary> [Test] public void TestBufferSize() { // Put two remote keys in advance. List<int> rmtKeys = PrimaryKeys(cache2, 2); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); qry.BufferSize = 2; qry.TimeInterval = TimeSpan.FromMilliseconds(1000000); using (cache1.QueryContinuous(qry)) { qry.BufferSize = 2; cache1.GetAndPut(rmtKeys[0], Entry(rmtKeys[0])); CheckNoCallback(100); cache1.GetAndPut(rmtKeys[1], Entry(rmtKeys[1])); CallbackEvent evt; Assert.IsTrue(CB_EVTS.TryTake(out evt, 1000)); Assert.AreEqual(2, evt.entries.Count); var entryRmt0 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[0]); }); var entryRmt1 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[1]); }); Assert.AreEqual(rmtKeys[0], entryRmt0.Key); Assert.IsNull(entryRmt0.OldValue); Assert.AreEqual(Entry(rmtKeys[0]), entryRmt0.Value); Assert.AreEqual(rmtKeys[1], entryRmt1.Key); Assert.IsNull(entryRmt1.OldValue); Assert.AreEqual(Entry(rmtKeys[1]), entryRmt1.Value); } cache1.Remove(rmtKeys[0]); cache1.Remove(rmtKeys[1]); } /// <summary> /// Test whether timeout works fine. /// </summary> [Test] public void TestTimeout() { int key1 = PrimaryKey(cache1); int key2 = PrimaryKey(cache2); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); qry.BufferSize = 2; qry.TimeInterval = TimeSpan.FromMilliseconds(500); using (cache1.QueryContinuous(qry)) { // Put from local node. cache1.GetAndPut(key1, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); // Put from remote node. cache1.GetAndPut(key2, Entry(key2)); CheckNoCallback(100); CheckCallbackSingle(key2, null, Entry(key2), 1000); } } /// <summary> /// Test whether nested Ignite API call from callback works fine. /// </summary> [Test] public void TestNestedCallFromCallback() { var cache = cache1.WithKeepBinary<int, IBinaryObject>(); int key = PrimaryKey(cache1); NestedCallListener cb = new NestedCallListener(); using (cache.QueryContinuous(new ContinuousQuery<int, IBinaryObject>(cb))) { cache1.GetAndPut(key, Entry(key)); cb.countDown.Wait(); } cache.Remove(key); } /// <summary> /// Tests the initial query. /// </summary> [Test] public void TestInitialQuery() { // Scan query, GetAll TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.GetAll()); // Scan query, iterator TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.ToList()); // Sql query, GetAll TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.GetAll()); // Sql query, iterator TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.ToList()); // Text query, GetAll TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.GetAll()); // Text query, iterator TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.ToList()); // Test exception: invalid initial query var ex = Assert.Throws<IgniteException>( () => TestInitialQuery(new TextQuery(typeof (BinarizableEntry), "*"), cur => cur.GetAll())); Assert.AreEqual("Cannot parse '*': '*' or '?' not allowed as first character in WildcardQuery", ex.Message); } /// <summary> /// Tests the initial query. /// </summary> private void TestInitialQuery(QueryBase initialQry, Func<IQueryCursor<ICacheEntry<int, BinarizableEntry>>, IEnumerable<ICacheEntry<int, BinarizableEntry>>> getAllFunc) { var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); cache1.Put(11, Entry(11)); cache1.Put(12, Entry(12)); cache1.Put(33, Entry(33)); try { IContinuousQueryHandle<ICacheEntry<int, BinarizableEntry>> contQry; using (contQry = cache1.QueryContinuous(qry, initialQry)) { // Check initial query var initialEntries = getAllFunc(contQry.GetInitialQueryCursor()).Distinct().OrderBy(x => x.Key).ToList(); Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor()); Assert.AreEqual(2, initialEntries.Count); for (int i = 0; i < initialEntries.Count; i++) { Assert.AreEqual(i + 11, initialEntries[i].Key); Assert.AreEqual(i + 11, initialEntries[i].Value.val); } // Check continuous query cache1.Put(44, Entry(44)); CheckCallbackSingle(44, null, Entry(44)); } Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor()); contQry.Dispose(); // multiple dispose calls are ok } finally { cache1.Clear(); } } /// <summary> /// Check single filter event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected value.</param> private void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal) { CheckFilterSingle(expKey, expOldVal, expVal, 1000); ClearEvents(); } /// <summary> /// Check single filter event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected value.</param> /// <param name="timeout">Timeout.</param> private static void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout) { FilterEvent evt; Assert.IsTrue(FILTER_EVTS.TryTake(out evt, timeout)); Assert.AreEqual(expKey, evt.entry.Key); Assert.AreEqual(expOldVal, evt.entry.OldValue); Assert.AreEqual(expVal, evt.entry.Value); ClearEvents(); } /// <summary> /// Clears the events collection. /// </summary> private static void ClearEvents() { while (FILTER_EVTS.Count > 0) FILTER_EVTS.Take(); } /// <summary> /// Ensure that no filter events are logged. /// </summary> /// <param name="timeout">Timeout.</param> private static void CheckNoFilter(int timeout) { FilterEvent evt; Assert.IsFalse(FILTER_EVTS.TryTake(out evt, timeout)); } /// <summary> /// Check single callback event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected new value.</param> private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal) { CheckCallbackSingle(expKey, expOldVal, expVal, 1000); } /// <summary> /// Check single callback event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected new value.</param> /// <param name="timeout">Timeout.</param> private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout) { CallbackEvent evt; Assert.IsTrue(CB_EVTS.TryTake(out evt, timeout)); Assert.AreEqual(1, evt.entries.Count); Assert.AreEqual(expKey, evt.entries.First().Key); Assert.AreEqual(expOldVal, evt.entries.First().OldValue); Assert.AreEqual(expVal, evt.entries.First().Value); } /// <summary> /// Ensure that no callback events are logged. /// </summary> /// <param name="timeout">Timeout.</param> private void CheckNoCallback(int timeout) { CallbackEvent evt; Assert.IsFalse(CB_EVTS.TryTake(out evt, timeout)); } /// <summary> /// Craate entry. /// </summary> /// <param name="val">Value.</param> /// <returns>Entry.</returns> private static BinarizableEntry Entry(int val) { return new BinarizableEntry(val); } /// <summary> /// Get primary key for cache. /// </summary> /// <param name="cache">Cache.</param> /// <returns>Primary key.</returns> private static int PrimaryKey<T>(ICache<int, T> cache) { return PrimaryKeys(cache, 1)[0]; } /// <summary> /// Get primary keys for cache. /// </summary> /// <param name="cache">Cache.</param> /// <param name="cnt">Amount of keys.</param> /// <param name="startFrom">Value to start from.</param> /// <returns></returns> private static List<int> PrimaryKeys<T>(ICache<int, T> cache, int cnt, int startFrom = 0) { IClusterNode node = cache.Ignite.GetCluster().GetLocalNode(); ICacheAffinity aff = cache.Ignite.GetAffinity(cache.Name); List<int> keys = new List<int>(cnt); for (int i = startFrom; i < startFrom + 100000; i++) { if (aff.IsPrimary(node, i)) { keys.Add(i); if (keys.Count == cnt) return keys; } } Assert.Fail("Failed to find " + cnt + " primary keys."); return null; } /// <summary> /// Creates object-typed event. /// </summary> private static ICacheEntryEvent<object, object> CreateEvent<T, V>(ICacheEntryEvent<T,V> e) { if (!e.HasOldValue) return new CacheEntryCreateEvent<object, object>(e.Key, e.Value); if (!e.HasValue) return new CacheEntryRemoveEvent<object, object>(e.Key, e.OldValue); return new CacheEntryUpdateEvent<object, object>(e.Key, e.OldValue, e.Value); } /// <summary> /// Binarizable entry. /// </summary> public class BinarizableEntry { /** Value. */ public readonly int val; /** <inheritDot /> */ public override int GetHashCode() { return val; } /// <summary> /// Constructor. /// </summary> /// <param name="val">Value.</param> public BinarizableEntry(int val) { this.val = val; } /** <inheritDoc /> */ public override bool Equals(object obj) { return obj != null && obj is BinarizableEntry && ((BinarizableEntry)obj).val == val; } } /// <summary> /// Abstract filter. /// </summary> [Serializable] public abstract class AbstractFilter<V> : ICacheEntryEventFilter<int, V> { /** Result. */ public static volatile bool res = true; /** Throw error on invocation. */ public static volatile bool err; /** Throw error during marshalling. */ public static volatile bool marshErr; /** Throw error during unmarshalling. */ public static volatile bool unmarshErr; /** Grid. */ [InstanceResource] public IIgnite ignite; /** <inheritDoc /> */ public bool Evaluate(ICacheEntryEvent<int, V> evt) { if (err) throw new Exception("Filter error."); FILTER_EVTS.Add(new FilterEvent(ignite, CreateEvent(evt))); return res; } } /// <summary> /// Filter which cannot be serialized. /// </summary> public class LocalFilter : AbstractFilter<BinarizableEntry> { // No-op. } /// <summary> /// Binarizable filter. /// </summary> public class BinarizableFilter : AbstractFilter<BinarizableEntry>, IBinarizable { /** <inheritDoc /> */ public void WriteBinary(IBinaryWriter writer) { if (marshErr) throw new Exception("Filter marshalling error."); } /** <inheritDoc /> */ public void ReadBinary(IBinaryReader reader) { if (unmarshErr) throw new Exception("Filter unmarshalling error."); } } /// <summary> /// Serializable filter. /// </summary> [Serializable] public class SerializableFilter : AbstractFilter<BinarizableEntry>, ISerializable { /// <summary> /// Constructor. /// </summary> public SerializableFilter() { // No-op. } /// <summary> /// Serialization constructor. /// </summary> /// <param name="info">Info.</param> /// <param name="context">Context.</param> protected SerializableFilter(SerializationInfo info, StreamingContext context) { if (unmarshErr) throw new Exception("Filter unmarshalling error."); } /** <inheritDoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { if (marshErr) throw new Exception("Filter marshalling error."); } } /// <summary> /// Filter for "keep-binary" scenario. /// </summary> public class KeepBinaryFilter : AbstractFilter<IBinaryObject> { // No-op. } /// <summary> /// Listener. /// </summary> public class Listener<V> : ICacheEntryEventListener<int, V> { [InstanceResource] public IIgnite ignite; /** <inheritDoc /> */ public void OnEvent(IEnumerable<ICacheEntryEvent<int, V>> evts) { CB_EVTS.Add(new CallbackEvent(evts.Select(CreateEvent).ToList())); } } /// <summary> /// Listener with nested Ignite API call. /// </summary> public class NestedCallListener : ICacheEntryEventListener<int, IBinaryObject> { /** Event. */ public readonly CountdownEvent countDown = new CountdownEvent(1); public void OnEvent(IEnumerable<ICacheEntryEvent<int, IBinaryObject>> evts) { foreach (ICacheEntryEvent<int, IBinaryObject> evt in evts) { IBinaryObject val = evt.Value; IBinaryType meta = val.GetBinaryType(); Assert.AreEqual(typeof(BinarizableEntry).Name, meta.TypeName); } countDown.Signal(); } } /// <summary> /// Filter event. /// </summary> public class FilterEvent { /** Grid. */ public IIgnite ignite; /** Entry. */ public ICacheEntryEvent<object, object> entry; /// <summary> /// Constructor. /// </summary> /// <param name="ignite">Grid.</param> /// <param name="entry">Entry.</param> public FilterEvent(IIgnite ignite, ICacheEntryEvent<object, object> entry) { this.ignite = ignite; this.entry = entry; } } /// <summary> /// Callbakc event. /// </summary> public class CallbackEvent { /** Entries. */ public ICollection<ICacheEntryEvent<object, object>> entries; /// <summary> /// Constructor. /// </summary> /// <param name="entries">Entries.</param> public CallbackEvent(ICollection<ICacheEntryEvent<object, object>> entries) { this.entries = entries; } } /// <summary> /// ScanQuery filter for InitialQuery test. /// </summary> [Serializable] private class InitialQueryScanFilter : ICacheEntryFilter<int, BinarizableEntry> { /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, BinarizableEntry> entry) { return entry.Key < 33; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Analyzer.Utilities.PooledObjects; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { using static MicrosoftCodeQualityAnalyzersResources; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldDifferByMoreThanCaseAnalyzer : DiagnosticAnalyzer { public const string RuleId = "CA1708"; public const string Namespace = "Namespaces"; public const string Type = "Types"; public const string Member = "Members"; public const string Parameter = "Parameters of"; internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( RuleId, CreateLocalizableResourceString(nameof(IdentifiersShouldDifferByMoreThanCaseTitle)), CreateLocalizableResourceString(nameof(IdentifiersShouldDifferByMoreThanCaseMessage)), DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: CreateLocalizableResourceString(nameof(IdentifiersShouldDifferByMoreThanCaseDescription)), isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationAction(AnalyzeCompilation); context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType); } private static void AnalyzeCompilation(CompilationAnalysisContext context) { IEnumerable<INamespaceSymbol> globalNamespaces = context.Compilation.GlobalNamespace.GetNamespaceMembers() .Where(item => Equals(item.ContainingAssembly, context.Compilation.Assembly)); IEnumerable<INamedTypeSymbol> globalTypes = context.Compilation.GlobalNamespace.GetTypeMembers().Where(item => Equals(item.ContainingAssembly, context.Compilation.Assembly) && MatchesConfiguredVisibility(item, context.Options, context.Compilation)); CheckTypeNames(globalTypes, context); CheckNamespaceMembers(globalNamespaces, context); } private static void AnalyzeSymbol(SymbolAnalysisContext context) { var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; // Do not descent into non-publicly visible types by default // Note: This is the behavior of FxCop, it might be more correct to descend into internal but not private // types because "InternalsVisibleTo" could be set. But it might be bad for users to start seeing warnings // where they previously did not from FxCop. // Note that end user can now override this default behavior via options. if (!context.Options.MatchesConfiguredVisibility(Rule, namedTypeSymbol, context.Compilation)) { return; } // Get externally visible members in the given type IEnumerable<ISymbol> members = namedTypeSymbol.GetMembers() .Where(item => !item.IsAccessorMethod() && MatchesConfiguredVisibility(item, context.Options, context.Compilation)); if (members.Any()) { // Check parameters names of externally visible members with parameters CheckParameterMembers(members, context.ReportDiagnostic); // Check names of externally visible type members and their members CheckTypeMembers(members, context.ReportDiagnostic); } } private static void CheckNamespaceMembers(IEnumerable<INamespaceSymbol> namespaces, CompilationAnalysisContext context) { HashSet<INamespaceSymbol> excludedNamespaces = new HashSet<INamespaceSymbol>(); foreach (INamespaceSymbol @namespace in namespaces) { // Get all the potentially externally visible types in the namespace IEnumerable<INamedTypeSymbol> typeMembers = @namespace.GetTypeMembers().Where(item => Equals(item.ContainingAssembly, context.Compilation.Assembly) && MatchesConfiguredVisibility(item, context.Options, context.Compilation)); if (typeMembers.Any()) { CheckTypeNames(typeMembers, context); } else { // If the namespace does not contain any externally visible types then exclude it from name check excludedNamespaces.Add(@namespace); } IEnumerable<INamespaceSymbol> namespaceMembers = @namespace.GetNamespaceMembers(); if (namespaceMembers.Any()) { CheckNamespaceMembers(namespaceMembers, context); // If there is a child namespace that has externally visible types, then remove the parent namespace from exclusion list if (namespaceMembers.Any(item => !excludedNamespaces.Contains(item))) { excludedNamespaces.Remove(@namespace); } } } // Before name check, remove all namespaces that don't contain externally visible types in current scope namespaces = namespaces.Where(item => !excludedNamespaces.Contains(item)); CheckNamespaceNames(namespaces, context); } private static void CheckTypeMembers(IEnumerable<ISymbol> members, Action<Diagnostic> addDiagnostic) { // If there is only one member, then return if (!members.Skip(1).Any()) { return; } using var overloadsToSkip = PooledHashSet<ISymbol>.GetInstance(); using var membersByName = PooledDictionary<string, PooledHashSet<ISymbol>>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var member in members) { // Ignore constructors, indexers, operators and destructors for name check if (member.IsConstructor() || member.IsDestructor() || member.IsIndexer() || member.IsUserDefinedOperator() || overloadsToSkip.Contains(member)) { continue; } var name = DiagnosticHelpers.GetMemberName(member); if (!membersByName.TryGetValue(name, out var membersWithName)) { membersWithName = PooledHashSet<ISymbol>.GetInstance(); membersByName[name] = membersWithName; } membersWithName.Add(member); if (member is IMethodSymbol method) { foreach (var overload in method.GetOverloads()) { overloadsToSkip.Add(overload); } } } foreach (var (name, membersWithName) in membersByName) { if (membersWithName.Count > 1 && !membersWithName.All(m => m.IsOverride)) { ISymbol symbol = membersWithName.First().ContainingSymbol; addDiagnostic(symbol.CreateDiagnostic(Rule, Member, GetSymbolDisplayString(membersWithName))); } membersWithName.Dispose(); } } private static void CheckParameterMembers(IEnumerable<ISymbol> members, Action<Diagnostic> addDiagnostic) { foreach (var member in members) { if (IsViolatingMember(member) || IsViolatingDelegate(member)) { addDiagnostic(member.CreateDiagnostic(Rule, Parameter, member.ToDisplayString())); } } return; // Local functions static bool IsViolatingMember(ISymbol member) => member.ContainingType.DelegateInvokeMethod == null && HasViolatingParameters(member); static bool IsViolatingDelegate(ISymbol member) => member is INamedTypeSymbol typeSymbol && typeSymbol.DelegateInvokeMethod != null && HasViolatingParameters(typeSymbol.DelegateInvokeMethod); } #region NameCheck Methods private static bool HasViolatingParameters(ISymbol symbol) { var parameters = symbol.GetParameters(); // We only analyze symbols with more then one parameter. if (parameters.Length <= 1) { return false; } using var uniqueNames = PooledHashSet<string>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var parameter in parameters) { if (!uniqueNames.Add(parameter.Name)) { return true; } } return false; } private static void CheckTypeNames(IEnumerable<INamedTypeSymbol> types, CompilationAnalysisContext context) { // If there is only one type, then return if (!types.Skip(1).Any()) { return; } using var typesByName = PooledDictionary<string, PooledHashSet<ISymbol>>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var type in types) { var name = DiagnosticHelpers.GetMemberName(type); if (!typesByName.TryGetValue(name, out var typesWithName)) { typesWithName = PooledHashSet<ISymbol>.GetInstance(); typesByName[name] = typesWithName; } typesWithName.Add(type); } foreach (var (_, typesWithName) in typesByName) { if (typesWithName.Count > 1) { context.ReportNoLocationDiagnostic(Rule, Type, GetSymbolDisplayString(typesWithName)); } typesWithName.Dispose(); } } private static void CheckNamespaceNames(IEnumerable<INamespaceSymbol> namespaces, CompilationAnalysisContext context) { // If there is only one namespace, then return if (!namespaces.Skip(1).Any()) { return; } using var namespacesByName = PooledDictionary<string, PooledHashSet<ISymbol>>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var namespaceSym in namespaces) { var name = namespaceSym.ToDisplayString(); if (!namespacesByName.TryGetValue(name, out var namespacesWithName)) { namespacesWithName = PooledHashSet<ISymbol>.GetInstance(); namespacesByName[name] = namespacesWithName; } namespacesWithName.Add(namespaceSym); } foreach (var (_, namespacesWithName) in namespacesByName) { if (namespacesWithName.Count > 1) { context.ReportNoLocationDiagnostic(Rule, Namespace, GetSymbolDisplayString(namespacesWithName)); } namespacesWithName.Dispose(); } } #endregion #region Helper Methods private static string GetSymbolDisplayString(PooledHashSet<ISymbol> group) { return string.Join(", ", group.Select(s => s.ToDisplayString()).OrderBy(k => k, StringComparer.Ordinal)); } public static bool MatchesConfiguredVisibility(ISymbol symbol, AnalyzerOptions options, Compilation compilation) { var defaultAllowedVisibilties = SymbolVisibilityGroup.Public | SymbolVisibilityGroup.Internal; var allowedVisibilities = options.GetSymbolVisibilityGroupOption(Rule, symbol, compilation, defaultAllowedVisibilties); return allowedVisibilities.Contains(symbol.GetResultantVisibility()); } #endregion } }
/* * 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 Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Grid { public class GridServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 414 private static string LogHeader = "[GRID HANDLER]"; #pragma warning restore 414 private IGridService m_GridService; public GridServerPostHandler(IGridService service, IServiceAuth auth) : base("POST", "/grid", auth) { m_GridService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string body; using(StreamReader sr = new StreamReader(requestData)) body = sr.ReadToEnd(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); switch (method) { case "register": return Register(request); case "deregister": return Deregister(request); case "get_neighbours": return GetNeighbours(request); case "get_region_by_uuid": return GetRegionByUUID(request); case "get_region_by_position": return GetRegionByPosition(request); case "get_region_by_name": return GetRegionByName(request); case "get_regions_by_name": return GetRegionsByName(request); case "get_region_range": return GetRegionRange(request); case "get_default_regions": return GetDefaultRegions(request); case "get_default_hypergrid_regions": return GetDefaultHypergridRegions(request); case "get_fallback_regions": return GetFallbackRegions(request); case "get_hyperlinks": return GetHyperlinks(request); case "get_region_flags": return GetRegionFlags(request); case "get_grid_extra_features": return GetGridExtraFeatures(request); } m_log.DebugFormat("[GRID HANDLER]: unknown method request {0}", method); } catch (Exception e) { m_log.ErrorFormat("[GRID HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } return FailureResult(); } #region Method-specific handlers byte[] Register(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to register region"); int versionNumberMin = 0, versionNumberMax = 0; if (request.ContainsKey("VERSIONMIN")) Int32.TryParse(request["VERSIONMIN"].ToString(), out versionNumberMin); else m_log.WarnFormat("[GRID HANDLER]: no minimum protocol version in request to register region"); if (request.ContainsKey("VERSIONMAX")) Int32.TryParse(request["VERSIONMAX"].ToString(), out versionNumberMax); else m_log.WarnFormat("[GRID HANDLER]: no maximum protocol version in request to register region"); // Check the protocol version // This is how it works: // Example 1: // Client: [0 0] // Server: [1 1] // ==> fail // Example 2: // Client: [1 1] // Server: [0 0] // ==> fail // Example 3: // Client: [0 1] // Server: [1 1] // ==> success // Example 4: // Client: [1 1] // Server: [0 1] // ==> success if ((versionNumberMin > ProtocolVersions.ServerProtocolVersionMax || versionNumberMax < ProtocolVersions.ServerProtocolVersionMin)) { // Can't do, there is no overlap in the acceptable ranges return FailureResult(); } Dictionary<string, object> rinfoData = new Dictionary<string, object>(); GridRegion rinfo = null; try { foreach (KeyValuePair<string, object> kvp in request) rinfoData[kvp.Key] = kvp.Value.ToString(); rinfo = new GridRegion(rinfoData); } catch (Exception e) { m_log.DebugFormat("[GRID HANDLER]: exception unpacking region data: {0}", e); } string result = "Error communicating with grid service"; if (rinfo != null) result = m_GridService.RegisterRegion(scopeID, rinfo); if (result == String.Empty) return SuccessResult(); else return FailureResult(result); } byte[] Deregister(Dictionary<string, object> request) { UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to deregister region"); bool result = m_GridService.DeregisterRegion(regionID); if (result) return SuccessResult(); else return FailureResult(); } byte[] GetNeighbours(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); List<GridRegion> rinfos = m_GridService.GetNeighbours(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionByUUID(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); GridRegion rinfo = m_GridService.GetRegionByUUID(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionByPosition(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by position"); int x = 0, y = 0; if (request.ContainsKey("X")) Int32.TryParse(request["X"].ToString(), out x); else m_log.WarnFormat("[GRID HANDLER]: no X in request to get region by position"); if (request.ContainsKey("Y")) Int32.TryParse(request["Y"].ToString(), out y); else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get region by position"); // m_log.DebugFormat("{0} GetRegionByPosition: loc=<{1},{2}>", LogHeader, x, y); GridRegion rinfo = m_GridService.GetRegionByPosition(scopeID, x, y); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionByName(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by name"); string regionName = string.Empty; if (request.ContainsKey("NAME")) regionName = request["NAME"].ToString(); else m_log.WarnFormat("[GRID HANDLER]: no name in request to get region by name"); GridRegion rinfo = m_GridService.GetRegionByName(scopeID, regionName); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionsByName(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get regions by name"); string regionName = string.Empty; if (request.ContainsKey("NAME")) regionName = request["NAME"].ToString(); else m_log.WarnFormat("[GRID HANDLER]: no NAME in request to get regions by name"); int max = 0; if (request.ContainsKey("MAX")) Int32.TryParse(request["MAX"].ToString(), out max); else m_log.WarnFormat("[GRID HANDLER]: no MAX in request to get regions by name"); List<GridRegion> rinfos = m_GridService.GetRegionsByName(scopeID, regionName, max); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionRange(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); int xmin = 0, xmax = 0, ymin = 0, ymax = 0; if (request.ContainsKey("XMIN")) Int32.TryParse(request["XMIN"].ToString(), out xmin); else m_log.WarnFormat("[GRID HANDLER]: no XMIN in request to get region range"); if (request.ContainsKey("XMAX")) Int32.TryParse(request["XMAX"].ToString(), out xmax); else m_log.WarnFormat("[GRID HANDLER]: no XMAX in request to get region range"); if (request.ContainsKey("YMIN")) Int32.TryParse(request["YMIN"].ToString(), out ymin); else m_log.WarnFormat("[GRID HANDLER]: no YMIN in request to get region range"); if (request.ContainsKey("YMAX")) Int32.TryParse(request["YMAX"].ToString(), out ymax); else m_log.WarnFormat("[GRID HANDLER]: no YMAX in request to get region range"); List<GridRegion> rinfos = m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetDefaultRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); List<GridRegion> rinfos = m_GridService.GetDefaultRegions(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetDefaultHypergridRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); List<GridRegion> rinfos = m_GridService.GetDefaultHypergridRegions(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetFallbackRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get fallback regions"); int x = 0, y = 0; if (request.ContainsKey("X")) Int32.TryParse(request["X"].ToString(), out x); else m_log.WarnFormat("[GRID HANDLER]: no X in request to get fallback regions"); if (request.ContainsKey("Y")) Int32.TryParse(request["Y"].ToString(), out y); else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get fallback regions"); List<GridRegion> rinfos = m_GridService.GetFallbackRegions(scopeID, x, y); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetHyperlinks(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetHyperlinks"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get linked regions"); List<GridRegion> rinfos = m_GridService.GetHyperlinks(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionFlags(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get RegionFlags"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get RegionFlags"); int flags = m_GridService.GetRegionFlags(scopeID, regionID); // m_log.DebugFormat("[GRID HANDLER]: flags for region {0}: {1}", regionID, flags); Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = flags.ToString(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetGridExtraFeatures(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object> (); Dictionary<string, object> extraFeatures = m_GridService.GetExtraFeatures (); foreach (string key in extraFeatures.Keys) { result [key] = extraFeatures [key]; } string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } #endregion #region Misc private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] FailureResult() { return FailureResult(String.Empty); } private byte[] FailureResult(string msg) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); XmlElement message = doc.CreateElement("", "Message", ""); message.AppendChild(doc.CreateTextNode(msg)); rootElement.AppendChild(message); return Util.DocToBytes(doc); } #endregion } }
/* Copyright 2019 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. */ namespace EditingSampleApp { partial class EditingForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditingForm)); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.GroupBox1 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.Label7 = new System.Windows.Forms.Label(); this.Label6 = new System.Windows.Forms.Label(); this.Label5 = new System.Windows.Forms.Label(); this.Label4 = new System.Windows.Forms.Label(); this.Label3 = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.Label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl(); this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axEditorToolbar = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); this.tableLayoutPanel1.SuspendLayout(); this.GroupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axEditorToolbar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 26.94611F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 73.05389F)); this.tableLayoutPanel1.Controls.Add(this.GroupBox1, 0, 3); this.tableLayoutPanel1.Controls.Add(this.axMapControl1, 1, 2); this.tableLayoutPanel1.Controls.Add(this.axToolbarControl1, 0, 1); this.tableLayoutPanel1.Controls.Add(this.axEditorToolbar, 0, 0); this.tableLayoutPanel1.Controls.Add(this.axTOCControl1, 0, 2); this.tableLayoutPanel1.Location = new System.Drawing.Point(0, -3); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 4; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 32F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 14.38849F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 85.61151F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 236F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(905, 547); this.tableLayoutPanel1.TabIndex = 1; // // GroupBox1 // this.GroupBox1.Controls.Add(this.label1); this.GroupBox1.Controls.Add(this.Label7); this.GroupBox1.Controls.Add(this.Label6); this.GroupBox1.Controls.Add(this.Label5); this.GroupBox1.Controls.Add(this.Label4); this.GroupBox1.Controls.Add(this.Label3); this.GroupBox1.Controls.Add(this.Label2); this.GroupBox1.Controls.Add(this.label16); this.GroupBox1.Controls.Add(this.Label8); this.GroupBox1.Controls.Add(this.label9); this.GroupBox1.Controls.Add(this.label10); this.GroupBox1.Controls.Add(this.label11); this.GroupBox1.Controls.Add(this.label12); this.GroupBox1.Location = new System.Drawing.Point(2, 312); this.GroupBox1.Margin = new System.Windows.Forms.Padding(2); this.GroupBox1.Name = "GroupBox1"; this.GroupBox1.Padding = new System.Windows.Forms.Padding(2); this.GroupBox1.Size = new System.Drawing.Size(238, 225); this.GroupBox1.TabIndex = 6; this.GroupBox1.TabStop = false; this.GroupBox1.Text = "Steps..."; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 113); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(225, 13); this.label1.TabIndex = 23; this.label1.Text = "6. Move close to points and observe snapping"; // // Label7 // this.Label7.AutoSize = true; this.Label7.Location = new System.Drawing.Point(12, 145); this.Label7.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label7.Name = "Label7"; this.Label7.Size = new System.Drawing.Size(129, 13); this.Label7.TabIndex = 22; this.Label7.Text = "8. Stop editing, save edits"; // // Label6 // this.Label6.AutoSize = true; this.Label6.Location = new System.Drawing.Point(12, 129); this.Label6.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label6.Name = "Label6"; this.Label6.Size = new System.Drawing.Size(84, 13); this.Label6.TabIndex = 21; this.Label6.Text = "7. Digitize points"; // // Label5 // this.Label5.AutoSize = true; this.Label5.Location = new System.Drawing.Point(12, 97); this.Label5.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label5.Name = "Label5"; this.Label5.Size = new System.Drawing.Size(104, 13); this.Label5.TabIndex = 20; this.Label5.Text = "5. Select sketch tool"; // // Label4 // this.Label4.AutoSize = true; this.Label4.Location = new System.Drawing.Point(12, 81); this.Label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label4.Name = "Label4"; this.Label4.Size = new System.Drawing.Size(155, 13); this.Label4.TabIndex = 19; this.Label4.Text = "4. Check on Buffer Snap Agent"; // // Label3 // this.Label3.AutoSize = true; this.Label3.Location = new System.Drawing.Point(12, 65); this.Label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label3.Name = "Label3"; this.Label3.Size = new System.Drawing.Size(222, 13); this.Label3.TabIndex = 18; this.Label3.Text = "3. Open Snapping Window (Editor>Snapping)"; // // Label2 // this.Label2.AutoSize = true; this.Label2.Location = new System.Drawing.Point(12, 33); this.Label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label2.Name = "Label2"; this.Label2.Size = new System.Drawing.Size(75, 13); this.Label2.TabIndex = 17; this.Label2.Text = "1. Start editing"; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(12, 49); this.label16.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(223, 13); this.label16.TabIndex = 16; this.label16.Text = "2. Zoom in on point features to about 1:30000"; // // Label8 // this.Label8.AutoSize = true; this.Label8.Location = new System.Drawing.Point(15, 269); this.Label8.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label8.Name = "Label8"; this.Label8.Size = new System.Drawing.Size(208, 13); this.Label8.TabIndex = 15; this.Label8.Text = "6. Digitize line, intersect feature in 2 places"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(15, 301); this.label9.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(129, 13); this.label9.TabIndex = 14; this.label9.Text = "8. Stop editing, save edits"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(15, 285); this.label10.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(172, 13); this.label10.TabIndex = 13; this.label10.Text = "7. Finish sketch to perform reshape"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(15, 253); this.label11.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(104, 13); this.label11.TabIndex = 12; this.label11.Text = "5. Select sketch tool"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(15, 237); this.label12.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(151, 13); this.label12.TabIndex = 11; this.label12.Text = "4. Select reshape polyline task"; // // axMapControl1 // this.axMapControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.axMapControl1.Location = new System.Drawing.Point(246, 75); this.axMapControl1.Name = "axMapControl1"; this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState"))); this.tableLayoutPanel1.SetRowSpan(this.axMapControl1, 2); this.axMapControl1.Size = new System.Drawing.Size(656, 469); this.axMapControl1.TabIndex = 1; // // axToolbarControl1 // this.tableLayoutPanel1.SetColumnSpan(this.axToolbarControl1, 2); this.axToolbarControl1.Location = new System.Drawing.Point(3, 35); this.axToolbarControl1.Name = "axToolbarControl1"; this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState"))); this.axToolbarControl1.Size = new System.Drawing.Size(899, 28); this.axToolbarControl1.TabIndex = 4; // // axEditorToolbar // this.tableLayoutPanel1.SetColumnSpan(this.axEditorToolbar, 2); this.axEditorToolbar.Location = new System.Drawing.Point(3, 3); this.axEditorToolbar.Name = "axEditorToolbar"; this.axEditorToolbar.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axEditorToolbar.OcxState"))); this.axEditorToolbar.Size = new System.Drawing.Size(899, 28); this.axEditorToolbar.TabIndex = 5; // // axTOCControl1 // this.axTOCControl1.Location = new System.Drawing.Point(3, 75); this.axTOCControl1.Name = "axTOCControl1"; this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState"))); this.axTOCControl1.Size = new System.Drawing.Size(237, 232); this.axTOCControl1.TabIndex = 2; // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(239, 476); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 2; // // EditingForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(911, 549); this.Controls.Add(this.axLicenseControl1); this.Controls.Add(this.tableLayoutPanel1); this.Name = "EditingForm"; this.Text = "Buffer Snap Agent Sample (C#)"; this.Load += new System.EventHandler(this.EngineEditingForm_Load); this.tableLayoutPanel1.ResumeLayout(false); this.GroupBox1.ResumeLayout(false); this.GroupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axEditorToolbar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private ESRI.ArcGIS.Controls.AxMapControl axMapControl1; private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1; private ESRI.ArcGIS.Controls.AxToolbarControl axEditorToolbar; internal System.Windows.Forms.GroupBox GroupBox1; internal System.Windows.Forms.Label label1; internal System.Windows.Forms.Label Label7; internal System.Windows.Forms.Label Label6; internal System.Windows.Forms.Label Label5; internal System.Windows.Forms.Label Label4; internal System.Windows.Forms.Label Label3; internal System.Windows.Forms.Label Label2; internal System.Windows.Forms.Label label16; internal System.Windows.Forms.Label Label8; internal System.Windows.Forms.Label label9; internal System.Windows.Forms.Label label10; internal System.Windows.Forms.Label label11; internal System.Windows.Forms.Label label12; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using JetBrains.Annotations; using JetBrains.Collections.Viewable; using JetBrains.Core; using JetBrains.Rider.Model.Unity.BackendUnity; using JetBrains.Diagnostics; using JetBrains.Lifetimes; using JetBrains.Rd; using JetBrains.Rd.Base; using JetBrains.Rd.Impl; using JetBrains.Rd.Tasks; using JetBrains.Rider.Model.Unity; using JetBrains.Rider.Unity.Editor.Logger; using JetBrains.Rider.Unity.Editor.NonUnity; using JetBrains.Rider.Unity.Editor.Utils; using UnityEditor; using UnityEditor.Callbacks; using Application = UnityEngine.Application; using Debug = UnityEngine.Debug; namespace JetBrains.Rider.Unity.Editor { [InitializeOnLoad] public static class PluginEntryPoint { public static Lifetime Lifetime; private static readonly IPluginSettings ourPluginSettings; private static readonly RiderPathProvider ourRiderPathProvider; public static readonly List<ModelWithLifetime> UnityModels = new List<ModelWithLifetime>(); private static bool ourInitialized; private static readonly ILog ourLogger = Log.GetLog("RiderPlugin"); internal static string SlnFile; private static long ourInitTime = DateTime.UtcNow.Ticks; // This an entry point static PluginEntryPoint() { if (UnityUtils.IsInBatchModeAndNotInRiderTests) return; LogInitializer.InitLog(PluginSettings.SelectedLoggingLevel); // init log before doing any logging UnityEventLogSender.Start(); // start collecting Unity messages asap ourPluginSettings = new PluginSettings(); ourRiderPathProvider = new RiderPathProvider(ourPluginSettings); if (IsLoadedFromAssets()) // old mechanism, when EditorPlugin was copied to Assets folder { var riderPath = ourRiderPathProvider.GetActualRider(EditorPrefsWrapper.ExternalScriptEditor, RiderPathLocator.GetAllFoundPaths(ourPluginSettings.OperatingSystemFamilyRider)); if (!string.IsNullOrEmpty(riderPath)) { AddRiderToRecentlyUsedScriptApp(riderPath); if (IsRiderDefaultEditor() && PluginSettings.UseLatestRiderFromToolbox) { EditorPrefsWrapper.ExternalScriptEditor = riderPath; } } if (!PluginSettings.RiderInitializedOnce) { EditorPrefsWrapper.ExternalScriptEditor = riderPath; PluginSettings.RiderInitializedOnce = true; } InitForPluginLoadedFromAssets(); Init(); } else { Init(); } } public delegate void OnModelInitializationHandler(UnityModelAndLifetime e); [UsedImplicitly] public static event OnModelInitializationHandler OnModelInitialization = delegate {}; internal static bool CheckConnectedToBackendSync(BackendUnityModel model) { if (model == null) return false; var connected = false; try { // HostConnected also means that in Rider and in Unity the same solution is opened connected = model.IsBackendConnected.Sync(Unit.Instance, new RpcTimeouts(TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(200))); } catch (Exception) { ourLogger.Verbose("Rider Protocol not connected."); } return connected; } public static bool CallRider(string args) { return OpenAssetHandler.CallRider(args); } public static bool IsRiderDefaultEditor() { if (UnityUtils.UseRiderTestPath) return true; // Regular check var defaultApp = EditorPrefsWrapper.ExternalScriptEditor; bool isEnabled = !string.IsNullOrEmpty(defaultApp) && Path.GetFileName(defaultApp).ToLower().Contains("rider") && !UnityUtils.IsInBatchModeAndNotInRiderTests; return isEnabled; } public static void Init() { if (ourInitialized) return; var projectDirectory = Directory.GetParent(Application.dataPath).FullName; var projectName = Path.GetFileName(projectDirectory); SlnFile = Path.GetFullPath($"{projectName}.sln"); InitializeEditorInstanceJson(); var lifetimeDefinition = Lifetime.Define(Lifetime.Eternal); Lifetime = lifetimeDefinition.Lifetime; AppDomain.CurrentDomain.DomainUnload += (EventHandler) ((_, __) => { ourLogger.Verbose("lifetimeDefinition.Terminate"); lifetimeDefinition.Terminate(); }); #if !UNITY_4_7 && !UNITY_5_5 && !UNITY_5_6 EditorApplication.playModeStateChanged += state => { if (state == PlayModeStateChange.EnteredPlayMode) { var time = DateTime.UtcNow.Ticks.ToString(); SessionState.SetString("Rider_EnterPlayMode_DateTime", time); } }; #endif if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.VERBOSE) { var executingAssembly = Assembly.GetExecutingAssembly(); var location = executingAssembly.Location; Debug.Log($"Rider plugin \"{executingAssembly.GetName().Name}\" initialized{(string.IsNullOrEmpty(location)? "" : " from: " + location )}. LoggingLevel: {PluginSettings.SelectedLoggingLevel}. Change it in Unity Preferences -> Rider. Logs path: {LogPath}."); } var protocolInstanceJsonPath = Path.GetFullPath("Library/ProtocolInstance.json"); InitializeProtocol(Lifetime, protocolInstanceJsonPath); OpenAssetHandler = new OnOpenAssetHandler(ourRiderPathProvider, ourPluginSettings, SlnFile); ourLogger.Verbose("Writing Library/ProtocolInstance.json"); AppDomain.CurrentDomain.DomainUnload += (sender, args) => { ourLogger.Verbose("Deleting Library/ProtocolInstance.json"); File.Delete(protocolInstanceJsonPath); }; PlayModeSavedState = GetPlayModeState(); ourInitialized = true; } private static void InitializeProtocol(Lifetime lifetime, string protocolInstancePath) { var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory()); var solutionNames = new List<string>() { currentDirectory.Name}; var solutionFiles = currentDirectory.GetFiles("*.sln", SearchOption.TopDirectoryOnly); foreach (var solutionFile in solutionFiles) { var solutionName = Path.GetFileNameWithoutExtension(solutionFile.FullName); if (!solutionName.Equals(currentDirectory.Name)) { solutionNames.Add(solutionName); } } var protocols = new List<ProtocolInstance>(); // if any protocol connection losts, we will drop all protocol and recreate them var allProtocolsLifetimeDefinition = lifetime.CreateNested(); foreach (var solutionName in solutionNames) { var port = CreateProtocolForSolution(allProtocolsLifetimeDefinition.Lifetime, solutionName, () => { allProtocolsLifetimeDefinition.Terminate(); }); if (port == -1) continue; protocols.Add(new ProtocolInstance(solutionName, port)); } allProtocolsLifetimeDefinition.Lifetime.OnTermination(() => { if (Lifetime.IsAlive) { ourLogger.Verbose("Recreating protocol, project lifetime is alive"); InitializeProtocol(lifetime, protocolInstancePath); } else { ourLogger.Verbose("Protocol will be recreating on next domain load, project lifetime is not alive"); } }); var result = ProtocolInstance.ToJson(protocols); File.WriteAllText(protocolInstancePath, result); } internal static void InitForPluginLoadedFromAssets() { if (ourInitialized) return; ResetDefaultFileExtensions(); // process csproj files once per Unity process if (!RiderScriptableSingleton.Instance.CsprojProcessedOnce) { // Perform on next editor frame update, so we avoid this exception: // "Must set an output directory through SetCompileScriptsOutputDirectory before compiling" EditorApplication.update += SyncSolutionOnceCallBack; } SetupAssemblyReloadEvents(); } private static void SyncSolutionOnceCallBack() { ourLogger.Verbose("Call SyncSolution once per Unity process."); UnityUtils.SyncSolution(); RiderScriptableSingleton.Instance.CsprojProcessedOnce = true; EditorApplication.update -= SyncSolutionOnceCallBack; } // Unity 2017.3 added "asmdef" to the default list of file extensions used to generate the C# projects, but only for // new projects. Existing projects have this value serialised, and Unity doesn't update or reset it. We need .asmdef // files in the project, so we'll add it if it's missing. // For the record, the default list of file extensions in Unity 2017.4.6f1 is: txt;xml;fnt;cd;asmdef;rsp private static void ResetDefaultFileExtensions() { // EditorSettings.projectGenerationUserExtensions (and projectGenerationBuiltinExtensions) were added in 5.2. We // support 5.0+, so yay! reflection var propertyInfo = typeof(EditorSettings) .GetProperty("projectGenerationUserExtensions", BindingFlags.Public | BindingFlags.Static); if (propertyInfo?.GetValue(null, null) is string[] currentValues) { if (!currentValues.Contains("asmdef")) { var newValues = new string[currentValues.Length + 1]; Array.Copy(currentValues, newValues, currentValues.Length); newValues[currentValues.Length] = "asmdef"; propertyInfo.SetValue(null, newValues, null); } } } public enum PlayModeState { Stopped, Playing, Paused } public static PlayModeState PlayModeSavedState = PlayModeState.Stopped; private static PlayModeState GetPlayModeState() { if (EditorApplication.isPaused) return PlayModeState.Paused; if (EditorApplication.isPlaying || EditorApplication.isPlayingOrWillChangePlaymode) return PlayModeState.Playing; return PlayModeState.Stopped; } private static void SetupAssemblyReloadEvents() { // Unity supports recompile/reload settings natively for Unity 2018.2+ if (UnityUtils.UnityVersion >= new Version(2018, 2)) return; // playmodeStateChanged was marked obsolete in 2017.1. Still working in 2018.3 #pragma warning disable 618 EditorApplication.playmodeStateChanged += () => #pragma warning restore 618 { if (PluginSettings.AssemblyReloadSettings == ScriptCompilationDuringPlay.RecompileAfterFinishedPlaying) { MainThreadDispatcher.Instance.Queue(() => { var newPlayModeState = GetPlayModeState(); if (PlayModeSavedState != newPlayModeState) { if (newPlayModeState == PlayModeState.Playing) { ourLogger.Info("LockReloadAssemblies"); EditorApplication.LockReloadAssemblies(); } else if (newPlayModeState == PlayModeState.Stopped) { ourLogger.Info("UnlockReloadAssemblies"); EditorApplication.UnlockReloadAssemblies(); } PlayModeSavedState = newPlayModeState; } }); } }; AppDomain.CurrentDomain.DomainUnload += (sender, args) => { if (PluginSettings.AssemblyReloadSettings == ScriptCompilationDuringPlay.StopPlayingAndRecompile) { if (EditorApplication.isPlaying) { EditorApplication.isPlaying = false; } } }; } private static int CreateProtocolForSolution(Lifetime lifetime, string solutionName, Action onDisconnected) { try { var dispatcher = MainThreadDispatcher.Instance; var currentWireAndProtocolLifetimeDef = lifetime.CreateNested(); var currentWireAndProtocolLifetime = currentWireAndProtocolLifetimeDef.Lifetime; var riderProtocolController = new RiderProtocolController(dispatcher, currentWireAndProtocolLifetime); var serializers = new Serializers(); var identities = new Identities(IdKind.Server); MainThreadDispatcher.AssertThread(); var protocol = new Protocol("UnityEditorPlugin" + solutionName, serializers, identities, MainThreadDispatcher.Instance, riderProtocolController.Wire, currentWireAndProtocolLifetime); riderProtocolController.Wire.Connected.WhenTrue(currentWireAndProtocolLifetime, connectionLifetime => { ourLogger.Log(LoggingLevel.VERBOSE, "Create UnityModel and advise for new sessions..."); var model = new BackendUnityModel(connectionLifetime, protocol); AdviseUnityActions(model, connectionLifetime); AdviseEditorState(model); OnModelInitialization(new UnityModelAndLifetime(model, connectionLifetime)); AdviseRefresh(model); var paths = GetLogPaths(); model.UnityApplicationData.SetValue(new UnityApplicationData( EditorApplication.applicationPath, EditorApplication.applicationContentsPath, UnityUtils.UnityApplicationVersion, paths[0], paths[1], Process.GetCurrentProcess().Id)); model.UnityApplicationSettings.ScriptCompilationDuringPlay.Set(UnityUtils.SafeScriptCompilationDuringPlay); model.UnityProjectSettings.ScriptingRuntime.SetValue(UnityUtils.ScriptingRuntime); AdviseShowPreferences(model, connectionLifetime, ourLogger); AdviseGenerateUISchema(model); AdviseExitUnity(model); GetBuildLocation(model); AdviseRunMethod(model); GetInitTime(model); ourLogger.Verbose("UnityModel initialized."); var pair = new ModelWithLifetime(model, connectionLifetime); connectionLifetime.OnTermination(() => { UnityModels.Remove(pair); }); UnityModels.Add(pair); connectionLifetime.OnTermination(() => { ourLogger.Verbose($"Connection lifetime is not alive for {solutionName}, destroying protocol"); onDisconnected(); }); }); return riderProtocolController.Wire.Port; } catch (Exception ex) { ourLogger.Error("Init Rider Plugin " + ex); return -1; } } private static void GetInitTime(BackendUnityModel model) { model.ConsoleLogging.LastInitTime.SetValue(ourInitTime); #if !UNITY_4_7 && !UNITY_5_5 && !UNITY_5_6 var enterPlayTime = long.Parse(SessionState.GetString("Rider_EnterPlayMode_DateTime", "0")); model.ConsoleLogging.LastPlayTime.SetValue(enterPlayTime); #endif } private static void AdviseRunMethod(BackendUnityModel model) { model.RunMethodInUnity.Set((lifetime, data) => { var task = new RdTask<RunMethodResult>(); MainThreadDispatcher.Instance.Queue(() => { if (!lifetime.IsAlive) { task.SetCancelled(); return; } try { ourLogger.Verbose($"Attempt to execute {data.MethodName}"); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var assembly = assemblies .FirstOrDefault(a => a.GetName().Name.Equals(data.AssemblyName)); if (assembly == null) throw new Exception($"Could not find {data.AssemblyName} assembly in current AppDomain"); var type = assembly.GetType(data.TypeName); if (type == null) throw new Exception($"Could not find {data.TypeName} in assembly {data.AssemblyName}."); var method = type.GetMethod(data.MethodName,BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); if (method == null) throw new Exception($"Could not find {data.MethodName} in type {data.TypeName}"); try { method.Invoke(null, null); } catch (Exception e) { Debug.LogException(e); } task.Set(new RunMethodResult(true, string.Empty, string.Empty)); } catch (Exception e) { ourLogger.Log(LoggingLevel.WARN, $"Execute {data.MethodName} failed.", e); task.Set(new RunMethodResult(false, e.Message, e.StackTrace)); } }); return task; }); } private static void GetBuildLocation(BackendUnityModel model) { var path = EditorUserBuildSettings.GetBuildLocation(EditorUserBuildSettings.selectedStandaloneTarget); if (PluginSettings.SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamilyRider.MacOSX) path = Path.Combine(Path.Combine(Path.Combine(path, "Contents"), "MacOS"), PlayerSettings.productName); if (!string.IsNullOrEmpty(path) && File.Exists(path)) model.UnityProjectSettings.BuildLocation.Value = path; } private static void AdviseGenerateUISchema(BackendUnityModel model) { model.GenerateUIElementsSchema.Set(_ => UIElementsSupport.GenerateSchema()); } private static void AdviseExitUnity(BackendUnityModel model) { model.ExitUnity.Set((_, rdVoid) => { var task = new RdTask<bool>(); MainThreadDispatcher.Instance.Queue(() => { try { ourLogger.Verbose("ExitUnity: Started"); EditorApplication.Exit(0); ourLogger.Verbose("ExitUnity: Completed"); task.Set(true); } catch (Exception e) { ourLogger.Log(LoggingLevel.WARN, "EditorApplication.Exit failed.", e); task.Set(false); } }); return task; }); } private static void AdviseShowPreferences(BackendUnityModel model, Lifetime connectionLifetime, ILog log) { model.ShowPreferences.Advise(connectionLifetime, result => { if (result != null) { MainThreadDispatcher.Instance.Queue(() => { try { var tab = UnityUtils.UnityVersion >= new Version(2018, 2) ? "_General" : "Rider"; var type = typeof(SceneView).Assembly.GetType("UnityEditor.SettingsService"); if (type != null) { // 2018+ var method = type.GetMethod("OpenUserPreferences", BindingFlags.Static | BindingFlags.Public); if (method == null) { log.Error("'OpenUserPreferences' was not found"); } else { method.Invoke(null, new object[] {$"Preferences/{tab}"}); } } else { // 5.5, 2017 ... type = typeof(SceneView).Assembly.GetType("UnityEditor.PreferencesWindow"); var method = type?.GetMethod("ShowPreferencesWindow", BindingFlags.Static | BindingFlags.NonPublic); if (method == null) { log.Error("'ShowPreferencesWindow' was not found"); } else { method.Invoke(null, null); } } } catch (Exception ex) { log.Error("Show preferences " + ex); } }); } }); } private static void AdviseEditorState(BackendUnityModel modelValue) { modelValue.GetUnityEditorState.Set(rdVoid => { if (EditorApplication.isPaused) { return UnityEditorState.Pause; } if (EditorApplication.isPlaying) { return UnityEditorState.Play; } if (EditorApplication.isCompiling || EditorApplication.isUpdating) { return UnityEditorState.Refresh; } return UnityEditorState.Idle; }); } private static void AdviseRefresh(BackendUnityModel model) { model.Refresh.Set((l, force) => { var refreshTask = new RdTask<Unit>(); void SendResult() { if (!EditorApplication.isCompiling) { // ReSharper disable once DelegateSubtraction EditorApplication.update -= SendResult; ourLogger.Verbose("Refresh: SyncSolution Completed"); refreshTask.Set(Unit.Instance); } } ourLogger.Verbose("Refresh: SyncSolution Enqueue"); MainThreadDispatcher.Instance.Queue(() => { if (!EditorApplication.isPlaying && EditorPrefsWrapper.AutoRefresh || force != RefreshType.Normal) { try { if (force == RefreshType.ForceRequestScriptReload) { ourLogger.Verbose("Refresh: RequestScriptReload"); UnityEditorInternal.InternalEditorUtility.RequestScriptReload(); } ourLogger.Verbose("Refresh: SyncSolution Started"); UnityUtils.SyncSolution(); } catch (Exception e) { ourLogger.Error("Refresh failed with exception", e); } finally { EditorApplication.update += SendResult; } } else { refreshTask.Set(Unit.Instance); ourLogger.Verbose("AutoRefresh is disabled via Unity settings."); } }); return refreshTask; }); } private static void AdviseUnityActions(BackendUnityModel model, Lifetime connectionLifetime) { var syncPlayState = new Action(() => { MainThreadDispatcher.Instance.Queue(() => { var isPlaying = EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying; if (!model.PlayControls.Play.HasValue() || model.PlayControls.Play.HasValue() && model.PlayControls.Play.Value != isPlaying) { ourLogger.Verbose("Reporting play mode change to model: {0}", isPlaying); model.PlayControls.Play.SetValue(isPlaying); } var isPaused = EditorApplication.isPaused; if (!model.PlayControls.Pause.HasValue() || model.PlayControls.Pause.HasValue() && model.PlayControls.Pause.Value != isPaused) { ourLogger.Verbose("Reporting pause mode change to model: {0}", isPaused); model.PlayControls.Pause.SetValue(isPaused); } }); }); syncPlayState(); model.PlayControls.Play.Advise(connectionLifetime, play => { MainThreadDispatcher.Instance.Queue(() => { var current = EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying; if (current != play) { ourLogger.Verbose("Request to change play mode from model: {0}", play); EditorApplication.isPlaying = play; } }); }); model.PlayControls.Pause.Advise(connectionLifetime, pause => { MainThreadDispatcher.Instance.Queue(() => { ourLogger.Verbose("Request to change pause mode from model: {0}", pause); EditorApplication.isPaused = pause; }); }); model.PlayControls.Step.Advise(connectionLifetime, x => { MainThreadDispatcher.Instance.Queue(EditorApplication.Step); }); var onPlaymodeStateChanged = new EditorApplication.CallbackFunction(() => syncPlayState()); // left for compatibility with Unity <= 5.5 #pragma warning disable 618 connectionLifetime.AddBracket(() => { EditorApplication.playmodeStateChanged += onPlaymodeStateChanged; }, () => { EditorApplication.playmodeStateChanged -= onPlaymodeStateChanged; }); #pragma warning restore 618 // new api - not present in Unity 5.5 // private static Action<PauseState> IsPauseStateChanged(UnityModel model) // { // return state => model?.Pause.SetValue(state == PauseState.Paused); // } } private static string[] GetLogPaths() { // https://docs.unity3d.com/Manual/LogFiles.html //PlayerSettings.productName; //PlayerSettings.companyName; //~/Library/Logs/Unity/Editor.log //C:\Users\username\AppData\Local\Unity\Editor\Editor.log //~/.config/unity3d/Editor.log string editorLogpath = string.Empty; string playerLogPath = string.Empty; switch (PluginSettings.SystemInfoRiderPlugin.operatingSystemFamily) { case OperatingSystemFamilyRider.Windows: { var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); editorLogpath = Path.Combine(localAppData, @"Unity\Editor\Editor.log"); var userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); if (!string.IsNullOrEmpty(userProfile)) playerLogPath = Path.Combine( Path.Combine(Path.Combine(Path.Combine(userProfile, @"AppData\LocalLow"), PlayerSettings.companyName), PlayerSettings.productName),"output_log.txt"); break; } case OperatingSystemFamilyRider.MacOSX: { var home = Environment.GetEnvironmentVariable("HOME"); if (!string.IsNullOrEmpty(home)) { editorLogpath = Path.Combine(home, "Library/Logs/Unity/Editor.log"); playerLogPath = Path.Combine(home, "Library/Logs/Unity/Player.log"); } break; } case OperatingSystemFamilyRider.Linux: { var home = Environment.GetEnvironmentVariable("HOME"); if (!string.IsNullOrEmpty(home)) { editorLogpath = Path.Combine(home, ".config/unity3d/Editor.log"); playerLogPath = Path.Combine(home, $".config/unity3d/{PlayerSettings.companyName}/{PlayerSettings.productName}/Player.log"); } break; } } return new[] {editorLogpath, playerLogPath}; } private static readonly string ourBaseLogPath = !UnityUtils.IsInRiderTests ? Path.GetTempPath() : new FileInfo(UnityUtils.UnityEditorLogPath).Directory.FullName; internal static readonly string LogPath = Path.Combine(Path.Combine(ourBaseLogPath, "Unity3dRider"), $"EditorPlugin.{Process.GetCurrentProcess().Id}.log"); [UsedImplicitly] internal static OnOpenAssetHandler OpenAssetHandler; // Creates and deletes Library/EditorInstance.json containing info about unity instance. Unity 2017.1+ writes this // file itself. We'll always overwrite, just to be sure it's up to date. The file contents are exactly the same private static void InitializeEditorInstanceJson() { if (UnityUtils.UnityVersion >= new Version(2017, 1)) return; ourLogger.Verbose("Writing Library/EditorInstance.json"); var editorInstanceJsonPath = Path.GetFullPath("Library/EditorInstance.json"); File.WriteAllText(editorInstanceJsonPath, $@"{{ ""process_id"": {Process.GetCurrentProcess().Id}, ""version"": ""{UnityUtils.UnityApplicationVersion}"" }}"); AppDomain.CurrentDomain.DomainUnload += (sender, args) => { ourLogger.Verbose("Deleting Library/EditorInstance.json"); File.Delete(editorInstanceJsonPath); }; } private static void AddRiderToRecentlyUsedScriptApp(string userAppPath) { const string recentAppsKey = "RecentlyUsedScriptApp"; for (var i = 0; i < 10; ++i) { var path = EditorPrefs.GetString($"{recentAppsKey}{i}"); if (File.Exists(path) && Path.GetFileName(path).ToLower().Contains("rider")) return; } EditorPrefs.SetString($"{recentAppsKey}{9}", userAppPath); } /// <summary> /// Called when Unity is about to open an asset. This method is for pre-2019.2 /// </summary> [OnOpenAsset] static bool OnOpenedAsset(int instanceID, int line) { if (!IsRiderDefaultEditor()) return false; // if (UnityUtils.UnityVersion >= new Version(2019, 2) // return false; return OpenAssetHandler.OnOpenedAsset(instanceID, line, 0); } public static bool IsLoadedFromAssets() { var currentDir = Directory.GetCurrentDirectory(); var location = Assembly.GetExecutingAssembly().Location; return location.StartsWith(currentDir, StringComparison.InvariantCultureIgnoreCase); } } public struct UnityModelAndLifetime { public BackendUnityModel Model; public Lifetime Lifetime; public UnityModelAndLifetime(BackendUnityModel model, Lifetime lifetime) { Model = model; Lifetime = lifetime; } } }
// 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; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using Microsoft.Build.BackEnd; using Microsoft.Build.Collections; using Microsoft.Build.Framework; using Microsoft.Build.Framework.Profiler; using Microsoft.Build.Shared; namespace Microsoft.Build.Logging { /// <summary> /// Deserializes and returns BuildEventArgs-derived objects from a BinaryReader /// </summary> public class BuildEventArgsReader : IDisposable { private readonly BinaryReader binaryReader; private readonly int fileFormatVersion; private long recordNumber = 0; /// <summary> /// A list of string records we've encountered so far. If it's a small string, it will be the string directly. /// If it's a large string, it will be a pointer into a temporary page file where the string content will be /// written out to. This is necessary so we don't keep all the strings in memory when reading large binlogs. /// We will OOM otherwise. /// </summary> private readonly List<object> stringRecords = new List<object>(); /// <summary> /// A list of dictionaries we've encountered so far. Dictionaries are referred to by their order in this list. /// </summary> /// <remarks>This is designed to not hold on to strings. We just store the string indices and /// hydrate the dictionary on demand before returning.</remarks> private readonly List<(int keyIndex, int valueIndex)[]> nameValueListRecords = new List<(int, int)[]>(); /// <summary> /// A "page-file" for storing strings we've read so far. Keeping them in memory would OOM the 32-bit MSBuild /// when reading large binlogs. This is a no-op in a 64-bit process. /// </summary> private StringStorage stringStorage = new StringStorage(); // reflection is needed to set these three fields because public constructors don't provide // a way to set these from the outside private static FieldInfo buildEventArgsFieldThreadId = typeof(BuildEventArgs).GetField("threadId", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo buildEventArgsFieldSenderName = typeof(BuildEventArgs).GetField("senderName", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo buildEventArgsFieldTimestamp = typeof(BuildEventArgs).GetField("timestamp", BindingFlags.Instance | BindingFlags.NonPublic); /// <summary> /// Initializes a new instance of BuildEventArgsReader using a BinaryReader instance /// </summary> /// <param name="binaryReader">The BinaryReader to read BuildEventArgs from</param> /// <param name="fileFormatVersion">The file format version of the log file being read.</param> public BuildEventArgsReader(BinaryReader binaryReader, int fileFormatVersion) { this.binaryReader = binaryReader; this.fileFormatVersion = fileFormatVersion; } public void Dispose() { if (stringStorage != null) { stringStorage.Dispose(); stringStorage = null; } } /// <summary> /// Raised when the log reader encounters a binary blob embedded in the stream. /// The arguments include the blob kind and the byte buffer with the contents. /// </summary> internal event Action<BinaryLogRecordKind, byte[]> OnBlobRead; /// <summary> /// Reads the next log record from the binary reader. If there are no more records, returns null. /// </summary> public BuildEventArgs Read() { BinaryLogRecordKind recordKind = (BinaryLogRecordKind)ReadInt32(); // Skip over data storage records since they don't result in a BuildEventArgs. // just ingest their data and continue. while (IsAuxiliaryRecord(recordKind)) { // these are ordered by commonality if (recordKind == BinaryLogRecordKind.String) { ReadStringRecord(); } else if (recordKind == BinaryLogRecordKind.NameValueList) { ReadNameValueList(); } else if (recordKind == BinaryLogRecordKind.ProjectImportArchive) { ReadBlob(recordKind); } recordNumber += 1; recordKind = (BinaryLogRecordKind)ReadInt32(); } BuildEventArgs result = null; switch (recordKind) { case BinaryLogRecordKind.EndOfFile: break; case BinaryLogRecordKind.BuildStarted: result = ReadBuildStartedEventArgs(); break; case BinaryLogRecordKind.BuildFinished: result = ReadBuildFinishedEventArgs(); break; case BinaryLogRecordKind.ProjectStarted: result = ReadProjectStartedEventArgs(); break; case BinaryLogRecordKind.ProjectFinished: result = ReadProjectFinishedEventArgs(); break; case BinaryLogRecordKind.TargetStarted: result = ReadTargetStartedEventArgs(); break; case BinaryLogRecordKind.TargetFinished: result = ReadTargetFinishedEventArgs(); break; case BinaryLogRecordKind.TaskStarted: result = ReadTaskStartedEventArgs(); break; case BinaryLogRecordKind.TaskFinished: result = ReadTaskFinishedEventArgs(); break; case BinaryLogRecordKind.Error: result = ReadBuildErrorEventArgs(); break; case BinaryLogRecordKind.Warning: result = ReadBuildWarningEventArgs(); break; case BinaryLogRecordKind.Message: result = ReadBuildMessageEventArgs(); break; case BinaryLogRecordKind.CriticalBuildMessage: result = ReadCriticalBuildMessageEventArgs(); break; case BinaryLogRecordKind.TaskCommandLine: result = ReadTaskCommandLineEventArgs(); break; case BinaryLogRecordKind.TaskParameter: result = ReadTaskParameterEventArgs(); break; case BinaryLogRecordKind.ProjectEvaluationStarted: result = ReadProjectEvaluationStartedEventArgs(); break; case BinaryLogRecordKind.ProjectEvaluationFinished: result = ReadProjectEvaluationFinishedEventArgs(); break; case BinaryLogRecordKind.ProjectImported: result = ReadProjectImportedEventArgs(); break; case BinaryLogRecordKind.TargetSkipped: result = ReadTargetSkippedEventArgs(); break; case BinaryLogRecordKind.EnvironmentVariableRead: result = ReadEnvironmentVariableReadEventArgs(); break; case BinaryLogRecordKind.PropertyReassignment: result = ReadPropertyReassignmentEventArgs(); break; case BinaryLogRecordKind.UninitializedPropertyRead: result = ReadUninitializedPropertyReadEventArgs(); break; case BinaryLogRecordKind.PropertyInitialValueSet: result = ReadPropertyInitialValueSetEventArgs(); break; default: break; } recordNumber += 1; return result; } private static bool IsAuxiliaryRecord(BinaryLogRecordKind recordKind) { return recordKind == BinaryLogRecordKind.String || recordKind == BinaryLogRecordKind.NameValueList || recordKind == BinaryLogRecordKind.ProjectImportArchive; } private void ReadBlob(BinaryLogRecordKind kind) { int length = ReadInt32(); byte[] bytes = binaryReader.ReadBytes(length); OnBlobRead?.Invoke(kind, bytes); } private void ReadNameValueList() { int count = ReadInt32(); var list = new (int, int)[count]; for (int i = 0; i < count; i++) { int key = ReadInt32(); int value = ReadInt32(); list[i] = (key, value); } nameValueListRecords.Add(list); } private IDictionary<string, string> GetNameValueList(int id) { id -= BuildEventArgsWriter.NameValueRecordStartIndex; if (id >= 0 && id < nameValueListRecords.Count) { var list = nameValueListRecords[id]; // We can't cache these as they would hold on to strings. // This reader is designed to not hold onto strings, // so that we can fit in a 32-bit process when reading huge binlogs var dictionary = ArrayDictionary<string, string>.Create(list.Length); for (int i = 0; i < list.Length; i++) { string key = GetStringFromRecord(list[i].keyIndex); string value = GetStringFromRecord(list[i].valueIndex); if (key != null) { dictionary.Add(key, value); } } return dictionary; } // this should never happen for valid binlogs throw new InvalidDataException( $"NameValueList record number {recordNumber} is invalid: index {id} is not within {stringRecords.Count}."); } private void ReadStringRecord() { string text = ReadString(); object storedString = stringStorage.Add(text); stringRecords.Add(storedString); } private BuildEventArgs ReadProjectImportedEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); bool importIgnored = false; // the ImportIgnored field was introduced in file format version 3 if (fileFormatVersion > 2) { importIgnored = ReadBoolean(); } var importedProjectFile = ReadOptionalString(); var unexpandedProject = ReadOptionalString(); var e = new ProjectImportedEventArgs( fields.LineNumber, fields.ColumnNumber, fields.Message, fields.Arguments); SetCommonFields(e, fields); e.ProjectFile = fields.ProjectFile; e.ImportedProjectFile = importedProjectFile; e.UnexpandedProject = unexpandedProject; e.ImportIgnored = importIgnored; return e; } private BuildEventArgs ReadTargetSkippedEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); var targetFile = ReadOptionalString(); var targetName = ReadOptionalString(); var parentTarget = ReadOptionalString(); string condition = null; string evaluatedCondition = null; bool originallySucceeded = false; TargetSkipReason skipReason = TargetSkipReason.None; BuildEventContext originalBuildEventContext = null; if (fileFormatVersion >= 13) { condition = ReadOptionalString(); evaluatedCondition = ReadOptionalString(); originallySucceeded = ReadBoolean(); // Attempt to infer skip reason from the data we have skipReason = condition != null ? TargetSkipReason.ConditionWasFalse // condition expression only stored when false : originallySucceeded ? TargetSkipReason.PreviouslyBuiltSuccessfully : TargetSkipReason.PreviouslyBuiltUnsuccessfully; } var buildReason = (TargetBuiltReason)ReadInt32(); if (fileFormatVersion >= 14) { skipReason = (TargetSkipReason)ReadInt32(); originalBuildEventContext = binaryReader.ReadOptionalBuildEventContext(); } var e = new TargetSkippedEventArgs( fields.Message, fields.Arguments); SetCommonFields(e, fields); e.ProjectFile = fields.ProjectFile; e.TargetFile = targetFile; e.TargetName = targetName; e.ParentTarget = parentTarget; e.BuildReason = buildReason; e.Condition = condition; e.EvaluatedCondition = evaluatedCondition; e.OriginallySucceeded = originallySucceeded; e.SkipReason = skipReason; e.OriginalBuildEventContext = originalBuildEventContext; return e; } private BuildEventArgs ReadBuildStartedEventArgs() { var fields = ReadBuildEventArgsFields(); var environment = ReadStringDictionary(); var e = new BuildStartedEventArgs( fields.Message, fields.HelpKeyword, environment); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadBuildFinishedEventArgs() { var fields = ReadBuildEventArgsFields(); var succeeded = ReadBoolean(); var e = new BuildFinishedEventArgs( fields.Message, fields.HelpKeyword, succeeded, fields.Timestamp); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadProjectEvaluationStartedEventArgs() { var fields = ReadBuildEventArgsFields(); var projectFile = ReadDeduplicatedString(); var e = new ProjectEvaluationStartedEventArgs( ResourceUtilities.GetResourceString("EvaluationStarted"), projectFile) { ProjectFile = projectFile }; SetCommonFields(e, fields); return e; } private BuildEventArgs ReadProjectEvaluationFinishedEventArgs() { var fields = ReadBuildEventArgsFields(); var projectFile = ReadDeduplicatedString(); var e = new ProjectEvaluationFinishedEventArgs( ResourceUtilities.GetResourceString("EvaluationFinished"), projectFile) { ProjectFile = projectFile }; SetCommonFields(e, fields); if (fileFormatVersion >= 12) { IEnumerable globalProperties = null; if (ReadBoolean()) { globalProperties = ReadStringDictionary(); } var propertyList = ReadPropertyList(); var itemList = ReadProjectItems(); e.GlobalProperties = globalProperties; e.Properties = propertyList; e.Items = itemList; } // ProfilerResult was introduced in version 5 if (fileFormatVersion > 4) { var hasProfileData = ReadBoolean(); if (hasProfileData) { var count = ReadInt32(); var d = new Dictionary<EvaluationLocation, ProfiledLocation>(count); for (int i = 0; i < count; i++) { var evaluationLocation = ReadEvaluationLocation(); var profiledLocation = ReadProfiledLocation(); d[evaluationLocation] = profiledLocation; } e.ProfilerResult = new ProfilerResult(d); } } return e; } private BuildEventArgs ReadProjectStartedEventArgs() { var fields = ReadBuildEventArgsFields(); BuildEventContext parentContext = null; if (ReadBoolean()) { parentContext = ReadBuildEventContext(); } var projectFile = ReadOptionalString(); var projectId = ReadInt32(); var targetNames = ReadDeduplicatedString(); var toolsVersion = ReadOptionalString(); IDictionary<string, string> globalProperties = null; if (fileFormatVersion > 6) { if (ReadBoolean()) { globalProperties = ReadStringDictionary(); } } var propertyList = ReadPropertyList(); var itemList = ReadProjectItems(); var e = new ProjectStartedEventArgs( projectId, fields.Message, fields.HelpKeyword, projectFile, targetNames, propertyList, itemList, parentContext, globalProperties, toolsVersion); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadProjectFinishedEventArgs() { var fields = ReadBuildEventArgsFields(); var projectFile = ReadOptionalString(); var succeeded = ReadBoolean(); var e = new ProjectFinishedEventArgs( fields.Message, fields.HelpKeyword, projectFile, succeeded, fields.Timestamp); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadTargetStartedEventArgs() { var fields = ReadBuildEventArgsFields(); var targetName = ReadOptionalString(); var projectFile = ReadOptionalString(); var targetFile = ReadOptionalString(); var parentTarget = ReadOptionalString(); // BuildReason was introduced in version 4 var buildReason = fileFormatVersion > 3 ? (TargetBuiltReason)ReadInt32() : TargetBuiltReason.None; var e = new TargetStartedEventArgs( fields.Message, fields.HelpKeyword, targetName, projectFile, targetFile, parentTarget, buildReason, fields.Timestamp); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadTargetFinishedEventArgs() { var fields = ReadBuildEventArgsFields(); var succeeded = ReadBoolean(); var projectFile = ReadOptionalString(); var targetFile = ReadOptionalString(); var targetName = ReadOptionalString(); var targetOutputItemList = ReadTaskItemList(); var e = new TargetFinishedEventArgs( fields.Message, fields.HelpKeyword, targetName, projectFile, targetFile, succeeded, fields.Timestamp, targetOutputItemList); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadTaskStartedEventArgs() { var fields = ReadBuildEventArgsFields(); var taskName = ReadOptionalString(); var projectFile = ReadOptionalString(); var taskFile = ReadOptionalString(); var e = new TaskStartedEventArgs( fields.Message, fields.HelpKeyword, projectFile, taskFile, taskName, fields.Timestamp); e.LineNumber = fields.LineNumber; e.ColumnNumber = fields.ColumnNumber; SetCommonFields(e, fields); return e; } private BuildEventArgs ReadTaskFinishedEventArgs() { var fields = ReadBuildEventArgsFields(); var succeeded = ReadBoolean(); var taskName = ReadOptionalString(); var projectFile = ReadOptionalString(); var taskFile = ReadOptionalString(); var e = new TaskFinishedEventArgs( fields.Message, fields.HelpKeyword, projectFile, taskFile, taskName, succeeded, fields.Timestamp); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadBuildErrorEventArgs() { var fields = ReadBuildEventArgsFields(); ReadDiagnosticFields(fields); var e = new BuildErrorEventArgs( fields.Subcategory, fields.Code, fields.File, fields.LineNumber, fields.ColumnNumber, fields.EndLineNumber, fields.EndColumnNumber, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Timestamp, fields.Arguments); e.BuildEventContext = fields.BuildEventContext; e.ProjectFile = fields.ProjectFile; return e; } private BuildEventArgs ReadBuildWarningEventArgs() { var fields = ReadBuildEventArgsFields(); ReadDiagnosticFields(fields); var e = new BuildWarningEventArgs( fields.Subcategory, fields.Code, fields.File, fields.LineNumber, fields.ColumnNumber, fields.EndLineNumber, fields.EndColumnNumber, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Timestamp, fields.Arguments); e.BuildEventContext = fields.BuildEventContext; e.ProjectFile = fields.ProjectFile; return e; } private BuildEventArgs ReadBuildMessageEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); var e = new BuildMessageEventArgs( fields.Subcategory, fields.Code, fields.File, fields.LineNumber, fields.ColumnNumber, fields.EndLineNumber, fields.EndColumnNumber, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Importance, fields.Timestamp, fields.Arguments); e.BuildEventContext = fields.BuildEventContext; e.ProjectFile = fields.ProjectFile; return e; } private BuildEventArgs ReadTaskCommandLineEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); var commandLine = ReadOptionalString(); var taskName = ReadOptionalString(); var e = new TaskCommandLineEventArgs( commandLine, taskName, fields.Importance, fields.Timestamp); e.BuildEventContext = fields.BuildEventContext; e.ProjectFile = fields.ProjectFile; return e; } private BuildEventArgs ReadTaskParameterEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); var kind = (TaskParameterMessageKind)ReadInt32(); var itemType = ReadDeduplicatedString(); var items = ReadTaskItemList() as IList; var e = ItemGroupLoggingHelper.CreateTaskParameterEventArgs( fields.BuildEventContext, kind, itemType, items, logItemMetadata: true, fields.Timestamp, fields.LineNumber, fields.ColumnNumber); e.ProjectFile = fields.ProjectFile; return e; } private BuildEventArgs ReadCriticalBuildMessageEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); var e = new CriticalBuildMessageEventArgs( fields.Subcategory, fields.Code, fields.File, fields.LineNumber, fields.ColumnNumber, fields.EndLineNumber, fields.EndColumnNumber, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Timestamp, fields.Arguments); e.BuildEventContext = fields.BuildEventContext; e.ProjectFile = fields.ProjectFile; return e; } private BuildEventArgs ReadEnvironmentVariableReadEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); var environmentVariableName = ReadDeduplicatedString(); var e = new EnvironmentVariableReadEventArgs( environmentVariableName, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Importance); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadPropertyReassignmentEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); string propertyName = ReadDeduplicatedString(); string previousValue = ReadDeduplicatedString(); string newValue = ReadDeduplicatedString(); string location = ReadDeduplicatedString(); var e = new PropertyReassignmentEventArgs( propertyName, previousValue, newValue, location, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Importance); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadUninitializedPropertyReadEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); string propertyName = ReadDeduplicatedString(); var e = new UninitializedPropertyReadEventArgs( propertyName, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Importance); SetCommonFields(e, fields); return e; } private BuildEventArgs ReadPropertyInitialValueSetEventArgs() { var fields = ReadBuildEventArgsFields(readImportance: true); string propertyName = ReadDeduplicatedString(); string propertyValue = ReadDeduplicatedString(); string propertySource = ReadDeduplicatedString(); var e = new PropertyInitialValueSetEventArgs( propertyName, propertyValue, propertySource, fields.Message, fields.HelpKeyword, fields.SenderName, fields.Importance); SetCommonFields(e, fields); return e; } /// <summary> /// For errors and warnings these 8 fields are written out explicitly /// (their presence is not marked as a bit in the flags). So we have to /// read explicitly. /// </summary> /// <param name="fields"></param> private void ReadDiagnosticFields(BuildEventArgsFields fields) { fields.Subcategory = ReadOptionalString(); fields.Code = ReadOptionalString(); fields.File = ReadOptionalString(); fields.ProjectFile = ReadOptionalString(); fields.LineNumber = ReadInt32(); fields.ColumnNumber = ReadInt32(); fields.EndLineNumber = ReadInt32(); fields.EndColumnNumber = ReadInt32(); } private BuildEventArgsFields ReadBuildEventArgsFields(bool readImportance = false) { BuildEventArgsFieldFlags flags = (BuildEventArgsFieldFlags)ReadInt32(); var result = new BuildEventArgsFields(); result.Flags = flags; if ((flags & BuildEventArgsFieldFlags.Message) != 0) { result.Message = ReadDeduplicatedString(); } if ((flags & BuildEventArgsFieldFlags.BuildEventContext) != 0) { result.BuildEventContext = ReadBuildEventContext(); } if ((flags & BuildEventArgsFieldFlags.ThreadId) != 0) { result.ThreadId = ReadInt32(); } if ((flags & BuildEventArgsFieldFlags.HelpKeyword) != 0) { result.HelpKeyword = ReadDeduplicatedString(); } if ((flags & BuildEventArgsFieldFlags.SenderName) != 0) { result.SenderName = ReadDeduplicatedString(); } if ((flags & BuildEventArgsFieldFlags.Timestamp) != 0) { result.Timestamp = ReadDateTime(); } if ((flags & BuildEventArgsFieldFlags.Subcategory) != 0) { result.Subcategory = ReadDeduplicatedString(); } if ((flags & BuildEventArgsFieldFlags.Code) != 0) { result.Code = ReadDeduplicatedString(); } if ((flags & BuildEventArgsFieldFlags.File) != 0) { result.File = ReadDeduplicatedString(); } if ((flags & BuildEventArgsFieldFlags.ProjectFile) != 0) { result.ProjectFile = ReadDeduplicatedString(); } if ((flags & BuildEventArgsFieldFlags.LineNumber) != 0) { result.LineNumber = ReadInt32(); } if ((flags & BuildEventArgsFieldFlags.ColumnNumber) != 0) { result.ColumnNumber = ReadInt32(); } if ((flags & BuildEventArgsFieldFlags.EndLineNumber) != 0) { result.EndLineNumber = ReadInt32(); } if ((flags & BuildEventArgsFieldFlags.EndColumnNumber) != 0) { result.EndColumnNumber = ReadInt32(); } if ((flags & BuildEventArgsFieldFlags.Arguments) != 0) { int count = ReadInt32(); object[] arguments = new object[count]; for (int i = 0; i < count; i++) { arguments[i] = ReadDeduplicatedString(); } result.Arguments = arguments; } if ((fileFormatVersion < 13 && readImportance) || (fileFormatVersion >= 13 && (flags & BuildEventArgsFieldFlags.Importance) != 0)) { result.Importance = (MessageImportance)ReadInt32(); } return result; } private void SetCommonFields(BuildEventArgs buildEventArgs, BuildEventArgsFields fields) { buildEventArgs.BuildEventContext = fields.BuildEventContext; if ((fields.Flags & BuildEventArgsFieldFlags.ThreadId) != 0) { buildEventArgsFieldThreadId.SetValue(buildEventArgs, fields.ThreadId); } if ((fields.Flags & BuildEventArgsFieldFlags.SenderName) != 0) { buildEventArgsFieldSenderName.SetValue(buildEventArgs, fields.SenderName); } if ((fields.Flags & BuildEventArgsFieldFlags.Timestamp) != 0) { buildEventArgs.RawTimestamp = fields.Timestamp; } } private IEnumerable ReadPropertyList() { var properties = ReadStringDictionary(); if (properties == null || properties.Count == 0) { return null; } int count = properties.Count; var list = new DictionaryEntry[count]; int i = 0; foreach (var property in properties) { list[i] = new DictionaryEntry(property.Key, property.Value); i++; } return list; } private BuildEventContext ReadBuildEventContext() { int nodeId = ReadInt32(); int projectContextId = ReadInt32(); int targetId = ReadInt32(); int taskId = ReadInt32(); int submissionId = ReadInt32(); int projectInstanceId = ReadInt32(); // evaluationId was introduced in format version 2 int evaluationId = BuildEventContext.InvalidEvaluationId; if (fileFormatVersion > 1) { evaluationId = ReadInt32(); } var result = new BuildEventContext( submissionId, nodeId, evaluationId, projectInstanceId, projectContextId, targetId, taskId); return result; } private IDictionary<string, string> ReadStringDictionary() { if (fileFormatVersion < 10) { return ReadLegacyStringDictionary(); } int index = ReadInt32(); if (index == 0) { return null; } var record = GetNameValueList(index); return record; } private IDictionary<string, string> ReadLegacyStringDictionary() { int count = ReadInt32(); if (count == 0) { return null; } var result = new Dictionary<string, string>(count); for (int i = 0; i < count; i++) { string key = ReadString(); string value = ReadString(); result[key] = value; } return result; } private ITaskItem ReadTaskItem() { string itemSpec = ReadDeduplicatedString(); var metadata = ReadStringDictionary(); var taskItem = new TaskItemData(itemSpec, metadata); return taskItem; } private IEnumerable ReadProjectItems() { IList<DictionaryEntry> list; // starting with format version 10 project items are grouped by name // so we only have to write the name once, and then the count of items // with that name. When reading a legacy binlog we need to read the // old style flat list where the name is duplicated for each item. if (fileFormatVersion < 10) { int count = ReadInt32(); if (count == 0) { return null; } list = new DictionaryEntry[count]; for (int i = 0; i < count; i++) { string itemName = ReadString(); ITaskItem item = ReadTaskItem(); list[i] = new DictionaryEntry(itemName, item); } } else if (fileFormatVersion < 12) { int count = ReadInt32(); if (count == 0) { return null; } list = new List<DictionaryEntry>(); for (int i = 0; i < count; i++) { string itemType = ReadDeduplicatedString(); var items = ReadTaskItemList(); if (items != null) { foreach (var item in items) { list.Add(new DictionaryEntry(itemType, item)); } } } if (list.Count == 0) { list = null; } } else { list = new List<DictionaryEntry>(); while (true) { string itemType = ReadDeduplicatedString(); if (string.IsNullOrEmpty(itemType)) { break; } var items = ReadTaskItemList(); if (items != null) { foreach (var item in items) { list.Add(new DictionaryEntry(itemType, item)); } } } if (list.Count == 0) { list = null; } } return list; } private IEnumerable ReadTaskItemList() { int count = ReadInt32(); if (count == 0) { return null; } var list = new ITaskItem[count]; for (int i = 0; i < count; i++) { ITaskItem item = ReadTaskItem(); list[i] = item; } return list; } private string ReadString() { return binaryReader.ReadString(); } private string ReadOptionalString() { if (fileFormatVersion < 10) { if (ReadBoolean()) { return ReadString(); } else { return null; } } return ReadDeduplicatedString(); } private string ReadDeduplicatedString() { if (fileFormatVersion < 10) { return ReadString(); } int index = ReadInt32(); return GetStringFromRecord(index); } private string GetStringFromRecord(int index) { if (index == 0) { return null; } else if (index == 1) { return string.Empty; } // we reserve numbers 2-9 for future use. // the writer assigns 10 as the index of the first string index -= BuildEventArgsWriter.StringStartIndex; if (index >= 0 && index < this.stringRecords.Count) { object storedString = stringRecords[index]; string result = stringStorage.Get(storedString); return result; } // this should never happen for valid binlogs throw new InvalidDataException( $"String record number {recordNumber} is invalid: string index {index} is not within {stringRecords.Count}."); } private int ReadInt32() { // on some platforms (net5) this method was added to BinaryReader // but it's not available on others. Call our own extension method // explicitly to avoid ambiguity. return BinaryReaderExtensions.Read7BitEncodedInt(binaryReader); } private long ReadInt64() { return binaryReader.ReadInt64(); } private bool ReadBoolean() { return binaryReader.ReadBoolean(); } private DateTime ReadDateTime() { return new DateTime(binaryReader.ReadInt64(), (DateTimeKind)ReadInt32()); } private TimeSpan ReadTimeSpan() { return new TimeSpan(binaryReader.ReadInt64()); } private ProfiledLocation ReadProfiledLocation() { var numberOfHits = ReadInt32(); var exclusiveTime = ReadTimeSpan(); var inclusiveTime = ReadTimeSpan(); return new ProfiledLocation(inclusiveTime, exclusiveTime, numberOfHits); } private EvaluationLocation ReadEvaluationLocation() { var elementName = ReadOptionalString(); var description = ReadOptionalString(); var evaluationDescription = ReadOptionalString(); var file = ReadOptionalString(); var kind = (EvaluationLocationKind)ReadInt32(); var evaluationPass = (EvaluationPass)ReadInt32(); int? line = null; var hasLine = ReadBoolean(); if (hasLine) { line = ReadInt32(); } // Id and parent Id were introduced in version 6 if (fileFormatVersion > 5) { var id = ReadInt64(); long? parentId = null; var hasParent = ReadBoolean(); if (hasParent) { parentId = ReadInt64(); } return new EvaluationLocation(id, parentId, evaluationPass, evaluationDescription, file, line, elementName, description, kind); } return new EvaluationLocation(0, null, evaluationPass, evaluationDescription, file, line, elementName, description, kind); } /// <summary> /// Locates the string in the page file. /// </summary> internal class StringPosition { /// <summary> /// Offset in the file. /// </summary> public long FilePosition; /// <summary> /// The length of the string in chars (not bytes). /// </summary> public int StringLength; } /// <summary> /// Stores large strings in a temp file on disk, to avoid keeping all strings in memory. /// Only creates a file for 32-bit MSBuild.exe, just returns the string directly on 64-bit. /// </summary> internal class StringStorage : IDisposable { private readonly string filePath; private FileStream stream; private StreamWriter streamWriter; private readonly StreamReader streamReader; private readonly StringBuilder stringBuilder; public const int StringSizeThreshold = 1024; public StringStorage() { if (!Environment.Is64BitProcess) { filePath = Path.GetTempFileName(); var utf8noBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); stream = new FileStream( filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, bufferSize: 4096, // 4096 seems to have the best performance on SSD FileOptions.RandomAccess | FileOptions.DeleteOnClose); // 65536 has no particular significance, and maybe could be tuned // but 65536 performs well enough and isn't a lot of memory for a singleton streamWriter = new StreamWriter(stream, utf8noBom, 65536); streamWriter.AutoFlush = true; streamReader = new StreamReader(stream, utf8noBom); stringBuilder = new StringBuilder(); } } private long totalAllocatedShortStrings = 0; public object Add(string text) { if (filePath == null) { // on 64-bit, we have as much memory as we want // so no need to write to the file at all return text; } // Tradeoff between not crashing with OOM on large binlogs and // keeping the playback of smaller binlogs relatively fast. // It is slow to store all small strings in the file and constantly // seek to retrieve them. Instead we'll keep storing small strings // in memory until we allocate 2 GB. After that, all strings go to // the file. // Win-win: small binlog playback is fast and large binlog playback // doesn't OOM. if (text.Length <= StringSizeThreshold && totalAllocatedShortStrings < 1_000_000_000) { totalAllocatedShortStrings += text.Length; return text; } var stringPosition = new StringPosition(); stringPosition.FilePosition = stream.Position; streamWriter.Write(text); stringPosition.StringLength = text.Length; return stringPosition; } public string Get(object storedString) { if (storedString is string text) { return text; } var position = (StringPosition)storedString; stream.Position = position.FilePosition; stringBuilder.Length = position.StringLength; for (int i = 0; i < position.StringLength; i++) { char ch = (char)streamReader.Read(); stringBuilder[i] = ch; } stream.Position = stream.Length; streamReader.DiscardBufferedData(); string result = stringBuilder.ToString(); stringBuilder.Clear(); return result; } public void Dispose() { try { if (streamWriter != null) { streamWriter.Dispose(); streamWriter = null; } if (stream != null) { stream.Dispose(); stream = null; } } catch { // The StringStorage class is not crucial for other functionality and if // there are exceptions when closing the temp file, it's too late to do anything about it. // Since we don't want to disrupt anything and the file is in the TEMP directory, it will // get cleaned up at some point anyway. } } } } }
// // CTRunDelegate.cs: Implements the managed CTRunDelegate // // Authors: Mono Team // // Copyright 2010 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.Drawing; using System.Reflection; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; namespace MonoMac.CoreText { #region Run Delegate Callbacks delegate void CTRunDelegateDeallocateCallback (IntPtr refCon); delegate float CTRunDelegateGetAscentCallback (IntPtr refCon); delegate float CTRunDelegateGetDescentCallback (IntPtr refCon); delegate float CTRunDelegateGetWidthCallback (IntPtr refCon); [StructLayout (LayoutKind.Sequential)] class CTRunDelegateCallbacks { public CTRunDelegateVersion version; public CTRunDelegateDeallocateCallback dealloc; public CTRunDelegateGetAscentCallback getAscent; public CTRunDelegateGetDescentCallback getDescent; public CTRunDelegateGetWidthCallback getWidth; } #endregion #region Run Delegate Versions enum CTRunDelegateVersion { Version1 = 1, CurrentVersion = Version1, } #endregion [Since (3,2)] public class CTRunDelegateOperations : IDisposable { internal GCHandle handle; protected CTRunDelegateOperations () { handle = GCHandle.Alloc (this); } public virtual void Dispose () { } public virtual float GetAscent () { return 0.0f; } public virtual float GetDescent () { return 0.0f; } public virtual float GetWidth () { return 0.0f; } internal CTRunDelegateCallbacks GetCallbacks () { var callbacks = new CTRunDelegateCallbacks () { version = CTRunDelegateVersion.Version1, dealloc = Deallocate, }; var flags = BindingFlags.Public | BindingFlags.Instance; MethodInfo m; if ((m = this.GetType ().GetMethod ("GetAscent", flags)) != null && m.DeclaringType != typeof (CTRunDelegateOperations)) { callbacks.getAscent = GetAscent; } if ((m = this.GetType ().GetMethod ("GetDescent", flags)) != null && m.DeclaringType != typeof (CTRunDelegateOperations)) { callbacks.getDescent = GetDescent; } if ((m = this.GetType ().GetMethod ("GetWidth", flags)) != null && m.DeclaringType != typeof (CTRunDelegateOperations)) { callbacks.getWidth = GetWidth; } return callbacks; } [MonoPInvokeCallback (typeof (CTRunDelegateDeallocateCallback))] static void Deallocate (IntPtr refCon) { var self = GetOperations (refCon); if (self == null) return; self.Dispose (); if (self.handle.IsAllocated) self.handle.Free (); self.handle = new GCHandle (); } internal static CTRunDelegateOperations GetOperations (IntPtr refCon) { GCHandle c = GCHandle.FromIntPtr (refCon); return c.Target as CTRunDelegateOperations; } [MonoPInvokeCallback (typeof (CTRunDelegateGetAscentCallback))] static float GetAscent (IntPtr refCon) { var self = GetOperations (refCon); if (self == null) return 0.0f; return self.GetAscent (); } [MonoPInvokeCallback (typeof (CTRunDelegateGetDescentCallback))] static float GetDescent (IntPtr refCon) { var self = GetOperations (refCon); if (self == null) return 0.0f; return self.GetDescent (); } [MonoPInvokeCallback (typeof (CTRunDelegateGetWidthCallback))] static float GetWidth (IntPtr refCon) { var self = GetOperations (refCon); if (self == null) return 0.0f; return self.GetWidth (); } } [Since (3,2)] public class CTRunDelegate : INativeObject, IDisposable { internal IntPtr handle; internal CTRunDelegate (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw new ArgumentNullException ("handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } public IntPtr Handle { get {return handle;} } ~CTRunDelegate () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #region RunDelegate Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTRunDelegateCreate (CTRunDelegateCallbacks callbacks, IntPtr refCon); public CTRunDelegate (CTRunDelegateOperations operations) { if (operations == null) throw ConstructorError.ArgumentNull (this, "operations"); handle = CTRunDelegateCreate (operations.GetCallbacks (), GCHandle.ToIntPtr (operations.handle)); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } #endregion #region Run Delegate Access [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTRunDelegateGetRefCon (IntPtr runDelegate); public CTRunDelegateOperations Operations { get { return CTRunDelegateOperations.GetOperations (CTRunDelegateGetRefCon (handle)); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System { using System.Text; using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Globalization; // TimeSpan represents a duration of time. A TimeSpan can be negative // or positive. // // TimeSpan is internally represented as a number of milliseconds. While // this maps well into units of time such as hours and days, any // periods longer than that aren't representable in a nice fashion. // For instance, a month can be between 28 and 31 days, while a year // can contain 365 or 364 days. A decade can have between 1 and 3 leapyears, // depending on when you map the TimeSpan into the calendar. This is why // we do not provide Years() or Months(). // // Note: System.TimeSpan needs to interop with the WinRT structure // type Windows::Foundation:TimeSpan. These types are currently binary-compatible in // memory so no custom marshalling is required. If at any point the implementation // details of this type should change, or new fields added, we need to remember to add // an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public struct TimeSpan : IComparable , IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable { public const long TicksPerMillisecond = 10000; private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond; public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000 private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001 public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000 private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9 public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000 private const double HoursPerTick = 1.0 / TicksPerHour; // 2.77777777777777778e-11 public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000 private const double DaysPerTick = 1.0 / TicksPerDay; // 1.1574074074074074074e-12 private const int MillisPerSecond = 1000; private const int MillisPerMinute = MillisPerSecond * 60; // 60,000 private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000 private const int MillisPerDay = MillisPerHour * 24; // 86,400,000 internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond; internal const long MinSeconds = Int64.MinValue / TicksPerSecond; internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond; internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond; internal const long TicksPerTenthSecond = TicksPerMillisecond * 100; public static readonly TimeSpan Zero = new TimeSpan(0); public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue); public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue); // internal so that DateTime doesn't have to call an extra get // method for some arithmetic operations. internal long _ticks; //public TimeSpan() { // _ticks = 0; //} public TimeSpan(long ticks) { this._ticks = ticks; } public TimeSpan(int hours, int minutes, int seconds) { _ticks = TimeToTicks(hours, minutes, seconds); } public TimeSpan(int days, int hours, int minutes, int seconds) : this(days,hours,minutes,seconds,0) { } public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds; if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds) throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong")); _ticks = (long)totalMilliSeconds * TicksPerMillisecond; } public long Ticks { get { return _ticks; } } public int Days { get { return (int)(_ticks / TicksPerDay); } } public int Hours { get { return (int)((_ticks / TicksPerHour) % 24); } } public int Milliseconds { get { return (int)((_ticks / TicksPerMillisecond) % 1000); } } public int Minutes { get { return (int)((_ticks / TicksPerMinute) % 60); } } public int Seconds { get { return (int)((_ticks / TicksPerSecond) % 60); } } public double TotalDays { get { return ((double)_ticks) * DaysPerTick; } } public double TotalHours { get { return (double)_ticks * HoursPerTick; } } public double TotalMilliseconds { get { double temp = (double)_ticks * MillisecondsPerTick; if (temp > MaxMilliSeconds) return (double)MaxMilliSeconds; if (temp < MinMilliSeconds) return (double)MinMilliSeconds; return temp; } } public double TotalMinutes { get { return (double)_ticks * MinutesPerTick; } } public double TotalSeconds { get { return (double)_ticks * SecondsPerTick; } } public TimeSpan Add(TimeSpan ts) { long result = _ticks + ts._ticks; // Overflow if signs of operands was identical and result's // sign was opposite. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong")); return new TimeSpan(result); } // Compares two TimeSpan values, returning an integer that indicates their // relationship. // public static int Compare(TimeSpan t1, TimeSpan t2) { if (t1._ticks > t2._ticks) return 1; if (t1._ticks < t2._ticks) return -1; return 0; } // Returns a value less than zero if this object public int CompareTo(Object value) { if (value == null) return 1; if (!(value is TimeSpan)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTimeSpan")); long t = ((TimeSpan)value)._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } public int CompareTo(TimeSpan value) { long t = value._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } public static TimeSpan FromDays(double value) { return Interval(value, MillisPerDay); } public TimeSpan Duration() { if (Ticks==TimeSpan.MinValue.Ticks) throw new OverflowException(Environment.GetResourceString("Overflow_Duration")); Contract.EndContractBlock(); return new TimeSpan(_ticks >= 0? _ticks: -_ticks); } public override bool Equals(Object value) { if (value is TimeSpan) { return _ticks == ((TimeSpan)value)._ticks; } return false; } public bool Equals(TimeSpan obj) { return _ticks == obj._ticks; } public static bool Equals(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public override int GetHashCode() { return (int)_ticks ^ (int)(_ticks >> 32); } public static TimeSpan FromHours(double value) { return Interval(value, MillisPerHour); } private static TimeSpan Interval(double value, int scale) { if (Double.IsNaN(value)) throw new ArgumentException(Environment.GetResourceString("Arg_CannotBeNaN")); Contract.EndContractBlock(); double tmp = value * scale; double millis = tmp + (value >= 0? 0.5: -0.5); if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond)) throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong")); return new TimeSpan((long)millis * TicksPerMillisecond); } public static TimeSpan FromMilliseconds(double value) { return Interval(value, 1); } public static TimeSpan FromMinutes(double value) { return Interval(value, MillisPerMinute); } public TimeSpan Negate() { if (Ticks==TimeSpan.MinValue.Ticks) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return new TimeSpan(-_ticks); } public static TimeSpan FromSeconds(double value) { return Interval(value, MillisPerSecond); } public TimeSpan Subtract(TimeSpan ts) { long result = _ticks - ts._ticks; // Overflow if signs of operands was different and result's // sign was opposite from the first argument's sign. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong")); return new TimeSpan(result); } public static TimeSpan FromTicks(long value) { return new TimeSpan(value); } internal static long TimeToTicks(int hour, int minute, int second) { // totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31, // which is less than 2^44, meaning we won't overflow totalSeconds. long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second; if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds) throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong")); return totalSeconds * TicksPerSecond; } // See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat #region ParseAndFormat public static TimeSpan Parse(String s) { /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } public static TimeSpan Parse(String input, IFormatProvider formatProvider) { return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider) { return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) { return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static Boolean TryParse(String s, out TimeSpan result) { return TimeSpanParse.TryParse(s, null, out result); } public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParse(input, formatProvider, out result); } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } public override String ToString() { return TimeSpanFormat.Format(this, null, null); } public String ToString(String format) { return TimeSpanFormat.Format(this, format, null); } public String ToString(String format, IFormatProvider formatProvider) { if (LegacyMode) { return TimeSpanFormat.Format(this, null, null); } else { return TimeSpanFormat.Format(this, format, formatProvider); } } #endregion public static TimeSpan operator -(TimeSpan t) { if (t._ticks==TimeSpan.MinValue._ticks) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); return new TimeSpan(-t._ticks); } public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) { return t1.Subtract(t2); } public static TimeSpan operator +(TimeSpan t) { return t; } public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) { return t1.Add(t2); } public static bool operator ==(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public static bool operator !=(TimeSpan t1, TimeSpan t2) { return t1._ticks != t2._ticks; } public static bool operator <(TimeSpan t1, TimeSpan t2) { return t1._ticks < t2._ticks; } public static bool operator <=(TimeSpan t1, TimeSpan t2) { return t1._ticks <= t2._ticks; } public static bool operator >(TimeSpan t1, TimeSpan t2) { return t1._ticks > t2._ticks; } public static bool operator >=(TimeSpan t1, TimeSpan t2) { return t1._ticks >= t2._ticks; } // // In .NET Framework v1.0 - v3.5 System.TimeSpan did not implement IFormattable // The composite formatter ignores format specifiers on types that do not implement // IFormattable, so the following code would 'just work' by using TimeSpan.ToString() // under the hood: // String.Format("{0:_someRandomFormatString_}", myTimeSpan); // // In .NET Framework v4.0 System.TimeSpan implements IFormattable. This causes the // composite formatter to call TimeSpan.ToString(string format, FormatProvider provider) // and pass in "_someRandomFormatString_" for the format parameter. When the format // parameter is invalid a FormatException is thrown. // // The 'NetFx40_TimeSpanLegacyFormatMode' per-AppDomain configuration option and the 'TimeSpan_LegacyFormatMode' // process-wide configuration option allows applications to run with the v1.0 - v3.5 legacy behavior. When // either switch is specified the format parameter is ignored and the default output is returned. // // There are three ways to use the process-wide configuration option: // // 1) Config file (MyApp.exe.config) // <?xml version ="1.0"?> // <configuration> // <runtime> // <TimeSpan_LegacyFormatMode enabled="true"/> // </runtime> // </configuration> // 2) Environment variable // set COMPLUS_TimeSpan_LegacyFormatMode=1 // 3) RegistryKey // [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework] // "TimeSpan_LegacyFormatMode"=dword:00000001 // #if !FEATURE_CORECLR [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool LegacyFormatMode(); #endif // !FEATURE_CORECLR // // In Silverlight v4, specifying the APP_EARLIER_THAN_SL4.0 quirks mode allows applications to // run in v2 - v3 legacy behavior. // #if !FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif private static bool GetLegacyFormatMode() { #if !FEATURE_CORECLR if (LegacyFormatMode()) // FCALL to check COMPLUS_TimeSpan_LegacyFormatMode return true; return CompatibilitySwitches.IsNetFx40TimeSpanLegacyFormatMode; #else return CompatibilitySwitches.IsAppEarlierThanSilverlight4; #endif // !FEATURE_CORECLR } private static volatile bool _legacyConfigChecked; private static volatile bool _legacyMode; private static bool LegacyMode { get { if (!_legacyConfigChecked) { // no need to lock - idempotent _legacyMode = GetLegacyFormatMode(); _legacyConfigChecked = true; } return _legacyMode; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using NUnit.Framework; using ServiceStack.Common.Extensions; using ServiceStack.Text; namespace ServiceStack.Redis.Tests { [TestFixture, Category("Integration")] public class RedisPubSubTests : RedisClientTestsBase { public override void OnBeforeEachTest() { base.OnBeforeEachTest(); Redis.NamespacePrefix = "RedisPubSubTests"; } [Test] public void Can_Subscribe_and_Publish_single_message() { var channelName = PrefixedKey("CHANNEL1"); const string message = "Hello, World!"; var key = PrefixedKey("Can_Subscribe_and_Publish_single_message"); Redis.IncrementValue(key); using (var subscription = Redis.CreateSubscription()) { subscription.OnSubscribe = channel => { Log("Subscribed to '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); }; subscription.OnUnSubscribe = channel => { Log("UnSubscribed from '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); }; subscription.OnMessage = (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelName)); Assert.That(msg, Is.EqualTo(message)); subscription.UnSubscribeFromAllChannels(); }; ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(100); // to be sure that we have subscribers using (var redisClient = CreateRedisClient()) { Log("Publishing '{0}' to '{1}'", message, channelName); redisClient.PublishMessage(channelName, message); } }); Log("Start Listening On " + channelName); subscription.SubscribeToChannels(channelName); //blocking } Log("Using as normal client again..."); Redis.IncrementValue(key); Assert.That(Redis.Get<int>(key), Is.EqualTo(2)); } [Test] public void Can_Subscribe_and_Publish_single_message_using_wildcard() { var channelWildcard = PrefixedKey("CHANNEL.*"); var channelName = PrefixedKey("CHANNEL.1"); const string message = "Hello, World!"; var key = PrefixedKey("Can_Subscribe_and_Publish_single_message"); Redis.IncrementValue(key); using (var subscription = Redis.CreateSubscription()) { subscription.OnSubscribe = channel => { Log("Subscribed to '{0}'", channelWildcard); Assert.That(channel, Is.EqualTo(channelWildcard)); }; subscription.OnUnSubscribe = channel => { Log("UnSubscribed from '{0}'", channelWildcard); Assert.That(channel, Is.EqualTo(channelWildcard)); }; subscription.OnMessage = (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelName)); Assert.That(msg, Is.EqualTo(message), "we should get the message, not the channel"); subscription.UnSubscribeFromChannelsMatching(); }; ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(100); // to be sure that we have subscribers using (var redisClient = CreateRedisClient()) { Log("Publishing '{0}' to '{1}'", message, channelName); redisClient.PublishMessage(channelName, message); } }); Log("Start Listening On " + channelName); subscription.SubscribeToChannelsMatching(channelWildcard); //blocking } Log("Using as normal client again..."); Redis.IncrementValue(key); Assert.That(Redis.Get<int>(key), Is.EqualTo(2)); } [Test] public void Can_Subscribe_and_Publish_multiple_message() { var channelName = PrefixedKey("CHANNEL2"); const string messagePrefix = "MESSAGE "; string key = PrefixedKey("Can_Subscribe_and_Publish_multiple_message"); const int publishMessageCount = 5; var messagesReceived = 0; Redis.IncrementValue(key); using (var subscription = Redis.CreateSubscription()) { subscription.OnSubscribe = channel => { Log("Subscribed to '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); }; subscription.OnUnSubscribe = channel => { Log("UnSubscribed from '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); }; subscription.OnMessage = (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelName)); Assert.That(msg, Is.EqualTo(messagePrefix + messagesReceived++)); if (messagesReceived == publishMessageCount) { subscription.UnSubscribeFromAllChannels(); } }; ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(100); // to be sure that we have subscribers using (var redisClient = CreateRedisClient()) { for (var i = 0; i < publishMessageCount; i++) { var message = messagePrefix + i; Log("Publishing '{0}' to '{1}'", message, channelName); redisClient.PublishMessage(channelName, message); } } }); Log("Start Listening On"); subscription.SubscribeToChannels(channelName); //blocking } Log("Using as normal client again..."); Redis.IncrementValue(key); Assert.That(Redis.Get<int>(key), Is.EqualTo(2)); Assert.That(messagesReceived, Is.EqualTo(publishMessageCount)); } [Test] public void Can_Subscribe_and_Publish_message_to_multiple_channels() { var channelPrefix = PrefixedKey("CHANNEL3 "); const string message = "MESSAGE"; const int publishChannelCount = 5; var key = PrefixedKey("Can_Subscribe_and_Publish_message_to_multiple_channels"); var channels = new List<string>(); publishChannelCount.Times(i => channels.Add(channelPrefix + i)); var messagesReceived = 0; var channelsSubscribed = 0; var channelsUnSubscribed = 0; Redis.IncrementValue(key); using (var subscription = Redis.CreateSubscription()) { subscription.OnSubscribe = channel => { Log("Subscribed to '{0}'", channel); Assert.That(channel, Is.EqualTo(channelPrefix + channelsSubscribed++)); }; subscription.OnUnSubscribe = channel => { Log("UnSubscribed from '{0}'", channel); Assert.That(channel, Is.EqualTo(channelPrefix + channelsUnSubscribed++)); }; subscription.OnMessage = (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelPrefix + messagesReceived++)); Assert.That(msg, Is.EqualTo(message)); subscription.UnSubscribeFromChannels(channel); }; ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(100); // to be sure that we have subscribers using (var redisClient = CreateRedisClient()) { foreach (var channel in channels) { Log("Publishing '{0}' to '{1}'", message, channel); redisClient.PublishMessage(channel, message); } } }); Log("Start Listening On"); subscription.SubscribeToChannels(channels.ToArray()); //blocking } Log("Using as normal client again..."); Redis.IncrementValue(key); Assert.That(Redis.Get<int>(key), Is.EqualTo(2)); Assert.That(messagesReceived, Is.EqualTo(publishChannelCount)); Assert.That(channelsSubscribed, Is.EqualTo(publishChannelCount)); Assert.That(channelsUnSubscribed, Is.EqualTo(publishChannelCount)); } [Test] public void Can_Subscribe_to_channel_pattern() { int msgs = 0; using (var subscription = Redis.CreateSubscription()) { subscription.OnMessage = (channel, msg) => { Debug.WriteLine(String.Format("{0}: {1}", channel, msg + msgs++)); subscription.UnSubscribeFromChannelsMatching(PrefixedKey("CHANNEL4:TITLE*")); }; ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(100); // to be sure that we have subscribers using (var redisClient = CreateRedisClient()) { Log("Publishing msg..."); redisClient.Publish(PrefixedKey("CHANNEL4:TITLE1"), "hello".ToUtf8Bytes()); } }); Log("Start Listening On"); subscription.SubscribeToChannelsMatching(PrefixedKey("CHANNEL4:TITLE*")); } } [Test] public void Can_Subscribe_to_multiplechannel_pattern() { var channels = new[] {PrefixedKey("CHANNEL5:TITLE*"), PrefixedKey("CHANNEL5:BODY*")}; int msgs = 0; using (var subscription = Redis.CreateSubscription()) { subscription.OnMessage = (channel, msg) => { Debug.WriteLine(String.Format("{0}: {1}", channel, msg + msgs++)); subscription.UnSubscribeFromChannelsMatching(channels); }; ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(100); // to be sure that we have subscribers using (var redisClient = CreateRedisClient()) { Log("Publishing msg..."); redisClient.Publish(PrefixedKey("CHANNEL5:BODY"), "hello".ToUtf8Bytes()); } }); Log("Start Listening On"); subscription.SubscribeToChannelsMatching(channels); } } } }
// // SiriRemote.cs // tvRemote // // Created by Kevin Mullins on 10/22/15. // Copyright (c) 2015 Xamarin. All rights reserved. // // Generated by PaintCode (www.paintcodeapp.com) // using System; using System.Drawing; using Foundation; using UIKit; using CoreGraphics; // Fix to allow tvOS to consume iOS Core Graphics #if __TVOS__ using UIColor = global::UIKit.TVColor; using UIFont = global::UIKit.TVFont; #endif namespace tvRemote { [Register ("SiriRemote")] public class SiriRemote : NSObject { //// Initialization static SiriRemote() { } //// Drawing Methods public static void DrawSiriRemote(string pressed, string arrow) { //// General Declarations var colorSpace = CGColorSpace.CreateDeviceRGB(); var context = UIGraphics.GetCurrentContext(); //// Color Declarations var gradientColor = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); var gradientColor2 = UIColor.FromRGBA(0.000f, 0.000f, 0.000f, 1.000f); var gradientColor3 = UIColor.FromRGBA(0.368f, 0.368f, 0.368f, 1.000f); var gradientColor4 = UIColor.FromRGBA(0.147f, 0.147f, 0.147f, 1.000f); var strokeColor = UIColor.FromRGBA(0.521f, 0.521f, 0.521f, 1.000f); var strokeColor2 = UIColor.FromRGBA(0.264f, 0.260f, 0.260f, 1.000f); var fillColor = UIColor.FromRGBA(0.000f, 0.000f, 0.000f, 1.000f); var textForeground = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); var strokeColor3 = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); var fillColor2 = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); var pressedColor = UIColor.FromRGBA(0.847f, 0.187f, 0.187f, 1.000f); var gradientColor5 = UIColor.FromRGBA(0.401f, 0.015f, 0.015f, 1.000f); //// Gradient Declarations var radialGradient1Colors = new CGColor [] {gradientColor.CGColor, gradientColor2.CGColor}; var radialGradient1Locations = new nfloat [] {0.0f, 1.0f}; var radialGradient1 = new CGGradient(colorSpace, radialGradient1Colors, radialGradient1Locations); var touchGradientColors = new CGColor [] {gradientColor3.CGColor, gradientColor4.CGColor}; var touchGradientLocations = new nfloat [] {0.0f, 1.0f}; var touchGradient = new CGGradient(colorSpace, touchGradientColors, touchGradientLocations); var pressedGradientColors = new CGColor [] {pressedColor.CGColor, gradientColor5.CGColor}; var pressedGradientLocations = new nfloat [] {0.0f, 1.0f}; var pressedGradient = new CGGradient(colorSpace, pressedGradientColors, pressedGradientLocations); //// Variable Declarations var menuPressed = pressed == "Menu" ? pressedColor : fillColor; var homePressed = pressed == "Home" ? pressedColor : fillColor; var siriPressed = pressed == "Siri" ? pressedColor : fillColor; var volumePressed = pressed == "Volume" ? pressedColor : fillColor; var playPausePressed = pressed == "PlayPause" ? pressedColor : fillColor; var touchSurfacePressed = pressed == "Touch" ? pressedGradient : touchGradient; var upArrow = arrow == "Up" ? true : false; var downArrow = arrow == "Down" ? true : false; var leftArrow = arrow == "Left" ? true : false; var rightArrow = arrow == "Right" ? true : false; //// Page-1 { //// Intro01 { //// Siri-Remote-Render { //// Rectangle-4 Drawing var rectangle4Path = UIBezierPath.FromRoundedRect(new CGRect(1.0f, 0.0f, 253.0f, 747.0f), 40.0f); context.SaveState(); rectangle4Path.AddClip(); context.DrawRadialGradient(radialGradient1, new CGPoint(8.62f, 234.62f), 0.0f, new CGPoint(8.62f, 234.62f), 567.36f, CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); context.RestoreState(); strokeColor.SetStroke(); rectangle4Path.LineWidth = 3.0f; rectangle4Path.Stroke(); //// Rectangle-4-Copy Drawing UIBezierPath rectangle4CopyPath = new UIBezierPath(); rectangle4CopyPath.MoveTo(new CGPoint(254.0f, 312.0f)); rectangle4CopyPath.AddLineTo(new CGPoint(254.0f, 40.0f)); rectangle4CopyPath.AddCurveToPoint(new CGPoint(214.0f, 0.0f), new CGPoint(254.0f, 17.91f), new CGPoint(236.09f, 0.0f)); rectangle4CopyPath.AddLineTo(new CGPoint(41.0f, 0.0f)); rectangle4CopyPath.AddCurveToPoint(new CGPoint(1.0f, 40.0f), new CGPoint(18.92f, 0.0f), new CGPoint(1.0f, 17.91f)); rectangle4CopyPath.AddLineTo(new CGPoint(1.0f, 312.0f)); rectangle4CopyPath.AddLineTo(new CGPoint(254.0f, 312.0f)); rectangle4CopyPath.ClosePath(); rectangle4CopyPath.MiterLimit = 4.0f; rectangle4CopyPath.UsesEvenOddFillRule = true; context.SaveState(); rectangle4CopyPath.AddClip(); context.DrawLinearGradient(touchSurfacePressed, new CGPoint(127.5f, 0.0f), new CGPoint(127.5f, 312.0f), CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); context.RestoreState(); strokeColor2.SetStroke(); rectangle4CopyPath.LineWidth = 3.0f; rectangle4CopyPath.Stroke(); //// Menu-Button { //// Oval-1 Drawing var oval1Path = UIBezierPath.FromOval(new CGRect(18.0f, 214.0f, 87.0f, 87.0f)); menuPressed.SetFill(); oval1Path.Fill(); //// Label Drawing CGRect labelRect = new CGRect(31.42f, 243.0f, 71.58f, 30.0f); textForeground.SetFill(); new NSString("MENU").DrawString(labelRect, UIFont.BoldSystemFontOfSize(20.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); if (upArrow) { //// Bezier Drawing UIBezierPath bezierPath = new UIBezierPath(); bezierPath.MoveTo(new CGPoint(105.5f, 74.5f)); bezierPath.AddLineTo(new CGPoint(149.5f, 74.5f)); bezierPath.AddLineTo(new CGPoint(127.5f, 44.5f)); bezierPath.AddLineTo(new CGPoint(105.5f, 74.5f)); pressedColor.SetFill(); bezierPath.Fill(); } if (downArrow) { //// Bezier 2 Drawing UIBezierPath bezier2Path = new UIBezierPath(); bezier2Path.MoveTo(new CGPoint(106.0f, 180.0f)); bezier2Path.AddLineTo(new CGPoint(150.0f, 180.0f)); bezier2Path.AddLineTo(new CGPoint(128.0f, 210.0f)); bezier2Path.AddLineTo(new CGPoint(106.0f, 180.0f)); pressedColor.SetFill(); bezier2Path.Fill(); } if (rightArrow) { //// Bezier 3 Drawing context.SaveState(); context.TranslateCTM(212.0f, 129.0f); context.RotateCTM(90.0f * NMath.PI / 180.0f); UIBezierPath bezier3Path = new UIBezierPath(); bezier3Path.MoveTo(new CGPoint(-22.0f, 15.0f)); bezier3Path.AddLineTo(new CGPoint(22.0f, 15.0f)); bezier3Path.AddLineTo(new CGPoint(0.0f, -15.0f)); bezier3Path.AddLineTo(new CGPoint(-22.0f, 15.0f)); pressedColor.SetFill(); bezier3Path.Fill(); context.RestoreState(); } if (leftArrow) { //// Bezier 4 Drawing context.SaveState(); context.TranslateCTM(38.0f, 129.0f); context.RotateCTM(-90.0f * NMath.PI / 180.0f); UIBezierPath bezier4Path = new UIBezierPath(); bezier4Path.MoveTo(new CGPoint(-22.0f, 15.0f)); bezier4Path.AddLineTo(new CGPoint(22.0f, 15.0f)); bezier4Path.AddLineTo(new CGPoint(0.0f, -15.0f)); bezier4Path.AddLineTo(new CGPoint(-22.0f, 15.0f)); pressedColor.SetFill(); bezier4Path.Fill(); context.RestoreState(); } } //// Home-Button { //// Oval-1-Copy Drawing var oval1CopyPath = UIBezierPath.FromOval(new CGRect(147.0f, 214.0f, 87.0f, 87.0f)); homePressed.SetFill(); oval1CopyPath.Fill(); //// Rectangle-1-+-Line { //// Rectangle-1 Drawing var rectangle1Path = UIBezierPath.FromRect(new CGRect(166.0f, 239.0f, 49.0f, 32.0f)); strokeColor3.SetStroke(); rectangle1Path.LineWidth = 2.0f; rectangle1Path.Stroke(); //// Line Drawing UIBezierPath linePath = new UIBezierPath(); linePath.MoveTo(new CGPoint(174.5f, 276.0f)); linePath.AddLineTo(new CGPoint(205.56f, 276.0f)); linePath.MiterLimit = 4.0f; linePath.LineCapStyle = CGLineCap.Square; linePath.UsesEvenOddFillRule = true; strokeColor3.SetStroke(); linePath.LineWidth = 2.0f; linePath.Stroke(); } } //// Volume-Button { //// Rectangle- 6 Drawing var rectangle6Path = UIBezierPath.FromRoundedRect(new CGRect(147.0f, 321.0f, 87.0f, 197.0f), 40.0f); volumePressed.SetFill(); rectangle6Path.Fill(); //// Label 2 Drawing CGRect label2Rect = new CGRect(174.96f, 329.0f, 31.08f, 71.0f); textForeground.SetFill(); new NSString("+\n").DrawString(label2Rect, UIFont.BoldSystemFontOfSize(48.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); //// Label 3 Drawing CGRect label3Rect = new CGRect(179.89f, 436.0f, 21.21f, 71.0f); textForeground.SetFill(); new NSString("-").DrawString(label3Rect, UIFont.BoldSystemFontOfSize(48.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); } //// Siri-Button { //// Oval-1-Copy-2 Drawing var oval1Copy2Path = UIBezierPath.FromOval(new CGRect(18.0f, 321.0f, 87.0f, 87.0f)); siriPressed.SetFill(); oval1Copy2Path.Fill(); //// Group 11 { //// Rectangle- 10 Drawing var rectangle10Path = UIBezierPath.FromRoundedRect(new CGRect(49.52f, 338.0f, 22.55f, 38.57f), 11.27f); fillColor2.SetFill(); rectangle10Path.Fill(); //// Path-2 Drawing UIBezierPath path2Path = new UIBezierPath(); path2Path.MoveTo(new CGPoint(46.0f, 363.63f)); path2Path.AddCurveToPoint(new CGPoint(61.24f, 381.48f), new CGPoint(46.0f, 363.63f), new CGPoint(45.67f, 381.58f)); path2Path.AddCurveToPoint(new CGPoint(76.81f, 363.25f), new CGPoint(76.81f, 381.38f), new CGPoint(76.81f, 363.25f)); path2Path.MiterLimit = 4.0f; path2Path.UsesEvenOddFillRule = true; strokeColor3.SetStroke(); path2Path.LineWidth = 4.0f; path2Path.Stroke(); //// Line 2 Drawing UIBezierPath line2Path = new UIBezierPath(); line2Path.MoveTo(new CGPoint(61.5f, 381.83f)); line2Path.AddLineTo(new CGPoint(61.5f, 389.55f)); line2Path.MiterLimit = 4.0f; line2Path.LineCapStyle = CGLineCap.Square; line2Path.UsesEvenOddFillRule = true; strokeColor3.SetStroke(); line2Path.LineWidth = 4.0f; line2Path.Stroke(); //// Line 3 Drawing UIBezierPath line3Path = new UIBezierPath(); line3Path.MoveTo(new CGPoint(49.88f, 390.6f)); line3Path.AddLineTo(new CGPoint(72.46f, 390.6f)); line3Path.MiterLimit = 4.0f; line3Path.LineCapStyle = CGLineCap.Square; line3Path.UsesEvenOddFillRule = true; strokeColor3.SetStroke(); line3Path.LineWidth = 4.0f; line3Path.Stroke(); } } //// Play/Pause-Button { //// Oval-1-Copy-3 Drawing var oval1Copy3Path = UIBezierPath.FromOval(new CGRect(18.0f, 428.0f, 87.0f, 87.0f)); playPausePressed.SetFill(); oval1Copy3Path.Fill(); //// Path-5-+-Line-+-Line-Copy { //// Path-5 Drawing UIBezierPath path5Path = new UIBezierPath(); path5Path.MoveTo(new CGPoint(40.98f, 457.24f)); path5Path.AddLineTo(new CGPoint(40.98f, 485.25f)); path5Path.AddLineTo(new CGPoint(59.77f, 471.25f)); path5Path.AddLineTo(new CGPoint(40.98f, 457.24f)); path5Path.ClosePath(); path5Path.MiterLimit = 4.0f; path5Path.UsesEvenOddFillRule = true; fillColor2.SetFill(); path5Path.Fill(); //// Line 4 Drawing UIBezierPath line4Path = new UIBezierPath(); line4Path.MoveTo(new CGPoint(69.18f, 457.72f)); line4Path.AddLineTo(new CGPoint(69.18f, 484.8f)); line4Path.MiterLimit = 4.0f; line4Path.LineCapStyle = CGLineCap.Square; line4Path.UsesEvenOddFillRule = true; strokeColor3.SetStroke(); line4Path.LineWidth = 4.0f; line4Path.Stroke(); //// Line-Copy Drawing UIBezierPath lineCopyPath = new UIBezierPath(); lineCopyPath.MoveTo(new CGPoint(79.61f, 457.72f)); lineCopyPath.AddLineTo(new CGPoint(79.61f, 484.8f)); lineCopyPath.MiterLimit = 4.0f; lineCopyPath.LineCapStyle = CGLineCap.Square; lineCopyPath.UsesEvenOddFillRule = true; strokeColor3.SetStroke(); lineCopyPath.LineWidth = 4.0f; lineCopyPath.Stroke(); } } //// Rectangle- 12 Drawing var rectangle12Path = UIBezierPath.FromRoundedRect(new CGRect(110.0f, 13.0f, 34.0f, 13.0f), 6.5f); fillColor.SetFill(); rectangle12Path.Fill(); strokeColor.SetStroke(); rectangle12Path.LineWidth = 1.0f; rectangle12Path.Stroke(); } } } } } }
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { partial class VetLabReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VetLabReport)); DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary(); DevExpress.XtraReports.UI.XRSummary xrSummary2 = new DevExpress.XtraReports.UI.XRSummary(); DevExpress.XtraReports.UI.XRSummary xrSummary3 = new DevExpress.XtraReports.UI.XRSummary(); this.VetReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.SignatureTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.DateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.FooterDataTable = new DevExpress.XtraReports.UI.XRTable(); this.FooterDataRow = new DevExpress.XtraReports.UI.XRTableRow(); this.FooterTotalCell = new DevExpress.XtraReports.UI.XRTableCell(); this.AmountOfSpecimenTotalCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestCountTotalCell_1 = new DevExpress.XtraReports.UI.XRTableCell(); this.PositiveResultsTotalCell = new DevExpress.XtraReports.UI.XRTableCell(); this.VetDetail = new DevExpress.XtraReports.UI.DetailBand(); this.DetailsDataTable = new DevExpress.XtraReports.UI.XRTable(); this.DetailsDataRow = new DevExpress.XtraReports.UI.XRTableRow(); this.RowNumberCell = new DevExpress.XtraReports.UI.XRTableCell(); this.DiseaseCell = new DevExpress.XtraReports.UI.XRTableCell(); this.OIECell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpeciesCell = new DevExpress.XtraReports.UI.XRTableCell(); this.AmountOfSpecimenCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestCountCell_1 = new DevExpress.XtraReports.UI.XRTableCell(); this.PositiveResultsCell = new DevExpress.XtraReports.UI.XRTableCell(); this.VetReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderDataTable = new DevExpress.XtraReports.UI.XRTable(); this.HeaderDataRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.UnderRowNumberHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderDiseaseHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderOIEHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderSpeciesHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderAmountOfSpecimenHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestsConductedHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderPositiveResultsHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderDataRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.RowNumberHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.DiseaseHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.OIEHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpeciesHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.AmountOfSpecimenHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestNameHeaderCell_1 = new DevExpress.XtraReports.UI.XRTableCell(); this.PositiveResultsHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.RecipientHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.SentByCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.ForDateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrPictureBox1 = new DevExpress.XtraReports.UI.XRPictureBox(); this.GroupHeaderDiagnosis = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.GroupFooterDiagnosis = new DevExpress.XtraReports.UI.GroupFooterBand(); this.GroupHeaderLine = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.xrLine2 = new DevExpress.XtraReports.UI.XRLine(); this.GroupFooterLine = new DevExpress.XtraReports.UI.GroupFooterBand(); this.xrLine1 = new DevExpress.XtraReports.UI.XRLine(); this.m_DataAdapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetLabReportDataSetTableAdapters.VetLabAdapter(); this.m_DataSet = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetLabReportDataSet(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.FooterDataTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.DetailsDataTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderDataTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; resources.ApplyResources(this.Detail, "Detail"); // // PageHeader // this.PageHeader.Expanded = false; resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Expanded = false; resources.ApplyResources(this.ReportHeader, "ReportHeader"); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; this.xrPageInfo1.StylePriority.UseFont = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); // // cellBaseCountry // resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // VetReport // this.VetReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.ReportFooter, this.VetDetail, this.VetReportHeader, this.GroupHeaderDiagnosis, this.GroupFooterDiagnosis, this.GroupHeaderLine, this.GroupFooterLine}); this.VetReport.DataAdapter = this.m_DataAdapter; this.VetReport.DataMember = "spRepVetLabReportAZ"; this.VetReport.DataSource = this.m_DataSet; this.VetReport.Level = 0; this.VetReport.Name = "VetReport"; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.SignatureTable, this.FooterDataTable}); resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; this.ReportFooter.StylePriority.UseFont = false; // // SignatureTable // resources.ApplyResources(this.SignatureTable, "SignatureTable"); this.SignatureTable.Name = "SignatureTable"; this.SignatureTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow12, this.xrTableRow13}); this.SignatureTable.StylePriority.UseFont = false; this.SignatureTable.StylePriority.UseTextAlignment = false; // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1}); this.xrTableRow12.Name = "xrTableRow12"; resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell2, this.DateCell, this.xrTableCell17, this.xrTableCell19}); this.xrTableRow13.Name = "xrTableRow13"; resources.ApplyResources(this.xrTableRow13, "xrTableRow13"); // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); // // DateCell // resources.ApplyResources(this.DateCell, "DateCell"); this.DateCell.Name = "DateCell"; this.DateCell.StylePriority.UseFont = false; // // xrTableCell17 // this.xrTableCell17.Name = "xrTableCell17"; resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); // // xrTableCell19 // this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strUserOrganization")}); resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.StylePriority.UseFont = false; // // FooterDataTable // this.FooterDataTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.FooterDataTable, "FooterDataTable"); this.FooterDataTable.Name = "FooterDataTable"; this.FooterDataTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.FooterDataRow}); this.FooterDataTable.StylePriority.UseBorders = false; this.FooterDataTable.StylePriority.UseTextAlignment = false; // // FooterDataRow // this.FooterDataRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.FooterTotalCell, this.AmountOfSpecimenTotalCell, this.TestCountTotalCell_1, this.PositiveResultsTotalCell}); this.FooterDataRow.Name = "FooterDataRow"; resources.ApplyResources(this.FooterDataRow, "FooterDataRow"); // // FooterTotalCell // this.FooterTotalCell.Name = "FooterTotalCell"; resources.ApplyResources(this.FooterTotalCell, "FooterTotalCell"); // // AmountOfSpecimenTotalCell // this.AmountOfSpecimenTotalCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.AmountOfSpecimenTaken")}); this.AmountOfSpecimenTotalCell.Name = "AmountOfSpecimenTotalCell"; xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.AmountOfSpecimenTotalCell.Summary = xrSummary1; resources.ApplyResources(this.AmountOfSpecimenTotalCell, "AmountOfSpecimenTotalCell"); // // TestCountTotalCell_1 // this.TestCountTotalCell_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.intTest_1")}); this.TestCountTotalCell_1.Name = "TestCountTotalCell_1"; xrSummary2.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.TestCountTotalCell_1.Summary = xrSummary2; resources.ApplyResources(this.TestCountTotalCell_1, "TestCountTotalCell_1"); // // PositiveResultsTotalCell // this.PositiveResultsTotalCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.PositiveResults")}); this.PositiveResultsTotalCell.Name = "PositiveResultsTotalCell"; xrSummary3.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.PositiveResultsTotalCell.Summary = xrSummary3; resources.ApplyResources(this.PositiveResultsTotalCell, "PositiveResultsTotalCell"); // // VetDetail // this.VetDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.DetailsDataTable}); resources.ApplyResources(this.VetDetail, "VetDetail"); this.VetDetail.KeepTogether = true; this.VetDetail.Name = "VetDetail"; this.VetDetail.StylePriority.UseFont = false; // // DetailsDataTable // this.DetailsDataTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.DetailsDataTable, "DetailsDataTable"); this.DetailsDataTable.Name = "DetailsDataTable"; this.DetailsDataTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.DetailsDataRow}); this.DetailsDataTable.StylePriority.UseBorders = false; this.DetailsDataTable.StylePriority.UseTextAlignment = false; // // DetailsDataRow // this.DetailsDataRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.RowNumberCell, this.DiseaseCell, this.OIECell, this.SpeciesCell, this.AmountOfSpecimenCell, this.TestCountCell_1, this.PositiveResultsCell}); this.DetailsDataRow.Name = "DetailsDataRow"; resources.ApplyResources(this.DetailsDataRow, "DetailsDataRow"); // // RowNumberCell // this.RowNumberCell.Name = "RowNumberCell"; resources.ApplyResources(this.RowNumberCell, "RowNumberCell"); this.RowNumberCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.RowNumberCell_BeforePrint); // // DiseaseCell // this.DiseaseCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strDiagnosisName")}); this.DiseaseCell.Name = "DiseaseCell"; resources.ApplyResources(this.DiseaseCell, "DiseaseCell"); // // OIECell // this.OIECell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strOIECode")}); this.OIECell.Name = "OIECell"; resources.ApplyResources(this.OIECell, "OIECell"); // // SpeciesCell // this.SpeciesCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strSpecies")}); this.SpeciesCell.Name = "SpeciesCell"; resources.ApplyResources(this.SpeciesCell, "SpeciesCell"); // // AmountOfSpecimenCell // this.AmountOfSpecimenCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.AmountOfSpecimenTaken")}); this.AmountOfSpecimenCell.Name = "AmountOfSpecimenCell"; resources.ApplyResources(this.AmountOfSpecimenCell, "AmountOfSpecimenCell"); // // TestCountCell_1 // this.TestCountCell_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.intTest_1")}); this.TestCountCell_1.Name = "TestCountCell_1"; resources.ApplyResources(this.TestCountCell_1, "TestCountCell_1"); // // PositiveResultsCell // this.PositiveResultsCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.PositiveResults")}); this.PositiveResultsCell.Name = "PositiveResultsCell"; resources.ApplyResources(this.PositiveResultsCell, "PositiveResultsCell"); // // VetReportHeader // this.VetReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1, this.HeaderDataTable, this.HeaderTable, this.xrPictureBox1}); resources.ApplyResources(this.VetReportHeader, "VetReportHeader"); this.VetReportHeader.Name = "VetReportHeader"; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow4, this.xrTableRow6, this.xrTableRow7, this.xrTableRow8, this.xrTableRow9}); this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UsePadding = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell8}); this.xrTableRow4.Name = "xrTableRow4"; resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); // // xrTableCell8 // resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Multiline = true; this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseFont = false; // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell10}); this.xrTableRow6.Name = "xrTableRow6"; resources.ApplyResources(this.xrTableRow6, "xrTableRow6"); // // xrTableCell10 // this.xrTableCell10.Multiline = true; this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell13, this.xrTableCell12}); this.xrTableRow7.Name = "xrTableRow7"; resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); // // xrTableCell13 // resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.StylePriority.UseFont = false; // // xrTableCell12 // resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.StylePriority.UseFont = false; // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell18}); this.xrTableRow8.Name = "xrTableRow8"; resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); // // xrTableCell18 // this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell20}); this.xrTableRow9.Name = "xrTableRow9"; resources.ApplyResources(this.xrTableRow9, "xrTableRow9"); // // xrTableCell20 // this.xrTableCell20.Multiline = true; this.xrTableCell20.Name = "xrTableCell20"; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // HeaderDataTable // this.HeaderDataTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.HeaderDataTable, "HeaderDataTable"); this.HeaderDataTable.Name = "HeaderDataTable"; this.HeaderDataTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.HeaderDataRow1, this.HeaderDataRow2}); this.HeaderDataTable.StylePriority.UseBorders = false; this.HeaderDataTable.StylePriority.UseFont = false; this.HeaderDataTable.StylePriority.UseTextAlignment = false; // // HeaderDataRow1 // this.HeaderDataRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.UnderRowNumberHeaderCell, this.UnderDiseaseHeaderCell, this.UnderOIEHeaderCell, this.UnderSpeciesHeaderCell, this.UnderAmountOfSpecimenHeaderCell, this.TestsConductedHeaderCell, this.UnderPositiveResultsHeaderCell}); this.HeaderDataRow1.Name = "HeaderDataRow1"; resources.ApplyResources(this.HeaderDataRow1, "HeaderDataRow1"); // // UnderRowNumberHeaderCell // this.UnderRowNumberHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.UnderRowNumberHeaderCell.Name = "UnderRowNumberHeaderCell"; this.UnderRowNumberHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.UnderRowNumberHeaderCell, "UnderRowNumberHeaderCell"); // // UnderDiseaseHeaderCell // this.UnderDiseaseHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.UnderDiseaseHeaderCell.Name = "UnderDiseaseHeaderCell"; this.UnderDiseaseHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.UnderDiseaseHeaderCell, "UnderDiseaseHeaderCell"); // // UnderOIEHeaderCell // this.UnderOIEHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.UnderOIEHeaderCell.Name = "UnderOIEHeaderCell"; this.UnderOIEHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.UnderOIEHeaderCell, "UnderOIEHeaderCell"); // // UnderSpeciesHeaderCell // this.UnderSpeciesHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.UnderSpeciesHeaderCell.Name = "UnderSpeciesHeaderCell"; this.UnderSpeciesHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.UnderSpeciesHeaderCell, "UnderSpeciesHeaderCell"); // // UnderAmountOfSpecimenHeaderCell // this.UnderAmountOfSpecimenHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.UnderAmountOfSpecimenHeaderCell.Name = "UnderAmountOfSpecimenHeaderCell"; this.UnderAmountOfSpecimenHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.UnderAmountOfSpecimenHeaderCell, "UnderAmountOfSpecimenHeaderCell"); // // TestsConductedHeaderCell // this.TestsConductedHeaderCell.Name = "TestsConductedHeaderCell"; resources.ApplyResources(this.TestsConductedHeaderCell, "TestsConductedHeaderCell"); // // UnderPositiveResultsHeaderCell // this.UnderPositiveResultsHeaderCell.Name = "UnderPositiveResultsHeaderCell"; resources.ApplyResources(this.UnderPositiveResultsHeaderCell, "UnderPositiveResultsHeaderCell"); // // HeaderDataRow2 // this.HeaderDataRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.RowNumberHeaderCell, this.DiseaseHeaderCell, this.OIEHeaderCell, this.SpeciesHeaderCell, this.AmountOfSpecimenHeaderCell, this.TestNameHeaderCell_1, this.PositiveResultsHeaderCell}); this.HeaderDataRow2.Name = "HeaderDataRow2"; resources.ApplyResources(this.HeaderDataRow2, "HeaderDataRow2"); // // RowNumberHeaderCell // this.RowNumberHeaderCell.Angle = 90F; this.RowNumberHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); this.RowNumberHeaderCell.Name = "RowNumberHeaderCell"; this.RowNumberHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.RowNumberHeaderCell, "RowNumberHeaderCell"); // // DiseaseHeaderCell // this.DiseaseHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); this.DiseaseHeaderCell.Name = "DiseaseHeaderCell"; this.DiseaseHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.DiseaseHeaderCell, "DiseaseHeaderCell"); // // OIEHeaderCell // this.OIEHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); this.OIEHeaderCell.Name = "OIEHeaderCell"; this.OIEHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.OIEHeaderCell, "OIEHeaderCell"); // // SpeciesHeaderCell // this.SpeciesHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); this.SpeciesHeaderCell.Name = "SpeciesHeaderCell"; this.SpeciesHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.SpeciesHeaderCell, "SpeciesHeaderCell"); // // AmountOfSpecimenHeaderCell // this.AmountOfSpecimenHeaderCell.Angle = 90F; this.AmountOfSpecimenHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); this.AmountOfSpecimenHeaderCell.Name = "AmountOfSpecimenHeaderCell"; this.AmountOfSpecimenHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.AmountOfSpecimenHeaderCell, "AmountOfSpecimenHeaderCell"); // // TestNameHeaderCell_1 // this.TestNameHeaderCell_1.Angle = 90F; this.TestNameHeaderCell_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strTestName_1")}); this.TestNameHeaderCell_1.Name = "TestNameHeaderCell_1"; resources.ApplyResources(this.TestNameHeaderCell_1, "TestNameHeaderCell_1"); // // PositiveResultsHeaderCell // this.PositiveResultsHeaderCell.Angle = 90F; this.PositiveResultsHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); this.PositiveResultsHeaderCell.Name = "PositiveResultsHeaderCell"; this.PositiveResultsHeaderCell.StylePriority.UseBorders = false; resources.ApplyResources(this.PositiveResultsHeaderCell, "PositiveResultsHeaderCell"); // // HeaderTable // resources.ApplyResources(this.HeaderTable, "HeaderTable"); this.HeaderTable.Name = "HeaderTable"; this.HeaderTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow5, this.xrTableRow3, this.xrTableRow2, this.xrTableRow1}); this.HeaderTable.StylePriority.UseFont = false; this.HeaderTable.StylePriority.UsePadding = false; this.HeaderTable.StylePriority.UseTextAlignment = false; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell4, this.RecipientHeaderCell, this.xrTableCell7}); this.xrTableRow5.Name = "xrTableRow5"; resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); // // xrTableCell4 // this.xrTableCell4.Name = "xrTableCell4"; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // RecipientHeaderCell // this.RecipientHeaderCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.RecipientHeaderCell, "RecipientHeaderCell"); this.RecipientHeaderCell.Name = "RecipientHeaderCell"; this.RecipientHeaderCell.StylePriority.UseBorders = false; this.RecipientHeaderCell.StylePriority.UseFont = false; // // xrTableCell7 // this.xrTableCell7.Name = "xrTableCell7"; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.SentByCell, this.xrTableCell9}); this.xrTableRow3.Name = "xrTableRow3"; resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // SentByCell // this.SentByCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.SentByCell, "SentByCell"); this.SentByCell.Multiline = true; this.SentByCell.Name = "SentByCell"; this.SentByCell.StylePriority.UseBorders = false; this.SentByCell.StylePriority.UseFont = false; // // xrTableCell9 // this.xrTableCell9.Name = "xrTableCell9"; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell6, this.ForDateCell, this.xrTableCell11}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell6 // this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // ForDateCell // this.ForDateCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.ForDateCell, "ForDateCell"); this.ForDateCell.Name = "ForDateCell"; this.ForDateCell.StylePriority.UseBorders = false; this.ForDateCell.StylePriority.UseFont = false; // // xrTableCell11 // this.xrTableCell11.Name = "xrTableCell11"; resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCell}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // HeaderCell // resources.ApplyResources(this.HeaderCell, "HeaderCell"); this.HeaderCell.Name = "HeaderCell"; this.HeaderCell.StylePriority.UseFont = false; this.HeaderCell.StylePriority.UseTextAlignment = false; // // xrPictureBox1 // this.xrPictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("xrPictureBox1.Image"))); resources.ApplyResources(this.xrPictureBox1, "xrPictureBox1"); this.xrPictureBox1.Name = "xrPictureBox1"; this.xrPictureBox1.Sizing = DevExpress.XtraPrinting.ImageSizeMode.ZoomImage; // // GroupHeaderDiagnosis // this.GroupHeaderDiagnosis.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] { new DevExpress.XtraReports.UI.GroupField("DiagniosisOrder", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending), new DevExpress.XtraReports.UI.GroupField("strDiagnosisName", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)}); resources.ApplyResources(this.GroupHeaderDiagnosis, "GroupHeaderDiagnosis"); this.GroupHeaderDiagnosis.Name = "GroupHeaderDiagnosis"; // // GroupFooterDiagnosis // resources.ApplyResources(this.GroupFooterDiagnosis, "GroupFooterDiagnosis"); this.GroupFooterDiagnosis.Name = "GroupFooterDiagnosis"; this.GroupFooterDiagnosis.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.GroupFooterDiagnosis_BeforePrint); // // GroupHeaderLine // this.GroupHeaderLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLine2}); resources.ApplyResources(this.GroupHeaderLine, "GroupHeaderLine"); this.GroupHeaderLine.Level = 1; this.GroupHeaderLine.Name = "GroupHeaderLine"; this.GroupHeaderLine.RepeatEveryPage = true; this.GroupHeaderLine.StylePriority.UseTextAlignment = false; // // xrLine2 // this.xrLine2.BorderWidth = 0F; this.xrLine2.LineWidth = 0; resources.ApplyResources(this.xrLine2, "xrLine2"); this.xrLine2.Name = "xrLine2"; this.xrLine2.StylePriority.UseBorderWidth = false; // // GroupFooterLine // this.GroupFooterLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLine1}); resources.ApplyResources(this.GroupFooterLine, "GroupFooterLine"); this.GroupFooterLine.Level = 1; this.GroupFooterLine.Name = "GroupFooterLine"; this.GroupFooterLine.RepeatEveryPage = true; // // xrLine1 // this.xrLine1.BorderWidth = 0F; this.xrLine1.LineWidth = 0; resources.ApplyResources(this.xrLine1, "xrLine1"); this.xrLine1.Name = "xrLine1"; this.xrLine1.StylePriority.UseBorderWidth = false; // // m_DataAdapter // this.m_DataAdapter.ClearBeforeFill = true; // // m_DataSet // this.m_DataSet.DataSetName = "VetLabReportDataSet"; this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // VetLabReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.VetReport}); resources.ApplyResources(this, "$this"); this.Version = "14.1"; this.Controls.SetChildIndex(this.VetReport, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.FooterDataTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.DetailsDataTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderDataTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand VetReport; private DevExpress.XtraReports.UI.DetailBand VetDetail; private DevExpress.XtraReports.UI.ReportHeaderBand VetReportHeader; private DevExpress.XtraReports.UI.XRTable HeaderTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell HeaderCell; private DevExpress.XtraReports.UI.XRTable HeaderDataTable; private DevExpress.XtraReports.UI.XRTableRow HeaderDataRow2; private DevExpress.XtraReports.UI.XRTableCell RowNumberHeaderCell; private DevExpress.XtraReports.UI.XRTableCell DiseaseHeaderCell; private DevExpress.XtraReports.UI.XRTableCell OIEHeaderCell; private DevExpress.XtraReports.UI.XRTableCell SpeciesHeaderCell; private DevExpress.XtraReports.UI.XRTableCell PositiveResultsHeaderCell; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderDiagnosis; private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterDiagnosis; private DevExpress.XtraReports.UI.XRLine xrLine1; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderLine; private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterLine; private DevExpress.XtraReports.UI.XRTable DetailsDataTable; private DevExpress.XtraReports.UI.XRTableRow DetailsDataRow; private DevExpress.XtraReports.UI.XRTableCell RowNumberCell; private DevExpress.XtraReports.UI.XRTableCell DiseaseCell; private DevExpress.XtraReports.UI.XRTableCell OIECell; private DevExpress.XtraReports.UI.XRTableCell SpeciesCell; private DevExpress.XtraReports.UI.XRTableCell PositiveResultsCell; private DataSets.VetLabReportDataSet m_DataSet; private DataSets.VetLabReportDataSetTableAdapters.VetLabAdapter m_DataAdapter; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRLine xrLine2; private DevExpress.XtraReports.UI.XRTableRow HeaderDataRow1; private DevExpress.XtraReports.UI.XRTableCell UnderRowNumberHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderDiseaseHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderOIEHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderSpeciesHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderAmountOfSpecimenHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderPositiveResultsHeaderCell; private DevExpress.XtraReports.UI.XRTableCell AmountOfSpecimenHeaderCell; private DevExpress.XtraReports.UI.XRTableCell TestsConductedHeaderCell; private DevExpress.XtraReports.UI.XRTableCell TestNameHeaderCell_1; private DevExpress.XtraReports.UI.XRTableCell AmountOfSpecimenCell; private DevExpress.XtraReports.UI.XRTableCell TestCountCell_1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell RecipientHeaderCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell SentByCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell ForDateCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRPictureBox xrPictureBox1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTable FooterDataTable; private DevExpress.XtraReports.UI.XRTableRow FooterDataRow; private DevExpress.XtraReports.UI.XRTableCell FooterTotalCell; private DevExpress.XtraReports.UI.XRTableCell AmountOfSpecimenTotalCell; private DevExpress.XtraReports.UI.XRTableCell TestCountTotalCell_1; private DevExpress.XtraReports.UI.XRTableCell PositiveResultsTotalCell; private DevExpress.XtraReports.UI.XRTable SignatureTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell DateCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Reactive.Subjects; using Avalonia.Data; using Avalonia.Logging; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Base.UnitTests { public class AvaloniaObjectTests_Direct { [Fact] public void GetValue_Gets_Value() { var target = new Class1(); Assert.Equal("initial", target.GetValue(Class1.FooProperty)); } [Fact] public void GetValue_Gets_Value_NonGeneric() { var target = new Class1(); Assert.Equal("initial", target.GetValue((AvaloniaProperty)Class1.FooProperty)); } [Fact] public void GetValue_On_Unregistered_Property_Throws_Exception() { var target = new Class2(); Assert.Throws<ArgumentException>(() => target.GetValue(Class1.BarProperty)); } [Fact] public void SetValue_Sets_Value() { var target = new Class1(); target.SetValue(Class1.FooProperty, "newvalue"); Assert.Equal("newvalue", target.Foo); } [Fact] public void SetValue_Sets_Value_NonGeneric() { var target = new Class1(); target.SetValue((AvaloniaProperty)Class1.FooProperty, "newvalue"); Assert.Equal("newvalue", target.Foo); } [Fact] public void SetValue_NonGeneric_Coerces_UnsetValue_To_Default_Value() { var target = new Class1(); target.SetValue((AvaloniaProperty)Class1.BazProperty, AvaloniaProperty.UnsetValue); Assert.Equal(-1, target.Baz); } [Fact] public void SetValue_Raises_PropertyChanged() { var target = new Class1(); bool raised = false; target.PropertyChanged += (s, e) => raised = e.Property == Class1.FooProperty && (string)e.OldValue == "initial" && (string)e.NewValue == "newvalue" && e.Priority == BindingPriority.LocalValue; target.SetValue(Class1.FooProperty, "newvalue"); Assert.True(raised); } [Fact] public void SetValue_Raises_Changed() { var target = new Class1(); bool raised = false; Class1.FooProperty.Changed.Subscribe(e => raised = e.Property == Class1.FooProperty && (string)e.OldValue == "initial" && (string)e.NewValue == "newvalue" && e.Priority == BindingPriority.LocalValue); target.SetValue(Class1.FooProperty, "newvalue"); Assert.True(raised); } [Fact] public void SetValue_On_Unregistered_Property_Throws_Exception() { var target = new Class2(); Assert.Throws<ArgumentException>(() => target.SetValue(Class1.BarProperty, "value")); } [Fact] public void GetObservable_Returns_Values() { var target = new Class1(); List<string> values = new List<string>(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); target.Foo = "newvalue"; Assert.Equal(new[] { "initial", "newvalue" }, values); } [Fact] public void Bind_Binds_Property_Value() { var target = new Class1(); var source = new Subject<string>(); var sub = target.Bind(Class1.FooProperty, source); Assert.Equal("initial", target.Foo); source.OnNext("first"); Assert.Equal("first", target.Foo); source.OnNext("second"); Assert.Equal("second", target.Foo); sub.Dispose(); source.OnNext("third"); Assert.Equal("second", target.Foo); } [Fact] public void Bind_Binds_Property_Value_NonGeneric() { var target = new Class1(); var source = new Subject<string>(); var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source); Assert.Equal("initial", target.Foo); source.OnNext("first"); Assert.Equal("first", target.Foo); source.OnNext("second"); Assert.Equal("second", target.Foo); sub.Dispose(); source.OnNext("third"); Assert.Equal("second", target.Foo); } [Fact] public void Bind_NonGeneric_Uses_UnsetValue() { var target = new Class1(); var source = new Subject<object>(); var sub = target.Bind((AvaloniaProperty)Class1.BazProperty, source); Assert.Equal(5, target.Baz); source.OnNext(6); Assert.Equal(6, target.Baz); source.OnNext(AvaloniaProperty.UnsetValue); Assert.Equal(-1, target.Baz); } [Fact] public void Bind_Handles_Wrong_Type() { var target = new Class1(); var source = new Subject<object>(); var sub = target.Bind(Class1.FooProperty, source); source.OnNext(45); Assert.Equal(null, target.Foo); } [Fact] public void Bind_Handles_Wrong_Value_Type() { var target = new Class1(); var source = new Subject<object>(); var sub = target.Bind(Class1.BazProperty, source); source.OnNext("foo"); Assert.Equal(0, target.Baz); } [Fact] public void ReadOnly_Property_Cannot_Be_Set() { var target = new Class1(); Assert.Throws<ArgumentException>(() => target.SetValue(Class1.BarProperty, "newvalue")); } [Fact] public void ReadOnly_Property_Cannot_Be_Set_NonGeneric() { var target = new Class1(); Assert.Throws<ArgumentException>(() => target.SetValue((AvaloniaProperty)Class1.BarProperty, "newvalue")); } [Fact] public void ReadOnly_Property_Cannot_Be_Bound() { var target = new Class1(); var source = new Subject<string>(); Assert.Throws<ArgumentException>(() => target.Bind(Class1.BarProperty, source)); } [Fact] public void ReadOnly_Property_Cannot_Be_Bound_NonGeneric() { var target = new Class1(); var source = new Subject<string>(); Assert.Throws<ArgumentException>(() => target.Bind(Class1.BarProperty, source)); } [Fact] public void GetValue_Gets_Value_On_AddOwnered_Property() { var target = new Class2(); Assert.Equal("initial2", target.GetValue(Class2.FooProperty)); } [Fact] public void GetValue_Gets_Value_On_AddOwnered_Property_Using_Original() { var target = new Class2(); Assert.Equal("initial2", target.GetValue(Class1.FooProperty)); } [Fact] public void GetValue_Gets_Value_On_AddOwnered_Property_Using_Original_NonGeneric() { var target = new Class2(); Assert.Equal("initial2", target.GetValue((AvaloniaProperty)Class1.FooProperty)); } [Fact] public void SetValue_Sets_Value_On_AddOwnered_Property_Using_Original() { var target = new Class2(); target.SetValue(Class1.FooProperty, "newvalue"); Assert.Equal("newvalue", target.Foo); } [Fact] public void SetValue_Sets_Value_On_AddOwnered_Property_Using_Original_NonGeneric() { var target = new Class2(); target.SetValue((AvaloniaProperty)Class1.FooProperty, "newvalue"); Assert.Equal("newvalue", target.Foo); } [Fact] public void UnsetValue_Is_Used_On_AddOwnered_Property() { var target = new Class2(); target.SetValue((AvaloniaProperty)Class1.FooProperty, AvaloniaProperty.UnsetValue); Assert.Equal("unset", target.Foo); } [Fact] public void Bind_Binds_AddOwnered_Property_Value() { var target = new Class2(); var source = new Subject<string>(); var sub = target.Bind(Class1.FooProperty, source); Assert.Equal("initial2", target.Foo); source.OnNext("first"); Assert.Equal("first", target.Foo); source.OnNext("second"); Assert.Equal("second", target.Foo); sub.Dispose(); source.OnNext("third"); Assert.Equal("second", target.Foo); } [Fact] public void Bind_Binds_AddOwnered_Property_Value_NonGeneric() { var target = new Class2(); var source = new Subject<string>(); var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source); Assert.Equal("initial2", target.Foo); source.OnNext("first"); Assert.Equal("first", target.Foo); source.OnNext("second"); Assert.Equal("second", target.Foo); sub.Dispose(); source.OnNext("third"); Assert.Equal("second", target.Foo); } [Fact] public void Binding_To_Direct_Property_Does_Not_Get_Collected() { var target = new Class2(); Func<WeakReference> setupBinding = () => { var source = new Subject<string>(); var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source); source.OnNext("foo"); return new WeakReference(source); }; var weakSource = setupBinding(); GC.Collect(); Assert.Equal("foo", target.Foo); Assert.True(weakSource.IsAlive); } [Fact] public void Binding_To_Direct_Property_Gets_Collected_When_Completed() { var target = new Class2(); Func<WeakReference> setupBinding = () => { var source = new Subject<string>(); var sub = target.Bind((AvaloniaProperty)Class1.FooProperty, source); return new WeakReference(source); }; var weakSource = setupBinding(); Action completeSource = () => { ((ISubject<string>)weakSource.Target).OnCompleted(); }; completeSource(); GC.Collect(); Assert.False(weakSource.IsAlive); } [Fact] public void Property_Notifies_Initialized() { Class1 target; bool raised = false; Class1.FooProperty.Initialized.Subscribe(e => raised = e.Property == Class1.FooProperty && e.OldValue == AvaloniaProperty.UnsetValue && (string)e.NewValue == "initial" && e.Priority == BindingPriority.Unset); target = new Class1(); Assert.True(raised); } [Fact] public void BindingError_Does_Not_Cause_Target_Update() { var target = new Class1(); var source = new Subject<object>(); target.Bind(Class1.FooProperty, source); source.OnNext("initial"); source.OnNext(new BindingError(new InvalidOperationException("Foo"))); Assert.Equal("initial", target.GetValue(Class1.FooProperty)); } [Fact] public void BindingError_With_FallbackValue_Causes_Target_Update() { var target = new Class1(); var source = new Subject<object>(); target.Bind(Class1.FooProperty, source); source.OnNext("initial"); source.OnNext(new BindingError(new InvalidOperationException("Foo"), "fallback")); Assert.Equal("fallback", target.GetValue(Class1.FooProperty)); } [Fact] public void Binding_To_Direct_Property_Logs_BindingError() { var target = new Class1(); var source = new Subject<object>(); var called = false; LogCallback checkLogMessage = (level, area, src, mt, pv) => { if (level == LogEventLevel.Error && area == LogArea.Binding && mt == "Error binding to {Target}.{Property}: {Message}" && pv.Length == 3 && pv[0] is Class1 && object.ReferenceEquals(pv[1], Class1.FooProperty) && (string)pv[2] == "Binding Error Message") { called = true; } }; using (TestLogSink.Start(checkLogMessage)) { target.Bind(Class1.FooProperty, source); source.OnNext("baz"); source.OnNext(new BindingError(new InvalidOperationException("Binding Error Message"))); } Assert.True(called); } private class Class1 : AvaloniaObject { public static readonly DirectProperty<Class1, string> FooProperty = AvaloniaProperty.RegisterDirect<Class1, string>( "Foo", o => o.Foo, (o, v) => o.Foo = v, unsetValue: "unset"); public static readonly DirectProperty<Class1, string> BarProperty = AvaloniaProperty.RegisterDirect<Class1, string>("Bar", o => o.Bar); public static readonly DirectProperty<Class1, int> BazProperty = AvaloniaProperty.RegisterDirect<Class1, int>( "Bar", o => o.Baz, (o,v) => o.Baz = v, unsetValue: -1); private string _foo = "initial"; private readonly string _bar = "bar"; private int _baz = 5; public string Foo { get { return _foo; } set { SetAndRaise(FooProperty, ref _foo, value); } } public string Bar { get { return _bar; } } public int Baz { get { return _baz; } set { SetAndRaise(BazProperty, ref _baz, value); } } } private class Class2 : AvaloniaObject { public static readonly DirectProperty<Class2, string> FooProperty = Class1.FooProperty.AddOwner<Class2>(o => o.Foo, (o, v) => o.Foo = v); private string _foo = "initial2"; static Class2() { } public string Foo { get { return _foo; } set { SetAndRaise(FooProperty, ref _foo, value); } } } } }
using System; namespace NBitcoin.Scripting { internal class ScriptToken : IEquatable<ScriptToken> { internal static class Tags { public const int BoolAnd = 0; public const int BoolOr = 1; public const int Add = 2; public const int Equal = 3; public const int EqualVerify = 4; public const int CheckSig = 5; public const int CheckSigVerify = 6; public const int CheckMultiSig = 7; public const int CheckMultiSigVerify = 8; public const int CheckSequenceVerify = 9; public const int FromAltStack = 10; public const int ToAltStack = 11; public const int Drop = 12; public const int Dup = 13; public const int If = 14; public const int IfDup = 15; public const int NotIf = 16; public const int Else = 17; public const int EndIf = 18; public const int ZeroNotEqual = 19; public const int Size = 20; public const int Swap = 21; public const int Verify = 23; public const int Hash160 = 24; public const int Sha256 = 25; public const int Number = 26; public const int Hash160Hash = 27; public const int Sha256Hash = 28; public const int Pk = 29; } private ScriptToken(int tag) => Tag = tag; internal int Tag { get; } internal static readonly ScriptToken _unique_BoolAnd = new ScriptToken(0); internal static ScriptToken BoolAnd { get { return _unique_BoolAnd; } } internal static readonly ScriptToken _unique_BoolOr = new ScriptToken(1); internal static ScriptToken BoolOr { get { return _unique_BoolOr; } } internal static readonly ScriptToken _unique_Add = new ScriptToken(2); internal static ScriptToken Add { get { return _unique_Add; } } internal static readonly ScriptToken _unique_Equal = new ScriptToken(3); internal static ScriptToken Equal { get { return _unique_Equal; } } internal static readonly ScriptToken _unique_EqualVerify = new ScriptToken(4); internal static ScriptToken EqualVerify { get { return _unique_EqualVerify; } } internal static readonly ScriptToken _unique_CheckSig = new ScriptToken(5); internal static ScriptToken CheckSig { get { return _unique_CheckSig; } } internal static readonly ScriptToken _unique_CheckSigVerify = new ScriptToken(6); internal static ScriptToken CheckSigVerify { get { return _unique_CheckSigVerify; } } internal static readonly ScriptToken _unique_CheckMultiSig = new ScriptToken(7); internal static ScriptToken CheckMultiSig { get { return _unique_CheckMultiSig; } } internal static readonly ScriptToken _unique_CheckMultiSigVerify = new ScriptToken(8); internal static ScriptToken CheckMultiSigVerify { get { return _unique_CheckMultiSigVerify; } } internal static readonly ScriptToken _unique_CheckSequenceVerify = new ScriptToken(9); internal static ScriptToken CheckSequenceVerify { get { return _unique_CheckSequenceVerify; } } internal static readonly ScriptToken _unique_FromAltStack = new ScriptToken(10); internal static ScriptToken FromAltStack { get { return _unique_FromAltStack; } } internal static readonly ScriptToken _unique_ToAltStack = new ScriptToken(11); internal static ScriptToken ToAltStack { get { return _unique_ToAltStack; } } internal static readonly ScriptToken _unique_Drop = new ScriptToken(12); internal static ScriptToken Drop { get { return _unique_Drop; } } internal static readonly ScriptToken _unique_Dup = new ScriptToken(13); internal static ScriptToken Dup { get { return _unique_Dup; } } internal static readonly ScriptToken _unique_If = new ScriptToken(14); internal static ScriptToken If { get { return _unique_If; } } internal static readonly ScriptToken _unique_IfDup = new ScriptToken(15); internal static ScriptToken IfDup { get { return _unique_IfDup; } } internal static readonly ScriptToken _unique_NotIf = new ScriptToken(16); internal static ScriptToken NotIf { get { return _unique_NotIf; } } internal static readonly ScriptToken _unique_Else = new ScriptToken(17); internal static ScriptToken Else { get { return _unique_Else; } } internal static readonly ScriptToken _unique_EndIf = new ScriptToken(18); internal static ScriptToken EndIf { get { return _unique_EndIf; } } internal static readonly ScriptToken _unique_ZeroNotEqual = new ScriptToken(19); internal static ScriptToken ZeroNotEqual { get { return _unique_ZeroNotEqual; } } internal static readonly ScriptToken _unique_Size = new ScriptToken(20); internal static ScriptToken Size { get { return _unique_Size; } } internal static readonly ScriptToken _unique_Swap = new ScriptToken(21); internal static ScriptToken Swap { get { return _unique_Swap; } } internal static readonly ScriptToken _unique_Verify = new ScriptToken(23); internal static ScriptToken Verify { get { return _unique_Verify; } } internal static readonly ScriptToken _unique_Hash160 = new ScriptToken(24); internal static ScriptToken Hash160 { get { return _unique_Hash160; } } internal static readonly ScriptToken _unique_Sha256 = new ScriptToken(25); internal static ScriptToken Sha256 { get { return _unique_Sha256; } } internal class Number : ScriptToken { internal uint Item { get; } internal Number(uint item) : base(26) => Item = item; } internal class Hash160Hash : ScriptToken { internal uint160 Item { get; } internal Hash160Hash(uint160 item) : base(27) { Item = item; } } internal class Sha256Hash : ScriptToken { internal uint256 Item { get; } internal Sha256Hash(uint256 item) : base(28) => Item = item; } internal class Pk : ScriptToken { internal PubKey Item { get; } internal Pk(PubKey item) : base(29) => Item = item; } public override string ToString() { switch (this.Tag) { case Tags.BoolAnd: return "BoolAnd"; case Tags.BoolOr: return "BoolAnd"; case Tags.Add: return "Add"; case Tags.Equal: return "Equal"; case Tags.EqualVerify: return "EqualVerify"; case Tags.CheckSig: return "CheckSig"; case Tags.CheckSigVerify: return "CheckSigVerify"; case Tags.CheckMultiSig: return "CheckMultiSig"; case Tags.CheckMultiSigVerify: return "CheckMultiSigVerify"; case Tags.CheckSequenceVerify: return "CheckSequenceVerify"; case Tags.FromAltStack: return "FromAltStack"; case Tags.ToAltStack: return "ToAltStack"; case Tags.Drop: return "Drop"; case Tags.Dup: return "Dup"; case Tags.If: return "If"; case Tags.IfDup: return "IfDup"; case Tags.NotIf: return "NotIf"; case Tags.Else: return "Else"; case Tags.EndIf: return "EndIf"; case Tags.ZeroNotEqual: return "ZeroNotEqual"; case Tags.Size: return "Size"; case Tags.Swap: return "Swap"; case Tags.Verify: return "Verify"; case Tags.Hash160: return "Hash160"; case Tags.Sha256: return "Sha256"; case Tags.Number: var n = ((Number)this).Item; return $"Number({n})"; case Tags.Hash160Hash: var hash160 = ((Hash160Hash)this).Item; return $"Hash160Hash({hash160})"; case Tags.Sha256Hash: var sha256 = ((Sha256Hash)this).Item; return $"Sha256Hash({sha256})"; case Tags.Pk: var pk = ((Pk)this).Item; return $"Pk({pk})"; } throw new Exception("Unreachable"); } public sealed override int GetHashCode() { if (this != null) { int num = 0; switch (Tag) { case 26: { Number number = (Number)this; num = 26; return -1640531527 + ((int)number.Item + ((num << 6) + (num >> 2))); } case 27: { Hash160Hash hash160Hash = (Hash160Hash)this; num = 27; return -1640531527 + (hash160Hash.Item.GetHashCode()) + ((num << 6) + (num >> 2)); } case 28: { Sha256Hash sha256Hash = (Sha256Hash)this; num = 28; return -1640531527 + (sha256Hash.Item.GetHashCode()) + ((num << 6) + (num >> 2)); } case 29: { Pk pk = (Pk)this; num = 29; return -1640531527 + (pk.Item.GetHashCode()) + ((num << 6) + (num >> 2)); } default: return Tag; } } return 0; } public sealed override bool Equals(object obj) { ScriptToken token = obj as ScriptToken; if (token != null) { return Equals(token); } return false; } public bool Equals(ScriptToken obj) { if (this != null) { if (obj != null) { int tag = Tag; int tag2 = obj.Tag; if (tag == tag2) { switch (Tag) { case 26: { Number number = (Number)this; Number number2 = (Number)obj; return number.Item == number2.Item; } case 27: { Hash160Hash hash160Hash = (Hash160Hash)this; Hash160Hash hash160Hash2 = (Hash160Hash)obj; return hash160Hash.Item == hash160Hash2.Item; } case 28: { Sha256Hash sha256Hash = (Sha256Hash)this; Sha256Hash sha256Hash2 = (Sha256Hash)obj; return sha256Hash.Item == sha256Hash2.Item; } case 29: { Pk pk = (Pk)this; Pk pk2 = (Pk)obj; return pk.Item == pk2.Item; } default: return true; } } return false; } return false; } return obj == null; } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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. // namespace DiscUtils.Fat { using System; using System.Collections.Generic; using System.IO; internal class Directory : IDisposable { private FatFileSystem _fileSystem; private Directory _parent; private long _parentId; private Stream _dirStream; private Dictionary<long, DirectoryEntry> _entries; private List<long> _freeEntries; private long _endOfEntries; private DirectoryEntry _selfEntry; private long _selfEntryLocation; private DirectoryEntry _parentEntry; private long _parentEntryLocation; /// <summary> /// Initializes a new instance of the Directory class. Use this constructor to represent non-root directories. /// </summary> /// <param name="parent">The parent directory</param> /// <param name="parentId">The identity of the entry representing this directory in the parent</param> internal Directory(Directory parent, long parentId) { _fileSystem = parent._fileSystem; _parent = parent; _parentId = parentId; DirectoryEntry dirEntry = ParentsChildEntry; _dirStream = new ClusterStream(_fileSystem, FileAccess.ReadWrite, dirEntry.FirstCluster, uint.MaxValue); LoadEntries(); } /// <summary> /// Initializes a new instance of the Directory class. Use this constructor to represent the root directory. /// </summary> /// <param name="fileSystem">The file system</param> /// <param name="dirStream">The stream containing the directory info</param> internal Directory(FatFileSystem fileSystem, Stream dirStream) { _fileSystem = fileSystem; _dirStream = dirStream; LoadEntries(); } public FatFileSystem FileSystem { get { return _fileSystem; } } public bool IsEmpty { get { return _entries.Count == 0; } } public DirectoryEntry[] Entries { get { return new List<DirectoryEntry>(_entries.Values).ToArray(); } } #region Convenient accessors for special entries internal DirectoryEntry ParentsChildEntry { get { if (_parent == null) { return new DirectoryEntry(_fileSystem.FatOptions, FileName.ParentEntryName, FatAttributes.Directory); } else { return _parent.GetEntry(_parentId); } } set { if (_parent != null) { _parent.UpdateEntry(_parentId, value); } } } internal DirectoryEntry SelfEntry { get { if (_parent == null) { // If we're the root directory, simulate the parent entry with a dummy record return new DirectoryEntry(_fileSystem.FatOptions, FileName.Null, FatAttributes.Directory); } else { return _selfEntry; } } set { if (_selfEntryLocation >= 0) { _dirStream.Position = _selfEntryLocation; value.WriteTo(_dirStream); _selfEntry = value; } } } internal DirectoryEntry ParentEntry { get { return _parentEntry; } set { if (_parentEntryLocation < 0) { throw new IOException("No parent entry on disk to update"); } _dirStream.Position = _parentEntryLocation; value.WriteTo(_dirStream); _parentEntry = value; } } #endregion public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public DirectoryEntry[] GetDirectories() { List<DirectoryEntry> dirs = new List<DirectoryEntry>(_entries.Count); foreach (DirectoryEntry dirEntry in _entries.Values) { if ((dirEntry.Attributes & FatAttributes.Directory) != 0) { dirs.Add(dirEntry); } } return dirs.ToArray(); } public DirectoryEntry[] GetFiles() { List<DirectoryEntry> files = new List<DirectoryEntry>(_entries.Count); foreach (DirectoryEntry dirEntry in _entries.Values) { if ((dirEntry.Attributes & (FatAttributes.Directory | FatAttributes.VolumeId)) == 0) { files.Add(dirEntry); } } return files.ToArray(); } public DirectoryEntry GetEntry(long id) { return (id < 0) ? null : _entries[id]; } public Directory GetChildDirectory(FileName name) { long id = FindEntry(name); if (id < 0) { return null; } else if ((_entries[id].Attributes & FatAttributes.Directory) == 0) { return null; } else { return _fileSystem.GetDirectory(this, id); } } internal Directory CreateChildDirectory(FileName name) { long id = FindEntry(name); if (id >= 0) { if ((_entries[id].Attributes & FatAttributes.Directory) == 0) { throw new IOException("A file exists with the same name"); } else { return _fileSystem.GetDirectory(this, id); } } else { try { uint firstCluster; if (!_fileSystem.Fat.TryGetFreeCluster(out firstCluster)) { throw new IOException("Failed to allocate first cluster for new directory"); } _fileSystem.Fat.SetEndOfChain(firstCluster); DirectoryEntry newEntry = new DirectoryEntry(_fileSystem.FatOptions, name, FatAttributes.Directory); newEntry.FirstCluster = firstCluster; newEntry.CreationTime = _fileSystem.ConvertFromUtc(DateTime.UtcNow); newEntry.LastWriteTime = newEntry.CreationTime; id = AddEntry(newEntry); PopulateNewChildDirectory(newEntry); // Rather than just creating a new instance, pull it through the fileSystem cache // to ensure the cache model is preserved. return _fileSystem.GetDirectory(this, id); } finally { _fileSystem.Fat.Flush(); } } } internal void AttachChildDirectory(FileName name, Directory newChild) { long id = FindEntry(name); if (id >= 0) { throw new IOException("Directory entry already exists"); } DirectoryEntry newEntry = new DirectoryEntry(newChild.ParentsChildEntry); newEntry.Name = name; AddEntry(newEntry); DirectoryEntry newParentEntry = new DirectoryEntry(SelfEntry); newParentEntry.Name = FileName.ParentEntryName; newChild.ParentEntry = newParentEntry; } internal long FindVolumeId() { foreach (long id in _entries.Keys) { DirectoryEntry focus = _entries[id]; if ((focus.Attributes & FatAttributes.VolumeId) != 0) { return id; } } return -1; } internal long FindEntry(FileName name) { foreach (long id in _entries.Keys) { DirectoryEntry focus = _entries[id]; if (focus.Name == name && (focus.Attributes & FatAttributes.VolumeId) == 0) { return id; } } return -1; } internal SparseStream OpenFile(FileName name, FileMode mode, FileAccess fileAccess) { if (mode == FileMode.Append || mode == FileMode.Truncate) { throw new NotImplementedException(); } long fileId = FindEntry(name); bool exists = fileId != -1; if (mode == FileMode.CreateNew && exists) { throw new IOException("File already exists"); } else if (mode == FileMode.Open && !exists) { throw new FileNotFoundException("File not found", name.GetDisplayName(_fileSystem.FatOptions.FileNameEncoding)); } else if ((mode == FileMode.Open || mode == FileMode.OpenOrCreate || mode == FileMode.Create) && exists) { SparseStream stream = new FatFileStream(_fileSystem, this, fileId, fileAccess); if (mode == FileMode.Create) { stream.SetLength(0); } HandleAccessed(false); return stream; } else if ((mode == FileMode.OpenOrCreate || mode == FileMode.CreateNew || mode == FileMode.Create) && !exists) { // Create new file DirectoryEntry newEntry = new DirectoryEntry(_fileSystem.FatOptions, name, FatAttributes.Archive); newEntry.FirstCluster = 0; // i.e. Zero-length newEntry.CreationTime = _fileSystem.ConvertFromUtc(DateTime.UtcNow); newEntry.LastWriteTime = newEntry.CreationTime; fileId = AddEntry(newEntry); return new FatFileStream(_fileSystem, this, fileId, fileAccess); } else { // Should never get here... throw new NotImplementedException(); } } internal long AddEntry(DirectoryEntry newEntry) { // Unlink an entry from the free list (or add to the end of the existing directory) long pos; if (_freeEntries.Count > 0) { pos = _freeEntries[0]; _freeEntries.RemoveAt(0); } else { pos = _endOfEntries; _endOfEntries += 32; } // Put the new entry into it's slot _dirStream.Position = pos; newEntry.WriteTo(_dirStream); // Update internal structures to reflect new entry (as if read from disk) _entries.Add(pos, newEntry); HandleAccessed(true); return pos; } internal void DeleteEntry(long id, bool releaseContents) { if (id < 0) { throw new IOException("Attempt to delete unknown directory entry"); } try { DirectoryEntry entry = _entries[id]; DirectoryEntry copy = new DirectoryEntry(entry); copy.Name = entry.Name.Deleted(); _dirStream.Position = id; copy.WriteTo(_dirStream); if (releaseContents) { _fileSystem.Fat.FreeChain(entry.FirstCluster); } _entries.Remove(id); _freeEntries.Add(id); HandleAccessed(true); } finally { _fileSystem.Fat.Flush(); } } internal void UpdateEntry(long id, DirectoryEntry entry) { if (id < 0) { throw new IOException("Attempt to update unknown directory entry"); } _dirStream.Position = id; entry.WriteTo(_dirStream); _entries[id] = entry; } private void LoadEntries() { _entries = new Dictionary<long, DirectoryEntry>(); _freeEntries = new List<long>(); _selfEntryLocation = -1; _parentEntryLocation = -1; while (_dirStream.Position < _dirStream.Length) { long streamPos = _dirStream.Position; DirectoryEntry entry = new DirectoryEntry(_fileSystem.FatOptions, _dirStream); if (entry.Attributes == (FatAttributes.ReadOnly | FatAttributes.Hidden | FatAttributes.System | FatAttributes.VolumeId)) { // Long File Name entry } else if (entry.Name.IsDeleted()) { // E5 = Free Entry _freeEntries.Add(streamPos); } else if (entry.Name == FileName.SelfEntryName) { _selfEntry = entry; _selfEntryLocation = streamPos; } else if (entry.Name == FileName.ParentEntryName) { _parentEntry = entry; _parentEntryLocation = streamPos; } else if (entry.Name.IsEndMarker()) { // Free Entry, no more entries available _endOfEntries = streamPos; break; } else { _entries.Add(streamPos, entry); } } } private void HandleAccessed(bool forWrite) { if (_fileSystem.CanWrite && _parent != null) { DateTime now = DateTime.Now; DirectoryEntry entry = SelfEntry; DateTime oldAccessTime = entry.LastAccessTime; DateTime oldWriteTime = entry.LastWriteTime; entry.LastAccessTime = now; if (forWrite) { entry.LastWriteTime = now; } if (entry.LastAccessTime != oldAccessTime || entry.LastWriteTime != oldWriteTime) { SelfEntry = entry; DirectoryEntry parentEntry = ParentsChildEntry; parentEntry.LastAccessTime = entry.LastAccessTime; parentEntry.LastWriteTime = entry.LastWriteTime; ParentsChildEntry = parentEntry; } } } private void PopulateNewChildDirectory(DirectoryEntry newEntry) { // Populate new directory with initial (special) entries. First one is easy, just change the name! using (ClusterStream stream = new ClusterStream(_fileSystem, FileAccess.Write, newEntry.FirstCluster, uint.MaxValue)) { // First is the self-referencing entry... DirectoryEntry selfEntry = new DirectoryEntry(newEntry); selfEntry.Name = FileName.SelfEntryName; selfEntry.WriteTo(stream); // Second is a clone of our self entry (i.e. parent) - though dates are odd... DirectoryEntry parentEntry = new DirectoryEntry(SelfEntry); parentEntry.Name = FileName.ParentEntryName; parentEntry.CreationTime = newEntry.CreationTime; parentEntry.LastWriteTime = newEntry.LastWriteTime; parentEntry.WriteTo(stream); } } private void Dispose(bool disposing) { if (disposing) { _dirStream.Dispose(); } } } }
using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Square.OkHttp; using Javax.Net.Ssl; using System.Text.RegularExpressions; using Java.IO; using System.Security.Cryptography.X509Certificates; using System.Globalization; using Android.OS; namespace ModernHttpClient { public class NativeMessageHandler : HttpClientHandler { readonly OkHttpClient client = new OkHttpClient(); readonly CacheControl noCacheCacheControl = default(CacheControl); readonly bool throwOnCaptiveNetwork; readonly Dictionary<HttpRequestMessage, WeakReference> registeredProgressCallbacks = new Dictionary<HttpRequestMessage, WeakReference>(); readonly Dictionary<string, string> headerSeparators = new Dictionary<string,string>(){ {"User-Agent", " "} }; public bool DisableCaching { get; set; } public TimeSpan? Timeout { get; set; } public NativeMessageHandler() : this(false, false) {} public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null) { this.throwOnCaptiveNetwork = throwOnCaptiveNetwork; if (customSSLVerification) client.SetHostnameVerifier(new HostnameVerifier()); noCacheCacheControl = (new CacheControl.Builder()).NoCache().Build(); } public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback) { if (callback == null && registeredProgressCallbacks.ContainsKey(request)) { registeredProgressCallbacks.Remove(request); return; } registeredProgressCallbacks[request] = new WeakReference(callback); } ProgressDelegate getAndRemoveCallbackFromRegister(HttpRequestMessage request) { ProgressDelegate emptyDelegate = delegate { }; lock (registeredProgressCallbacks) { if (!registeredProgressCallbacks.ContainsKey(request)) return emptyDelegate; var weakRef = registeredProgressCallbacks[request]; if (weakRef == null) return emptyDelegate; var callback = weakRef.Target as ProgressDelegate; if (callback == null) return emptyDelegate; registeredProgressCallbacks.Remove(request); return callback; } } string getHeaderSeparator(string name) { if (headerSeparators.ContainsKey(name)) { return headerSeparators[name]; } return ","; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (Timeout != null) { var timeout = (long)TimeOut.Value.TotalMilliseconds; client.SetConnectTimeout(timeout, TimeUnit.Milliseconds); client.SetWriteTimeout(timeout, TimeUnit.Milliseconds); client.SetReadTimeout(timeout, TimeUnit.Milliseconds); } var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped); var url = new Java.Net.URL(java_uri); var body = default(RequestBody); if (request.Content != null) { var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var contentType = "text/plain"; if (request.Content.Headers.ContentType != null) { contentType = String.Join(" ", request.Content.Headers.GetValues("Content-Type")); } body = RequestBody.Create(MediaType.Parse(contentType), bytes); } var builder = new Request.Builder() .Method(request.Method.Method.ToUpperInvariant(), body) .Url(url); if (DisableCaching) { builder.CacheControl(noCacheCacheControl); } var keyValuePairs = request.Headers .Union(request.Content != null ? (IEnumerable<KeyValuePair<string, IEnumerable<string>>>)request.Content.Headers : Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>()); foreach (var kvp in keyValuePairs) builder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value)); cancellationToken.ThrowIfCancellationRequested(); var rq = builder.Build(); var call = client.NewCall(rq); // NB: Even closing a socket must be done off the UI thread. Cray! cancellationToken.Register(() => Task.Run(() => call.Cancel())); var resp = default(Response); try { resp = await call.EnqueueAsync().ConfigureAwait(false); var newReq = resp.Request(); var newUri = newReq == null ? null : newReq.Uri(); request.RequestUri = new Uri(newUri.ToString()); if (throwOnCaptiveNetwork && newUri != null) { if (url.Host != newUri.Host) { throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString())); } } } catch (IOException ex) { if (ex.Message.ToLowerInvariant().Contains("canceled")) { throw new OperationCanceledException(); } throw; } var respBody = resp.Body(); cancellationToken.ThrowIfCancellationRequested(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()); ret.RequestMessage = request; ret.ReasonPhrase = resp.Message(); if (respBody != null) { var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None); content.Progress = getAndRemoveCallbackFromRegister(request); ret.Content = content; } else { ret.Content = new ByteArrayContent(new byte[0]); } var respHeaders = resp.Headers(); foreach (var k in respHeaders.Names()) { ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); } return ret; } } public static class AwaitableOkHttp { public static Task<Response> EnqueueAsync(this Call This) { var cb = new OkTaskCallback(); This.Enqueue(cb); return cb.Task; } class OkTaskCallback : Java.Lang.Object, ICallback { readonly TaskCompletionSource<Response> tcs = new TaskCompletionSource<Response>(); public Task<Response> Task { get { return tcs.Task; } } public void OnFailure(Request p0, Java.IO.IOException p1) { // Kind of a hack, but the simplest way to find out that server cert. validation failed if (p1.Message == String.Format("Hostname '{0}' was not verified", p0.Url().Host)) { tcs.TrySetException(new WebException(p1.LocalizedMessage, WebExceptionStatus.TrustFailure)); } else { tcs.TrySetException(p1); } } public void OnResponse(Response p0) { tcs.TrySetResult(p0); } } } class HostnameVerifier : Java.Lang.Object, IHostnameVerifier { static readonly Regex cnRegex = new Regex(@"CN\s*=\s*([^,]*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline); public bool Verify(string hostname, ISSLSession session) { return verifyServerCertificate(hostname, session) & verifyClientCiphers(hostname, session); } /// <summary> /// Verifies the server certificate by calling into ServicePointManager.ServerCertificateValidationCallback or, /// if the is no delegate attached to it by using the default hostname verifier. /// </summary> /// <returns><c>true</c>, if server certificate was verifyed, <c>false</c> otherwise.</returns> /// <param name="hostname"></param> /// <param name="session"></param> static bool verifyServerCertificate(string hostname, ISSLSession session) { var defaultVerifier = HttpsURLConnection.DefaultHostnameVerifier; if (ServicePointManager.ServerCertificateValidationCallback == null) return defaultVerifier.Verify(hostname, session); // Convert java certificates to .NET certificates and build cert chain from root certificate var certificates = session.GetPeerCertificateChain(); var chain = new X509Chain(); X509Certificate2 root = null; var errors = System.Net.Security.SslPolicyErrors.None; // Build certificate chain and check for errors if (certificates == null || certificates.Length == 0) {//no cert at all errors = System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable; goto bail; } if (certificates.Length == 1) {//no root? errors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors; goto bail; } var netCerts = certificates.Select(x => new X509Certificate2(x.GetEncoded())).ToArray(); for (int i = 1; i < netCerts.Length; i++) { chain.ChainPolicy.ExtraStore.Add(netCerts[i]); } root = netCerts[0]; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; if (!chain.Build(root)) { errors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors; goto bail; } var subject = root.Subject; var subjectCn = cnRegex.Match(subject).Groups[1].Value; if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(hostname, subjectCn)) { errors = System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch; goto bail; } bail: // Call the delegate to validate return ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors); } /// <summary> /// Verifies client ciphers and is only available in Mono and Xamarin products. /// </summary> /// <returns><c>true</c>, if client ciphers was verifyed, <c>false</c> otherwise.</returns> /// <param name="hostname"></param> /// <param name="session"></param> static bool verifyClientCiphers(string hostname, ISSLSession session) { var callback = ServicePointManager.ClientCipherSuitesCallback; if (callback == null) return true; var protocol = session.Protocol.StartsWith("SSL", StringComparison.InvariantCulture) ? SecurityProtocolType.Ssl3 : SecurityProtocolType.Tls; var acceptedCiphers = callback(protocol, new[] { session.CipherSuite }); return acceptedCiphers.Contains(session.CipherSuite); } } }
#define LOG_MEMORY_PERF_COUNTERS using Microsoft.Extensions.Logging; using Orleans.Runtime; using System; using System.Diagnostics; using System.Management; using System.Threading; using System.Threading.Tasks; namespace Orleans.Statistics { internal class PerfCounterEnvironmentStatistics : IHostEnvironmentStatistics, ILifecycleParticipant<ISiloLifecycle>, ILifecycleParticipant<IClusterClientLifecycle>, ILifecycleObserver, IDisposable { private readonly ILogger logger; private const float KB = 1024f; private PerformanceCounter cpuCounterPF; private PerformanceCounter availableMemoryCounterPF; #if LOG_MEMORY_PERF_COUNTERS private PerformanceCounter timeInGCPF; private PerformanceCounter[] genSizesPF; private PerformanceCounter allocatedBytesPerSecPF; private PerformanceCounter promotedMemoryFromGen1PF; private PerformanceCounter numberOfInducedGCsPF; private PerformanceCounter largeObjectHeapSizePF; private PerformanceCounter promotedFinalizationMemoryFromGen0PF; #endif private SafeTimer cpuUsageTimer; private readonly TimeSpan CPU_CHECK_PERIOD = TimeSpan.FromSeconds(5); private readonly TimeSpan INITIALIZATION_TIMEOUT = TimeSpan.FromMinutes(1); private bool countersAvailable; public long MemoryUsage { get { return GC.GetTotalMemory(false); } } /// /// <summary>Amount of physical memory on the machine</summary> /// public long? TotalPhysicalMemory { get; private set; } /// /// <summary>Amount of memory available to processes running on the machine</summary> /// public long? AvailableMemory { get { return availableMemoryCounterPF != null ? Convert.ToInt64(availableMemoryCounterPF.NextValue()) : (long?)null; } } public float? CpuUsage { get; private set; } private static string GCGenCollectionCount { get { return String.Format("gen0={0}, gen1={1}, gen2={2}", GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2)); } } #if LOG_MEMORY_PERF_COUNTERS private string GCGenSizes { get { if (genSizesPF == null) return String.Empty; return String.Format("gen0={0:0.00}, gen1={1:0.00}, gen2={2:0.00}", genSizesPF[0].NextValue() / KB, genSizesPF[1].NextValue() / KB, genSizesPF[2].NextValue() / KB); } } #endif public PerfCounterEnvironmentStatistics(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger<PerfCounterEnvironmentStatistics>(); try { Task.Run(() => { InitCpuMemoryCounters(); }).WaitWithThrow(INITIALIZATION_TIMEOUT); } catch (TimeoutException) { logger.Warn(ErrorCode.PerfCounterConnectError, "Timeout occurred during initialization of CPU & Memory perf counters"); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void InitCpuMemoryCounters() { try { cpuCounterPF = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); availableMemoryCounterPF = new PerformanceCounter("Memory", "Available Bytes", true); #if LOG_MEMORY_PERF_COUNTERS string thisProcess = Process.GetCurrentProcess().ProcessName; timeInGCPF = new PerformanceCounter(".NET CLR Memory", "% Time in GC", thisProcess, true); genSizesPF = new PerformanceCounter[] { new PerformanceCounter(".NET CLR Memory", "Gen 0 heap size", thisProcess, true), new PerformanceCounter(".NET CLR Memory", "Gen 1 heap size", thisProcess, true), new PerformanceCounter(".NET CLR Memory", "Gen 2 heap size", thisProcess, true) }; allocatedBytesPerSecPF = new PerformanceCounter(".NET CLR Memory", "Allocated Bytes/sec", thisProcess, true); promotedMemoryFromGen1PF = new PerformanceCounter(".NET CLR Memory", "Promoted Memory from Gen 1", thisProcess, true); numberOfInducedGCsPF = new PerformanceCounter(".NET CLR Memory", "# Induced GC", thisProcess, true); largeObjectHeapSizePF = new PerformanceCounter(".NET CLR Memory", "Large Object Heap size", thisProcess, true); promotedFinalizationMemoryFromGen0PF = new PerformanceCounter(".NET CLR Memory", "Promoted Finalization-Memory from Gen 0", thisProcess, true); #endif //.NET on Windows without mono const string Query = "SELECT Capacity FROM Win32_PhysicalMemory"; var searcher = new ManagementObjectSearcher(Query); long Capacity = 0; foreach (ManagementObject WniPART in searcher.Get()) Capacity += Convert.ToInt64(WniPART.Properties["Capacity"].Value); if (Capacity == 0) throw new Exception("No physical ram installed on machine?"); TotalPhysicalMemory = Capacity; countersAvailable = true; } catch (Exception) { logger.Warn(ErrorCode.PerfCounterConnectError, "Error initializing CPU & Memory perf counters - you need to repair Windows perf counter config on this machine with 'lodctr /r' command"); } } private void CheckCpuUsage(object m) { if (cpuCounterPF != null) { var currentUsage = cpuCounterPF.NextValue(); // We calculate a decaying average for CPU utilization CpuUsage = (CpuUsage + 2 * currentUsage) / 3; } else { CpuUsage = 0; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] public void Dispose() { cpuCounterPF?.Dispose(); availableMemoryCounterPF?.Dispose(); timeInGCPF?.Dispose(); if (genSizesPF != null) foreach (var item in genSizesPF) { item?.Dispose(); } allocatedBytesPerSecPF?.Dispose(); promotedMemoryFromGen1PF?.Dispose(); numberOfInducedGCsPF?.Dispose(); largeObjectHeapSizePF?.Dispose(); promotedFinalizationMemoryFromGen0PF?.Dispose(); cpuUsageTimer?.Dispose(); } public Task OnStart(CancellationToken ct) { if (!countersAvailable) { logger.Warn(ErrorCode.PerfCounterNotRegistered, "CPU & Memory perf counters did not initialize correctly - try repairing Windows perf counter config on this machine with 'lodctr /r' command"); } if (cpuCounterPF != null) { cpuUsageTimer = new SafeTimer(this.logger, CheckCpuUsage, null, CPU_CHECK_PERIOD, CPU_CHECK_PERIOD); } try { if (cpuCounterPF != null) { // Read initial value of CPU Usage counter CpuUsage = cpuCounterPF.NextValue(); } } catch (InvalidOperationException) { // Can sometimes get exception accessing CPU Usage counter for first time in some runtime environments CpuUsage = 0; } FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_CPUUSAGE, () => CpuUsage.Value); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_TOTALMEMORYKB, () => (long)((MemoryUsage + KB - 1.0) / KB)); // Round up #if LOG_MEMORY_PERF_COUNTERS // print GC stats in the silo log file. StringValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_GENCOLLECTIONCOUNT, () => GCGenCollectionCount); StringValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_GENSIZESKB, () => GCGenSizes); if (timeInGCPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PERCENTOFTIMEINGC, () => timeInGCPF.NextValue()); } if (allocatedBytesPerSecPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_ALLOCATEDBYTESINKBPERSEC, () => allocatedBytesPerSecPF.NextValue() / KB); } if (promotedMemoryFromGen1PF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PROMOTEDMEMORYFROMGEN1KB, () => promotedMemoryFromGen1PF.NextValue() / KB); } if (largeObjectHeapSizePF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_LARGEOBJECTHEAPSIZEKB, () => largeObjectHeapSizePF.NextValue() / KB); } if (promotedFinalizationMemoryFromGen0PF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PROMOTEDMEMORYFROMGEN0KB, () => promotedFinalizationMemoryFromGen0PF.NextValue() / KB); } if (numberOfInducedGCsPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_NUMBEROFINDUCEDGCS, () => numberOfInducedGCsPF.NextValue()); } IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_TOTALPHYSICALMEMORYMB, () => (long)((TotalPhysicalMemory / KB) / KB)); if (availableMemoryCounterPF != null) { IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_AVAILABLEMEMORYMB, () => (long)((AvailableMemory / KB) / KB)); // Round up } #endif IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_WORKERTHREADS, () => { int maXworkerThreads; int maXcompletionPortThreads; ThreadPool.GetMaxThreads(out maXworkerThreads, out maXcompletionPortThreads); int workerThreads; int completionPortThreads; // GetAvailableThreads Retrieves the difference between the maximum number of thread pool threads // and the number currently active. // So max-Available is the actual number in use. If it goes beyond min, it means we are stressing the thread pool. ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); return maXworkerThreads - workerThreads; }); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_COMPLETIONPORTTHREADS, () => { int maxWorkerThreads; int maxCompletionPortThreads; ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads); int workerThreads; int completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); return maxCompletionPortThreads - completionPortThreads; }); return Task.CompletedTask; } public Task OnStop(CancellationToken ct) { cpuUsageTimer?.Dispose(); cpuUsageTimer = null; return Task.CompletedTask; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe<PerfCounterEnvironmentStatistics>(ServiceLifecycleStage.RuntimeInitialize, this); } public void Participate(IClusterClientLifecycle lifecycle) { lifecycle.Subscribe(ServiceLifecycleStage.RuntimeInitialize, this); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Threading; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTextures : FrameworkTestScene { [Cached] private TextureStore normalStore; [Cached] private LargeTextureStore largeStore; private BlockingOnlineStore blockingOnlineStore; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { var host = parent.Get<GameHost>(); blockingOnlineStore = new BlockingOnlineStore(); normalStore = new TextureStore(host.CreateTextureLoaderStore(blockingOnlineStore)); largeStore = new LargeTextureStore(host.CreateTextureLoaderStore(blockingOnlineStore)); return base.CreateChildDependencies(parent); } [SetUpSteps] public void SetUpSteps() { AddStep("reset online store", () => blockingOnlineStore.Reset()); // required to drop reference counts and allow fresh lookups to occur on the LargeTextureStore. AddStep("dispose children", () => Clear()); } /// <summary> /// Tests that a ref-counted texture is disposed when all references are lost. /// </summary> [Test] public void TestRefCountTextureDisposal() { Avatar avatar1 = null; Avatar avatar2 = null; Texture texture = null; AddStep("add disposable sprite", () => avatar1 = addSprite("https://a.ppy.sh/3")); AddStep("add disposable sprite", () => avatar2 = addSprite("https://a.ppy.sh/3")); AddUntilStep("wait for texture load", () => avatar1.Texture != null && avatar2.Texture != null); AddAssert("both textures are RefCount", () => avatar1.Texture is TextureWithRefCount && avatar2.Texture is TextureWithRefCount); AddAssert("textures share gl texture", () => avatar1.Texture.TextureGL == avatar2.Texture.TextureGL); AddAssert("textures have different refcount textures", () => avatar1.Texture != avatar2.Texture); AddStep("dispose children", () => { texture = avatar1.Texture; Clear(); avatar1.Dispose(); avatar2.Dispose(); }); assertAvailability(() => texture, false); } /// <summary> /// Tests the case where multiple lookups occur for different textures, which shouldn't block each other. /// </summary> [Test] public void TestFetchContentionDifferentLookup() { Avatar avatar1 = null; Avatar avatar2 = null; AddStep("begin blocking load", () => blockingOnlineStore.StartBlocking("https://a.ppy.sh/3")); AddStep("get first", () => avatar1 = addSprite("https://a.ppy.sh/3")); AddUntilStep("wait for first to begin loading", () => blockingOnlineStore.TotalInitiatedLookups == 1); AddStep("get second", () => avatar2 = addSprite("https://a.ppy.sh/2")); AddUntilStep("wait for avatar2 load", () => avatar2.Texture != null); AddAssert("avatar1 not loaded", () => avatar1.Texture == null); AddAssert("only one lookup occurred", () => blockingOnlineStore.TotalCompletedLookups == 1); AddStep("unblock load", () => blockingOnlineStore.AllowLoad()); AddUntilStep("wait for texture load", () => avatar1.Texture != null); AddAssert("two lookups occurred", () => blockingOnlineStore.TotalCompletedLookups == 2); } /// <summary> /// Tests the case where multiple lookups occur which overlap each other, for the same texture. /// </summary> [Test] public void TestFetchContentionSameLookup() { Avatar avatar1 = null; Avatar avatar2 = null; AddStep("begin blocking load", () => blockingOnlineStore.StartBlocking()); AddStep("get first", () => avatar1 = addSprite("https://a.ppy.sh/3")); AddStep("get second", () => avatar2 = addSprite("https://a.ppy.sh/3")); AddAssert("neither are loaded", () => avatar1.Texture == null && avatar2.Texture == null); AddStep("unblock load", () => blockingOnlineStore.AllowLoad()); AddUntilStep("wait for texture load", () => avatar1.Texture != null && avatar2.Texture != null); AddAssert("only one lookup occurred", () => blockingOnlineStore.TotalInitiatedLookups == 1); } /// <summary> /// Tests that a ref-counted texture gets put in a non-available state when disposed. /// </summary> [Test] public void TestRefCountTextureAvailability() { Texture texture = null; AddStep("get texture", () => texture = largeStore.Get("https://a.ppy.sh/3")); AddStep("dispose texture", () => texture.Dispose()); assertAvailability(() => texture, false); } /// <summary> /// Tests that a non-ref-counted texture remains in an available state when disposed. /// </summary> [Test] public void TestTextureAvailability() { Texture texture = null; AddStep("get texture", () => texture = normalStore.Get("https://a.ppy.sh/3")); AddStep("dispose texture", () => texture.Dispose()); AddAssert("texture is still available", () => texture.Available); } private void assertAvailability(Func<Texture> textureFunc, bool available) => AddAssert($"texture available = {available}", () => ((TextureWithRefCount)textureFunc()).IsDisposed == !available); private Avatar addSprite(string url) { var avatar = new Avatar(url); Add(new DelayedLoadWrapper(avatar)); return avatar; } [LongRunningLoad] private class Avatar : Sprite { private readonly string url; public Avatar(string url) { this.url = url; } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { Texture = textures.Get(url); } } private class BlockingOnlineStore : OnlineStore { /// <summary> /// The total number of lookups requested on this store (including blocked lookups). /// </summary> public int TotalInitiatedLookups { get; private set; } /// <summary> /// The total number of completed lookups. /// </summary> public int TotalCompletedLookups { get; private set; } private readonly ManualResetEventSlim resetEvent = new ManualResetEventSlim(true); private string blockingUrl; /// <summary> /// Block load until <see cref="AllowLoad"/> is called. /// </summary> /// <param name="blockingUrl">If not <c>null</c> or empty, only lookups for this particular URL will be blocked.</param> public void StartBlocking(string blockingUrl = null) { this.blockingUrl = blockingUrl; resetEvent.Reset(); } public void AllowLoad() => resetEvent.Set(); public override byte[] Get(string url) { TotalInitiatedLookups++; if (string.IsNullOrEmpty(blockingUrl) || url == blockingUrl) resetEvent.Wait(); TotalCompletedLookups++; return base.Get(url); } public void Reset() { AllowLoad(); TotalInitiatedLookups = 0; TotalCompletedLookups = 0; } } } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Collections.Generic; using System.Linq; using NodaTime.Text; using NUnit.Framework; using System.Globalization; namespace NodaTime.Test.Text { public class OffsetPatternTest : PatternTestBase<Offset> { /// <summary> /// A non-breaking space. /// </summary> public const string Nbsp = "\u00a0"; /// <summary> /// Test data that can only be used to test formatting. /// </summary> internal static readonly Data[] FormatOnlyData = { new Data(3, 0, 0) { Culture = Cultures.EnUs, Text = "", Pattern = "%-", }, // Losing information new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = "05", Pattern = "HH" }, new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = "06", Pattern = "mm" }, new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = "07", Pattern = "ss" }, new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = "5", Pattern = "%H" }, new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = "6", Pattern = "%m" }, new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = "7", Pattern = "%s" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "+18", Pattern = "g" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "18", Pattern = "%H" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "0", Pattern = "%m" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "0", Pattern = "%s" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "m", Pattern = "\\m" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "m", Pattern = "'m'" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "mmmmmmmmmm", Pattern = "'mmmmmmmmmm'" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "z", Pattern = "'z'" }, new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = "zqw", Pattern = "'zqw'" }, new Data(3, 0, 0, true) { Culture = Cultures.EnUs, Text = "-", Pattern = "%-" }, new Data(3, 0, 0) { Culture = Cultures.EnUs, Text = "+", Pattern = "%+" }, new Data(3, 0, 0, true) { Culture = Cultures.EnUs, Text = "-", Pattern = "%+" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+05", Pattern = "s" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+05:12", Pattern = "m" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+05:12:34", Pattern = "l" }, }; /// <summary> /// Test data that can only be used to test successful parsing. /// </summary> internal static readonly Data[] ParseOnlyData = { new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "*", Pattern = "%*" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "zqw", Pattern = "'zqw'" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "-", Pattern = "%-" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+", Pattern = "%+" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "-", Pattern = "%+" }, new Data(5, 0, 0) { Culture = Cultures.EnUs, Text = "+05", Pattern = "s" }, new Data(5, 12, 0) { Culture = Cultures.EnUs, Text = "+05:12", Pattern = "m" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+05:12:34", Pattern = "l" }, new Data(Offset.Zero) { Pattern = "Z+HH:mm", Text = "+00:00" } // Lenient when parsing Z-prefixed patterns. }; /// <summary> /// Test data for invalid patterns /// </summary> internal static readonly Data[] InvalidPatternData = { new Data(Offset.Zero) { Pattern = "", Message = TextErrorMessages.FormatStringEmpty }, new Data(Offset.Zero) { Pattern = "%Z", Message = TextErrorMessages.EmptyZPrefixedOffsetPattern }, new Data(Offset.Zero) { Pattern = "HH:mmZ", Message = TextErrorMessages.ZPrefixNotAtStartOfPattern }, new Data(Offset.Zero) { Pattern = "%%H", Message = TextErrorMessages.PercentDoubled}, new Data(Offset.Zero) { Pattern = "HH:HH", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'H'} }, new Data(Offset.Zero) { Pattern = "mm:mm", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'m'} }, new Data(Offset.Zero) { Pattern = "ss:ss", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'s'} }, new Data(Offset.Zero) { Pattern = "+HH:-mm", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'-'} }, new Data(Offset.Zero) { Pattern = "-HH:+mm", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'+'} }, new Data(Offset.Zero) { Pattern = "!", Message = TextErrorMessages.UnknownStandardFormat, Parameters = {'!', typeof(Offset).FullName}}, new Data(Offset.Zero) { Pattern = "%", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '%', typeof(Offset).FullName } }, new Data(Offset.Zero) { Pattern = "%%", Message = TextErrorMessages.PercentDoubled }, new Data(Offset.Zero) { Pattern = "%\\", Message = TextErrorMessages.EscapeAtEndOfString }, new Data(Offset.Zero) { Pattern = "\\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '\\', typeof(Offset).FullName } }, new Data(Offset.Zero) { Pattern = "H%", Message = TextErrorMessages.PercentAtEndOfString }, new Data(Offset.Zero) { Pattern = "hh", Message = TextErrorMessages.Hour12PatternNotSupported, Parameters = { typeof(Offset).FullName } }, new Data(Offset.Zero) { Pattern = "HHH", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'H', 2 } }, new Data(Offset.Zero) { Pattern = "mmm", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } }, new Data(Offset.Zero) { Pattern = "mmmmmmmmmmmmmmmmmmm", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } }, new Data(Offset.Zero) { Pattern = "'qwe", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } }, new Data(Offset.Zero) { Pattern = "'qwe\\", Message = TextErrorMessages.EscapeAtEndOfString }, new Data(Offset.Zero) { Pattern = "'qwe\\'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } }, new Data(Offset.Zero) { Pattern = "sss", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 's', 2 } }, }; /// <summary> /// Tests for parsing failures (of values) /// </summary> internal static readonly Data[] ParseFailureData = { new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "", Pattern = "g", Message = TextErrorMessages.ValueStringEmpty }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "1", Pattern = "HH", Message = TextErrorMessages.MismatchedNumber, Parameters = {"HH"} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "1", Pattern = "mm", Message = TextErrorMessages.MismatchedNumber, Parameters = {"mm"} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "1", Pattern = "ss", Message = TextErrorMessages.MismatchedNumber, Parameters = {"ss"} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "12:34 ", Pattern = "HH:mm", Message = TextErrorMessages.ExtraValueCharacters, Parameters = {" "} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "1a", Pattern = "H ", Message = TextErrorMessages.MismatchedCharacter, Parameters = {' '}}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "2:", Pattern = "%H", Message = TextErrorMessages.ExtraValueCharacters, Parameters = {":"}}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "a", Pattern = "%.", Message = TextErrorMessages.MismatchedCharacter, Parameters = {'.'}}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "a", Pattern = "%:", Message = TextErrorMessages.TimeSeparatorMismatch}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "a", Pattern = "%H", Message = TextErrorMessages.MismatchedNumber, Parameters = {"H"} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "a", Pattern = "%m", Message = TextErrorMessages.MismatchedNumber, Parameters = {"m"} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "a", Pattern = "%s", Message = TextErrorMessages.MismatchedNumber, Parameters = {"s"} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "a", Pattern = ".H", Message = TextErrorMessages.MismatchedCharacter, Parameters = {'.'}}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "a", Pattern = "\\'", Message = TextErrorMessages.EscapedCharacterMismatch, Parameters = {'\''} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "axc", Pattern = "'abc'", Message = TextErrorMessages.QuotedStringMismatch}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "z", Pattern = "%*", Message = TextErrorMessages.MismatchedCharacter, Parameters = {'*'} }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "24", Pattern = "HH", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = {24, 'H', typeof(Offset) }}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "60", Pattern = "mm", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = {60, 'm', typeof(Offset) }}, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "60", Pattern = "ss", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = {60, 's', typeof(Offset) }}, new Data(Offset.Zero) { Text = "+12", Pattern = "-HH", Message = TextErrorMessages.PositiveSignInvalid }, }; /// <summary> /// Common test data for both formatting and parsing. A test should be placed here unless is truly /// cannot be run both ways. This ensures that as many round-trip type tests are performed as possible. /// </summary> internal static readonly Data[] FormatAndParseData = { /*XXX*/ new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = ".", Pattern = "%." }, // decimal separator new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = ":", Pattern = "%:" }, // date separator /*XXX*/ new Data(Offset.Zero) { Culture = Cultures.DotTimeSeparator, Text = ".", Pattern = "%." }, // decimal separator (always period) new Data(Offset.Zero) { Culture = Cultures.DotTimeSeparator, Text = ".", Pattern = "%:" }, // date separator new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "H", Pattern = "\\H" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "HHss", Pattern = "'HHss'" }, new Data(0, 0, 12) { Culture = Cultures.EnUs, Text = "12", Pattern = "%s" }, new Data(0, 0, 12) { Culture = Cultures.EnUs, Text = "12", Pattern = "ss" }, new Data(0, 0, 2) { Culture = Cultures.EnUs, Text = "2", Pattern = "%s" }, new Data(0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%m" }, new Data(0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "mm" }, new Data(0, 2, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%m" }, new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%H" }, new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "HH" }, new Data(2, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%H" }, // Standard patterns with punctuation... new Data(5, 0, 0) { Culture = Cultures.EnUs, Text = "+05", Pattern = "G" }, new Data(5, 12, 0) { Culture = Cultures.EnUs, Text = "+05:12", Pattern = "G" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+05:12:34", Pattern = "G" }, new Data(5, 0, 0) { Culture = Cultures.EnUs, Text = "+05", Pattern = "g" }, new Data(5, 12, 0) { Culture = Cultures.EnUs, Text = "+05:12", Pattern = "g" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+05:12:34", Pattern = "g" }, new Data(Offset.MinValue) { Culture = Cultures.EnUs, Text = "-18", Pattern = "g" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "Z", Pattern = "G" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+00", Pattern = "g" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+00", Pattern = "s" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+00:00", Pattern = "m" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+00:00:00", Pattern = "l" }, new Data(5, 0, 0) { Culture = Cultures.FrFr, Text = "+05", Pattern = "g" }, new Data(5, 12, 0) { Culture = Cultures.FrFr, Text = "+05:12", Pattern = "g" }, new Data(5, 12, 34) { Culture = Cultures.FrFr, Text = "+05:12:34", Pattern = "g" }, new Data(Offset.MaxValue) { Culture = Cultures.FrFr, Text = "+18", Pattern = "g" }, new Data(Offset.MinValue) { Culture = Cultures.FrFr, Text = "-18", Pattern = "g" }, new Data(5, 0, 0) { Culture = Cultures.DotTimeSeparator, Text = "+05", Pattern = "g" }, new Data(5, 12, 0) { Culture = Cultures.DotTimeSeparator, Text = "+05.12", Pattern = "g" }, new Data(5, 12, 34) { Culture = Cultures.DotTimeSeparator, Text = "+05.12.34", Pattern = "g" }, new Data(Offset.MaxValue) { Culture = Cultures.DotTimeSeparator, Text = "+18", Pattern = "g" }, new Data(Offset.MinValue) { Culture = Cultures.DotTimeSeparator, Text = "-18", Pattern = "g" }, // Standard patterns without punctuation new Data(5, 0, 0) { Culture = Cultures.EnUs, Text = "+05", Pattern = "I" }, new Data(5, 12, 0) { Culture = Cultures.EnUs, Text = "+0512", Pattern = "I" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+051234", Pattern = "I" }, new Data(5, 0, 0) { Culture = Cultures.EnUs, Text = "+05", Pattern = "i" }, new Data(5, 12, 0) { Culture = Cultures.EnUs, Text = "+0512", Pattern = "i" }, new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = "+051234", Pattern = "i" }, new Data(Offset.MinValue) { Culture = Cultures.EnUs, Text = "-18", Pattern = "i" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "Z", Pattern = "I" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+00", Pattern = "i" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+00", Pattern = "S" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+0000", Pattern = "M" }, new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = "+000000", Pattern = "L" }, new Data(5, 0, 0) { Culture = Cultures.FrFr, Text = "+05", Pattern = "i" }, new Data(5, 12, 0) { Culture = Cultures.FrFr, Text = "+0512", Pattern = "i" }, new Data(5, 12, 34) { Culture = Cultures.FrFr, Text = "+051234", Pattern = "i" }, new Data(Offset.MaxValue) { Culture = Cultures.FrFr, Text = "+18", Pattern = "i" }, new Data(Offset.MinValue) { Culture = Cultures.FrFr, Text = "-18", Pattern = "i" }, new Data(5, 0, 0) { Culture = Cultures.DotTimeSeparator, Text = "+05", Pattern = "i" }, new Data(5, 12, 0) { Culture = Cultures.DotTimeSeparator, Text = "+0512", Pattern = "i" }, new Data(5, 12, 34) { Culture = Cultures.DotTimeSeparator, Text = "+051234", Pattern = "i" }, new Data(Offset.MaxValue) { Culture = Cultures.DotTimeSeparator, Text = "+18", Pattern = "i" }, new Data(Offset.MinValue) { Culture = Cultures.DotTimeSeparator, Text = "-18", Pattern = "i" }, // Explicit patterns new Data(0, 30, 0, true) { Culture = Cultures.EnUs, Text = "-00:30", Pattern = "+HH:mm" }, new Data(0, 30, 0, true) { Culture = Cultures.EnUs, Text = "-00:30", Pattern = "-HH:mm" }, new Data(0, 30, 0, false) { Culture = Cultures.EnUs, Text = "00:30", Pattern = "-HH:mm" }, // Z-prefixes new Data(Offset.Zero) { Text = "Z", Pattern = "Z+HH:mm:ss" }, new Data(5, 12, 34) { Text = "+05:12:34", Pattern = "Z+HH:mm:ss" }, new Data(5, 12) { Text = "+05:12", Pattern = "Z+HH:mm" }, }; internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData); internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData); [Test] [TestCaseSource(nameof(ParseData))] public void ParsePartial(PatternTestData<Offset> data) { data.TestParsePartial(); } [Test] public void ParseNull() => AssertParseNull(OffsetPattern.GeneralInvariant); [Test] public void NumberFormatIgnored() { var culture = (CultureInfo) Cultures.EnUs.Clone(); culture.NumberFormat.PositiveSign = "P"; culture.NumberFormat.NegativeSign = "N"; var pattern = OffsetPattern.Create("+HH:mm", culture); Assert.AreEqual("+05:00", pattern.Format(Offset.FromHours(5))); Assert.AreEqual("-05:00", pattern.Format(Offset.FromHours(-5))); } [Test] public void CreateWithCurrentCulture() { using (CultureSaver.SetCultures(Cultures.DotTimeSeparator)) { var pattern = OffsetPattern.CreateWithCurrentCulture("H:mm"); var text = pattern.Format(Offset.FromHoursAndMinutes(1, 30)); Assert.AreEqual("1.30", text); } } /// <summary> /// A container for test data for formatting and parsing <see cref="Offset" /> objects. /// </summary> public sealed class Data : PatternTestData<Offset> { // Ignored anyway... protected override Offset DefaultTemplate => Offset.Zero; public Data(Offset value) : base(value) { } public Data(int hours, int minutes) : this(Offset.FromHoursAndMinutes(hours, minutes)) { } public Data(int hours, int minutes, int seconds) : this(TestObjects.CreatePositiveOffset(hours, minutes, seconds)) { } public Data(int hours, int minutes, int seconds, bool negative) : this(negative ? TestObjects.CreateNegativeOffset(hours, minutes, seconds) : TestObjects.CreatePositiveOffset(hours, minutes, seconds)) { } internal override IPattern<Offset> CreatePattern() => OffsetPattern.CreateWithInvariantCulture(Pattern!) .WithCulture(Culture); internal override IPartialPattern<Offset> CreatePartialPattern() => OffsetPattern.CreateWithInvariantCulture(Pattern!).WithCulture(Culture).UnderlyingPattern; } } }
/* * Copyright (c) 2015, Wisconsin Robotics * 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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 BadgerJaus.Util; namespace BadgerJaus.Messages { public enum AckNak { // AckNak Flags NOT_REQUIRED = 0, // ordinal 0 REQUIRED = 1, // ordinal 1 NEGATIVE_ACK = 2, // ordinal 2 ACKNOWLEDGE = 3 // ordinal 3 } public enum Broadcast { // Bcast Flags NO = 0, //Ordinal 0 LOCAL = 1, //Ordinal 1 GLOBAL = 2 //Ordinal 2 } public enum DataFlag { // Data Flags SINGLE_DATA_PACKET = 0, // ordinal 0 FIRST_DATA_PACKET = 1, // ordinal 1 NORMAL_DATA_PACKET = 2, // ordinal 2 LAST_DATA_PACKET = 3 // ordinal 3 } public enum HCFlags { // HCFlags NO_HEADER_COMPRESSION = 0, // ordinal 0 HEADER_COMPRESSION_REQUEST = 1, // ordinal 1 HEADER_COMPRESSION_TWO = 2, // ordinal 2 HEADER_COMPRESSION_ENGAGED = 3 // ordinal 3 } public enum Priority { // Priority Flags LOW = 0, // ordinal 0 NORMAL = 1, // ordinal 1 HIGH = 2, // ordinal 2 SAFETY = 3 // ordinal 3 } /// <summary> /// The message class serves as the base class for all JAUS messages. It /// provides a skeleton that extracts header values and information about /// the data payload. Child classes override specific methods that perform /// the actual unpacking of message fields into usable forms. /// </summary> public class Message { // The following are constants defined for the header properties in JUDP public const byte JUDP_HEADER = 2; // Version of JUDP public const int JUDP_HEADER_SIZE_BYTES = 1; // The following are constants defined for the header properties in JTCP public const byte JTCP_HEADER = 2; // Version of JTCP public const int JTCP_HEADER_SIZE_BYTES = 1; public const int HEADER_SIZE_BYTES_CMP = 15; public const int HEADER_SIZE_BYTES_NCMP = 12; private int headerBaseSize = HEADER_SIZE_BYTES_NCMP; // Assuming No Compression public const int UDP_MAX_PACKET_SIZE = 4101; // Including JUDP Header, General Transport Header, // and uncompressed message payload public const int SEQUENCE_NUMBER_MAX = 65535; public const int SEQUENCE_NUMBER_SIZE_BYTES = JausBaseType.SHORT_BYTE_SIZE; public const int COMMAND_CODE_SIZE_BYTES = JausBaseType.SHORT_BYTE_SIZE; // Properties Bit Positions public const int PRIORITY_BIT_POSITION = 0; public const int BCAST_BIT_POSITION = 2; public const int ACK_NAK_BIT_POSITION = 4; public const int DATA_FLAGS_BIT_POSITION = 6; // First Byte Bit Positions public const int MESSAGE_TYPE_BIT_POSITION = 0; public const int HC_FLAGS_BIT_POSITION = 6; // ***** JausMessage Header Fields ***** private byte messageType = 0; protected JausUnsignedShort commandCode;// = new JausUnsignedShort(); // Initial value = 0 // Values 1 through 32 are reserved for future use. // TODO: Implement header compression private HCFlags hcFlags; // Header Compression Flags // 0: No header compression is used // 1: The sender of this message is requesting // that the receiver engage in header compression // 2: Meaning depends upon HC Length field // 3: The sender is sending a message containing compressed data. protected JausUnsignedShort dataSize; // Size of General Transport Header + data // private byte HCNumber; // Used if HCFlags != 0 range 0 - 255 // private byte HCLength; // Used if HCflags != 0 range 0 - 255 private Priority priority; private Broadcast bCast; private AckNak ackNak; private DataFlag dataFlags; private JausAddress destination; private JausAddress source; // TODO: Make the following private protected byte[] data; private JausUnsignedShort sequenceNumber; // ******** End JausMessage Header Fields ******** /** * Default Constructor. */ public Message() { InitData(); Configure(); } protected void Configure() { messageType = 0; // Transport Type of Message hcFlags = HCFlags.NO_HEADER_COMPRESSION; priority = Priority.NORMAL; bCast = Broadcast.NO; ackNak = AckNak.NOT_REQUIRED; dataFlags = DataFlag.SINGLE_DATA_PACKET; commandCode.Value = CommandCode; } private void InitData() { dataSize = new JausUnsignedShort(); commandCode = new JausUnsignedShort(); destination = new JausAddress(); source = new JausAddress(); sequenceNumber = new JausUnsignedShort(); data = null; InitFieldData(); } /// <summary> /// <c>InitFieldData</c> is used to initialize the member classes that /// represent the fields of a JAUS message. This method is only /// relevant to child classes that have payloads. /// </summary> protected virtual void InitFieldData() { } /// <summary> /// <c>UdpSize</c> provides the size of the entire message plus the /// UDP packet tag. /// </summary> public int UdpSize() { return JUDP_HEADER_SIZE_BYTES + MessageSize(); } /** * Size returns the total number of bytes of the JAUS Packet (not including * the JUDP Header). Other messages should override this method in order to * properly set the size requirements for their particular message. This * method is primarily used to set the size of buffers. * * @return The size of the message in bytes. */ public virtual int MessageSize() { return headerBaseSize + Message.COMMAND_CODE_SIZE_BYTES + Message.SEQUENCE_NUMBER_SIZE_BYTES + GetPayloadSize(); } public AckNak AckNak { get { return ackNak; } set { ackNak = value; } } public Broadcast BCast { get { return bCast; } set { bCast = value; } } public DataFlag DataFlags { get { return dataFlags; } set { dataFlags = value; } } public HCFlags HCFlags { get { return hcFlags; } set { hcFlags = (HCFlags)value; } } public byte MessageType { get { return messageType; } set { messageType = value; } } /// <summary> /// <c>GetPayloadSize</c> provides the size of the data payload that /// a message may have. Child classes that have additional fields need /// to override this method to calculate sizes specific to their /// fields. /// </summary> /// <returns></returns> public virtual int GetPayloadSize() { if (data != null) return data.Length; return 0; } protected virtual int CommandCode { get { return JausCommandCode.NONE; } } public int GetCommandCode() { return (int)commandCode.Value; } public JausAddress GetDestination() { return destination; } public void SetDestination(long id) { destination.Value = id; } public void SetDestination(JausAddress address) { destination.Value = address.Value; } public JausAddress GetSource() { return source; } public void SetSource(long id) { this.source.Value = id; } public void SetSource(JausAddress address) { source.Value = address.Value; } public byte[] GetPayload() { byte[] payload = new byte[data.Length]; Array.Copy(data, 0, payload, 0, payload.Length); return payload; } public bool SetPayload(byte[] payload) { if (payload == null) return false; this.data = new byte[payload.Length]; Array.Copy(payload, 0, data, 0, payload.Length); return true; } public String payloadToString() { String str = ""; for (int i = 0; i < data.Length; i++) { str += "0x" + Convert.ToString(data[i], 16).ToUpper() + " "; } return str; } /// <summary> /// This method is intended to be overridden by child classes that /// encode their respective fields into the byte buffer in the order /// detailed in the specification. The base implementation handles /// copying of already existing buffers when dealing with a generic or /// not yet differentiated message instance. /// </summary> /// <param name="data">Array to copy data to.</param> /// <param name="index">Offset into array to start copying to.</param> /// <returns></returns> protected virtual bool PayloadToJausBuffer(byte[] data, int index, out int indexOffset) { indexOffset = index; if (this.data != null) { Array.Copy(this.data, 0, data, index, this.data.Length); indexOffset += this.data.Length; } return true; } protected virtual bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset) { int payloadSize; // The data size field includes the size of the entire message // including the header and sequence number but not the JUDP // tag. To get just the size of the data payload we need to // subtract all that out. payloadSize = (int)dataSize.Value - HEADER_SIZE_BYTES_NCMP - COMMAND_CODE_SIZE_BYTES - SEQUENCE_NUMBER_SIZE_BYTES; data = new byte[payloadSize]; Array.Copy(buffer, index, data, 0, payloadSize); indexOffset = index + payloadSize; return true; } public int GetSequenceNumber() { return (int)sequenceNumber.Value; } public void SetSequenceNumber(int sequenceNumber) { this.sequenceNumber.Value = sequenceNumber; } public void SetFromJausMessage(Message jausMessage) { int indexOffset; SetHeaderFromJausMessage(jausMessage); SetPayloadFromJausBuffer(jausMessage.GetPayload(), 0, out indexOffset); } private void SetHeaderFromJausMessage(Message jausMessage) { SetAddressFromJausMessage(jausMessage); dataSize.Value = jausMessage.MessageSize(); } public void SetAddressFromJausMessage(Message jausMessage) { SetDestination(jausMessage.GetDestination().Value); SetSource(jausMessage.GetSource().Value); } public int Deserialize(byte[] buffer, int index = 0) { if (!SetHeaderFromJausBuffer(buffer, index)) { //Console.Error.WriteLine("setFromJausBuffer Failed. Set header from Jause Buffer"); Console.Error.WriteLine("setFromJausBuffer Failed"); return -1; // setHeaderFromJausBuffer failed } // Store Data Byte Array index += headerBaseSize; // TODO: Implement Multiple Packets Per Message if (dataFlags != DataFlag.SINGLE_DATA_PACKET) { Console.Error.WriteLine("Receiving Multiple Packets Per Message Not Supported"); return -1; } // TODO: Implement Ack/Nak if (ackNak != AckNak.NOT_REQUIRED) { return -1; } if(CommandCode == JausCommandCode.NONE) { if (!commandCode.Deserialize(buffer, index, out index)) { return -1; // setCommandCodeFromJausBuffer failed } } else { JausUnsignedShort bufferCommandCode = new JausUnsignedShort(buffer, index); index += COMMAND_CODE_SIZE_BYTES; if (bufferCommandCode.Value != CommandCode) return -1; } SetPayloadFromJausBuffer(buffer, index, out index); int dataSize = GetPayloadSize(); if (dataSize < 0 || dataSize > 10000) { return -1; } if (!sequenceNumber.Deserialize(buffer, index, out index)) { return -1; // setSequenceNumberFromJausBuffer failed } return index; } public bool ToJausBuffer(byte[] buffer, out int indexOffset) { return ToJausBuffer(buffer, 0, out indexOffset); } // Takes the header and data byte array and packs them into a data buffer // This method needs to be overridden for all subclasses of JausMessage to reflect the correct pack routine public bool ToJausBuffer(byte[] buffer, int index, out int indexOffset) { indexOffset = index; // TODO: Implement Compression if (hcFlags != HCFlags.NO_HEADER_COMPRESSION) { Console.Error.WriteLine("Sending Compression Not Supported"); return false; } // TODO: Implement Ack/Nak if (ackNak != AckNak.NOT_REQUIRED) { Console.Error.WriteLine("Sending Ack/Nak Not Supported"); return false; } if (buffer.Length < (indexOffset + GetPayloadSize() + Message.SEQUENCE_NUMBER_SIZE_BYTES)) { Console.Error.WriteLine("Error in toJausBuffer: Not Enough Size"); return false; // Not Enough Size } if (!HeaderToJausBuffer(buffer, indexOffset, out indexOffset)) { Console.Error.WriteLine("ToJausBuffer Failed"); return false; //headerToJausBuffer failed } if (!commandCode.Serialize(buffer, indexOffset, out indexOffset)) return false; PayloadToJausBuffer(buffer, indexOffset, out indexOffset); //Console.WriteLine("Claimed payload size: " + GetPayloadSize()); //Console.WriteLine("Sequence index position: " + index); if (!sequenceNumber.Serialize(buffer, indexOffset, out indexOffset)) { Console.Error.WriteLine("Failed to write sequence number to buffer"); return false; //headerToJausBuffer failed } return true; } // This function takes a byte array and attempts to extract a JAUS // message from it. It also attempts to find where the message it is // extracting ends, so that if the array has multiple messages the // array can be split appropriately. public int SetFromJausUdpBuffer(byte[] buffer, int index) { if (buffer == null) return -1; if (buffer.Length <= index) return -1; if (buffer[index] != Message.JUDP_HEADER) { return -1; // improper JUDP header / incompatible version } index += JUDP_HEADER_SIZE_BYTES; index = Deserialize(buffer, index); return index; } public int SetFromJausUdpBuffer(byte[] buffer) { return SetFromJausUdpBuffer(buffer, 0); } public bool ToJausUdpBuffer(byte[] buffer, int index, out int indexOffset) { indexOffset = index; if (buffer.Length < (index + JUDP_HEADER_SIZE_BYTES)) { return false; // Not Enough Size } buffer[indexOffset] = Message.JUDP_HEADER; indexOffset += Message.JUDP_HEADER_SIZE_BYTES; return ToJausBuffer(buffer, indexOffset, out indexOffset); } // Overloaded method to accept a buffer and pack this message into its UDP form public bool ToJausUdpBuffer(byte[] buffer, out int indexOffset) { return ToJausUdpBuffer(buffer, 0, out indexOffset); } // This private method takes a buffer at the given index and unpacks it into the header properties and data fields // This method is called whenever a message is unpacked to pull the header properties private bool SetHeaderFromJausBuffer(byte[] buffer, int index) { int indexOffset; byte properties; byte messageTypeHCflags; if (buffer.Length < index + headerBaseSize) return false; // Not Enough Size messageTypeHCflags = buffer[index]; messageType = (byte)((messageTypeHCflags >> MESSAGE_TYPE_BIT_POSITION) & 0x3F); hcFlags = (HCFlags)((messageTypeHCflags >> HC_FLAGS_BIT_POSITION) & 0x3); // TODO: Implement Compression if (hcFlags != HCFlags.NO_HEADER_COMPRESSION) { Console.Error.WriteLine("Compression Not Supported"); return false; } // int data1 = buffer[index+2]; dataSize.Deserialize(buffer, index + 1, out indexOffset); // No Compression Assumed properties = buffer[index + 3]; ackNak = (AckNak)((properties >> ACK_NAK_BIT_POSITION) & 0x03); bCast = (Broadcast)((properties >> BCAST_BIT_POSITION) & 0x03); dataFlags = (DataFlag)((properties >> DATA_FLAGS_BIT_POSITION) & 0x03); priority = (Priority)((properties >> PRIORITY_BIT_POSITION) & 0x3); destination.setComponent(buffer[index + 4]); destination.setNode(buffer[index + 5]); destination.setSubsystem((int)(new JausUnsignedShort(buffer, index + 6).Value)); source.setComponent(buffer[index + 8]); source.setNode(buffer[index + 9]); source.setSubsystem((int)(new JausUnsignedShort(buffer, index + 10).Value)); return true; } // This private method packs the header properties and data fields into the provided buffer at the given index // This method is called whenever a message is packed to put the header properties private bool HeaderToJausBuffer(byte[] buffer, int index, out int indexOffset) { byte properties = 0; byte messageTypeHCflags = messageType; indexOffset = index; if (buffer.Length < index + headerBaseSize) return false; // Not Enough Size messageTypeHCflags = (byte)(((byte)hcFlags << HC_FLAGS_BIT_POSITION) | (messageTypeHCflags & 0x3F)); buffer[indexOffset] = messageTypeHCflags; // Message type indexOffset += 1; //Console.WriteLine("Size: " + size()); dataSize.Value = MessageSize(); dataSize.Serialize(buffer, indexOffset, out indexOffset); //buffer[index + 3] = 0; // HC number, not needed //buffer[index + 4] = 0; // HC Length, not needed properties = (byte)(((byte)ackNak << ACK_NAK_BIT_POSITION) | properties); properties = (byte)(((byte)bCast << BCAST_BIT_POSITION) | properties); properties = (byte)(((byte)dataFlags << DATA_FLAGS_BIT_POSITION) | properties); properties = (byte)(((byte)priority << PRIORITY_BIT_POSITION) | properties); buffer[indexOffset] = properties; // Message Properties indexOffset += 1; buffer[indexOffset] = (byte)destination.getComponent(); // Destination component indexOffset += 1; buffer[indexOffset] = (byte)destination.getNode(); // Destination node indexOffset += 1; new JausUnsignedShort(destination.SubsystemID).Serialize(buffer, indexOffset, out indexOffset); buffer[indexOffset] = (byte)source.getComponent(); // Source component indexOffset += 1; buffer[indexOffset] = (byte)source.getNode(); // Source node indexOffset += 1; new JausUnsignedShort(source.SubsystemID).Serialize(buffer, indexOffset, out indexOffset); return true; } public override string ToString() { string str = "Command Code: " + JausCommandCode.Lookup((int)(commandCode.Value)) + " (0x" + Convert.ToString(commandCode.Value, 16).ToUpper() + ") " + "\n"; return str; } public String headerToString() { String str = ""; // str += "JUDP Version: " + JausMessage.JUDP_HEADER + "\n"; str += "Message Type: " + this.messageType + "\n"; str += "HC flags: " + this.hcFlags + "\n"; str += "Data Size: " + this.dataSize.Value + "\n"; // str += "HC Number: " + this.getHCnumber() + "\n"; // str += "HC Length: " + this.getHCLength() + "\n"; str += "Priority: " + this.priority + "\n"; str += "Broadcast: " + this.bCast + "\n"; str += "Ack/Nak: " + this.ackNak + "\n"; str += "Data Flags: " + this.dataFlags + "\n"; str += "Destination: " + this.destination.ToString() + "\n"; str += "Source: " + this.source.ToString() + "\n"; //str += "Command Code: " + commandCodeJT + " (0x" + Integer.toString(this.commandCodeJT.COMMAND_CODE(), 16).toUpperCase() + ") " + "\n"; str += "Data: " + this.payloadToString() + "\n"; str += "Sequence Number: " + sequenceNumber.Value + "\n"; return str; } } }
/* ------------------------------------------------------------------------ * (c)copyright 2009-2012 Catfood Software and contributors - http://catfood.net * Provided under the ms-PL license, see LICENSE.txt * ------------------------------------------------------------------------ */ using System; using System.Collections.Generic; using System.Text; namespace Catfood.Shapefile { /// <summary> /// The ShapeType of a shape in a Shapefile /// </summary> public enum ShapeType { /// <summary> /// Null Shape /// </summary> Null = 0, /// <summary> /// Point Shape /// </summary> Point = 1, /// <summary> /// PolyLine Shape /// </summary> PolyLine = 3, /// <summary> /// Polygon Shape /// </summary> Polygon = 5, /// <summary> /// MultiPoint Shape /// </summary> MultiPoint = 8, /// <summary> /// PointZ Shape /// </summary> PointZ = 11, /// <summary> /// PolyLineZ Shape /// </summary> PolyLineZ = 13, /// <summary> /// PolygonZ Shape /// </summary> PolygonZ = 15, /// <summary> /// MultiPointZ Shape /// </summary> MultiPointZ = 18, /// <summary> /// PointM Shape /// </summary> PointM = 21, /// <summary> /// PolyLineM Shape /// </summary> PolyLineM = 23, /// <summary> /// PolygonM Shape /// </summary> PolygonM = 25, /// <summary> /// MultiPointM Shape /// </summary> MultiPointM = 28, /// <summary> /// MultiPatch Shape /// </summary> MultiPatch = 31 } /// <summary> /// The header data for a Shapefile main file or Index file /// </summary> class Header { /// <summary> /// The length of a Shapefile header in bytes /// </summary> public const int HeaderLength = 100; private const int ExpectedFileCode = 9994; private const int ExpectedVersion = 1000; private int _fileCode; private int _fileLength; private int _version; private ShapeType _shapeType; private double _xMin; private double _yMin; private double _xMax; private double _yMax; private double _zMin; private double _zMax; private double _mMin; private double _mMax; /// <summary> /// The header data for a Shapefile main file or Index file /// </summary> /// <param name="headerBytes">The first 100 bytes of the Shapefile main file or Index file</param> /// <exception cref="ArgumentNullException">Thrown if headerBytes is null</exception> /// <exception cref="InvalidOperationException">Thrown if an error occurs parsing the header</exception> public Header(byte[] headerBytes) { if (headerBytes == null) { throw new ArgumentNullException("headerBytes"); } if (headerBytes.Length != HeaderLength) { throw new InvalidOperationException(string.Format("headerBytes must be {0} bytes long", HeaderLength)); } //Position Field Value Type Order //Byte 0 File Code 9994 Integer Big //Byte 4 Unused 0 Integer Big //Byte 8 Unused 0 Integer Big //Byte 12 Unused 0 Integer Big //Byte 16 Unused 0 Integer Big //Byte 20 Unused 0 Integer Big //Byte 24 File Length File Length Integer Big //Byte 28 Version 1000 Integer Little //Byte 32 Shape Type Shape Type Integer Little //Byte 36 Bounding Box Xmin Double Little //Byte 44 Bounding Box Ymin Double Little //Byte 52 Bounding Box Xmax Double Little //Byte 60 Bounding Box Ymax Double Little //Byte 68* Bounding Box Zmin Double Little //Byte 76* Bounding Box Zmax Double Little //Byte 84* Bounding Box Mmin Double Little //Byte 92* Bounding Box Mmax Double Little _fileCode = EndianBitConverter.ToInt32(headerBytes, 0, ProvidedOrder.Big); if (_fileCode != ExpectedFileCode) { throw new InvalidOperationException(string.Format("Header File code is {0}, expected {1}", _fileCode, ExpectedFileCode)); } _version = EndianBitConverter.ToInt32(headerBytes, 28, ProvidedOrder.Little); if (_version != ExpectedVersion) { throw new InvalidOperationException(string.Format("Header version is {0}, expected {1}", _version, ExpectedVersion)); } _fileLength = EndianBitConverter.ToInt32(headerBytes, 24, ProvidedOrder.Big); _shapeType = (ShapeType)EndianBitConverter.ToInt32(headerBytes, 32, ProvidedOrder.Little); _xMin = EndianBitConverter.ToDouble(headerBytes, 36, ProvidedOrder.Little); _yMin = EndianBitConverter.ToDouble(headerBytes, 44, ProvidedOrder.Little); _xMax = EndianBitConverter.ToDouble(headerBytes, 52, ProvidedOrder.Little); _yMax = EndianBitConverter.ToDouble(headerBytes, 60, ProvidedOrder.Little); _zMin = EndianBitConverter.ToDouble(headerBytes, 68, ProvidedOrder.Little); _zMax = EndianBitConverter.ToDouble(headerBytes, 76, ProvidedOrder.Little); _mMin = EndianBitConverter.ToDouble(headerBytes, 84, ProvidedOrder.Little); _mMax = EndianBitConverter.ToDouble(headerBytes, 92, ProvidedOrder.Little); } /// <summary> /// Gets the FileCode /// </summary> public int FileCode { get { return _fileCode; } } /// <summary> /// Gets the file length, in 16-bit words, including the header bytes /// </summary> public int FileLength { get { return _fileLength; } } /// <summary> /// Gets the file version /// </summary> public int Version { get { return _version; } } /// <summary> /// Gets the ShapeType contained in this Shapefile /// </summary> public ShapeType ShapeType { get { return _shapeType; } } /// <summary> /// Gets min x for the bounding box /// </summary> public double XMin { get { return _xMin; } } /// <summary> /// Gets min y for the bounding box /// </summary> public double YMin { get { return _yMin; } } /// <summary> /// Gets max x for the bounding box /// </summary> public double XMax { get { return _xMax; } } /// <summary> /// Gets max y for the bounding box /// </summary> public double YMax { get { return _yMax; } } /// <summary> /// Gets min z for the bounding box (0 if unused) /// </summary> public double ZMin { get { return _zMin; } } /// <summary> /// Gets max z for the bounding box (0 if unused) /// </summary> public double ZMax { get { return _zMax; } } /// <summary> /// Gets min m for the bounding box (0 if unused) /// </summary> public double MMin { get { return _mMin; } } /// <summary> /// Gets max m for the bounding box (0 if unused) /// </summary> public double MMax { get { return _mMax; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.PowerShell.Commands; namespace System.Management.Automation { /// <summary> /// Class to manage the caching of analysis data. /// For performance, module command caching is flattened after discovery. Many modules have nested /// modules that can only be resolved at runtime - for example, /// script modules that declare: $env:PATH += "; $psScriptRoot". When /// doing initial analysis, we include these in 'ExportedCommands'. /// Changes to these type of modules will not be re-analyzed, unless the user re-imports the module, /// or runs Get-Module -List. /// </summary> internal class AnalysisCache { private static AnalysisCacheData s_cacheData = AnalysisCacheData.Get(); // This dictionary shouldn't see much use, so low concurrency and capacity private static ConcurrentDictionary<string, string> s_modulesBeingAnalyzed = new ConcurrentDictionary<string, string>( /*concurrency*/1, /*capacity*/2, StringComparer.OrdinalIgnoreCase); internal static char[] InvalidCommandNameCharacters = new[] { '#', ',', '(', ')', '{', '}', '[', ']', '&', '/', '\\', '$', '^', ';', ':', '"', '\'', '<', '>', '|', '?', '@', '`', '*', '%', '+', '=', '~' }; internal static ConcurrentDictionary<string, CommandTypes> GetExportedCommands(string modulePath, bool testOnly, ExecutionContext context) { bool etwEnabled = CommandDiscoveryEventSource.Log.IsEnabled(); if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStart(modulePath); DateTime lastWriteTime; ModuleCacheEntry moduleCacheEntry; if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry)) { if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStop(modulePath); return moduleCacheEntry.Commands; } ConcurrentDictionary<string, CommandTypes> result = null; if (!testOnly) { var extension = Path.GetExtension(modulePath); if (extension.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { result = AnalyzeManifestModule(modulePath, context, lastWriteTime, etwEnabled); } else if (extension.Equals(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase)) { result = AnalyzeScriptModule(modulePath, context, lastWriteTime); } else if (extension.Equals(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase)) { result = AnalyzeCdxmlModule(modulePath, context, lastWriteTime); } else if (extension.Equals(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase)) { result = AnalyzeDllModule(modulePath, context, lastWriteTime); } else if (extension.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase)) { result = AnalyzeDllModule(modulePath, context, lastWriteTime); } } if (result != null) { s_cacheData.QueueSerialization(); ModuleIntrinsics.Tracer.WriteLine("Returning {0} exported commands.", result.Count); } else { ModuleIntrinsics.Tracer.WriteLine("Returning NULL for exported commands."); } if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStop(modulePath); return result; } private static ConcurrentDictionary<string, CommandTypes> AnalyzeManifestModule(string modulePath, ExecutionContext context, DateTime lastWriteTime, bool etwEnabled) { ConcurrentDictionary<string, CommandTypes> result = null; try { var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames); if (moduleManifestProperties != null) { if (ModuleIsEditionIncompatible(modulePath, moduleManifestProperties)) { ModuleIntrinsics.Tracer.WriteLine($"Module lies on the Windows System32 legacy module path and is incompatible with current PowerShell edition, skipping module: {modulePath}"); return null; } Version version; if (ModuleUtils.IsModuleInVersionSubdirectory(modulePath, out version)) { var versionInManifest = LanguagePrimitives.ConvertTo<Version>(moduleManifestProperties["ModuleVersion"]); if (version != versionInManifest) { ModuleIntrinsics.Tracer.WriteLine("ModuleVersion in manifest does not match versioned module directory, skipping module: {0}", modulePath); return null; } } result = new ConcurrentDictionary<string, CommandTypes>(3, moduleManifestProperties.Count, StringComparer.OrdinalIgnoreCase); var sawWildcard = false; var hadCmdlets = AddPsd1EntryToResult(result, moduleManifestProperties["CmdletsToExport"], CommandTypes.Cmdlet, ref sawWildcard); var hadFunctions = AddPsd1EntryToResult(result, moduleManifestProperties["FunctionsToExport"], CommandTypes.Function, ref sawWildcard); var hadAliases = AddPsd1EntryToResult(result, moduleManifestProperties["AliasesToExport"], CommandTypes.Alias, ref sawWildcard); var analysisSucceeded = hadCmdlets && hadFunctions && hadAliases; if (!analysisSucceeded && !sawWildcard && (hadCmdlets || hadFunctions)) { // If we're missing CmdletsToExport, that might still be OK, but only if we have a script module. // Likewise, if we're missing FunctionsToExport, that might be OK, but only if we have a binary module. analysisSucceeded = !CheckModulesTypesInManifestAgainstExportedCommands(moduleManifestProperties, hadCmdlets, hadFunctions, hadAliases); } if (analysisSucceeded) { var moduleCacheEntry = new ModuleCacheEntry { ModulePath = modulePath, LastWriteTime = lastWriteTime, Commands = result, TypesAnalyzed = false, Types = new ConcurrentDictionary<string, TypeAttributes>(1, 8, StringComparer.OrdinalIgnoreCase) }; s_cacheData.Entries[modulePath] = moduleCacheEntry; } else { result = null; } } } catch (Exception e) { if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisException(modulePath, e.Message); // Ignore the errors, proceed with the usual module analysis ModuleIntrinsics.Tracer.WriteLine("Exception on fast-path analysis of module {0}", modulePath); } if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(modulePath, result != null); return result ?? AnalyzeTheOldWay(modulePath, context, lastWriteTime); } /// <summary> /// Check if a module is compatible with the current PSEdition given its path and its manifest properties. /// </summary> /// <param name="modulePath">The path to the module.</param> /// <param name="moduleManifestProperties">The properties of the module's manifest.</param> /// <returns></returns> internal static bool ModuleIsEditionIncompatible(string modulePath, Hashtable moduleManifestProperties) { #if UNIX return false; #else if (!ModuleUtils.IsOnSystem32ModulePath(modulePath)) { return false; } if (!moduleManifestProperties.ContainsKey("CompatiblePSEditions")) { return true; } return !Utils.IsPSEditionSupported(LanguagePrimitives.ConvertTo<string[]>(moduleManifestProperties["CompatiblePSEditions"])); #endif } internal static bool ModuleAnalysisViaGetModuleRequired(object modulePathObj, bool hadCmdlets, bool hadFunctions, bool hadAliases) { var modulePath = modulePathObj as string; if (modulePath == null) return true; if (modulePath.EndsWith(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase)) { // A script module can't exactly define cmdlets, but it can import a binary module (as nested), so // it can indirectly define cmdlets. And obviously a script module can define functions and aliases. // If we got here, one of those is missing, so analysis is required. return true; } if (modulePath.EndsWith(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase)) { // A cdxml module can only define functions and aliases, so if we have both, no more analysis is required. return !hadFunctions || !hadAliases; } if (modulePath.EndsWith(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase)) { // A dll just exports cmdlets, so if the manifest doesn't explicitly export any cmdlets, // more analysis is required. If the module exports aliases, we can't discover that analyzing // the binary, so aliases are always required to be explicit (no wildcards) in the manifest. return !hadCmdlets; } if (modulePath.EndsWith(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase)) { // A dll just exports cmdlets, so if the manifest doesn't explicitly export any cmdlets, // more analysis is required. If the module exports aliases, we can't discover that analyzing // the binary, so aliases are always required to be explicit (no wildcards) in the manifest. return !hadCmdlets; } // Any other extension (or no extension), just assume the worst and analyze the module return true; } // Returns true if we need to analyze the manifest module in Get-Module because // our quick and dirty module manifest analysis is missing something not easily // discovered. // // TODO - psm1 modules are actually easily handled, so if we only saw a psm1 here, // we should just analyze it and not fall back on Get-Module -List. private static bool CheckModulesTypesInManifestAgainstExportedCommands(Hashtable moduleManifestProperties, bool hadCmdlets, bool hadFunctions, bool hadAliases) { var rootModule = moduleManifestProperties["RootModule"]; if (rootModule != null && ModuleAnalysisViaGetModuleRequired(rootModule, hadCmdlets, hadFunctions, hadAliases)) return true; var moduleToProcess = moduleManifestProperties["ModuleToProcess"]; if (moduleToProcess != null && ModuleAnalysisViaGetModuleRequired(moduleToProcess, hadCmdlets, hadFunctions, hadAliases)) return true; var nestedModules = moduleManifestProperties["NestedModules"]; if (nestedModules != null) { var nestedModule = nestedModules as string; if (nestedModule != null) { return ModuleAnalysisViaGetModuleRequired(nestedModule, hadCmdlets, hadFunctions, hadAliases); } var nestedModuleArray = nestedModules as object[]; if (nestedModuleArray == null) return true; foreach (var element in nestedModuleArray) { if (ModuleAnalysisViaGetModuleRequired(element, hadCmdlets, hadFunctions, hadAliases)) return true; } } return false; } private static bool AddPsd1EntryToResult(ConcurrentDictionary<string, CommandTypes> result, string command, CommandTypes commandTypeToAdd, ref bool sawWildcard) { if (WildcardPattern.ContainsWildcardCharacters(command)) { sawWildcard = true; return false; } // An empty string is one way of saying "no exported commands". if (command.Length != 0) { CommandTypes commandTypes; if (result.TryGetValue(command, out commandTypes)) { commandTypes |= commandTypeToAdd; } else { commandTypes = commandTypeToAdd; } result[command] = commandTypes; } return true; } private static bool AddPsd1EntryToResult(ConcurrentDictionary<string, CommandTypes> result, object value, CommandTypes commandTypeToAdd, ref bool sawWildcard) { string command = value as string; if (command != null) { return AddPsd1EntryToResult(result, command, commandTypeToAdd, ref sawWildcard); } object[] commands = value as object[]; if (commands != null) { foreach (var o in commands) { if (!AddPsd1EntryToResult(result, o, commandTypeToAdd, ref sawWildcard)) return false; } // An empty array is still success, that's how a manifest declares that // no entries are exported (unlike the lack of an entry, or $null). return true; } // Unknown type, let Get-Module -List deal with this manifest return false; } private static ConcurrentDictionary<string, CommandTypes> AnalyzeScriptModule(string modulePath, ExecutionContext context, DateTime lastWriteTime) { var scriptAnalysis = ScriptAnalysis.Analyze(modulePath, context); if (scriptAnalysis == null) { return null; } List<WildcardPattern> scriptAnalysisPatterns = new List<WildcardPattern>(); foreach (string discoveredCommandFilter in scriptAnalysis.DiscoveredCommandFilters) { scriptAnalysisPatterns.Add(new WildcardPattern(discoveredCommandFilter)); } var result = new ConcurrentDictionary<string, CommandTypes>(3, scriptAnalysis.DiscoveredExports.Count + scriptAnalysis.DiscoveredAliases.Count, StringComparer.OrdinalIgnoreCase); // Add any directly discovered exports foreach (var command in scriptAnalysis.DiscoveredExports) { if (SessionStateUtilities.MatchesAnyWildcardPattern(command, scriptAnalysisPatterns, true)) { if (command.IndexOfAny(InvalidCommandNameCharacters) < 0) { result[command] = CommandTypes.Function; } } } // Add the discovered aliases foreach (var pair in scriptAnalysis.DiscoveredAliases) { var commandName = pair.Key; // These are already filtered if (commandName.IndexOfAny(InvalidCommandNameCharacters) < 0) { result.AddOrUpdate(commandName, CommandTypes.Alias, (_, existingCommandType) => existingCommandType | CommandTypes.Alias); } } // Add any files in PsScriptRoot if it added itself to the path if (scriptAnalysis.AddsSelfToPath) { string baseDirectory = Path.GetDirectoryName(modulePath); try { foreach (string item in Directory.GetFiles(baseDirectory, "*.ps1")) { var command = Path.GetFileNameWithoutExtension(item); result.AddOrUpdate(command, CommandTypes.ExternalScript, (_, existingCommandType) => existingCommandType | CommandTypes.ExternalScript); } } catch (UnauthorizedAccessException) { // Consume this exception here } } var exportedClasses = new ConcurrentDictionary<string, TypeAttributes>( /*concurrency*/ 1, scriptAnalysis.DiscoveredClasses.Count, StringComparer.OrdinalIgnoreCase); foreach (var exportedClass in scriptAnalysis.DiscoveredClasses) { exportedClasses[exportedClass.Name] = exportedClass.TypeAttributes; } var moduleCacheEntry = new ModuleCacheEntry { ModulePath = modulePath, LastWriteTime = lastWriteTime, Commands = result, TypesAnalyzed = true, Types = exportedClasses }; s_cacheData.Entries[modulePath] = moduleCacheEntry; return result; } private static ConcurrentDictionary<string, CommandTypes> AnalyzeCdxmlModule(string modulePath, ExecutionContext context, DateTime lastWriteTime) { return AnalyzeTheOldWay(modulePath, context, lastWriteTime); } private static ConcurrentDictionary<string, CommandTypes> AnalyzeDllModule(string modulePath, ExecutionContext context, DateTime lastWriteTime) { return AnalyzeTheOldWay(modulePath, context, lastWriteTime); } private static ConcurrentDictionary<string, CommandTypes> AnalyzeTheOldWay(string modulePath, ExecutionContext context, DateTime lastWriteTime) { try { // If we're already analyzing this module, let the recursion bottom out. if (!s_modulesBeingAnalyzed.TryAdd(modulePath, modulePath)) { ModuleIntrinsics.Tracer.WriteLine("{0} is already being analyzed. Exiting.", modulePath); return null; } // Record that we're analyzing this specific module so that we don't get stuck in recursion ModuleIntrinsics.Tracer.WriteLine("Started analysis: {0}", modulePath); CallGetModuleDashList(context, modulePath); ModuleCacheEntry moduleCacheEntry; if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry)) { return moduleCacheEntry.Commands; } } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e); // Catch-all OK, third-party call-out. } finally { ModuleIntrinsics.Tracer.WriteLine("Finished analysis: {0}", modulePath); s_modulesBeingAnalyzed.TryRemove(modulePath, out modulePath); } return null; } /// <summary> /// Return the exported types for a specific module. /// If the module is already cache, return from cache, else cache the module. /// Also re-cache the module if the cached item is stale. /// </summary> /// <param name="modulePath">Path to the module to get exported types from.</param> /// <param name="context">Current Context.</param> /// <returns></returns> internal static ConcurrentDictionary<string, TypeAttributes> GetExportedClasses(string modulePath, ExecutionContext context) { DateTime lastWriteTime; ModuleCacheEntry moduleCacheEntry; if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry) && moduleCacheEntry.TypesAnalyzed) { return moduleCacheEntry.Types; } try { CallGetModuleDashList(context, modulePath); if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry)) { return moduleCacheEntry.Types; } } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e); // Catch-all OK, third-party call-out. } return null; } internal static void CacheModuleExports(PSModuleInfo module, ExecutionContext context) { ModuleIntrinsics.Tracer.WriteLine("Requested caching for {0}", module.Name); // Don't cache incompatible modules on the system32 module path even if loaded with // -SkipEditionCheck, since it will break subsequent sessions. if (!module.IsConsideredEditionCompatible) { ModuleIntrinsics.Tracer.WriteLine($"Module '{module.Name}' not edition compatible and not cached."); return; } DateTime lastWriteTime; ModuleCacheEntry moduleCacheEntry; GetModuleEntryFromCache(module.Path, out lastWriteTime, out moduleCacheEntry); var realExportedCommands = module.ExportedCommands; var realExportedClasses = module.GetExportedTypeDefinitions(); ConcurrentDictionary<string, CommandTypes> exportedCommands; ConcurrentDictionary<string, TypeAttributes> exportedClasses; // First see if the existing module info is sufficient. GetModuleEntryFromCache does LastWriteTime // verification, so this will also return nothing if the cache is out of date or corrupt. if (moduleCacheEntry != null) { bool needToUpdate = false; // We need to iterate and check as exportedCommands will have more item as it can have aliases as well. exportedCommands = moduleCacheEntry.Commands; foreach (var pair in realExportedCommands) { var commandName = pair.Key; var realCommandType = pair.Value.CommandType; CommandTypes commandType; if (!exportedCommands.TryGetValue(commandName, out commandType) || commandType != realCommandType) { needToUpdate = true; break; } } exportedClasses = moduleCacheEntry.Types; foreach (var pair in realExportedClasses) { var className = pair.Key; var realTypeAttributes = pair.Value.TypeAttributes; TypeAttributes typeAttributes; if (!exportedClasses.TryGetValue(className, out typeAttributes) || typeAttributes != realTypeAttributes) { needToUpdate = true; break; } } // Update or not, we've analyzed commands and types now. moduleCacheEntry.TypesAnalyzed = true; if (!needToUpdate) { ModuleIntrinsics.Tracer.WriteLine("Existing cached info up-to-date. Skipping."); return; } exportedCommands.Clear(); exportedClasses.Clear(); } else { exportedCommands = new ConcurrentDictionary<string, CommandTypes>(3, realExportedCommands.Count, StringComparer.OrdinalIgnoreCase); exportedClasses = new ConcurrentDictionary<string, TypeAttributes>(1, realExportedClasses.Count, StringComparer.OrdinalIgnoreCase); moduleCacheEntry = new ModuleCacheEntry { ModulePath = module.Path, LastWriteTime = lastWriteTime, Commands = exportedCommands, TypesAnalyzed = true, Types = exportedClasses }; moduleCacheEntry = s_cacheData.Entries.GetOrAdd(module.Path, moduleCacheEntry); } // We need to update the cache foreach (var exportedCommand in realExportedCommands.Values) { ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", exportedCommand.Name); exportedCommands.GetOrAdd(exportedCommand.Name, exportedCommand.CommandType); } foreach (var pair in realExportedClasses) { var className = pair.Key; ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", className); moduleCacheEntry.Types.AddOrUpdate(className, pair.Value.TypeAttributes, (k, t) => t); } s_cacheData.QueueSerialization(); } private static void CallGetModuleDashList(ExecutionContext context, string modulePath) { CommandInfo commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand), null, null, context); Command getModuleCommand = new Command(commandInfo); try { PowerShell.Create(RunspaceMode.CurrentRunspace) .AddCommand(getModuleCommand) .AddParameter("List", true) .AddParameter("ErrorAction", ActionPreference.Ignore) .AddParameter("WarningAction", ActionPreference.Ignore) .AddParameter("InformationAction", ActionPreference.Ignore) .AddParameter("Verbose", false) .AddParameter("Debug", false) .AddParameter("Name", modulePath) .Invoke(); } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e); // Catch-all OK, third-party call-out. } } private static bool GetModuleEntryFromCache(string modulePath, out DateTime lastWriteTime, out ModuleCacheEntry moduleCacheEntry) { try { lastWriteTime = new FileInfo(modulePath).LastWriteTime; } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Exception checking LastWriteTime on module {0}: {1}", modulePath, e.Message); lastWriteTime = DateTime.MinValue; } if (s_cacheData.Entries.TryGetValue(modulePath, out moduleCacheEntry)) { if (lastWriteTime == moduleCacheEntry.LastWriteTime) { return true; } ModuleIntrinsics.Tracer.WriteLine("{0}: cache entry out of date, cached on {1}, last updated on {2}", modulePath, moduleCacheEntry.LastWriteTime, lastWriteTime); s_cacheData.Entries.TryRemove(modulePath, out moduleCacheEntry); } moduleCacheEntry = null; return false; } } internal class AnalysisCacheData { private static byte[] GetHeader() { return new byte[] { 0x50, 0x53, 0x4d, 0x4f, 0x44, 0x55, 0x4c, 0x45, 0x43, 0x41, 0x43, 0x48, 0x45, // PSMODULECACHE 0x01 // version # }; } // The last time the index was maintained. public DateTime LastReadTime { get; set; } public ConcurrentDictionary<string, ModuleCacheEntry> Entries { get; set; } private int _saveCacheToDiskQueued; private bool _saveCacheToDisk = true; public void QueueSerialization() { // We expect many modules to rapidly call for serialization. // Instead of doing it right away, we'll queue a task that starts writing // after it seems like we've stopped adding stuff to write out. This is // avoids blocking the pipeline thread waiting for the write to finish. // We want to make sure we only queue one task. if (_saveCacheToDisk && Interlocked.Increment(ref _saveCacheToDiskQueued) == 1) { Task.Run(async delegate { // Wait a while before assuming we've finished the updates, // writing the cache out in a timely matter isn't too important // now anyway. await Task.Delay(10000).ConfigureAwait(false); int counter1, counter2; do { // Check the counter a couple times with a delay, // if it's stable, then proceed with writing. counter1 = _saveCacheToDiskQueued; await Task.Delay(3000).ConfigureAwait(false); counter2 = _saveCacheToDiskQueued; } while (counter1 != counter2); Serialize(s_cacheStoreLocation); }); } } // Remove entries that are not needed anymore, e.g. if a module was removed. // If anything is removed, save the cache. private void Cleanup() { Diagnostics.Assert(Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null, "Caller to check environment variable before calling"); bool removedSomething = false; var keys = Entries.Keys; foreach (var key in keys) { if (!File.Exists(key)) { removedSomething |= Entries.TryRemove(key, out ModuleCacheEntry _); } } if (removedSomething) { QueueSerialization(); } } private static unsafe void Write(int val, byte[] bytes, FileStream stream) { Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array"); fixed (byte* b = bytes) *((int*)b) = val; stream.Write(bytes, 0, 4); } private static unsafe void Write(long val, byte[] bytes, FileStream stream) { Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array"); fixed (byte* b = bytes) *((long*)b) = val; stream.Write(bytes, 0, 8); } private static void Write(string val, byte[] bytes, FileStream stream) { Write(val.Length, bytes, stream); bytes = Encoding.UTF8.GetBytes(val); stream.Write(bytes, 0, bytes.Length); } private void Serialize(string filename) { AnalysisCacheData fromOtherProcess = null; Diagnostics.Assert(_saveCacheToDisk != false, "Serialize should never be called without going through QueueSerialization which has a check"); try { if (File.Exists(filename)) { var fileLastWriteTime = new FileInfo(filename).LastWriteTime; if (fileLastWriteTime > this.LastReadTime) { fromOtherProcess = Deserialize(filename); } } else { // Make sure the folder exists var folder = Path.GetDirectoryName(filename); if (!Directory.Exists(folder)) { try { Directory.CreateDirectory(folder); } catch (UnauthorizedAccessException) { // service accounts won't be able to create directory _saveCacheToDisk = false; return; } } } } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache {0}: {1} ", filename, e.Message); } if (fromOtherProcess != null) { // We should merge with what another process wrote so we don't clobber useful analysis foreach (var otherEntryPair in fromOtherProcess.Entries) { var otherModuleName = otherEntryPair.Key; var otherEntry = otherEntryPair.Value; ModuleCacheEntry thisEntry; if (Entries.TryGetValue(otherModuleName, out thisEntry)) { if (otherEntry.LastWriteTime > thisEntry.LastWriteTime) { // The other entry is newer, take it over ours Entries[otherModuleName] = otherEntry; } } else { Entries[otherModuleName] = otherEntry; } } } // "PSMODULECACHE" -> 13 bytes // byte ( 1 byte) -> version // int ( 4 bytes) -> count of entries // entries (?? bytes) -> all entries // // each entry is // DateTime ( 8 bytes) -> last write time for module file // int ( 4 bytes) -> path length // string (?? bytes) -> utf8 encoded path // int ( 4 bytes) -> count of commands // commands (?? bytes) -> all commands // int ( 4 bytes) -> count of types, -1 means unanalyzed (and 0 items serialized) // types (?? bytes) -> all types // // each command is // int ( 4 bytes) -> command name length // string (?? bytes) -> utf8 encoded command name // int ( 4 bytes) -> CommandTypes enum // // each type is // int ( 4 bytes) -> type name length // string (?? bytes) -> utf8 encoded type name // int ( 4 bytes) -> type attributes try { var bytes = new byte[8]; using (var stream = File.Create(filename)) { var headerBytes = GetHeader(); stream.Write(headerBytes, 0, headerBytes.Length); // Count of entries Write(Entries.Count, bytes, stream); foreach (var pair in Entries.ToArray()) { var path = pair.Key; var entry = pair.Value; // Module last write time Write(entry.LastWriteTime.Ticks, bytes, stream); // Module path Write(path, bytes, stream); // Commands var commandPairs = entry.Commands.ToArray(); Write(commandPairs.Length, bytes, stream); foreach (var command in commandPairs) { Write(command.Key, bytes, stream); Write((int)command.Value, bytes, stream); } // Types var typePairs = entry.Types.ToArray(); Write(entry.TypesAnalyzed ? typePairs.Length : -1, bytes, stream); foreach (var type in typePairs) { Write(type.Key, bytes, stream); Write((int)type.Value, bytes, stream); } } } // We just wrote the file, note this so we can detect writes from another process LastReadTime = new FileInfo(filename).LastWriteTime; } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Exception writing module analysis cache {0}: {1} ", filename, e.Message); } // Reset our counter so we can write again if asked. Interlocked.Exchange(ref _saveCacheToDiskQueued, 0); } private const string TruncatedErrorMessage = "module cache file appears truncated"; private const string InvalidSignatureErrorMessage = "module cache signature not valid"; private const string PossibleCorruptionErrorMessage = "possible corruption in module cache"; private static unsafe long ReadLong(FileStream stream, byte[] bytes) { Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array"); if (stream.Read(bytes, 0, 8) != 8) throw new Exception(TruncatedErrorMessage); fixed (byte* b = bytes) return *(long*)b; } private static unsafe int ReadInt(FileStream stream, byte[] bytes) { Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array"); if (stream.Read(bytes, 0, 4) != 4) throw new Exception(TruncatedErrorMessage); fixed (byte* b = bytes) return *(int*)b; } private static string ReadString(FileStream stream, ref byte[] bytes) { int length = ReadInt(stream, bytes); if (length > 10 * 1024) throw new Exception(PossibleCorruptionErrorMessage); if (length > bytes.Length) bytes = new byte[length]; if (stream.Read(bytes, 0, length) != length) throw new Exception(TruncatedErrorMessage); return Encoding.UTF8.GetString(bytes, 0, length); } private static void ReadHeader(FileStream stream, byte[] bytes) { var headerBytes = GetHeader(); var length = headerBytes.Length; Diagnostics.Assert(bytes.Length >= length, "must pass a large enough byte array"); if (stream.Read(bytes, 0, length) != length) throw new Exception(TruncatedErrorMessage); for (int i = 0; i < length; i++) { if (bytes[i] != headerBytes[i]) { throw new Exception(InvalidSignatureErrorMessage); } } // No need to return - we don't use it other than to detect the correct file format } public static AnalysisCacheData Deserialize(string filename) { using (var stream = File.OpenRead(filename)) { var result = new AnalysisCacheData { LastReadTime = DateTime.Now }; var bytes = new byte[1024]; // Header // "PSMODULECACHE" -> 13 bytes // byte ( 1 byte) -> version ReadHeader(stream, bytes); // int ( 4 bytes) -> count of entries int entries = ReadInt(stream, bytes); if (entries > 20 * 1024) throw new Exception(PossibleCorruptionErrorMessage); result.Entries = new ConcurrentDictionary<string, ModuleCacheEntry>(/*concurrency*/3, entries, StringComparer.OrdinalIgnoreCase); // entries (?? bytes) -> all entries while (entries > 0) { // DateTime ( 8 bytes) -> last write time for module file var lastWriteTime = new DateTime(ReadLong(stream, bytes)); // int ( 4 bytes) -> path length // string (?? bytes) -> utf8 encoded path var path = ReadString(stream, ref bytes); // int ( 4 bytes) -> count of commands var countItems = ReadInt(stream, bytes); if (countItems > 20 * 1024) throw new Exception(PossibleCorruptionErrorMessage); var commands = new ConcurrentDictionary<string, CommandTypes>(/*concurrency*/3, countItems, StringComparer.OrdinalIgnoreCase); // commands (?? bytes) -> all commands while (countItems > 0) { // int ( 4 bytes) -> command name length // string (?? bytes) -> utf8 encoded command name var commandName = ReadString(stream, ref bytes); // int ( 4 bytes) -> CommandTypes enum var commandTypes = (CommandTypes)ReadInt(stream, bytes); // Ignore empty entries (possible corruption in the cache or bug?) if (!string.IsNullOrWhiteSpace(commandName)) commands[commandName] = commandTypes; countItems -= 1; } // int ( 4 bytes) -> count of types countItems = ReadInt(stream, bytes); bool typesAnalyzed = countItems != -1; if (!typesAnalyzed) countItems = 0; if (countItems > 20 * 1024) throw new Exception(PossibleCorruptionErrorMessage); var types = new ConcurrentDictionary<string, TypeAttributes>(1, countItems, StringComparer.OrdinalIgnoreCase); // types (?? bytes) -> all types while (countItems > 0) { // int ( 4 bytes) -> type name length // string (?? bytes) -> utf8 encoded type name var typeName = ReadString(stream, ref bytes); // int ( 4 bytes) -> type attributes var typeAttributes = (TypeAttributes)ReadInt(stream, bytes); // Ignore empty entries (possible corruption in the cache or bug?) if (!string.IsNullOrWhiteSpace(typeName)) types[typeName] = typeAttributes; countItems -= 1; } var entry = new ModuleCacheEntry { ModulePath = path, LastWriteTime = lastWriteTime, Commands = commands, TypesAnalyzed = typesAnalyzed, Types = types }; result.Entries[path] = entry; entries -= 1; } if (Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null) { Task.Delay(10000).ContinueWith(_ => result.Cleanup()); } return result; } } internal static AnalysisCacheData Get() { int retryCount = 3; do { try { if (File.Exists(s_cacheStoreLocation)) { return Deserialize(s_cacheStoreLocation); } } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache: " + e.Message); if ((object)e.Message == (object)TruncatedErrorMessage || (object)e.Message == (object)InvalidSignatureErrorMessage || (object)e.Message == (object)PossibleCorruptionErrorMessage) { // Don't retry if we detected something is wrong with the file // (as opposed to the file being locked or something else) break; } } retryCount -= 1; Thread.Sleep(25); // Sleep a bit to give time for another process to finish writing the cache } while (retryCount > 0); return new AnalysisCacheData { LastReadTime = DateTime.Now, // Capacity set to 100 - a bit bigger than the # of modules on a default Win10 client machine // Concurrency=3 to not create too many locks, contention is unclear, but the old code had a single lock Entries = new ConcurrentDictionary<string, ModuleCacheEntry>(/*concurrency*/3, /*capacity*/100, StringComparer.OrdinalIgnoreCase) }; } private AnalysisCacheData() { } private static readonly string s_cacheStoreLocation; static AnalysisCacheData() { // If user defines a custom cache path, then use that. string userDefinedCachePath = Environment.GetEnvironmentVariable("PSModuleAnalysisCachePath"); if (!string.IsNullOrEmpty(userDefinedCachePath)) { s_cacheStoreLocation = userDefinedCachePath; return; } string cacheFileName = "ModuleAnalysisCache"; // When multiple copies of pwsh are on the system, they should use their own copy of the cache. // Append hash of `$PSHOME` to cacheFileName. string hashString = CRC32Hash.ComputeHash(Utils.DefaultPowerShellAppBase); cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString); if (ExperimentalFeature.EnabledExperimentalFeatureNames.Count > 0) { // If any experimental features are enabled, we cannot use the default cache file because those // features may expose commands that are not available in a regular powershell session, and we // should not cache those commands in the default cache file because that will result in wrong // auto-completion suggestions when the default cache file is used in another powershell session. // // Here we will generate a cache file name that represent the combination of enabled feature names. // We first convert enabled feature names to lower case, then we sort the feature names, and then // compute an CRC32 hash from the sorted feature names. We will use the CRC32 hash to generate the // cache file name. int index = 0; string[] featureNames = new string[ExperimentalFeature.EnabledExperimentalFeatureNames.Count]; foreach (string featureName in ExperimentalFeature.EnabledExperimentalFeatureNames) { featureNames[index++] = featureName.ToLowerInvariant(); } Array.Sort(featureNames); string allNames = string.Join(Environment.NewLine, featureNames); // Use CRC32 because it's faster. // It's very unlikely to get collision from hashing the combinations of enabled features names. hashString = CRC32Hash.ComputeHash(allNames); cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString); } #if UNIX s_cacheStoreLocation = Path.Combine(Platform.SelectProductNameForDirectory(Platform.XDG_Type.CACHE), cacheFileName); #else s_cacheStoreLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\PowerShell", cacheFileName); #endif } } [DebuggerDisplay("ModulePath = {ModulePath}")] internal class ModuleCacheEntry { public DateTime LastWriteTime; public string ModulePath; public bool TypesAnalyzed; public ConcurrentDictionary<string, CommandTypes> Commands; public ConcurrentDictionary<string, TypeAttributes> Types; } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { /// <summary> /// Gets formatting information from the loading format information database. /// </summary> /// <remarks>Currently supports only table controls /// </remarks> [Cmdlet(VerbsCommon.Get, "FormatData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096614")] [OutputType(typeof(System.Management.Automation.ExtendedTypeDefinition))] public class GetFormatDataCommand : PSCmdlet { private string[] _typename; private WildcardPattern[] _filter = new WildcardPattern[1]; /// <summary> /// Get Formatting information only for the specified typename. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [ValidateNotNullOrEmpty] [Parameter(Position = 0)] public string[] TypeName { get { return _typename; } set { _typename = value; if (_typename == null) { _filter = Array.Empty<WildcardPattern>(); } else { _filter = new WildcardPattern[_typename.Length]; for (int i = 0; i < _filter.Length; i++) { _filter[i] = WildcardPattern.Get(_typename[i], WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } } } /// <summary> /// When specified, helps control whether or not to send richer formatting data /// that was not supported by earlier versions of PowerShell. /// </summary> [Parameter] public Version PowerShellVersion { get; set; } /// <summary> /// Set the default filter. /// </summary> protected override void BeginProcessing() { if (_filter[0] == null) { _filter[0] = WildcardPattern.Get("*", WildcardOptions.None); } } private static Dictionary<string, List<string>> GetTypeGroupMap(IEnumerable<TypeGroupDefinition> groupDefinitions) { var typeGroupMap = new Dictionary<string, List<string>>(); foreach (TypeGroupDefinition typeGroup in groupDefinitions) { // The format system actually allows you to define multiple SelectionSets with the same name, but only the // first type group will take effect. So we skip the rest groups that have the same name. if (!typeGroupMap.ContainsKey(typeGroup.name)) { var typesInGroup = typeGroup.typeReferenceList.ConvertAll(static typeReference => typeReference.name); typeGroupMap.Add(typeGroup.name, typesInGroup); } } return typeGroupMap; } /// <summary> /// Takes out the content from the database and writes them out. /// </summary> protected override void ProcessRecord() { // Remoting detection: // * Automatic variable $PSSenderInfo is defined in true remoting contexts as well as in background jobs. // * $PSSenderInfo.ApplicationArguments.PSVersionTable.PSVersion contains the client version, as a [version] instance. // Note: Even though $PSVersionTable.PSVersion is of type [semver] in PowerShell 6+, it is of type [version] here, // presumably because only the latter type deserializes type-faithfully. var clientVersion = PowerShellVersion; PSSenderInfo remotingClientInfo = GetVariableValue("PSSenderInfo") as PSSenderInfo; if (clientVersion == null && remotingClientInfo != null) { clientVersion = PSObject.Base((PSObject.Base(remotingClientInfo.ApplicationArguments["PSVersionTable"]) as PSPrimitiveDictionary)?["PSVersion"]) as Version; } // During remoting, remain compatible with v5.0- clients by default. // Passing a -PowerShellVersion argument allows overriding the client version. bool writeOldWay = (remotingClientInfo != null && clientVersion == null) // To be safe: Remoting client version could unexpectedly not be determined. || (clientVersion != null && (clientVersion.Major < 5 || (clientVersion.Major == 5 && clientVersion.Minor < 1))); TypeInfoDataBase db = this.Context.FormatDBManager.Database; List<ViewDefinition> viewdefinitions = db.viewDefinitionsSection.viewDefinitionList; Dictionary<string, List<string>> typeGroupMap = GetTypeGroupMap(db.typeGroupSection.typeGroupDefinitionList); var typedefs = new Dictionary<ConsolidatedString, List<FormatViewDefinition>>(ConsolidatedString.EqualityComparer); foreach (ViewDefinition definition in viewdefinitions) { if (definition.isHelpFormatter) continue; var consolidatedTypeName = CreateConsolidatedTypeName(definition, typeGroupMap); if (!ShouldGenerateView(consolidatedTypeName)) continue; PSControl control; var tableControlBody = definition.mainControl as TableControlBody; if (tableControlBody != null) { control = new TableControl(tableControlBody, definition); } else { var listControlBody = definition.mainControl as ListControlBody; if (listControlBody != null) { control = new ListControl(listControlBody, definition); } else { var wideControlBody = definition.mainControl as WideControlBody; if (wideControlBody != null) { control = new WideControl(wideControlBody, definition); if (writeOldWay) { // Alignment was added to WideControl in V2, but wasn't // used. It was removed in V5, but old PowerShell clients // expect this property or fail to rehydrate the remote object. var psobj = new PSObject(control); psobj.Properties.Add(new PSNoteProperty("Alignment", 0)); } } else { var complexControlBody = (ComplexControlBody)definition.mainControl; control = new CustomControl(complexControlBody, definition); } } } // Older version of PowerShell do not know about something in the control, so // don't return it. if (writeOldWay && !control.CompatibleWithOldPowerShell()) continue; var formatdef = new FormatViewDefinition(definition.name, control, definition.InstanceId); List<FormatViewDefinition> viewList; if (!typedefs.TryGetValue(consolidatedTypeName, out viewList)) { viewList = new List<FormatViewDefinition>(); typedefs.Add(consolidatedTypeName, viewList); } viewList.Add(formatdef); } // write out all the available type definitions foreach (var pair in typedefs) { var typeNames = pair.Key; if (writeOldWay) { foreach (var typeName in typeNames) { var etd = new ExtendedTypeDefinition(typeName, pair.Value); WriteObject(etd); } } else { var etd = new ExtendedTypeDefinition(typeNames[0], pair.Value); for (int i = 1; i < typeNames.Count; i++) { etd.TypeNames.Add(typeNames[i]); } WriteObject(etd); } } } private static ConsolidatedString CreateConsolidatedTypeName(ViewDefinition definition, Dictionary<string, List<string>> typeGroupMap) { // Create our "consolidated string" typename which is used as a dictionary key var reflist = definition.appliesTo.referenceList; var consolidatedTypeName = new ConsolidatedString(ConsolidatedString.Empty); foreach (TypeOrGroupReference item in reflist) { // If it's a TypeGroup, we need to look that up and add it's members if (item is TypeGroupReference) { List<string> typesInGroup; if (typeGroupMap.TryGetValue(item.name, out typesInGroup)) { foreach (string typeName in typesInGroup) { consolidatedTypeName.Add(typeName); } } } else { consolidatedTypeName.Add(item.name); } } return consolidatedTypeName; } private bool ShouldGenerateView(ConsolidatedString consolidatedTypeName) { foreach (WildcardPattern pattern in _filter) { foreach (var typeName in consolidatedTypeName) { if (pattern.IsMatch(typeName)) { return true; } } } return false; } } }
namespace AgileObjects.AgileMapper.UnitTests.Configuration.MemberIgnores { using System; using System.Collections.Generic; using System.Linq; using AgileMapper.Configuration; using AgileMapper.Configuration.MemberIgnores; using Common; using NetStandardPolyfills; using TestClasses; #if !NET35 using Xunit; #else using Fact = NUnit.Framework.TestAttribute; [NUnit.Framework.TestFixture] #endif public class WhenIgnoringMembers { [Fact] public void ShouldIgnoreAConfiguredMember() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<PersonViewModel>() .ToANew<Person>() .Ignore(pvm => pvm.Name); var source = new PersonViewModel { Name = "Jon" }; var result = mapper.Map(source).ToANew<Person>(); result.Name.ShouldBeNull(); } } [Fact] public void ShouldIgnoreAConfiguredMemberInARootCollection() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<Person>() .Over<Person>() .Ignore(p => p.Address); var source = new[] { new Person { Name = "Jon", Address = new Address { Line1 = "Blah" } } }; var target = new[] { new Person() }; var result = mapper.Map(source).Over(target); result.Length.ShouldBe(1); result.First().Address.ShouldBeNull(); } } [Fact] public void ShouldIgnoreAConfiguredMemberConditionally() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<PersonViewModel>() .ToANew<Person>() .If(ctx => ctx.Source.Name == "Bilbo") .Ignore(x => x.Name); var matchingSource = new PersonViewModel { Name = "Bilbo" }; var matchingResult = mapper.Map(matchingSource).ToANew<Person>(); matchingResult.Name.ShouldBeNull(); var nonMatchingSource = new PersonViewModel { Name = "Frodo" }; var nonMatchingResult = mapper.Map(nonMatchingSource).ToANew<Person>(); nonMatchingResult.Name.ShouldBe("Frodo"); } } [Fact] public void ShouldIgnoreAConfiguredMemberForASpecifiedRuleSetConditionally() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<PersonViewModel>() .OnTo<Address>() .If(ctx => ctx.Source.Name == "Gandalf") .Ignore(a => a.Line1); var source = new PersonViewModel { Name = "Gandalf", AddressLine1 = "??" }; var onToResult = mapper.Map(source).OnTo(new Person { Address = new Address() }); onToResult.Name.ShouldBe("Gandalf"); onToResult.Address.Line1.ShouldBeNull(); var createNewResult = mapper.Map(source).ToANew<Person>(); createNewResult.Name.ShouldBe("Gandalf"); createNewResult.Address.Line1.ShouldBe("??"); } } [Fact] public void ShouldIgnoreMultipleConfiguredMembers() { using (var mapper = Mapper.CreateNew()) { var source = new { Id = Guid.NewGuid().ToString(), Name = "Bilbo", AddressLine1 = "House Street", AddressLine2 = "Town City" }; mapper.WhenMapping .From(source) .ToANew<Person>() .Ignore(p => p.Name, p => p.Address.Line1); var matchingResult = mapper.Map(source).ToANew<Person>(); matchingResult.Id.ToString().ShouldBe(source.Id); matchingResult.Name.ShouldBeNull(); matchingResult.Address.ShouldNotBeNull(); matchingResult.Address.Line1.ShouldBeNull(); matchingResult.Address.Line2.ShouldBe("Town City"); } } [Fact] public void ShouldIgnoreAConfiguredMemberInACollectionConditionally() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<PersonViewModel>() .ToANew<Person>() .If(ctx => ctx.Source.Name.StartsWith("F")) .Ignore(p => p.Name); var source = new[] { new PersonViewModel { Name = "Bilbo" }, new PersonViewModel { Name = "Frodo" } }; var result = mapper.Map(source).ToANew<IEnumerable<Person>>(); result.Count().ShouldBe(2); result.First().Name.ShouldBe("Bilbo"); result.Second().Name.ShouldBeNull(); } } [Fact] public void ShouldIgnoreAConfiguredMemberByEnumerableElementConditionally() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<PublicProperty<int>>() .ToANew<PublicProperty<string>>() .If(ctx => ctx.ElementIndex > 0) .Ignore(p => p.Value); var source = new[] { new PublicProperty<int> { Value = 123 }, new PublicProperty<int> { Value = 456 } }; var result = mapper.Map(source).ToANew<IEnumerable<PublicProperty<string>>>(); result.Count().ShouldBe(2); result.First().Value.ShouldBe("123"); result.Second().Value.ShouldBeNull(); } } [Fact] public void ShouldIgnoreAReadOnlyComplexTypeMember() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .To<PublicReadOnlyProperty<Address>>() .Ignore(psm => psm.Value); var source = new PublicField<Address> { Value = new Address { Line1 = "Use this!" } }; var target = new PublicReadOnlyProperty<Address>(new Address { Line1 = "Ignore this!" }); mapper.Map(source).Over(target); target.Value.Line1.ShouldBe("Ignore this!"); } } [Fact] public void ShouldSupportRedundantIgnoreConflictingWithConditionalIgnore() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<Person>() .To<PersonViewModel>() .If((p, pvm) => p.Name == "Frank") .Ignore(pvm => pvm.Name); mapper.WhenMapping .From<Customer>() .To<CustomerViewModel>() .Ignore(cvm => cvm.Name); var matchingPersonResult = mapper.Map(new Person { Name = "Frank" }).ToANew<PersonViewModel>(); matchingPersonResult.Name.ShouldBeNull(); var nonMatchingPersonResult = mapper.Map(new Person { Name = "Dennis" }).ToANew<PersonViewModel>(); nonMatchingPersonResult.Name.ShouldBe("Dennis"); var customerResult = mapper.Map(new Customer { Name = "Mac" }).ToANew<CustomerViewModel>(); customerResult.Name.ShouldBeNull(); } } [Fact] public void ShouldSupportRedundantConditionalIgnoreConflictingWithIgnore() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<Person>() .To<PersonViewModel>() .Ignore(pvm => pvm.Name); mapper.WhenMapping .From<Customer>() .To<CustomerViewModel>() .If((c, cvm) => c.Name == "Frank") .Ignore(cvm => cvm.Name); var personResult = mapper.Map(new Person { Name = "Dennis" }).ToANew<PersonViewModel>(); var matchingCustomerResult = mapper.Map(new Customer { Name = "Mac" }).ToANew<CustomerViewModel>(); var nonMatchingCustomerResult = mapper.Map(new Customer { Name = "Frank" }).ToANew<CustomerViewModel>(); personResult.Name.ShouldBeNull(); matchingCustomerResult.Name.ShouldBe("Mac"); nonMatchingCustomerResult.Name.ShouldBeNull(); } } [Fact] public void ShouldSupportSamePathIgnoredMembersWithDifferentSourceTypes() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<PublicField<int>>() .To<PublicProperty<int>>() .Ignore(pp => pp.Value); mapper.WhenMapping .From<PublicGetMethod<int>>() .To<PublicProperty<int>>() .Ignore(pp => pp.Value); } } [Fact] public void ShouldSupportSamePathIgnoredMembersWithDifferentTargetTypes() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<Person>() .To<PersonViewModel>() .Ignore(x => x.Name); mapper.WhenMapping .From<PersonViewModel>() .To<Person>() .Ignore(x => x.Name); } } // See https://github.com/agileobjects/AgileMapper/issues/183 [Fact] public void ShouldIgnoreBaseClassSourcesOnly() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping.ThrowIfAnyMappingPlanIsIncomplete(); mapper.WhenMapping .From<Issue183.ThingBase>().ButNotDerivedTypes .To<Issue183.ThingDto>() .Ignore(t => t.Value); var source = new PublicField<Issue183.ThingBase> { Value = new Issue183.Thing { Value = "From the source!" } }; var result = mapper.Map(source).ToANew<PublicField<Issue183.ThingBaseDto>>(); result.ShouldNotBeNull() .Value .ShouldNotBeNull() .ShouldBeOfType<Issue183.ThingDto>() .Value.ShouldBe("From the source!"); } } [Fact] public void ShouldCompareIgnoredMembersConsistently() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping.To<PublicField<string>>().Ignore(pf => pf.Value); mapper.WhenMapping.To<PublicProperty<string>>().Ignore(pp => pp.Value); var configurations = ((IMapperInternal)mapper).Context.UserConfigurations; var ignoredMembersProperty = configurations.GetType().GetNonPublicInstanceProperty("IgnoredMembers"); var ignoredMembersValue = ignoredMembersProperty.GetValue(configurations, Enumerable<object>.EmptyArray); var ignoredMembers = (IList<ConfiguredMemberIgnoreBase>)ignoredMembersValue; ignoredMembers.Count.ShouldBe(2); var ignore1 = (IComparable<UserConfiguredItemBase>)ignoredMembers.First(); var ignore2 = (IComparable<UserConfiguredItemBase>)ignoredMembers.Second(); var compareResult1 = ignore1.CompareTo(ignoredMembers.Second()); var compareResult2 = ignore2.CompareTo(ignoredMembers.First()); compareResult1.ShouldNotBe(compareResult2); } } #region Helper Classes public static class Issue183 { public abstract class ThingBase { } public class Thing : ThingBase { public string Value { get; set; } } public abstract class ThingBaseDto { } public class ThingDto : ThingBaseDto { public string Value { get; set; } } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery.Models { /// <summary> /// The properties of a Job object. /// </summary> public partial class JobProperties : ResourceBaseExtended { private string _activityId; /// <summary> /// Required. Activity Id. /// </summary> public string ActivityId { get { return this._activityId; } set { this._activityId = value; } } private IList<string> _allowedActions; /// <summary> /// Required. Allowed action. /// </summary> public IList<string> AllowedActions { get { return this._allowedActions; } set { this._allowedActions = value; } } private JobDetails _customDetails; /// <summary> /// Required. Custom details about the job. /// </summary> public JobDetails CustomDetails { get { return this._customDetails; } set { this._customDetails = value; } } private System.DateTime? _endTime; /// <summary> /// Required. End time stamp. /// </summary> public System.DateTime? EndTime { get { return this._endTime; } set { this._endTime = value; } } private IList<JobErrorDetails> _errors; /// <summary> /// Required. List of errors. /// </summary> public IList<JobErrorDetails> Errors { get { return this._errors; } set { this._errors = value; } } private string _friendlyName; /// <summary> /// Required. Display name. /// </summary> public string FriendlyName { get { return this._friendlyName; } set { this._friendlyName = value; } } private string _scenarioName; /// <summary> /// Required. Scenario name. /// </summary> public string ScenarioName { get { return this._scenarioName; } set { this._scenarioName = value; } } private System.DateTime? _startTime; /// <summary> /// Required. Start time stamp. /// </summary> public System.DateTime? StartTime { get { return this._startTime; } set { this._startTime = value; } } private string _state; /// <summary> /// Required. Current State of the job. Example: "In Progress", /// "Cancelled" /// </summary> public string State { get { return this._state; } set { this._state = value; } } private string _stateDescription; /// <summary> /// Required. Description of the current state. It shows the detailed /// state of the job. /// </summary> public string StateDescription { get { return this._stateDescription; } set { this._stateDescription = value; } } private string _targetInstanceType; /// <summary> /// Required. Affected ObjectT ype. /// </summary> public string TargetInstanceType { get { return this._targetInstanceType; } set { this._targetInstanceType = value; } } private string _targetObjectId; /// <summary> /// Required. Affected ObjectId. /// </summary> public string TargetObjectId { get { return this._targetObjectId; } set { this._targetObjectId = value; } } private string _targetObjectName; /// <summary> /// Required. Affected object name. /// </summary> public string TargetObjectName { get { return this._targetObjectName; } set { this._targetObjectName = value; } } private IList<AsrTask> _tasks; /// <summary> /// Required. Tasks of the job object. /// </summary> public IList<AsrTask> Tasks { get { return this._tasks; } set { this._tasks = value; } } /// <summary> /// Initializes a new instance of the JobProperties class. /// </summary> public JobProperties() { this.AllowedActions = new LazyList<string>(); this.Errors = new LazyList<JobErrorDetails>(); this.Tasks = new LazyList<AsrTask>(); } } }
/* * Copyright 2006 Jeremias Maerki in part, and ZXing Authors in part * * 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. */ /* * This file has been modified from its original form in Barcode4J. */ using System; using System.Text; using ZXing.Writer; namespace ZXing.PDF417.Internal { /// <summary> /// Top-level class for the logic part of the PDF417 implementation. /// </summary> internal sealed class PDF417 { /// <summary> /// The start pattern (17 bits) /// </summary> private const int START_PATTERN = 0x1fea8; /// <summary> /// The stop pattern (18 bits) /// </summary> private const int STOP_PATTERN = 0x3fa29; /// <summary> /// The codeword table from the Annex A of ISO/IEC 15438:2001(E). /// </summary> private static readonly int[][] CODEWORD_TABLE = { new[] { 0x1d5c0, 0x1eaf0, 0x1f57c, 0x1d4e0, 0x1ea78, 0x1f53e, 0x1a8c0, 0x1d470, 0x1a860, 0x15040, 0x1a830, 0x15020, 0x1adc0, 0x1d6f0, 0x1eb7c, 0x1ace0, 0x1d678, 0x1eb3e, 0x158c0, 0x1ac70, 0x15860, 0x15dc0, 0x1aef0, 0x1d77c, 0x15ce0, 0x1ae78, 0x1d73e, 0x15c70, 0x1ae3c, 0x15ef0, 0x1af7c, 0x15e78, 0x1af3e, 0x15f7c, 0x1f5fa, 0x1d2e0, 0x1e978, 0x1f4be, 0x1a4c0, 0x1d270, 0x1e93c, 0x1a460, 0x1d238, 0x14840, 0x1a430, 0x1d21c, 0x14820, 0x1a418, 0x14810, 0x1a6e0, 0x1d378, 0x1e9be, 0x14cc0, 0x1a670, 0x1d33c, 0x14c60, 0x1a638, 0x1d31e, 0x14c30, 0x1a61c, 0x14ee0, 0x1a778, 0x1d3be, 0x14e70, 0x1a73c, 0x14e38, 0x1a71e, 0x14f78, 0x1a7be, 0x14f3c, 0x14f1e, 0x1a2c0, 0x1d170, 0x1e8bc, 0x1a260, 0x1d138, 0x1e89e, 0x14440, 0x1a230, 0x1d11c, 0x14420, 0x1a218, 0x14410, 0x14408, 0x146c0, 0x1a370, 0x1d1bc, 0x14660, 0x1a338, 0x1d19e, 0x14630, 0x1a31c, 0x14618, 0x1460c, 0x14770, 0x1a3bc, 0x14738, 0x1a39e, 0x1471c, 0x147bc, 0x1a160, 0x1d0b8, 0x1e85e, 0x14240, 0x1a130, 0x1d09c, 0x14220, 0x1a118, 0x1d08e, 0x14210, 0x1a10c, 0x14208, 0x1a106, 0x14360, 0x1a1b8, 0x1d0de, 0x14330, 0x1a19c, 0x14318, 0x1a18e, 0x1430c, 0x14306, 0x1a1de, 0x1438e, 0x14140, 0x1a0b0, 0x1d05c, 0x14120, 0x1a098, 0x1d04e, 0x14110, 0x1a08c, 0x14108, 0x1a086, 0x14104, 0x141b0, 0x14198, 0x1418c, 0x140a0, 0x1d02e, 0x1a04c, 0x1a046, 0x14082, 0x1cae0, 0x1e578, 0x1f2be, 0x194c0, 0x1ca70, 0x1e53c, 0x19460, 0x1ca38, 0x1e51e, 0x12840, 0x19430, 0x12820, 0x196e0, 0x1cb78, 0x1e5be, 0x12cc0, 0x19670, 0x1cb3c, 0x12c60, 0x19638, 0x12c30, 0x12c18, 0x12ee0, 0x19778, 0x1cbbe, 0x12e70, 0x1973c, 0x12e38, 0x12e1c, 0x12f78, 0x197be, 0x12f3c, 0x12fbe, 0x1dac0, 0x1ed70, 0x1f6bc, 0x1da60, 0x1ed38, 0x1f69e, 0x1b440, 0x1da30, 0x1ed1c, 0x1b420, 0x1da18, 0x1ed0e, 0x1b410, 0x1da0c, 0x192c0, 0x1c970, 0x1e4bc, 0x1b6c0, 0x19260, 0x1c938, 0x1e49e, 0x1b660, 0x1db38, 0x1ed9e, 0x16c40, 0x12420, 0x19218, 0x1c90e, 0x16c20, 0x1b618, 0x16c10, 0x126c0, 0x19370, 0x1c9bc, 0x16ec0, 0x12660, 0x19338, 0x1c99e, 0x16e60, 0x1b738, 0x1db9e, 0x16e30, 0x12618, 0x16e18, 0x12770, 0x193bc, 0x16f70, 0x12738, 0x1939e, 0x16f38, 0x1b79e, 0x16f1c, 0x127bc, 0x16fbc, 0x1279e, 0x16f9e, 0x1d960, 0x1ecb8, 0x1f65e, 0x1b240, 0x1d930, 0x1ec9c, 0x1b220, 0x1d918, 0x1ec8e, 0x1b210, 0x1d90c, 0x1b208, 0x1b204, 0x19160, 0x1c8b8, 0x1e45e, 0x1b360, 0x19130, 0x1c89c, 0x16640, 0x12220, 0x1d99c, 0x1c88e, 0x16620, 0x12210, 0x1910c, 0x16610, 0x1b30c, 0x19106, 0x12204, 0x12360, 0x191b8, 0x1c8de, 0x16760, 0x12330, 0x1919c, 0x16730, 0x1b39c, 0x1918e, 0x16718, 0x1230c, 0x12306, 0x123b8, 0x191de, 0x167b8, 0x1239c, 0x1679c, 0x1238e, 0x1678e, 0x167de, 0x1b140, 0x1d8b0, 0x1ec5c, 0x1b120, 0x1d898, 0x1ec4e, 0x1b110, 0x1d88c, 0x1b108, 0x1d886, 0x1b104, 0x1b102, 0x12140, 0x190b0, 0x1c85c, 0x16340, 0x12120, 0x19098, 0x1c84e, 0x16320, 0x1b198, 0x1d8ce, 0x16310, 0x12108, 0x19086, 0x16308, 0x1b186, 0x16304, 0x121b0, 0x190dc, 0x163b0, 0x12198, 0x190ce, 0x16398, 0x1b1ce, 0x1638c, 0x12186, 0x16386, 0x163dc, 0x163ce, 0x1b0a0, 0x1d858, 0x1ec2e, 0x1b090, 0x1d84c, 0x1b088, 0x1d846, 0x1b084, 0x1b082, 0x120a0, 0x19058, 0x1c82e, 0x161a0, 0x12090, 0x1904c, 0x16190, 0x1b0cc, 0x19046, 0x16188, 0x12084, 0x16184, 0x12082, 0x120d8, 0x161d8, 0x161cc, 0x161c6, 0x1d82c, 0x1d826, 0x1b042, 0x1902c, 0x12048, 0x160c8, 0x160c4, 0x160c2, 0x18ac0, 0x1c570, 0x1e2bc, 0x18a60, 0x1c538, 0x11440, 0x18a30, 0x1c51c, 0x11420, 0x18a18, 0x11410, 0x11408, 0x116c0, 0x18b70, 0x1c5bc, 0x11660, 0x18b38, 0x1c59e, 0x11630, 0x18b1c, 0x11618, 0x1160c, 0x11770, 0x18bbc, 0x11738, 0x18b9e, 0x1171c, 0x117bc, 0x1179e, 0x1cd60, 0x1e6b8, 0x1f35e, 0x19a40, 0x1cd30, 0x1e69c, 0x19a20, 0x1cd18, 0x1e68e, 0x19a10, 0x1cd0c, 0x19a08, 0x1cd06, 0x18960, 0x1c4b8, 0x1e25e, 0x19b60, 0x18930, 0x1c49c, 0x13640, 0x11220, 0x1cd9c, 0x1c48e, 0x13620, 0x19b18, 0x1890c, 0x13610, 0x11208, 0x13608, 0x11360, 0x189b8, 0x1c4de, 0x13760, 0x11330, 0x1cdde, 0x13730, 0x19b9c, 0x1898e, 0x13718, 0x1130c, 0x1370c, 0x113b8, 0x189de, 0x137b8, 0x1139c, 0x1379c, 0x1138e, 0x113de, 0x137de, 0x1dd40, 0x1eeb0, 0x1f75c, 0x1dd20, 0x1ee98, 0x1f74e, 0x1dd10, 0x1ee8c, 0x1dd08, 0x1ee86, 0x1dd04, 0x19940, 0x1ccb0, 0x1e65c, 0x1bb40, 0x19920, 0x1eedc, 0x1e64e, 0x1bb20, 0x1dd98, 0x1eece, 0x1bb10, 0x19908, 0x1cc86, 0x1bb08, 0x1dd86, 0x19902, 0x11140, 0x188b0, 0x1c45c, 0x13340, 0x11120, 0x18898, 0x1c44e, 0x17740, 0x13320, 0x19998, 0x1ccce, 0x17720, 0x1bb98, 0x1ddce, 0x18886, 0x17710, 0x13308, 0x19986, 0x17708, 0x11102, 0x111b0, 0x188dc, 0x133b0, 0x11198, 0x188ce, 0x177b0, 0x13398, 0x199ce, 0x17798, 0x1bbce, 0x11186, 0x13386, 0x111dc, 0x133dc, 0x111ce, 0x177dc, 0x133ce, 0x1dca0, 0x1ee58, 0x1f72e, 0x1dc90, 0x1ee4c, 0x1dc88, 0x1ee46, 0x1dc84, 0x1dc82, 0x198a0, 0x1cc58, 0x1e62e, 0x1b9a0, 0x19890, 0x1ee6e, 0x1b990, 0x1dccc, 0x1cc46, 0x1b988, 0x19884, 0x1b984, 0x19882, 0x1b982, 0x110a0, 0x18858, 0x1c42e, 0x131a0, 0x11090, 0x1884c, 0x173a0, 0x13190, 0x198cc, 0x18846, 0x17390, 0x1b9cc, 0x11084, 0x17388, 0x13184, 0x11082, 0x13182, 0x110d8, 0x1886e, 0x131d8, 0x110cc, 0x173d8, 0x131cc, 0x110c6, 0x173cc, 0x131c6, 0x110ee, 0x173ee, 0x1dc50, 0x1ee2c, 0x1dc48, 0x1ee26, 0x1dc44, 0x1dc42, 0x19850, 0x1cc2c, 0x1b8d0, 0x19848, 0x1cc26, 0x1b8c8, 0x1dc66, 0x1b8c4, 0x19842, 0x1b8c2, 0x11050, 0x1882c, 0x130d0, 0x11048, 0x18826, 0x171d0, 0x130c8, 0x19866, 0x171c8, 0x1b8e6, 0x11042, 0x171c4, 0x130c2, 0x171c2, 0x130ec, 0x171ec, 0x171e6, 0x1ee16, 0x1dc22, 0x1cc16, 0x19824, 0x19822, 0x11028, 0x13068, 0x170e8, 0x11022, 0x13062, 0x18560, 0x10a40, 0x18530, 0x10a20, 0x18518, 0x1c28e, 0x10a10, 0x1850c, 0x10a08, 0x18506, 0x10b60, 0x185b8, 0x1c2de, 0x10b30, 0x1859c, 0x10b18, 0x1858e, 0x10b0c, 0x10b06, 0x10bb8, 0x185de, 0x10b9c, 0x10b8e, 0x10bde, 0x18d40, 0x1c6b0, 0x1e35c, 0x18d20, 0x1c698, 0x18d10, 0x1c68c, 0x18d08, 0x1c686, 0x18d04, 0x10940, 0x184b0, 0x1c25c, 0x11b40, 0x10920, 0x1c6dc, 0x1c24e, 0x11b20, 0x18d98, 0x1c6ce, 0x11b10, 0x10908, 0x18486, 0x11b08, 0x18d86, 0x10902, 0x109b0, 0x184dc, 0x11bb0, 0x10998, 0x184ce, 0x11b98, 0x18dce, 0x11b8c, 0x10986, 0x109dc, 0x11bdc, 0x109ce, 0x11bce, 0x1cea0, 0x1e758, 0x1f3ae, 0x1ce90, 0x1e74c, 0x1ce88, 0x1e746, 0x1ce84, 0x1ce82, 0x18ca0, 0x1c658, 0x19da0, 0x18c90, 0x1c64c, 0x19d90, 0x1cecc, 0x1c646, 0x19d88, 0x18c84, 0x19d84, 0x18c82, 0x19d82, 0x108a0, 0x18458, 0x119a0, 0x10890, 0x1c66e, 0x13ba0, 0x11990, 0x18ccc, 0x18446, 0x13b90, 0x19dcc, 0x10884, 0x13b88, 0x11984, 0x10882, 0x11982, 0x108d8, 0x1846e, 0x119d8, 0x108cc, 0x13bd8, 0x119cc, 0x108c6, 0x13bcc, 0x119c6, 0x108ee, 0x119ee, 0x13bee, 0x1ef50, 0x1f7ac, 0x1ef48, 0x1f7a6, 0x1ef44, 0x1ef42, 0x1ce50, 0x1e72c, 0x1ded0, 0x1ef6c, 0x1e726, 0x1dec8, 0x1ef66, 0x1dec4, 0x1ce42, 0x1dec2, 0x18c50, 0x1c62c, 0x19cd0, 0x18c48, 0x1c626, 0x1bdd0, 0x19cc8, 0x1ce66, 0x1bdc8, 0x1dee6, 0x18c42, 0x1bdc4, 0x19cc2, 0x1bdc2, 0x10850, 0x1842c, 0x118d0, 0x10848, 0x18426, 0x139d0, 0x118c8, 0x18c66, 0x17bd0, 0x139c8, 0x19ce6, 0x10842, 0x17bc8, 0x1bde6, 0x118c2, 0x17bc4, 0x1086c, 0x118ec, 0x10866, 0x139ec, 0x118e6, 0x17bec, 0x139e6, 0x17be6, 0x1ef28, 0x1f796, 0x1ef24, 0x1ef22, 0x1ce28, 0x1e716, 0x1de68, 0x1ef36, 0x1de64, 0x1ce22, 0x1de62, 0x18c28, 0x1c616, 0x19c68, 0x18c24, 0x1bce8, 0x19c64, 0x18c22, 0x1bce4, 0x19c62, 0x1bce2, 0x10828, 0x18416, 0x11868, 0x18c36, 0x138e8, 0x11864, 0x10822, 0x179e8, 0x138e4, 0x11862, 0x179e4, 0x138e2, 0x179e2, 0x11876, 0x179f6, 0x1ef12, 0x1de34, 0x1de32, 0x19c34, 0x1bc74, 0x1bc72, 0x11834, 0x13874, 0x178f4, 0x178f2, 0x10540, 0x10520, 0x18298, 0x10510, 0x10508, 0x10504, 0x105b0, 0x10598, 0x1058c, 0x10586, 0x105dc, 0x105ce, 0x186a0, 0x18690, 0x1c34c, 0x18688, 0x1c346, 0x18684, 0x18682, 0x104a0, 0x18258, 0x10da0, 0x186d8, 0x1824c, 0x10d90, 0x186cc, 0x10d88, 0x186c6, 0x10d84, 0x10482, 0x10d82, 0x104d8, 0x1826e, 0x10dd8, 0x186ee, 0x10dcc, 0x104c6, 0x10dc6, 0x104ee, 0x10dee, 0x1c750, 0x1c748, 0x1c744, 0x1c742, 0x18650, 0x18ed0, 0x1c76c, 0x1c326, 0x18ec8, 0x1c766, 0x18ec4, 0x18642, 0x18ec2, 0x10450, 0x10cd0, 0x10448, 0x18226, 0x11dd0, 0x10cc8, 0x10444, 0x11dc8, 0x10cc4, 0x10442, 0x11dc4, 0x10cc2, 0x1046c, 0x10cec, 0x10466, 0x11dec, 0x10ce6, 0x11de6, 0x1e7a8, 0x1e7a4, 0x1e7a2, 0x1c728, 0x1cf68, 0x1e7b6, 0x1cf64, 0x1c722, 0x1cf62, 0x18628, 0x1c316, 0x18e68, 0x1c736, 0x19ee8, 0x18e64, 0x18622, 0x19ee4, 0x18e62, 0x19ee2, 0x10428, 0x18216, 0x10c68, 0x18636, 0x11ce8, 0x10c64, 0x10422, 0x13de8, 0x11ce4, 0x10c62, 0x13de4, 0x11ce2, 0x10436, 0x10c76, 0x11cf6, 0x13df6, 0x1f7d4, 0x1f7d2, 0x1e794, 0x1efb4, 0x1e792, 0x1efb2, 0x1c714, 0x1cf34, 0x1c712, 0x1df74, 0x1cf32, 0x1df72, 0x18614, 0x18e34, 0x18612, 0x19e74, 0x18e32, 0x1bef4 }, new[] { 0x1f560, 0x1fab8, 0x1ea40, 0x1f530, 0x1fa9c, 0x1ea20, 0x1f518, 0x1fa8e, 0x1ea10, 0x1f50c, 0x1ea08, 0x1f506, 0x1ea04, 0x1eb60, 0x1f5b8, 0x1fade, 0x1d640, 0x1eb30, 0x1f59c, 0x1d620, 0x1eb18, 0x1f58e, 0x1d610, 0x1eb0c, 0x1d608, 0x1eb06, 0x1d604, 0x1d760, 0x1ebb8, 0x1f5de, 0x1ae40, 0x1d730, 0x1eb9c, 0x1ae20, 0x1d718, 0x1eb8e, 0x1ae10, 0x1d70c, 0x1ae08, 0x1d706, 0x1ae04, 0x1af60, 0x1d7b8, 0x1ebde, 0x15e40, 0x1af30, 0x1d79c, 0x15e20, 0x1af18, 0x1d78e, 0x15e10, 0x1af0c, 0x15e08, 0x1af06, 0x15f60, 0x1afb8, 0x1d7de, 0x15f30, 0x1af9c, 0x15f18, 0x1af8e, 0x15f0c, 0x15fb8, 0x1afde, 0x15f9c, 0x15f8e, 0x1e940, 0x1f4b0, 0x1fa5c, 0x1e920, 0x1f498, 0x1fa4e, 0x1e910, 0x1f48c, 0x1e908, 0x1f486, 0x1e904, 0x1e902, 0x1d340, 0x1e9b0, 0x1f4dc, 0x1d320, 0x1e998, 0x1f4ce, 0x1d310, 0x1e98c, 0x1d308, 0x1e986, 0x1d304, 0x1d302, 0x1a740, 0x1d3b0, 0x1e9dc, 0x1a720, 0x1d398, 0x1e9ce, 0x1a710, 0x1d38c, 0x1a708, 0x1d386, 0x1a704, 0x1a702, 0x14f40, 0x1a7b0, 0x1d3dc, 0x14f20, 0x1a798, 0x1d3ce, 0x14f10, 0x1a78c, 0x14f08, 0x1a786, 0x14f04, 0x14fb0, 0x1a7dc, 0x14f98, 0x1a7ce, 0x14f8c, 0x14f86, 0x14fdc, 0x14fce, 0x1e8a0, 0x1f458, 0x1fa2e, 0x1e890, 0x1f44c, 0x1e888, 0x1f446, 0x1e884, 0x1e882, 0x1d1a0, 0x1e8d8, 0x1f46e, 0x1d190, 0x1e8cc, 0x1d188, 0x1e8c6, 0x1d184, 0x1d182, 0x1a3a0, 0x1d1d8, 0x1e8ee, 0x1a390, 0x1d1cc, 0x1a388, 0x1d1c6, 0x1a384, 0x1a382, 0x147a0, 0x1a3d8, 0x1d1ee, 0x14790, 0x1a3cc, 0x14788, 0x1a3c6, 0x14784, 0x14782, 0x147d8, 0x1a3ee, 0x147cc, 0x147c6, 0x147ee, 0x1e850, 0x1f42c, 0x1e848, 0x1f426, 0x1e844, 0x1e842, 0x1d0d0, 0x1e86c, 0x1d0c8, 0x1e866, 0x1d0c4, 0x1d0c2, 0x1a1d0, 0x1d0ec, 0x1a1c8, 0x1d0e6, 0x1a1c4, 0x1a1c2, 0x143d0, 0x1a1ec, 0x143c8, 0x1a1e6, 0x143c4, 0x143c2, 0x143ec, 0x143e6, 0x1e828, 0x1f416, 0x1e824, 0x1e822, 0x1d068, 0x1e836, 0x1d064, 0x1d062, 0x1a0e8, 0x1d076, 0x1a0e4, 0x1a0e2, 0x141e8, 0x1a0f6, 0x141e4, 0x141e2, 0x1e814, 0x1e812, 0x1d034, 0x1d032, 0x1a074, 0x1a072, 0x1e540, 0x1f2b0, 0x1f95c, 0x1e520, 0x1f298, 0x1f94e, 0x1e510, 0x1f28c, 0x1e508, 0x1f286, 0x1e504, 0x1e502, 0x1cb40, 0x1e5b0, 0x1f2dc, 0x1cb20, 0x1e598, 0x1f2ce, 0x1cb10, 0x1e58c, 0x1cb08, 0x1e586, 0x1cb04, 0x1cb02, 0x19740, 0x1cbb0, 0x1e5dc, 0x19720, 0x1cb98, 0x1e5ce, 0x19710, 0x1cb8c, 0x19708, 0x1cb86, 0x19704, 0x19702, 0x12f40, 0x197b0, 0x1cbdc, 0x12f20, 0x19798, 0x1cbce, 0x12f10, 0x1978c, 0x12f08, 0x19786, 0x12f04, 0x12fb0, 0x197dc, 0x12f98, 0x197ce, 0x12f8c, 0x12f86, 0x12fdc, 0x12fce, 0x1f6a0, 0x1fb58, 0x16bf0, 0x1f690, 0x1fb4c, 0x169f8, 0x1f688, 0x1fb46, 0x168fc, 0x1f684, 0x1f682, 0x1e4a0, 0x1f258, 0x1f92e, 0x1eda0, 0x1e490, 0x1fb6e, 0x1ed90, 0x1f6cc, 0x1f246, 0x1ed88, 0x1e484, 0x1ed84, 0x1e482, 0x1ed82, 0x1c9a0, 0x1e4d8, 0x1f26e, 0x1dba0, 0x1c990, 0x1e4cc, 0x1db90, 0x1edcc, 0x1e4c6, 0x1db88, 0x1c984, 0x1db84, 0x1c982, 0x1db82, 0x193a0, 0x1c9d8, 0x1e4ee, 0x1b7a0, 0x19390, 0x1c9cc, 0x1b790, 0x1dbcc, 0x1c9c6, 0x1b788, 0x19384, 0x1b784, 0x19382, 0x1b782, 0x127a0, 0x193d8, 0x1c9ee, 0x16fa0, 0x12790, 0x193cc, 0x16f90, 0x1b7cc, 0x193c6, 0x16f88, 0x12784, 0x16f84, 0x12782, 0x127d8, 0x193ee, 0x16fd8, 0x127cc, 0x16fcc, 0x127c6, 0x16fc6, 0x127ee, 0x1f650, 0x1fb2c, 0x165f8, 0x1f648, 0x1fb26, 0x164fc, 0x1f644, 0x1647e, 0x1f642, 0x1e450, 0x1f22c, 0x1ecd0, 0x1e448, 0x1f226, 0x1ecc8, 0x1f666, 0x1ecc4, 0x1e442, 0x1ecc2, 0x1c8d0, 0x1e46c, 0x1d9d0, 0x1c8c8, 0x1e466, 0x1d9c8, 0x1ece6, 0x1d9c4, 0x1c8c2, 0x1d9c2, 0x191d0, 0x1c8ec, 0x1b3d0, 0x191c8, 0x1c8e6, 0x1b3c8, 0x1d9e6, 0x1b3c4, 0x191c2, 0x1b3c2, 0x123d0, 0x191ec, 0x167d0, 0x123c8, 0x191e6, 0x167c8, 0x1b3e6, 0x167c4, 0x123c2, 0x167c2, 0x123ec, 0x167ec, 0x123e6, 0x167e6, 0x1f628, 0x1fb16, 0x162fc, 0x1f624, 0x1627e, 0x1f622, 0x1e428, 0x1f216, 0x1ec68, 0x1f636, 0x1ec64, 0x1e422, 0x1ec62, 0x1c868, 0x1e436, 0x1d8e8, 0x1c864, 0x1d8e4, 0x1c862, 0x1d8e2, 0x190e8, 0x1c876, 0x1b1e8, 0x1d8f6, 0x1b1e4, 0x190e2, 0x1b1e2, 0x121e8, 0x190f6, 0x163e8, 0x121e4, 0x163e4, 0x121e2, 0x163e2, 0x121f6, 0x163f6, 0x1f614, 0x1617e, 0x1f612, 0x1e414, 0x1ec34, 0x1e412, 0x1ec32, 0x1c834, 0x1d874, 0x1c832, 0x1d872, 0x19074, 0x1b0f4, 0x19072, 0x1b0f2, 0x120f4, 0x161f4, 0x120f2, 0x161f2, 0x1f60a, 0x1e40a, 0x1ec1a, 0x1c81a, 0x1d83a, 0x1903a, 0x1b07a, 0x1e2a0, 0x1f158, 0x1f8ae, 0x1e290, 0x1f14c, 0x1e288, 0x1f146, 0x1e284, 0x1e282, 0x1c5a0, 0x1e2d8, 0x1f16e, 0x1c590, 0x1e2cc, 0x1c588, 0x1e2c6, 0x1c584, 0x1c582, 0x18ba0, 0x1c5d8, 0x1e2ee, 0x18b90, 0x1c5cc, 0x18b88, 0x1c5c6, 0x18b84, 0x18b82, 0x117a0, 0x18bd8, 0x1c5ee, 0x11790, 0x18bcc, 0x11788, 0x18bc6, 0x11784, 0x11782, 0x117d8, 0x18bee, 0x117cc, 0x117c6, 0x117ee, 0x1f350, 0x1f9ac, 0x135f8, 0x1f348, 0x1f9a6, 0x134fc, 0x1f344, 0x1347e, 0x1f342, 0x1e250, 0x1f12c, 0x1e6d0, 0x1e248, 0x1f126, 0x1e6c8, 0x1f366, 0x1e6c4, 0x1e242, 0x1e6c2, 0x1c4d0, 0x1e26c, 0x1cdd0, 0x1c4c8, 0x1e266, 0x1cdc8, 0x1e6e6, 0x1cdc4, 0x1c4c2, 0x1cdc2, 0x189d0, 0x1c4ec, 0x19bd0, 0x189c8, 0x1c4e6, 0x19bc8, 0x1cde6, 0x19bc4, 0x189c2, 0x19bc2, 0x113d0, 0x189ec, 0x137d0, 0x113c8, 0x189e6, 0x137c8, 0x19be6, 0x137c4, 0x113c2, 0x137c2, 0x113ec, 0x137ec, 0x113e6, 0x137e6, 0x1fba8, 0x175f0, 0x1bafc, 0x1fba4, 0x174f8, 0x1ba7e, 0x1fba2, 0x1747c, 0x1743e, 0x1f328, 0x1f996, 0x132fc, 0x1f768, 0x1fbb6, 0x176fc, 0x1327e, 0x1f764, 0x1f322, 0x1767e, 0x1f762, 0x1e228, 0x1f116, 0x1e668, 0x1e224, 0x1eee8, 0x1f776, 0x1e222, 0x1eee4, 0x1e662, 0x1eee2, 0x1c468, 0x1e236, 0x1cce8, 0x1c464, 0x1dde8, 0x1cce4, 0x1c462, 0x1dde4, 0x1cce2, 0x1dde2, 0x188e8, 0x1c476, 0x199e8, 0x188e4, 0x1bbe8, 0x199e4, 0x188e2, 0x1bbe4, 0x199e2, 0x1bbe2, 0x111e8, 0x188f6, 0x133e8, 0x111e4, 0x177e8, 0x133e4, 0x111e2, 0x177e4, 0x133e2, 0x177e2, 0x111f6, 0x133f6, 0x1fb94, 0x172f8, 0x1b97e, 0x1fb92, 0x1727c, 0x1723e, 0x1f314, 0x1317e, 0x1f734, 0x1f312, 0x1737e, 0x1f732, 0x1e214, 0x1e634, 0x1e212, 0x1ee74, 0x1e632, 0x1ee72, 0x1c434, 0x1cc74, 0x1c432, 0x1dcf4, 0x1cc72, 0x1dcf2, 0x18874, 0x198f4, 0x18872, 0x1b9f4, 0x198f2, 0x1b9f2, 0x110f4, 0x131f4, 0x110f2, 0x173f4, 0x131f2, 0x173f2, 0x1fb8a, 0x1717c, 0x1713e, 0x1f30a, 0x1f71a, 0x1e20a, 0x1e61a, 0x1ee3a, 0x1c41a, 0x1cc3a, 0x1dc7a, 0x1883a, 0x1987a, 0x1b8fa, 0x1107a, 0x130fa, 0x171fa, 0x170be, 0x1e150, 0x1f0ac, 0x1e148, 0x1f0a6, 0x1e144, 0x1e142, 0x1c2d0, 0x1e16c, 0x1c2c8, 0x1e166, 0x1c2c4, 0x1c2c2, 0x185d0, 0x1c2ec, 0x185c8, 0x1c2e6, 0x185c4, 0x185c2, 0x10bd0, 0x185ec, 0x10bc8, 0x185e6, 0x10bc4, 0x10bc2, 0x10bec, 0x10be6, 0x1f1a8, 0x1f8d6, 0x11afc, 0x1f1a4, 0x11a7e, 0x1f1a2, 0x1e128, 0x1f096, 0x1e368, 0x1e124, 0x1e364, 0x1e122, 0x1e362, 0x1c268, 0x1e136, 0x1c6e8, 0x1c264, 0x1c6e4, 0x1c262, 0x1c6e2, 0x184e8, 0x1c276, 0x18de8, 0x184e4, 0x18de4, 0x184e2, 0x18de2, 0x109e8, 0x184f6, 0x11be8, 0x109e4, 0x11be4, 0x109e2, 0x11be2, 0x109f6, 0x11bf6, 0x1f9d4, 0x13af8, 0x19d7e, 0x1f9d2, 0x13a7c, 0x13a3e, 0x1f194, 0x1197e, 0x1f3b4, 0x1f192, 0x13b7e, 0x1f3b2, 0x1e114, 0x1e334, 0x1e112, 0x1e774, 0x1e332, 0x1e772, 0x1c234, 0x1c674, 0x1c232, 0x1cef4, 0x1c672, 0x1cef2, 0x18474, 0x18cf4, 0x18472, 0x19df4, 0x18cf2, 0x19df2, 0x108f4, 0x119f4, 0x108f2, 0x13bf4, 0x119f2, 0x13bf2, 0x17af0, 0x1bd7c, 0x17a78, 0x1bd3e, 0x17a3c, 0x17a1e, 0x1f9ca, 0x1397c, 0x1fbda, 0x17b7c, 0x1393e, 0x17b3e, 0x1f18a, 0x1f39a, 0x1f7ba, 0x1e10a, 0x1e31a, 0x1e73a, 0x1ef7a, 0x1c21a, 0x1c63a, 0x1ce7a, 0x1defa, 0x1843a, 0x18c7a, 0x19cfa, 0x1bdfa, 0x1087a, 0x118fa, 0x139fa, 0x17978, 0x1bcbe, 0x1793c, 0x1791e, 0x138be, 0x179be, 0x178bc, 0x1789e, 0x1785e, 0x1e0a8, 0x1e0a4, 0x1e0a2, 0x1c168, 0x1e0b6, 0x1c164, 0x1c162, 0x182e8, 0x1c176, 0x182e4, 0x182e2, 0x105e8, 0x182f6, 0x105e4, 0x105e2, 0x105f6, 0x1f0d4, 0x10d7e, 0x1f0d2, 0x1e094, 0x1e1b4, 0x1e092, 0x1e1b2, 0x1c134, 0x1c374, 0x1c132, 0x1c372, 0x18274, 0x186f4, 0x18272, 0x186f2, 0x104f4, 0x10df4, 0x104f2, 0x10df2, 0x1f8ea, 0x11d7c, 0x11d3e, 0x1f0ca, 0x1f1da, 0x1e08a, 0x1e19a, 0x1e3ba, 0x1c11a, 0x1c33a, 0x1c77a, 0x1823a, 0x1867a, 0x18efa, 0x1047a, 0x10cfa, 0x11dfa, 0x13d78, 0x19ebe, 0x13d3c, 0x13d1e, 0x11cbe, 0x13dbe, 0x17d70, 0x1bebc, 0x17d38, 0x1be9e, 0x17d1c, 0x17d0e, 0x13cbc, 0x17dbc, 0x13c9e, 0x17d9e, 0x17cb8, 0x1be5e, 0x17c9c, 0x17c8e, 0x13c5e, 0x17cde, 0x17c5c, 0x17c4e, 0x17c2e, 0x1c0b4, 0x1c0b2, 0x18174, 0x18172, 0x102f4, 0x102f2, 0x1e0da, 0x1c09a, 0x1c1ba, 0x1813a, 0x1837a, 0x1027a, 0x106fa, 0x10ebe, 0x11ebc, 0x11e9e, 0x13eb8, 0x19f5e, 0x13e9c, 0x13e8e, 0x11e5e, 0x13ede, 0x17eb0, 0x1bf5c, 0x17e98, 0x1bf4e, 0x17e8c, 0x17e86, 0x13e5c, 0x17edc, 0x13e4e, 0x17ece, 0x17e58, 0x1bf2e, 0x17e4c, 0x17e46, 0x13e2e, 0x17e6e, 0x17e2c, 0x17e26, 0x10f5e, 0x11f5c, 0x11f4e, 0x13f58, 0x19fae, 0x13f4c, 0x13f46, 0x11f2e, 0x13f6e, 0x13f2c, 0x13f26 }, new[] { 0x1abe0, 0x1d5f8, 0x153c0, 0x1a9f0, 0x1d4fc, 0x151e0, 0x1a8f8, 0x1d47e, 0x150f0, 0x1a87c, 0x15078, 0x1fad0, 0x15be0, 0x1adf8, 0x1fac8, 0x159f0, 0x1acfc, 0x1fac4, 0x158f8, 0x1ac7e, 0x1fac2, 0x1587c, 0x1f5d0, 0x1faec, 0x15df8, 0x1f5c8, 0x1fae6, 0x15cfc, 0x1f5c4, 0x15c7e, 0x1f5c2, 0x1ebd0, 0x1f5ec, 0x1ebc8, 0x1f5e6, 0x1ebc4, 0x1ebc2, 0x1d7d0, 0x1ebec, 0x1d7c8, 0x1ebe6, 0x1d7c4, 0x1d7c2, 0x1afd0, 0x1d7ec, 0x1afc8, 0x1d7e6, 0x1afc4, 0x14bc0, 0x1a5f0, 0x1d2fc, 0x149e0, 0x1a4f8, 0x1d27e, 0x148f0, 0x1a47c, 0x14878, 0x1a43e, 0x1483c, 0x1fa68, 0x14df0, 0x1a6fc, 0x1fa64, 0x14cf8, 0x1a67e, 0x1fa62, 0x14c7c, 0x14c3e, 0x1f4e8, 0x1fa76, 0x14efc, 0x1f4e4, 0x14e7e, 0x1f4e2, 0x1e9e8, 0x1f4f6, 0x1e9e4, 0x1e9e2, 0x1d3e8, 0x1e9f6, 0x1d3e4, 0x1d3e2, 0x1a7e8, 0x1d3f6, 0x1a7e4, 0x1a7e2, 0x145e0, 0x1a2f8, 0x1d17e, 0x144f0, 0x1a27c, 0x14478, 0x1a23e, 0x1443c, 0x1441e, 0x1fa34, 0x146f8, 0x1a37e, 0x1fa32, 0x1467c, 0x1463e, 0x1f474, 0x1477e, 0x1f472, 0x1e8f4, 0x1e8f2, 0x1d1f4, 0x1d1f2, 0x1a3f4, 0x1a3f2, 0x142f0, 0x1a17c, 0x14278, 0x1a13e, 0x1423c, 0x1421e, 0x1fa1a, 0x1437c, 0x1433e, 0x1f43a, 0x1e87a, 0x1d0fa, 0x14178, 0x1a0be, 0x1413c, 0x1411e, 0x141be, 0x140bc, 0x1409e, 0x12bc0, 0x195f0, 0x1cafc, 0x129e0, 0x194f8, 0x1ca7e, 0x128f0, 0x1947c, 0x12878, 0x1943e, 0x1283c, 0x1f968, 0x12df0, 0x196fc, 0x1f964, 0x12cf8, 0x1967e, 0x1f962, 0x12c7c, 0x12c3e, 0x1f2e8, 0x1f976, 0x12efc, 0x1f2e4, 0x12e7e, 0x1f2e2, 0x1e5e8, 0x1f2f6, 0x1e5e4, 0x1e5e2, 0x1cbe8, 0x1e5f6, 0x1cbe4, 0x1cbe2, 0x197e8, 0x1cbf6, 0x197e4, 0x197e2, 0x1b5e0, 0x1daf8, 0x1ed7e, 0x169c0, 0x1b4f0, 0x1da7c, 0x168e0, 0x1b478, 0x1da3e, 0x16870, 0x1b43c, 0x16838, 0x1b41e, 0x1681c, 0x125e0, 0x192f8, 0x1c97e, 0x16de0, 0x124f0, 0x1927c, 0x16cf0, 0x1b67c, 0x1923e, 0x16c78, 0x1243c, 0x16c3c, 0x1241e, 0x16c1e, 0x1f934, 0x126f8, 0x1937e, 0x1fb74, 0x1f932, 0x16ef8, 0x1267c, 0x1fb72, 0x16e7c, 0x1263e, 0x16e3e, 0x1f274, 0x1277e, 0x1f6f4, 0x1f272, 0x16f7e, 0x1f6f2, 0x1e4f4, 0x1edf4, 0x1e4f2, 0x1edf2, 0x1c9f4, 0x1dbf4, 0x1c9f2, 0x1dbf2, 0x193f4, 0x193f2, 0x165c0, 0x1b2f0, 0x1d97c, 0x164e0, 0x1b278, 0x1d93e, 0x16470, 0x1b23c, 0x16438, 0x1b21e, 0x1641c, 0x1640e, 0x122f0, 0x1917c, 0x166f0, 0x12278, 0x1913e, 0x16678, 0x1b33e, 0x1663c, 0x1221e, 0x1661e, 0x1f91a, 0x1237c, 0x1fb3a, 0x1677c, 0x1233e, 0x1673e, 0x1f23a, 0x1f67a, 0x1e47a, 0x1ecfa, 0x1c8fa, 0x1d9fa, 0x191fa, 0x162e0, 0x1b178, 0x1d8be, 0x16270, 0x1b13c, 0x16238, 0x1b11e, 0x1621c, 0x1620e, 0x12178, 0x190be, 0x16378, 0x1213c, 0x1633c, 0x1211e, 0x1631e, 0x121be, 0x163be, 0x16170, 0x1b0bc, 0x16138, 0x1b09e, 0x1611c, 0x1610e, 0x120bc, 0x161bc, 0x1209e, 0x1619e, 0x160b8, 0x1b05e, 0x1609c, 0x1608e, 0x1205e, 0x160de, 0x1605c, 0x1604e, 0x115e0, 0x18af8, 0x1c57e, 0x114f0, 0x18a7c, 0x11478, 0x18a3e, 0x1143c, 0x1141e, 0x1f8b4, 0x116f8, 0x18b7e, 0x1f8b2, 0x1167c, 0x1163e, 0x1f174, 0x1177e, 0x1f172, 0x1e2f4, 0x1e2f2, 0x1c5f4, 0x1c5f2, 0x18bf4, 0x18bf2, 0x135c0, 0x19af0, 0x1cd7c, 0x134e0, 0x19a78, 0x1cd3e, 0x13470, 0x19a3c, 0x13438, 0x19a1e, 0x1341c, 0x1340e, 0x112f0, 0x1897c, 0x136f0, 0x11278, 0x1893e, 0x13678, 0x19b3e, 0x1363c, 0x1121e, 0x1361e, 0x1f89a, 0x1137c, 0x1f9ba, 0x1377c, 0x1133e, 0x1373e, 0x1f13a, 0x1f37a, 0x1e27a, 0x1e6fa, 0x1c4fa, 0x1cdfa, 0x189fa, 0x1bae0, 0x1dd78, 0x1eebe, 0x174c0, 0x1ba70, 0x1dd3c, 0x17460, 0x1ba38, 0x1dd1e, 0x17430, 0x1ba1c, 0x17418, 0x1ba0e, 0x1740c, 0x132e0, 0x19978, 0x1ccbe, 0x176e0, 0x13270, 0x1993c, 0x17670, 0x1bb3c, 0x1991e, 0x17638, 0x1321c, 0x1761c, 0x1320e, 0x1760e, 0x11178, 0x188be, 0x13378, 0x1113c, 0x17778, 0x1333c, 0x1111e, 0x1773c, 0x1331e, 0x1771e, 0x111be, 0x133be, 0x177be, 0x172c0, 0x1b970, 0x1dcbc, 0x17260, 0x1b938, 0x1dc9e, 0x17230, 0x1b91c, 0x17218, 0x1b90e, 0x1720c, 0x17206, 0x13170, 0x198bc, 0x17370, 0x13138, 0x1989e, 0x17338, 0x1b99e, 0x1731c, 0x1310e, 0x1730e, 0x110bc, 0x131bc, 0x1109e, 0x173bc, 0x1319e, 0x1739e, 0x17160, 0x1b8b8, 0x1dc5e, 0x17130, 0x1b89c, 0x17118, 0x1b88e, 0x1710c, 0x17106, 0x130b8, 0x1985e, 0x171b8, 0x1309c, 0x1719c, 0x1308e, 0x1718e, 0x1105e, 0x130de, 0x171de, 0x170b0, 0x1b85c, 0x17098, 0x1b84e, 0x1708c, 0x17086, 0x1305c, 0x170dc, 0x1304e, 0x170ce, 0x17058, 0x1b82e, 0x1704c, 0x17046, 0x1302e, 0x1706e, 0x1702c, 0x17026, 0x10af0, 0x1857c, 0x10a78, 0x1853e, 0x10a3c, 0x10a1e, 0x10b7c, 0x10b3e, 0x1f0ba, 0x1e17a, 0x1c2fa, 0x185fa, 0x11ae0, 0x18d78, 0x1c6be, 0x11a70, 0x18d3c, 0x11a38, 0x18d1e, 0x11a1c, 0x11a0e, 0x10978, 0x184be, 0x11b78, 0x1093c, 0x11b3c, 0x1091e, 0x11b1e, 0x109be, 0x11bbe, 0x13ac0, 0x19d70, 0x1cebc, 0x13a60, 0x19d38, 0x1ce9e, 0x13a30, 0x19d1c, 0x13a18, 0x19d0e, 0x13a0c, 0x13a06, 0x11970, 0x18cbc, 0x13b70, 0x11938, 0x18c9e, 0x13b38, 0x1191c, 0x13b1c, 0x1190e, 0x13b0e, 0x108bc, 0x119bc, 0x1089e, 0x13bbc, 0x1199e, 0x13b9e, 0x1bd60, 0x1deb8, 0x1ef5e, 0x17a40, 0x1bd30, 0x1de9c, 0x17a20, 0x1bd18, 0x1de8e, 0x17a10, 0x1bd0c, 0x17a08, 0x1bd06, 0x17a04, 0x13960, 0x19cb8, 0x1ce5e, 0x17b60, 0x13930, 0x19c9c, 0x17b30, 0x1bd9c, 0x19c8e, 0x17b18, 0x1390c, 0x17b0c, 0x13906, 0x17b06, 0x118b8, 0x18c5e, 0x139b8, 0x1189c, 0x17bb8, 0x1399c, 0x1188e, 0x17b9c, 0x1398e, 0x17b8e, 0x1085e, 0x118de, 0x139de, 0x17bde, 0x17940, 0x1bcb0, 0x1de5c, 0x17920, 0x1bc98, 0x1de4e, 0x17910, 0x1bc8c, 0x17908, 0x1bc86, 0x17904, 0x17902, 0x138b0, 0x19c5c, 0x179b0, 0x13898, 0x19c4e, 0x17998, 0x1bcce, 0x1798c, 0x13886, 0x17986, 0x1185c, 0x138dc, 0x1184e, 0x179dc, 0x138ce, 0x179ce, 0x178a0, 0x1bc58, 0x1de2e, 0x17890, 0x1bc4c, 0x17888, 0x1bc46, 0x17884, 0x17882, 0x13858, 0x19c2e, 0x178d8, 0x1384c, 0x178cc, 0x13846, 0x178c6, 0x1182e, 0x1386e, 0x178ee, 0x17850, 0x1bc2c, 0x17848, 0x1bc26, 0x17844, 0x17842, 0x1382c, 0x1786c, 0x13826, 0x17866, 0x17828, 0x1bc16, 0x17824, 0x17822, 0x13816, 0x17836, 0x10578, 0x182be, 0x1053c, 0x1051e, 0x105be, 0x10d70, 0x186bc, 0x10d38, 0x1869e, 0x10d1c, 0x10d0e, 0x104bc, 0x10dbc, 0x1049e, 0x10d9e, 0x11d60, 0x18eb8, 0x1c75e, 0x11d30, 0x18e9c, 0x11d18, 0x18e8e, 0x11d0c, 0x11d06, 0x10cb8, 0x1865e, 0x11db8, 0x10c9c, 0x11d9c, 0x10c8e, 0x11d8e, 0x1045e, 0x10cde, 0x11dde, 0x13d40, 0x19eb0, 0x1cf5c, 0x13d20, 0x19e98, 0x1cf4e, 0x13d10, 0x19e8c, 0x13d08, 0x19e86, 0x13d04, 0x13d02, 0x11cb0, 0x18e5c, 0x13db0, 0x11c98, 0x18e4e, 0x13d98, 0x19ece, 0x13d8c, 0x11c86, 0x13d86, 0x10c5c, 0x11cdc, 0x10c4e, 0x13ddc, 0x11cce, 0x13dce, 0x1bea0, 0x1df58, 0x1efae, 0x1be90, 0x1df4c, 0x1be88, 0x1df46, 0x1be84, 0x1be82, 0x13ca0, 0x19e58, 0x1cf2e, 0x17da0, 0x13c90, 0x19e4c, 0x17d90, 0x1becc, 0x19e46, 0x17d88, 0x13c84, 0x17d84, 0x13c82, 0x17d82, 0x11c58, 0x18e2e, 0x13cd8, 0x11c4c, 0x17dd8, 0x13ccc, 0x11c46, 0x17dcc, 0x13cc6, 0x17dc6, 0x10c2e, 0x11c6e, 0x13cee, 0x17dee, 0x1be50, 0x1df2c, 0x1be48, 0x1df26, 0x1be44, 0x1be42, 0x13c50, 0x19e2c, 0x17cd0, 0x13c48, 0x19e26, 0x17cc8, 0x1be66, 0x17cc4, 0x13c42, 0x17cc2, 0x11c2c, 0x13c6c, 0x11c26, 0x17cec, 0x13c66, 0x17ce6, 0x1be28, 0x1df16, 0x1be24, 0x1be22, 0x13c28, 0x19e16, 0x17c68, 0x13c24, 0x17c64, 0x13c22, 0x17c62, 0x11c16, 0x13c36, 0x17c76, 0x1be14, 0x1be12, 0x13c14, 0x17c34, 0x13c12, 0x17c32, 0x102bc, 0x1029e, 0x106b8, 0x1835e, 0x1069c, 0x1068e, 0x1025e, 0x106de, 0x10eb0, 0x1875c, 0x10e98, 0x1874e, 0x10e8c, 0x10e86, 0x1065c, 0x10edc, 0x1064e, 0x10ece, 0x11ea0, 0x18f58, 0x1c7ae, 0x11e90, 0x18f4c, 0x11e88, 0x18f46, 0x11e84, 0x11e82, 0x10e58, 0x1872e, 0x11ed8, 0x18f6e, 0x11ecc, 0x10e46, 0x11ec6, 0x1062e, 0x10e6e, 0x11eee, 0x19f50, 0x1cfac, 0x19f48, 0x1cfa6, 0x19f44, 0x19f42, 0x11e50, 0x18f2c, 0x13ed0, 0x19f6c, 0x18f26, 0x13ec8, 0x11e44, 0x13ec4, 0x11e42, 0x13ec2, 0x10e2c, 0x11e6c, 0x10e26, 0x13eec, 0x11e66, 0x13ee6, 0x1dfa8, 0x1efd6, 0x1dfa4, 0x1dfa2, 0x19f28, 0x1cf96, 0x1bf68, 0x19f24, 0x1bf64, 0x19f22, 0x1bf62, 0x11e28, 0x18f16, 0x13e68, 0x11e24, 0x17ee8, 0x13e64, 0x11e22, 0x17ee4, 0x13e62, 0x17ee2, 0x10e16, 0x11e36, 0x13e76, 0x17ef6, 0x1df94, 0x1df92, 0x19f14, 0x1bf34, 0x19f12, 0x1bf32, 0x11e14, 0x13e34, 0x11e12, 0x17e74, 0x13e32, 0x17e72, 0x1df8a, 0x19f0a, 0x1bf1a, 0x11e0a, 0x13e1a, 0x17e3a, 0x1035c, 0x1034e, 0x10758, 0x183ae, 0x1074c, 0x10746, 0x1032e, 0x1076e, 0x10f50, 0x187ac, 0x10f48, 0x187a6, 0x10f44, 0x10f42, 0x1072c, 0x10f6c, 0x10726, 0x10f66, 0x18fa8, 0x1c7d6, 0x18fa4, 0x18fa2, 0x10f28, 0x18796, 0x11f68, 0x18fb6, 0x11f64, 0x10f22, 0x11f62, 0x10716, 0x10f36, 0x11f76, 0x1cfd4, 0x1cfd2, 0x18f94, 0x19fb4, 0x18f92, 0x19fb2, 0x10f14, 0x11f34, 0x10f12, 0x13f74, 0x11f32, 0x13f72, 0x1cfca, 0x18f8a, 0x19f9a, 0x10f0a, 0x11f1a, 0x13f3a, 0x103ac, 0x103a6, 0x107a8, 0x183d6, 0x107a4, 0x107a2, 0x10396, 0x107b6, 0x187d4, 0x187d2, 0x10794, 0x10fb4, 0x10792, 0x10fb2, 0x1c7ea } }; private const float PREFERRED_RATIO = 3.0f; private const float DEFAULT_MODULE_WIDTH = 0.357f; //1px in mm private const float HEIGHT = 2.0f; //mm private BarcodeMatrix barcodeMatrix; private bool compact; private Compaction compaction; private Encoding encoding; private bool disableEci; private int minCols; private int maxCols; private int maxRows; private int minRows; internal PDF417() : this(false) { } internal PDF417(bool compact) { this.compact = compact; compaction = Compaction.AUTO; encoding = PDF417HighLevelEncoder.DEFAULT_ENCODING; disableEci = false; minCols = 2; maxCols = 30; maxRows = 30; minRows = 2; } internal BarcodeMatrix BarcodeMatrix { get { return barcodeMatrix; } } /// <summary> /// Calculates the necessary number of rows as described in annex Q of ISO/IEC 15438:2001(E). /// </summary> /// <param name="m">the number of source codewords prior to the additional of the Symbol Length</param> /// Descriptor and any pad codewords /// <param name="k">the number of error correction codewords</param> /// <param name="c">the number of columns in the symbol in the data region (excluding start, stop and</param> /// row indicator codewords) /// <returns>the number of rows in the symbol (r)</returns> private static int calculateNumberOfRows(int m, int k, int c) { int r = ((m + 1 + k)/c) + 1; if (c*r >= (m + 1 + k + c)) { r--; } return r; } /// <summary> /// Calculates the number of pad codewords as described in 4.9.2 of ISO/IEC 15438:2001(E). /// </summary> /// <param name="m">the number of source codewords prior to the additional of the Symbol Length</param> /// Descriptor and any pad codewords /// <param name="k">the number of error correction codewords</param> /// <param name="c">the number of columns in the symbol in the data region (excluding start, stop and</param> /// row indicator codewords) /// <param name="r">the number of rows in the symbol</param> /// <returns>the number of pad codewords</returns> private static int getNumberOfPadCodewords(int m, int k, int c, int r) { int n = c*r - k; return n > m + 1 ? n - m - 1 : 0; } private static void encodeChar(int pattern, int len, BarcodeRow logic) { int map = 1 << len - 1; bool last = (pattern & map) != 0; //Initialize to inverse of first bit int width = 0; for (int i = 0; i < len; i++) { bool black = (pattern & map) != 0; if (last == black) { width++; } else { logic.addBar(last, width); last = black; width = 1; } map >>= 1; } logic.addBar(last, width); } private void encodeLowLevel(String fullCodewords, int c, int r, int errorCorrectionLevel, BarcodeMatrix logic) { int idx = 0; for (int y = 0; y < r; y++) { int cluster = y%3; logic.startRow(); encodeChar(START_PATTERN, 17, logic.getCurrentRow()); int left; int right; if (cluster == 0) { left = (30*(y/3)) + ((r - 1)/3); right = (30*(y/3)) + (c - 1); } else if (cluster == 1) { left = (30*(y/3)) + (errorCorrectionLevel*3) + ((r - 1)%3); right = (30*(y/3)) + ((r - 1)/3); } else { left = (30*(y/3)) + (c - 1); right = (30*(y/3)) + (errorCorrectionLevel*3) + ((r - 1)%3); } int pattern = CODEWORD_TABLE[cluster][left]; encodeChar(pattern, 17, logic.getCurrentRow()); for (int x = 0; x < c; x++) { pattern = CODEWORD_TABLE[cluster][fullCodewords[idx]]; encodeChar(pattern, 17, logic.getCurrentRow()); idx++; } if (compact) { encodeChar(STOP_PATTERN, 1, logic.getCurrentRow()); // encodes stop line for compact pdf417 } else { pattern = CODEWORD_TABLE[cluster][right]; encodeChar(pattern, 17, logic.getCurrentRow()); encodeChar(STOP_PATTERN, 18, logic.getCurrentRow()); } } } /// <summary> /// Generates the barcode logic. /// </summary> /// <param name="msg">the message to encode</param> internal void generateBarcodeLogic(String msg, int errorCorrectionLevel) { //1. step: High-level encoding int errorCorrectionCodeWords = PDF417ErrorCorrection.getErrorCorrectionCodewordCount(errorCorrectionLevel); String highLevel = PDF417HighLevelEncoder.encodeHighLevel(msg, compaction, encoding, disableEci); int sourceCodeWords = highLevel.Length; int[] dimension = determineDimensions(sourceCodeWords, errorCorrectionCodeWords); int cols = dimension[0]; int rows = dimension[1]; int pad = getNumberOfPadCodewords(sourceCodeWords, errorCorrectionCodeWords, cols, rows); //2. step: construct data codewords if (sourceCodeWords + errorCorrectionCodeWords + 1 > 929) { // +1 for symbol length CW throw new ZXingWriterException( "Encoded message contains to many code words, message to big (" + msg.Length + " bytes)"); } int n = sourceCodeWords + pad + 1; StringBuilder sb = new StringBuilder(n); sb.Append((char) n); sb.Append(highLevel); for (int i = 0; i < pad; i++) { sb.Append((char) 900); //PAD characters } String dataCodewords = sb.ToString(); //3. step: Error correction String ec = PDF417ErrorCorrection.generateErrorCorrection(dataCodewords, errorCorrectionLevel); String fullCodewords = dataCodewords + ec; //4. step: low-level encoding barcodeMatrix = new BarcodeMatrix(rows, cols); encodeLowLevel(fullCodewords, cols, rows, errorCorrectionLevel, barcodeMatrix); } /// <summary> /// Determine optimal nr of columns and rows for the specified number of /// codewords. /// </summary> /// <param name="sourceCodeWords">number of code words</param> /// <param name="errorCorrectionCodeWords">number of error correction code words</param> /// <returns>dimension object containing cols as width and rows as height</returns> private int[] determineDimensions(int sourceCodeWords, int errorCorrectionCodeWords) { float ratio = 0.0f; int[] dimension = null; for (int cols = minCols; cols <= maxCols; cols++) { int rows = calculateNumberOfRows(sourceCodeWords, errorCorrectionCodeWords, cols); if (rows < minRows) { break; } if (rows > maxRows) { continue; } float newRatio = ((17*cols + 69)*DEFAULT_MODULE_WIDTH)/(rows*HEIGHT); // ignore if previous ratio is closer to preferred ratio if (dimension != null && Math.Abs(newRatio - PREFERRED_RATIO) > Math.Abs(ratio - PREFERRED_RATIO)) { continue; } ratio = newRatio; dimension = new int[] {cols, rows}; } // Handle case when min values were larger than necessary if (dimension == null) { int rows = calculateNumberOfRows(sourceCodeWords, errorCorrectionCodeWords, minCols); if (rows < minRows) { dimension = new int[] {minCols, minRows}; } } if (dimension == null) { throw new ZXingWriterException("Unable to fit message in columns"); } return dimension; } /// <summary> /// Sets max/min row/col values /// </summary> internal void setDimensions(int maxCols, int minCols, int maxRows, int minRows) { this.maxCols = maxCols; this.minCols = minCols; this.maxRows = maxRows; this.minRows = minRows; } /// <summary> /// Sets compaction to values stored in <see cref="Compaction" />enum /// </summary> internal void setCompaction(Compaction compaction) { this.compaction = compaction; } /// <summary> /// Sets compact to be true or false /// </summary> internal void setCompact(bool compact) { this.compact = compact; } /// <summary> /// Sets output encoding. /// </summary> internal void setEncoding(String encodingname) { #if WindowsCE try { this.encoding = Encoding.GetEncoding(encodingname); } catch (PlatformNotSupportedException) { // WindowsCE doesn't support all encodings. But it is device depended. // So we try here the some different ones this.encoding = Encoding.GetEncoding(1252); } #else this.encoding = Encoding.GetEncoding(encodingname); #endif } /// <summary> /// Sets the disable eci. /// </summary> internal void setDisableEci(bool disabled) { this.disableEci = disabled; } } }
//----------------------------------------------------------------------------- // // <copyright file="IssuanceLicense.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // This class wraps the issuance license publishing serveces // // History: // 06/13/2005: IgorBel: Initial implementation. // //----------------------------------------------------------------------------- using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Security.RightsManagement; using SecurityHelper = MS.Internal.WindowsBase.SecurityHelper; using System.Globalization; // For CultureInfo using MS.Internal; // for Invariant using System.Windows; namespace MS.Internal.Security.RightsManagement { /// <SecurityNote> /// Critical: This class exposes access to methods that eventually do one or more of the the following /// 1. call into unmanaged code /// 2. affects state/data that will eventually cross over unmanaged code boundary /// 3. Return some RM related information which is considered private /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] internal class IssuanceLicense : IDisposable { internal IssuanceLicense( DateTime validFrom, DateTime validUntil, string referralInfoName, Uri referralInfoUri, ContentUser owner, string issuanceLicense, SafeRightsManagementHandle boundLicenseHandle, Guid contentId, ICollection<ContentGrant> grantCollection, IDictionary<int, LocalizedNameDescriptionPair> localizedNameDescriptionDictionary, IDictionary<string, string> applicationSpecificDataDictionary, int rightValidityIntervalDays, RevocationPoint revocationPoint) { Initialize( validFrom, validUntil, referralInfoName, referralInfoUri, owner, issuanceLicense, boundLicenseHandle, contentId, grantCollection, localizedNameDescriptionDictionary, applicationSpecificDataDictionary, rightValidityIntervalDays, revocationPoint); } /// <summary> /// constructor that buils an issuance license from scratch /// </summary> private void Initialize( DateTime validFrom, DateTime validUntil, string referralInfoName, Uri referralInfoUri, ContentUser owner, string issuanceLicense, SafeRightsManagementHandle boundLicenseHandle, Guid contentId, ICollection<ContentGrant> grantCollection, IDictionary<int, LocalizedNameDescriptionPair> localizedNameDescriptionDictionary, IDictionary<string, string> applicationSpecificDataDictionary, int rightValidityIntervalDays, RevocationPoint revocationPoint) { // according to the unmanaged RM SDK spec only the following scenarios are supported: // 1. This can be called to create an issuance license from a template. // issuanceLicense An unsigned issuance license from // a file or by passing an issuance license // handle into DRMGetIssuanceLicenseTemplate // boundLicenseHandle NULL // // 2. This allows you to reuse rights information (the list follows this table). // issuance license A signed issuance license // boundLicenseHandle Handle to license bound by OWNER or VIEWRIGHTSDATA right // // 3. This creates an issuance license from scratch. It includes no users, rights, metadata, or policies. // issuance license NULL // boundLicenseHandle NULL Debug.Assert(!boundLicenseHandle.IsClosed); // it must be either present or not // closed handle is an indication of some internal error Invariant.Assert((boundLicenseHandle.IsInvalid) || (issuanceLicense != null)); SystemTime validFromSysTime = null; SystemTime validUntilSysTime = null; if ((validFrom != DateTime.MinValue) || (validUntil != DateTime.MaxValue)) { // we need to use non null values if at least one of the time boundaries isn't default // DRM SDK will not enforce date time unless both timeFrom and timeUnti are set validFromSysTime = new SystemTime((DateTime)validFrom); validUntilSysTime = new SystemTime((DateTime)validUntil); } string referralInfoUriStr = null; if (referralInfoUri != null) { referralInfoUriStr = referralInfoUri.ToString(); } // input parameter must be initialized to the invalid handle // attempt to pass in a null throws an exception from the Safe // Handle Marshalling code SafeRightsManagementPubHandle ownerHandle; if (owner != null) { ownerHandle = GetHandleFromUser(owner); } else { ownerHandle = SafeRightsManagementPubHandle.InvalidHandle; } int hr; _issuanceLicenseHandle = null; hr = SafeNativeMethods.DRMCreateIssuanceLicense( validFromSysTime, validUntilSysTime, referralInfoName, referralInfoUriStr, ownerHandle, issuanceLicense, boundLicenseHandle, out _issuanceLicenseHandle); Errors.ThrowOnErrorCode(hr); Invariant.Assert((_issuanceLicenseHandle != null) && (!_issuanceLicenseHandle.IsInvalid)); Debug.Assert(rightValidityIntervalDays >= 0); // our internal code makes the guarantee that is is not negative if (rightValidityIntervalDays > 0) { // If it is 0 we shouldn't override the value as it might be coming from a template SafeNativeMethods.DRMSetIntervalTime(_issuanceLicenseHandle, (uint)rightValidityIntervalDays); } if (grantCollection != null) { foreach (ContentGrant grant in grantCollection) { AddGrant(grant); } } // Set localized name description info if (localizedNameDescriptionDictionary != null) { foreach (KeyValuePair<int, LocalizedNameDescriptionPair> nameDescriptionEntry in localizedNameDescriptionDictionary) { AddNameDescription(nameDescriptionEntry.Key, nameDescriptionEntry.Value); } } // Set application specific data if (applicationSpecificDataDictionary != null) { foreach (KeyValuePair<string, string> applicationSpecificDataEntry in applicationSpecificDataDictionary) { AddApplicationSpecificData(applicationSpecificDataEntry.Key, applicationSpecificDataEntry.Value); } } // set metafata as required if (contentId != null) { hr = SafeNativeMethods.DRMSetMetaData( _issuanceLicenseHandle, contentId.ToString("B"), DefaultContentType, null, null, null, null); Errors.ThrowOnErrorCode(hr); } // set revocation point if required if (revocationPoint != null) { SetRevocationPoint(revocationPoint); } } internal SafeRightsManagementPubHandle Handle { get { CheckDisposed(); return _issuanceLicenseHandle; } } override public string ToString() { uint issuanceLicenseTemplateLength = 0; StringBuilder issuanceLicenseTemplate = null; int hr = SafeNativeMethods.DRMGetIssuanceLicenseTemplate( _issuanceLicenseHandle, ref issuanceLicenseTemplateLength, null); Errors.ThrowOnErrorCode(hr); issuanceLicenseTemplate = new StringBuilder(checked((int)issuanceLicenseTemplateLength)); hr = SafeNativeMethods.DRMGetIssuanceLicenseTemplate( _issuanceLicenseHandle, ref issuanceLicenseTemplateLength, issuanceLicenseTemplate); Errors.ThrowOnErrorCode(hr); return issuanceLicenseTemplate.ToString(); } internal void UpdateUnsignedPublishLicense(UnsignedPublishLicense unsignedPublishLicense) { Invariant.Assert(unsignedPublishLicense != null); DateTime timeFrom; DateTime timeUntil; DistributionPointInfo distributionPointInfo = DistributionPointInfo.ReferralInfo; string distributionPointName; string distributionPointUri; ContentUser owner; bool officialFlag; GetIssuanceLicenseInfo(out timeFrom, out timeUntil, distributionPointInfo, out distributionPointName, out distributionPointUri, out owner, out officialFlag); unsignedPublishLicense.ReferralInfoName = distributionPointName; if (distributionPointUri != null) { unsignedPublishLicense.ReferralInfoUri = new Uri(distributionPointUri); } else { unsignedPublishLicense.ReferralInfoUri = null; } unsignedPublishLicense.Owner = owner; // Let's get the validity Iterval information (days) and save it in the license uint validityDays = 0; int hr = SafeNativeMethods.DRMGetIntervalTime(_issuanceLicenseHandle, ref validityDays); Errors.ThrowOnErrorCode(hr); checked { unsignedPublishLicense.RightValidityIntervalDays = (int)validityDays; } // let's get the rights information int userIndex = 0; while (true) // in this loop we are enumerating users mentioned in the license { SafeRightsManagementPubHandle userHandle = null; // extract the user based on the index ContentUser user = GetIssuanceLicenseUser(userIndex, out userHandle); if ((user == null) || (userHandle == null)) { break; } int rightIndex = 0; while (true) // now we can enumerate rights granted to the given user { SafeRightsManagementPubHandle rightHandle = null; DateTime validFrom; DateTime validUntil; // extract the right based on the index and the user Nullable<ContentRight> right = GetIssuanceLicenseUserRight (userHandle, rightIndex, out rightHandle, out validFrom, out validUntil); // 0 right handle is an indication of the end of the list if (rightHandle == null) { break; } // right == null is an indication of a right that we didn't recognize // we should still continue the enumeration if (right != null) { // Add the grant for the User Right pair here unsignedPublishLicense.Grants.Add( new ContentGrant(user, right.Value, validFrom, validUntil)); } rightIndex++; } userIndex++; } // let's get the localized name description pairs int nameIndex = 0; while (true) // in this loop we are enumerating nameDescription pairs mentioned in the license { int localeId; // extract the user based on the index LocalizedNameDescriptionPair nameDescription = GetLocalizedNameDescriptionPair(nameIndex, out localeId); if (nameDescription == null) { break; } // Add the name description info to the license unsignedPublishLicense.LocalizedNameDescriptionDictionary.Add(localeId, nameDescription); nameIndex++; } // let's get the application specific data int appDataIndex = 0; while (true) // in this loop we are enumerating nameDescription pairs mentioned in the license { // extract the user based on the index Nullable<KeyValuePair<string, string>> appSpecificDataEntry = GetApplicationSpecificData(appDataIndex); if (appSpecificDataEntry == null) { break; } // Add the name description info to the license unsignedPublishLicense.ApplicationSpecificDataDictionary.Add(appSpecificDataEntry.Value.Key, appSpecificDataEntry.Value.Value); appDataIndex++; } // Get the revocation Point information, it is optional and can be null unsignedPublishLicense.RevocationPoint = GetRevocationPoint(); } ~IssuanceLicense() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { try { if (_issuanceLicenseHandle != null) { _issuanceLicenseHandle.Dispose(); // After some investigation it was determined that ArrayList // is a safe member ,and could be used in Finalizers // so we do not check for disposing flag. // It seems that Finalizers are called in nondeterministic order // but if we have a combination of classes with Finalizers and without Finalizers // referencing each other, the classes with Finalizers wil be Disposed first. foreach (SafeRightsManagementPubHandle handler in _pubHandlesList) { handler.Dispose(); } } } finally { _issuanceLicenseHandle = null; _pubHandlesList.Clear(); } } } private void AddGrant(ContentGrant grant) { Invariant.Assert(grant != null); Invariant.Assert(grant.User != null); SafeRightsManagementPubHandle right = GetRightHandle(grant); SafeRightsManagementPubHandle user = GetHandleFromUser(grant.User); int hr = SafeNativeMethods.DRMAddRightWithUser( _issuanceLicenseHandle, right, user); Errors.ThrowOnErrorCode(hr); } private void AddNameDescription(int localeId, LocalizedNameDescriptionPair nameDescription) { // the managed APIs treat Locale Id as int and the unmanaged ones as uint // we need to convert it back and force uint locId; checked { locId = (uint)localeId; } int hr = SafeNativeMethods.DRMSetNameAndDescription( _issuanceLicenseHandle, false, // true - means delete ; false - add locId, nameDescription.Name, nameDescription.Description); Errors.ThrowOnErrorCode(hr); } private void AddApplicationSpecificData(string name, string value) { int hr = SafeNativeMethods.DRMSetApplicationSpecificData( _issuanceLicenseHandle, false, // true - means delete ; false - add name, value); Errors.ThrowOnErrorCode(hr); } private SafeRightsManagementPubHandle GetRightHandle(ContentGrant grant) { SafeRightsManagementPubHandle rightHandle = null; // we only need to use date time inteval if at least one of the values isn't default to Min max // If both of the Min Max we can leave tyhem as nulls otherwise (if at least one not default) // we need to set both SystemTime systemTimeValidFrom = null; SystemTime systemTimeValidUntil = null; if ((grant.ValidFrom != DateTime.MinValue) || (grant.ValidUntil != DateTime.MaxValue)) { // we need to use non null values if at least one of the time boundaries isn't default // DRM SDK will not enforce date time unless both timeFrom and timeUnti are set systemTimeValidFrom = new SystemTime(grant.ValidFrom); systemTimeValidUntil = new SystemTime(grant.ValidUntil); } int hr = SafeNativeMethods.DRMCreateRight( ClientSession.GetStringFromRight(grant.Right), systemTimeValidFrom, // SystemTime timeFrom, systemTimeValidUntil, // SystemTime timeUntil, 0, // countExtendedInfo, null, // string [] extendedInfoNames, null, // string [] extendedInfoValues, out rightHandle); Errors.ThrowOnErrorCode(hr); Debug.Assert((rightHandle != null) && (!rightHandle.IsInvalid)); _pubHandlesList.Add(rightHandle); return rightHandle; } private SafeRightsManagementPubHandle GetHandleFromUser(ContentUser user) { SafeRightsManagementPubHandle userHandle = null; int hr; // We need to create Internal Authnetication type Users differently if (user.GenericEquals(ContentUser.AnyoneUser) || user.GenericEquals(ContentUser.OwnerUser)) { // Anyone user hr = SafeNativeMethods.DRMCreateUser( user.Name, // This is an optional UI Name (some applications use this and do not work well when it is missing) user.Name, // that would be string Anyone or Owner ConvertAuthenticationTypeToString(user), // this would be internal out userHandle); } else { // Windws Passport or WindowsPassport authentication type user hr = SafeNativeMethods.DRMCreateUser( user.Name, null, ConvertAuthenticationTypeToString(user), out userHandle); } Errors.ThrowOnErrorCode(hr); Debug.Assert((userHandle != null) && (!userHandle.IsInvalid)); _pubHandlesList.Add(userHandle); return userHandle; } static private Nullable<ContentRight> GetRightFromHandle(SafeRightsManagementPubHandle rightHandle, out DateTime validFrom, out DateTime validUntil) { uint rightNameLength = 0; StringBuilder rightName; int hr = SafeNativeMethods.DRMGetRightInfo(rightHandle, ref rightNameLength, null, null, null); Errors.ThrowOnErrorCode(hr); rightName = new StringBuilder(checked((int)rightNameLength)); SystemTime validFromSysTime = new SystemTime(DateTime.Now); SystemTime validUntilSysTime = new SystemTime(DateTime.Now); hr = SafeNativeMethods.DRMGetRightInfo(rightHandle, ref rightNameLength, rightName, validFromSysTime, validUntilSysTime); Errors.ThrowOnErrorCode(hr); validFrom = validFromSysTime.GetDateTime(DateTime.MinValue); validUntil = validUntilSysTime.GetDateTime(DateTime.MaxValue); return ClientSession.GetRightFromString(rightName.ToString()); } static private ContentUser GetUserFromHandle(SafeRightsManagementPubHandle userHandle) { uint userNameLength = 0; StringBuilder userName = null; uint userIdLength = 0; StringBuilder userId = null; uint userIdTypeLength = 0; StringBuilder userIdType = null; int hr = SafeNativeMethods.DRMGetUserInfo(userHandle, ref userNameLength, null, ref userIdLength, null, ref userIdTypeLength, null); Errors.ThrowOnErrorCode(hr); if (userNameLength > 0) { // only allocate memory if we got a non-zero size back userName = new StringBuilder(checked((int)userNameLength)); } if (userIdLength > 0) { // only allocate memory if we got a non-zero size back userId = new StringBuilder(checked((int)userIdLength)); } if (userIdTypeLength > 0) { // only allocate memory if we got a non-zero size back userIdType = new StringBuilder(checked((int)userIdTypeLength)); } hr = SafeNativeMethods.DRMGetUserInfo(userHandle, ref userNameLength, userName, ref userIdLength, userId, ref userIdTypeLength, userIdType); Errors.ThrowOnErrorCode(hr); // Convert String Builder values to string values string userNameStr = null; if (userName != null) { userNameStr = userName.ToString(); } string userIdTypeStr = null; if (userIdType != null) { userIdTypeStr = userIdType.ToString().ToUpperInvariant(); } string userIdStr = null; if (userId != null) { userIdStr = userId.ToString().ToUpperInvariant(); } // based on the UserTypeId build appropriate instance of User class if (String.CompareOrdinal(userIdTypeStr, AuthenticationType.Windows.ToString().ToUpperInvariant()) == 0) { return new ContentUser(userNameStr, AuthenticationType.Windows); } else if (String.CompareOrdinal(userIdTypeStr, AuthenticationType.Passport.ToString().ToUpperInvariant()) == 0) { return new ContentUser(userNameStr, AuthenticationType.Passport); } else if (String.CompareOrdinal(userIdTypeStr, AuthenticationType.Internal.ToString().ToUpperInvariant()) == 0) { // internal anyone user if (ContentUser.CompareToAnyone(userIdStr)) { return ContentUser.AnyoneUser; } else if (ContentUser.CompareToOwner(userIdStr)) { return ContentUser.OwnerUser; } } else if (String.CompareOrdinal(userIdTypeStr, UnspecifiedAuthenticationType.ToUpperInvariant()) == 0) { return new ContentUser(userNameStr, AuthenticationType.WindowsPassport); } throw new RightsManagementException(RightsManagementFailureCode.InvalidLicense); } private ContentUser GetIssuanceLicenseUser(int index, out SafeRightsManagementPubHandle userHandle) { Invariant.Assert(index >= 0); int hr = SafeNativeMethods.DRMGetUsers( _issuanceLicenseHandle, (uint)index, out userHandle); // there is a special code indication end of the enumeration if (hr == (int)RightsManagementFailureCode.NoMoreData) { userHandle = null; return null; } // check for errors Errors.ThrowOnErrorCode(hr); Debug.Assert((userHandle != null) && (!userHandle.IsInvalid)); // preserve handle so we can destruct it later _pubHandlesList.Add(userHandle); // now we can build a ContentUser return GetUserFromHandle(userHandle); } private LocalizedNameDescriptionPair GetLocalizedNameDescriptionPair (int index, out int localeId) { Invariant.Assert(index >= 0); uint locId = 0; uint nameLength = 0; StringBuilder name = null; uint descriptionLength = 0; StringBuilder description = null; int hr = SafeNativeMethods.DRMGetNameAndDescription( _issuanceLicenseHandle, (uint)index, out locId, ref nameLength, name, ref descriptionLength, description); // there is a special code indication end of the enumeration if (hr == (int)RightsManagementFailureCode.NoMoreData) { localeId = 0; return null; } // check for errors Errors.ThrowOnErrorCode(hr); if (nameLength > 0) { // only allocate memory if we got a non-zero size back name = new StringBuilder(checked((int)nameLength)); } if (descriptionLength > 0) { // only allocate memory if we got a non-zero size back description = new StringBuilder(checked((int)descriptionLength)); } hr = SafeNativeMethods.DRMGetNameAndDescription( _issuanceLicenseHandle, (uint)index, out locId, ref nameLength, name, ref descriptionLength, description); Errors.ThrowOnErrorCode(hr); // the managed APIs treat Locale Id as int and the unmanaged ones as uint // we need to convert it back and force checked { localeId = (int)locId; } // now we can build a ContentUser return new LocalizedNameDescriptionPair(name == null ? null : name.ToString(), description == null ? null : description.ToString()); } private Nullable<KeyValuePair<string, string>> GetApplicationSpecificData(int index) { Invariant.Assert(index >= 0); uint nameLength = 0; uint valueLength = 0; // check whether element with such index is present, // and if it is get the sizes of the name value strings int hr = SafeNativeMethods.DRMGetApplicationSpecificData( _issuanceLicenseHandle, (uint)index, // safe cast as the caller responsible for keeping this postive ref nameLength, null, ref valueLength, null); // there is a special code indicating end of the enumeration if (hr == (int)RightsManagementFailureCode.NoMoreData) { return null; } // check for errors Errors.ThrowOnErrorCode(hr); StringBuilder tempName = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (nameLength > 0) { tempName = new StringBuilder(checked((int)nameLength)); } StringBuilder tempValue = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (valueLength > 0) { tempValue = new StringBuilder(checked((int)valueLength)); } // The second call supposed to return the actual string values fcheck whether element with such index is present, // and if it is get the sizes of the name value strings hr = SafeNativeMethods.DRMGetApplicationSpecificData( _issuanceLicenseHandle, (uint)index, // safe cast as the caller responsible for keeping this postive ref nameLength, tempName, ref valueLength, tempValue); // check for errors Errors.ThrowOnErrorCode(hr); // build strings from the StringBuilder instances string name = (tempName == null) ? null : tempName.ToString(); string value = (tempValue == null) ? null : tempValue.ToString(); KeyValuePair<string, string> result = new KeyValuePair<string, string>(name, value); return result; } private Nullable<ContentRight> GetIssuanceLicenseUserRight (SafeRightsManagementPubHandle userHandle, int index, out SafeRightsManagementPubHandle rightHandle, out DateTime validFrom, out DateTime validUntil) { Invariant.Assert(index >= 0); int hr = SafeNativeMethods.DRMGetUserRights(_issuanceLicenseHandle, userHandle, (uint)index, out rightHandle); // there is a special code indicating end of the enumeration if (hr == (int)RightsManagementFailureCode.NoMoreData) { rightHandle = null; validFrom = DateTime.MinValue; validUntil = DateTime.MaxValue; return null; // intentionally we return an invalid value, to make use client // properly verify right handle } // check for errors Errors.ThrowOnErrorCode(hr); Debug.Assert((rightHandle != null) && (!rightHandle.IsInvalid)); // preserve handle so we can destruct it later _pubHandlesList.Add(rightHandle); // now we can build a User return GetRightFromHandle(rightHandle, out validFrom, out validUntil); } private void GetIssuanceLicenseInfo( out DateTime timeFrom, out DateTime timeUntil, DistributionPointInfo distributionPointInfo, out string distributionPointName, out string distributionPointUri, out ContentUser owner, out bool officialFlag) { uint distributionPointNameLength = 0; uint distributionPointUriLength = 0; bool officialFlagTemp = false; SafeRightsManagementPubHandle ownerHandleTemp = null; int hr = SafeNativeMethods.DRMGetIssuanceLicenseInfo( _issuanceLicenseHandle, null, null, (uint)distributionPointInfo, ref distributionPointNameLength, null, ref distributionPointUriLength, null, out ownerHandleTemp, out officialFlagTemp); Errors.ThrowOnErrorCode(hr); if (ownerHandleTemp != null) { // As a result of calling DRMGetIssuanceLicenseInfo twice, // we are getting 2 handles. We are going to dispose the first one // and preserve the second one. ownerHandleTemp.Dispose(); ownerHandleTemp = null; } StringBuilder distributionPointNameTemp = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (distributionPointNameLength > 0) { distributionPointNameTemp = new StringBuilder(checked((int)distributionPointNameLength)); } StringBuilder distributionPointUriTemp = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (distributionPointUriLength > 0) { distributionPointUriTemp = new StringBuilder(checked((int)distributionPointUriLength)); } SystemTime timeFromTemp = new SystemTime(DateTime.Now); SystemTime timeUntilTemp = new SystemTime(DateTime.Now); hr = SafeNativeMethods.DRMGetIssuanceLicenseInfo( _issuanceLicenseHandle, timeFromTemp, timeUntilTemp, (uint)distributionPointInfo, ref distributionPointNameLength, distributionPointNameTemp, ref distributionPointUriLength, distributionPointUriTemp, out ownerHandleTemp, out officialFlagTemp); Errors.ThrowOnErrorCode(hr); timeFrom = timeFromTemp.GetDateTime(DateTime.MinValue); timeUntil = timeUntilTemp.GetDateTime(DateTime.MaxValue); // only if we got some data back we shall try to process it if (distributionPointNameTemp != null) { distributionPointName = distributionPointNameTemp.ToString(); } else { distributionPointName = null; } // only if we got some data back we shall try to process it if (distributionPointUriTemp != null) { distributionPointUri = distributionPointUriTemp.ToString(); } else { distributionPointUri = null; } // if we have owner let's convert it to a user and preserve // handler for further destruction owner = null; if (ownerHandleTemp != null) { _pubHandlesList.Add(ownerHandleTemp); if (!ownerHandleTemp.IsInvalid) { owner = GetUserFromHandle(ownerHandleTemp); } } officialFlag = officialFlagTemp; } private void SetRevocationPoint(RevocationPoint revocationPoint) { int hr = SafeNativeMethods.DRMSetRevocationPoint( _issuanceLicenseHandle, false, // flagDelete, revocationPoint.Id, revocationPoint.IdType, revocationPoint.Url.AbsoluteUri, // We are using Uri class as a basic validation mechanism. These URIs come from unmanaged // code libraries and go back as parameters into the unmanaged code libraries. // We use AbsoluteUri property as means of verifying that it is actually an absolute and // well formed Uri. If by any chance it happened to be a relative URI, an exception will // be thrown here. This will perform the necessary escaping. revocationPoint.Frequency, revocationPoint.Name, revocationPoint.PublicKey); Errors.ThrowOnErrorCode(hr); } private RevocationPoint GetRevocationPoint() { uint idLength = 0; uint idTypeLength = 0; uint urlLength = 0; uint nameLength = 0; uint publicKeyLength = 0; SystemTime frequency = new SystemTime(DateTime.Now); int hr = SafeNativeMethods.DRMGetRevocationPoint( _issuanceLicenseHandle, ref idLength, null, ref idTypeLength, null, ref urlLength, null, frequency, ref nameLength, null, ref publicKeyLength, null); if (hr == (int)RightsManagementFailureCode.RevocationInfoNotSet) { return null; } Errors.ThrowOnErrorCode(hr); // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 StringBuilder idTemp = null; if (idLength > 0) { idTemp = new StringBuilder(checked((int)idLength)); } StringBuilder idTypeTemp = null; if (idTypeLength > 0) { idTypeTemp = new StringBuilder(checked((int)idTypeLength)); } StringBuilder urlTemp = null; if (urlLength > 0) { urlTemp = new StringBuilder(checked((int)urlLength)); } StringBuilder nameTemp = null; if (nameLength > 0) { nameTemp = new StringBuilder(checked((int)nameLength)); } StringBuilder publicKeyTemp = null; if (publicKeyLength > 0) { publicKeyTemp = new StringBuilder(checked((int)publicKeyLength)); } hr = SafeNativeMethods.DRMGetRevocationPoint( _issuanceLicenseHandle, ref idLength, idTemp, ref idTypeLength, idTypeTemp, ref urlLength, urlTemp, frequency, ref nameLength, nameTemp, ref publicKeyLength, publicKeyTemp); Errors.ThrowOnErrorCode(hr); RevocationPoint resultRevocationPoint = new RevocationPoint(); resultRevocationPoint.Id = (idTemp == null) ? null : idTemp.ToString(); resultRevocationPoint.IdType = (idTypeTemp == null) ? null : idTypeTemp.ToString(); resultRevocationPoint.Url = (urlTemp == null) ? null : new Uri(urlTemp.ToString()); resultRevocationPoint.Name = (nameTemp == null) ? null : nameTemp.ToString(); resultRevocationPoint.PublicKey = (publicKeyTemp == null) ? null : publicKeyTemp.ToString(); resultRevocationPoint.Frequency = frequency; return resultRevocationPoint; } /// <summary> /// Call this before accepting any API call /// </summary> private void CheckDisposed() { //As this class is not public, and the corresponding public class (Unsigned Publish License //that uses this class is not disposable, it means, that the only probable reason for using //Disposed instance of this class is a bug in our internal logic; therefore, Invariant Assert is //more appropriate. Throwing ObjectDisposedException exception would be misleading //as users will not deal with a Disposable class. Invariant.Assert((_issuanceLicenseHandle != null) && (!_issuanceLicenseHandle.IsInvalid)); } /// <summary> /// Converts Authentication type enumeration into a string that can be accepted by the unmanaged code /// </summary> private string ConvertAuthenticationTypeToString(ContentUser user) { if (user.AuthenticationType == AuthenticationType.WindowsPassport) { return UnspecifiedAuthenticationType; } else { return user.AuthenticationType.ToString(); } } private List<SafeRightsManagementPubHandle> _pubHandlesList = new List<SafeRightsManagementPubHandle>(50); // initial capacity private SafeRightsManagementPubHandle _issuanceLicenseHandle = null; // if this is null, we are disposed private const string DefaultContentType = "MS-GUID"; private const string UnspecifiedAuthenticationType = "Unspecified"; } }
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.dll // Description: A library for managing GPS connections. // ******************************************************************************************************** // // The Original Code is from http://geoframework.codeplex.com/ version 2.0 // // The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup) // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------------------------------------------------------------------------------------------- // | Developer | Date | Comments // |--------------------------|------------|-------------------------------------------------------------- // | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0 // | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper. // ******************************************************************************************************** using System; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace DotSpatial.Positioning { /// <summary> /// Represents a measurement of an object's rate of travel in a particular direction. /// </summary> /// <remarks>Instances of this class are guaranteed to be thread-safe because the class is /// immutable (its properties can only be changed via constructors).</remarks> public struct Velocity : IFormattable, IEquatable<Velocity>, ICloneable<Velocity>, IXmlSerializable { /// <summary> /// /// </summary> private Speed _speed; /// <summary> /// /// </summary> private Azimuth _bearing; #region Fields /// <summary> /// Represents a velocity with no speed or direction. /// </summary> public static readonly Velocity Empty = new Velocity(Speed.Empty, Azimuth.Empty); /// <summary> /// Represents a velocity with an invalid or unspecified speed and direction. /// </summary> public static readonly Velocity Invalid = new Velocity(Speed.Invalid, Azimuth.Invalid); #endregion Fields #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Velocity"/> struct. /// </summary> /// <param name="speed">The speed.</param> /// <param name="bearing">The bearing.</param> public Velocity(Speed speed, Azimuth bearing) { _speed = speed; _bearing = bearing; } /// <summary> /// Initializes a new instance of the <see cref="Velocity"/> struct. /// </summary> /// <param name="speed">The speed.</param> /// <param name="bearingDegrees">The bearing degrees.</param> public Velocity(Speed speed, double bearingDegrees) { _speed = speed; _bearing = new Azimuth(bearingDegrees); } /// <summary> /// Initializes a new instance of the <see cref="Velocity"/> struct. /// </summary> /// <param name="speed">The speed.</param> /// <param name="speedUnits">The speed units.</param> /// <param name="bearing">The bearing.</param> public Velocity(double speed, SpeedUnit speedUnits, Azimuth bearing) { _speed = new Speed(speed, speedUnits); _bearing = bearing; } /// <summary> /// Initializes a new instance of the <see cref="Velocity"/> struct. /// </summary> /// <param name="speed">The speed.</param> /// <param name="speedUnits">The speed units.</param> /// <param name="bearingDegrees">The bearing degrees.</param> public Velocity(double speed, SpeedUnit speedUnits, double bearingDegrees) { _speed = new Speed(speed, speedUnits); _bearing = new Azimuth(bearingDegrees); } /// <summary> /// Creates a new instance by parsing speed and bearing from the specified strings. /// </summary> /// <param name="speed">The speed.</param> /// <param name="bearing">The bearing.</param> public Velocity(string speed, string bearing) : this(speed, bearing, CultureInfo.CurrentCulture) { } /// <summary> /// Creates a new instance by converting the specified strings using the specific culture. /// </summary> /// <param name="speed">The speed.</param> /// <param name="bearing">The bearing.</param> /// <param name="culture">The culture.</param> public Velocity(string speed, string bearing, CultureInfo culture) { _speed = new Speed(speed, culture); _bearing = new Azimuth(bearing, culture); } /// <summary> /// Initializes a new instance of the <see cref="Velocity"/> struct. /// </summary> /// <param name="reader">The reader.</param> public Velocity(XmlReader reader) { // Initialize all fields _speed = Speed.Invalid; _bearing = Azimuth.Invalid; // Deserialize the object from XML ReadXml(reader); } #endregion Constructors #region Public Properties /// <summary> /// Gets the objects rate of travel. /// </summary> public Speed Speed { get { return _speed; } } /// <summary> /// Gets the objects direction of travel. /// </summary> public Azimuth Bearing { get { return _bearing; } } /// <summary> /// Indicates whether the speed and bearing are both zero. /// </summary> public bool IsEmpty { get { return _speed.IsEmpty && _bearing.IsEmpty; } } /// <summary> /// Indicates whether the speed or bearing is invalid or unspecified. /// </summary> public bool IsInvalid { get { return _speed.IsInvalid || _bearing.IsInvalid; } } #endregion Public Properties #region Operators /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Velocity left, Velocity right) { return left.Equals(right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Velocity left, Velocity right) { return !left.Equals(right); } #endregion Operators #region Overrides /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return _speed.GetHashCode() ^ _bearing.GetHashCode(); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (obj is Velocity) return Equals((Velocity)obj); return false; } /// <summary> /// Outputs the current instance as a string using the default format. /// </summary> /// <returns>A <strong>String</strong> representing the current instance.</returns> public override string ToString() { return ToString("g", CultureInfo.CurrentCulture); } #endregion Overrides #region IEquatable<Velocity> /// <summary> /// Compares the current instance to the specified velocity. /// </summary> /// <param name="other">A <strong>Velocity</strong> object to compare with.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> public bool Equals(Velocity other) { return _speed.Equals(other.Speed) && _bearing.Equals(other.Bearing); } /// <summary> /// Compares the current instance to the specified velocity using the specified numeric precision. /// </summary> /// <param name="other">A <strong>Velocity</strong> object to compare with.</param> /// <param name="decimals">An <strong>Integer</strong> specifying the number of fractional digits to compare.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> public bool Equals(Velocity other, int decimals) { return _speed.Equals(other.Speed, decimals) && _bearing.Equals(other.Bearing, decimals); } #endregion IEquatable<Velocity> #region IFormattable Members /// <summary> /// Outputs the current instance as a string using the specified format and culture information. /// </summary> /// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param> /// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param> /// <returns>A <see cref="System.String"/> that represents this instance.</returns> public string ToString(string format, IFormatProvider formatProvider) { CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture; if (string.IsNullOrEmpty(format)) format = "G"; // Output as speed and bearing return _speed.ToString(format, culture) + " " + _bearing.ToString(format, culture); } #endregion IFormattable Members #region IXmlSerializable Members /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns>An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.</returns> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param> public void WriteXml(XmlWriter writer) { writer.WriteStartElement("Speed"); _speed.WriteXml(writer); writer.WriteEndElement(); writer.WriteStartElement("Bearing"); _bearing.WriteXml(writer); writer.WriteEndElement(); } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> public void ReadXml(XmlReader reader) { // Move to the <Speed> element if (!reader.IsStartElement("Speed")) reader.ReadToDescendant("Speed"); _speed.ReadXml(reader); _bearing.ReadXml(reader); reader.Read(); } #endregion IXmlSerializable Members #region ICloneable<Velocity> Members /// <summary> /// Clones this instance. /// </summary> /// <returns></returns> public Velocity Clone() { return new Velocity(_speed, _bearing); } #endregion ICloneable<Velocity> Members } }
#region File Description //----------------------------------------------------------------------------- // IKSample.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace InverseKinematicsSample { /// <summary> /// This sample demonstrates how to update an IK chain using the Cyclic Coordinate /// Descent algorithm (CCD). It also demonstrates how to hook up that IK chain to /// an avatar model. /// </summary> public class IKSample : Microsoft.Xna.Framework.Game { #region Fields and Constants //The number of links in the cylinder chain const int CylinderCount = 20; // Rendering stuff GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Model cylinderModel; SpriteFont font; // Keeps track of the input for this sample KeyboardState currentKeyboardState; GamePadState currentGamePadState; GamePadState prevGamePadState; KeyboardState prevKeyboardState; // Camera related controls float cameraRotX; float cameraRotY; float cameraRadius = 5; Matrix view; Matrix projection; /// <summary> /// The player controlled object that the IK chain attempts to reach. /// </summary> Cat cat; /// <summary> /// When set to true, the simulation will run continuously. /// </summary> bool runSimulation = true; /// <summary> /// Allows the player to step through each bone update of the IK chain. /// By default, the entire IK chain is updated once per frame. /// </summary> bool singleStep; /// <summary> /// The avatar renderer object used for drawing the avatar and /// accessing the avatar's bind pose. /// </summary> AvatarRenderer avatarRenderer; /// <summary> /// The list of bones to be updated as part of the IK chain. The order /// and number of bones in the IK chain will affect the way it animates to reach /// the cat. The default IK chain for the avatar in this sample is: /// FingerMiddle3Left, WristLeft, ElbowLeft, and ShoulderLeft. /// </summary> List<int> avatarBoneChain = new List<int>(); /// <summary> /// The list of bone transformation offsets from the avatar's bind pose. This /// list is akin to the AvatarAnimation.BoneTransforms. This list of transform /// matricies will be used to save the rotation information that moves the end /// effector toward the cat. /// </summary> List<Matrix> avatarBoneTransforms; /// <summary> /// Stores the entire list of world transforms for the avatar /// </summary> List<Matrix> avatarWorldTransforms; /// <summary> /// The list of local transforms for the avatar. The bones relevant to the /// IK chain are updated and stored in this list. /// </summary> List<Matrix> avatarLocalTransforms; /// <summary> /// The index into the avatarBoneChain for the currently updating bone. /// </summary> int avatarChainIndex = 1; /// <summary> /// Used for initializing the avatar transforms once. /// </summary> bool isAvatarInitialized = false; /// <summary> /// The list of bones to be updated as part of the IK chain. The order and /// number of bones in the IK chain will affect the way it animates to reach /// the cat. /// </summary> List<int> cylinderChain; /// <summary> /// The list of default position and orientation of the cylinder IK chain bones. /// These positions and orientations are in local space, and are relative to the /// parent bone. /// </summary> List<Matrix> cylinderChainBindPose = new List<Matrix>(); /// <summary> /// The list of bone transformation offsets from the cylinder chain's bind pose. /// This list is akin to the AvatarAnimation.BoneTransforms. This list of /// transform matricies will be used to save the rotation information that /// moves the end effector toward the cat. /// </summary> List<Matrix> cylinderChainTransforms; /// <summary> /// The collection of the parent indices for each bone in the related /// cylinderChainBindPose collection. This is identical to the implementation /// of the AvatarRenderer.ParentBones. /// </summary> List<int> cylinderChainParentBones; /// <summary> /// Stores the entire list of world transforms for the cylinder chain /// </summary> List<Matrix> cylinderWorldTransforms; /// <summary> /// The list of local transforms for the cylinder chain. The bones relevant /// to the IK chain are updated and stored in this list. /// </summary> List<Matrix> cylinderLocalTransforms; /// <summary> /// The world transform of the cylinder. /// </summary> Matrix cylinderRootWorldTransform = Matrix.Identity; /// <summary> /// The index into the cylinderChain for the currently updating bone. /// </summary> int cylinderChainIndex = 1; #endregion #region Initialization /// <summary> /// Constructor /// </summary> public IKSample() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 853; graphics.PreferredBackBufferHeight = 480; graphics.PreferMultiSampling = true; Components.Add(new GamerServicesComponent(this)); Content.RootDirectory = "Content"; } /// <summary> /// Creates the IK chains for the avatar and they cylinder chain /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("font"); LoadCylinderModel(); // Create the cat cat = new Cat(GraphicsDevice) { Scale = .3f, Position = new Vector3(-1, .25f, -2), Texture = Content.Load<Texture2D>("cat"), }; LoadAvatar(); InitializeCylinderChain(); } /// <summary> /// Load the cylinder model and configure its BasicEffect /// </summary> private void LoadCylinderModel() { //Load cylinder model cylinderModel = Content.Load<Model>("cylinder"); //Set the basic effect lighting for the cylinder model foreach (ModelMesh mesh in cylinderModel.Meshes) { foreach (Effect effect in mesh.Effects) { BasicEffect basicEffect = effect as BasicEffect; if (basicEffect != null) { basicEffect.EnableDefaultLighting(); basicEffect.PreferPerPixelLighting = true; } } } } /// <summary> /// Load the avatar and initialize the avatar IK chain. /// </summary> private void LoadAvatar() { // Create a new avatar renderer. avatarRenderer = new AvatarRenderer(AvatarDescription.CreateRandom(), true); // Create the avatar IK chain. avatarBoneChain.Clear(); avatarBoneChain.Add((int)AvatarBone.FingerMiddle3Left); avatarBoneChain.Add((int)AvatarBone.WristLeft); avatarBoneChain.Add((int)AvatarBone.ElbowLeft); avatarBoneChain.Add((int)AvatarBone.ShoulderLeft); // Initialize the avatar transform lists to the identity. int boneCount = AvatarRenderer.BoneCount; avatarBoneTransforms = Enumerable.Repeat(Matrix.Identity, boneCount).ToList(); avatarWorldTransforms = avatarBoneTransforms.ToList(); avatarLocalTransforms = avatarBoneTransforms.ToList(); // Rotate the right arm down so it's idle at the avatar's hip. avatarBoneTransforms[(int)AvatarBone.ShoulderRight] = Matrix.CreateRotationZ( MathHelper.ToRadians(80)); // Position the avatar. avatarRenderer.World = Matrix.CreateTranslation(1, 0, 0); } /// <summary> /// Create and initialize the cylinder IK chain /// </summary> private void InitializeCylinderChain() { // Initialize chain bind pose. Matrix T = Matrix.CreateTranslation(0, .1f, 0); cylinderChainBindPose = Enumerable.Repeat(T, CylinderCount).ToList(); // Initialize the chain transform lists to the identity cylinderChainTransforms = Enumerable.Repeat(Matrix.Identity, CylinderCount).ToList(); cylinderWorldTransforms = cylinderChainTransforms.ToList(); cylinderLocalTransforms = cylinderChainTransforms.ToList(); // Initialize the parent index list. For the cylinder chain, the parent bone // is the one just before it in the list. This gives us a list of parent // bones like this : {-1, 0, 1, 2, 3, ..., chainBindPose.Count - 2}. Each // number is the parent bone index into cylinderChainBindPose and // cylinderChainTransforms. This is identical to the implementation of // the AvatarRenderer class. cylinderChainParentBones = Enumerable.Range(-1, CylinderCount).ToList(); // Initialize the IK chain. This will give an IK chain that looks like this: // {CylinderCount - 1, CylinderCount - 2, ..., 1, 0}. The bone index at // cylinderChain[0] is used as the end effector of the IK chain. Each // number is the bone index into cylinderChainBindPose // and cylinderChainTransforms. cylinderChain = Enumerable.Range(0, CylinderCount).Reverse().ToList(); //Initialize the World and Local transform lists UpdateTransforms(cylinderWorldTransforms, cylinderLocalTransforms, cylinderRootWorldTransform, cylinderChainBindPose, cylinderChainTransforms, cylinderChainParentBones); } #endregion #region Update /// <summary> /// Allows the game logic to run /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { HandleInput(gameTime); UpdateCamera(); // Only run the IK simulation if the user has unpaused the simulation or // chosen to step through it. if (runSimulation || IsTriggered(Buttons.B) || IsTriggered(Keys.Space)) { UpdateAvatarIK(); UpdateCylinderChainIK(); } base.Update(gameTime); } /// <summary> /// Update the view and projection matrices. /// </summary> private void UpdateCamera() { view = Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotY)) * Matrix.CreateRotationX(MathHelper.ToRadians(cameraRotX)) * Matrix.CreateLookAt(new Vector3(0, 0, -cameraRadius), new Vector3(0, 0, 0), Vector3.Up); float aspectRatio = GraphicsDevice.Viewport.AspectRatio; projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), aspectRatio, 1, 1000); } #endregion #region Inverse Kinematics /// <summary> /// Loop over the Avatar IK chain and update each bone. The goal is to bring the /// end effector closer to the cat /// </summary> private void UpdateAvatarIK() { if ( avatarRenderer.State != AvatarRendererState.Ready) { isAvatarInitialized = false; } else { // We need to initialize the avatars transforms once it's loaded if (isAvatarInitialized == false) { UpdateTransforms(avatarWorldTransforms, avatarLocalTransforms, avatarRenderer.World, avatarRenderer.BindPose, avatarBoneTransforms, avatarRenderer.ParentBones); isAvatarInitialized = true; } //Make the avatar look at the cat AvatarLookAt(cat.Position); // Update avatar chain while (avatarChainIndex < avatarBoneChain.Count) { // Update the current IK bone. UpdateBone(avatarBoneTransforms, avatarBoneChain[avatarChainIndex], avatarBoneChain[0], cat.Position, avatarWorldTransforms, avatarLocalTransforms); // Update the local and world transforms for the IK chain now that // bones have moved. UpdateTransforms(avatarWorldTransforms, avatarLocalTransforms, avatarRenderer.World, avatarRenderer.BindPose, avatarBoneTransforms, avatarRenderer.ParentBones); // Move to the next bone. ++avatarChainIndex; // If the user wants to view each bone update one at a time, we // exit the loop here. if (singleStep) break; } // Reset the IK chain index to one after the end effector if (avatarChainIndex >= avatarBoneChain.Count) avatarChainIndex = 1; } } /// <summary> /// Makes the avatar look at a position in world space. /// </summary> /// <param name="position">The position in world space to look at</param> private void AvatarLookAt(Vector3 position) { int headIndex = (int)AvatarBone.Head; Vector3 target = position - avatarWorldTransforms[headIndex].Translation; target.X = -target.X; //Flip the X axis. Matrix lookAt = Matrix.CreateLookAt( Vector3.Zero, target, Vector3.Up); avatarBoneTransforms[headIndex] = lookAt; } /// <summary> /// Loop over the cylinder IK chain and update each bone to bring the /// end effector closer to the cat /// </summary> private void UpdateCylinderChainIK() { // Update cylinder chain while (cylinderChainIndex < cylinderChain.Count) { // Update the current IK bone UpdateBone(cylinderChainTransforms, cylinderChain[cylinderChainIndex], cylinderChain[0], cat.Position, cylinderWorldTransforms, cylinderLocalTransforms); // Update the local and world transforms for the IK chain now that // bones have moved. UpdateTransforms(cylinderWorldTransforms, cylinderLocalTransforms, cylinderRootWorldTransform, cylinderChainBindPose, cylinderChainTransforms, cylinderChainParentBones); // Move to the next bone ++cylinderChainIndex; // If the user wants to view each bone update one at a time, we // exit the loop her. if (singleStep) break; } // Reset the IK chain index to one after the end effector if (cylinderChainIndex >= cylinderChain.Count) cylinderChainIndex = 1; } /// <summary> /// This is the primary function for updating inverse kinematics. Here, we /// implement the Cyclic Coordinate Decsent algorithm. In a nutshell this is /// what we are trying to do: Given a goal position, end effector (often /// the end bone in a chain), and a current bone, we want to rotate the current /// bone such that it will bring the end effector closer to the goal position. /// We do this iteratively for every bone in the chain. /// /// Here's a very basic idea of how the algorithm works: /// 1) Compute vector directions for the bone to /// the goal and the bone to end effector. /// 2) Compute a matrix that rotates the end effector vector onto /// the goal vector. /// 3) Rotate the current bone by this rotation matrix. /// 4) Repeat steps 1-3 for each bone in the chain. /// </summary> /// <param name="curBone">The index into the bone chain for the current /// bone to update.</param> /// <param name="endEffector">The index of the end effector in bone chain. The /// end effector is the end bone that we want to move toward the cat.</param> /// <param name="goal">The world position of the object the IK chain is trying /// to move to.</param> /// <param name="rootWorldTransform">The world transform for the root of /// the bone chain</param> /// <param name="bindPose">The bind pose of the IK objects or the default /// position and orientation of the bones in the IK chain</param> /// <param name="transforms">The list of rotational offsets from /// the bind pose</param> /// <param name="parentBones">The list of parent bones for each /// bone index.</param> static private void UpdateBone(IList<Matrix> transforms, int curBone, int endEffector, Vector3 goal, IList<Matrix> worldTransforms, IList<Matrix> localTransforms) { // We first compute the vector directions for the current bone to the goal // and the current bone to end effector. We will do all this in the current // bone's local coordinates which makes it easier to generate our final // rotation matrix for the bone. // Get the world transform of the current bone Matrix curBoneWorld = worldTransforms[curBone]; // Transform the goal into coordinate system of current bone. To do this, we // transform the goal position by the inverse world transform of the // current bone. Vector3 goalInBoneSpace = Vector3.Transform( goal, Matrix.Invert(curBoneWorld)); // Transform the end effector into coordinate system of the current bone. To // do this, we first compute the current world transform of the end effector // then we multiply it by the Inverse of the current bone's world transform. // We then store the position. Matrix endEffectorWorld = worldTransforms[endEffector]; Vector3 endEffectorInBoneSpace = Matrix.Multiply(endEffectorWorld, Matrix.Invert(curBoneWorld)).Translation; // After we normalize, we will have unit vectors that represent the // direction to the end effector and the goal in the local coordinate space // of the current bone. endEffectorInBoneSpace.Normalize(); goalInBoneSpace.Normalize(); // Next we build the rotation matrix that rotates the end effector onto the // goal and apply that rotation to the current bone. // Compute axis of rotation: the cross product of the two vectors. Vector3 axis = Vector3.Cross(endEffectorInBoneSpace, goalInBoneSpace); // Use TransformNormal to orient the axis by the local coordinate // transform of the current bone axis = Vector3.TransformNormal(axis, localTransforms[curBone]); axis.Normalize(); // Compute the angle we will be rotating by which is just the angle // between the vectors float dot = Vector3.Dot(goalInBoneSpace, endEffectorInBoneSpace); //Clamp to -1 and 1 to avoid any possible floating point precision errors dot = MathHelper.Clamp(dot, -1, 1); //Compute the angle. float angle = (float)Math.Acos(dot); angle = MathHelper.WrapAngle(angle); // We can clamp the angle here which will make the animation look smoother. // However, for demonstration purposes we will comment this out for now. //float clampAmount = MathHelper.ToRadians(.1f); //angle = MathHelper.Clamp(angle, -clampAmount, clampAmount); // Create the rotation matrix Matrix rotation = Matrix.CreateFromAxisAngle(axis, angle); // Rotate the current bone by the new rotation matrix transforms[curBone] *= rotation; } /// <summary> /// Updates the list of world transforms for a bone hierarchy. The hierarchy /// must be sorted by bone depth where the parent bone is at the head of /// the list /// </summary> /// <param name="worldTransforms">The list of world transforms to update</param> /// <param name="rootWorldTransform">The root world transform of /// the root bone</param> /// <param name="bindPose">The defaulft pose of the bone hierarchy</param> /// <param name="animationTransforms">The transform offsets from the bind /// pose</param> /// <param name="parentBones">The list of parent bones for each bone /// index.</param> static public void UpdateTransforms(IList<Matrix> worldTransforms, IList<Matrix> localTransforms, Matrix rootWorldTransform, IList<Matrix> bindPose, IList<Matrix> animationTransforms, IList<int> parentBones) { //Set the parent bone transform localTransforms[0] = Matrix.Multiply( animationTransforms[0], bindPose[0]); worldTransforms[0] = Matrix.Multiply( localTransforms[0], rootWorldTransform); // Loop all of the bones. // Since the bone hierarchy is sorted by depth // we will transform the parent before any child. for (int curBone = 1; curBone < worldTransforms.Count; curBone++) { //calculate the local transform of the bone Matrix local = Matrix.Multiply(animationTransforms[curBone], bindPose[curBone]); // Find the transform of this bones parent. // If this is the first bone use the world matrix used on the avatar Matrix parentMatrix = worldTransforms[parentBones[curBone]]; // Calculate this bones world space position localTransforms[curBone] = local; worldTransforms[curBone] = Matrix.Multiply( local, parentMatrix); } } #endregion #region Draw /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); GraphicsDevice.BlendState = BlendState.AlphaBlend; GraphicsDevice.DepthStencilState = DepthStencilState.Default; DrawCylinderChain(); DrawAvatar(); // Draw the cat Vector3 cameraPosition = Matrix.Invert(view).Translation; cat.Draw(cameraPosition, view, projection); DrawHUD(); } /// <summary> /// Draws the platform specific HUD /// </summary> private void DrawHUD() { #if XBOX DrawXboxSpecificHUD(); #else DrawWindowsSpecificHUD(); #endif } /// <summary> /// Render the controls on the screen /// </summary> private void DrawXboxSpecificHUD() { string pausedText = "Simulation: Running"; if (!runSimulation) pausedText = "Simulation: Paused"; pausedText += "\nPress 'A' to toggle"; string singleStepText = "Single Step is: ON"; if (!singleStep) singleStepText = "Single Step is: OFF"; singleStepText += "\nPress 'Start' to toggle"; string stepThrough = ""; if (singleStep || !runSimulation) stepThrough = "\nPress 'B' to step once"; string controlsText = "-Controls-\n"; controlsText += "Move camera: Right Thumbstick\n"; controlsText += "Zoom camera: Left/Right Trigger\n"; controlsText += "Move cat: Left Thumbstick\n"; controlsText += "Zoom cat: X/Y Button\n"; controlsText += "Reset: Thumbstick Down"; spriteBatch.Begin(); spriteBatch.DrawString(font, pausedText, new Vector2(100, 80), Color.White); spriteBatch.DrawString(font, singleStepText, new Vector2(100, 120), Color.White); spriteBatch.DrawString(font, stepThrough, new Vector2(100, 160), Color.White); spriteBatch.DrawString(font, controlsText, new Vector2(100, 300), Color.White); spriteBatch.End(); } /// <summary> /// Render the controls on the screen /// </summary> private void DrawWindowsSpecificHUD() { string pausedText = "Simulation: Running"; if (!runSimulation) pausedText = "Simulation: Paused"; pausedText += "\nPress 'P' to toggle"; string singleStepText = "Single Step is: ON"; if (!singleStep) singleStepText = "Single Step is: OFF"; singleStepText += "\nPress 'Enter' to toggle"; string stepThrough = ""; if (singleStep || !runSimulation) stepThrough = "\nPress 'Space' to step once"; string controlsText = "-Controls-\n"; controlsText += "Move camera: Arrow Keys\n"; controlsText += "Zoom camera: Z/X Key\n"; controlsText += "Move cat: W,A,S,D Keys\n"; controlsText += "Zoom cat: Q/E Key\n"; controlsText += "Reset: R Key"; spriteBatch.Begin(); spriteBatch.DrawString(font, pausedText, new Vector2(100, 80), Color.White); spriteBatch.DrawString(font, singleStepText, new Vector2(100, 120), Color.White); spriteBatch.DrawString(font, stepThrough, new Vector2(100, 160), Color.White); spriteBatch.DrawString(font, controlsText, new Vector2(100, 300), Color.White); spriteBatch.End(); } /// <summary> /// Draws the cylinder chain /// </summary> private void DrawCylinderChain() { Matrix modelTransform = Matrix.CreateScale(.04f, .025f, .04f); DrawBones(cylinderModel, modelTransform, cylinderChainIndex, cylinderChain, cylinderWorldTransforms); } /// <summary> /// Draws the Avatar and it's IK Chain /// </summary> private void DrawAvatar() { avatarRenderer.View = view; avatarRenderer.Projection = projection; avatarRenderer.Draw(avatarBoneTransforms, new AvatarExpression()); // Draw the avatar bone chain Matrix S = Matrix.CreateScale(.04f, .01f, .04f); Matrix R = Matrix.CreateRotationZ(MathHelper.ToRadians(90)); Matrix modelTransform = Matrix.Multiply(S, R); if (avatarRenderer.State == AvatarRendererState.Ready) { DrawBones(cylinderModel, modelTransform, avatarChainIndex, avatarBoneChain, avatarWorldTransforms); } } /// <summary> /// Draws the bones of a bone chain using a given model and scale /// </summary> /// <param name="model">The model to use to represent the bones</param> /// <param name="scale">The scale of the model when drawing the bones</param> /// <param name="boneToColor">The current updating bone that will appear as a /// unique color. This param is only used if the user is watching each bone /// update one at a time: (singStep == true)</param> /// <param name="rootWorldTransform">The world transform for the /// root of the bone chain</param> /// <param name="boneChain">The bone chain to draw</param> /// <param name="bindPose">The bind pose of the IK objects or the default /// position and orientation of the bones in the IK chain</param> /// <param name="transforms">The list of rotational offsets from the /// bind pose</param> /// <param name="parentBones">The list of parent bones for each /// bone index.</param> private void DrawBones(Model model, Matrix modelTransform, int boneToColor, IList<int> boneChain, IList<Matrix> worldTransfroms) { //Compute the colors we will use to render the bone chain Vector3 red = Color.Red.ToVector3(); Vector3 black = Color.Black.ToVector3(); Vector3 lightGray = Color.LightGray.ToVector3(); // Configure the BasicEffect foreach (int curBone in boneChain) { // Change the color of the bone we are updating if single // step is enabled Vector3 diffuseColor = lightGray; if (singleStep) { if (boneChain[boneToColor] == curBone) diffuseColor = red; else if (curBone == boneChain[0]) diffuseColor = black; } //Draw the model foreach (ModelMesh mesh in model.Meshes) { //Configure the basic effects foreach (Effect effect in mesh.Effects) { BasicEffect basicEffect = effect as BasicEffect; if(basicEffect != null) { basicEffect.World = modelTransform * worldTransfroms[curBone]; basicEffect.View = view; basicEffect.Projection = projection; basicEffect.DiffuseColor = diffuseColor; } } mesh.Draw(); } } } #endregion #region Handle Input /// <summary> /// Handle controler and keyboad input to move the cat the camera and to allow /// the user to exit the sample /// </summary> private void HandleInput(GameTime gameTime) { float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds; // Save current input states as the previous states for the next update. prevGamePadState = currentGamePadState; prevKeyboardState = currentKeyboardState; //Get the new input states currentGamePadState = GamePad.GetState(PlayerIndex.One); currentKeyboardState = Keyboard.GetState(); // Allows the game to exit if (IsDown(Buttons.Back) || IsDown(Keys.Escape)) this.Exit(); // Allow the user to reset the camera and cat. if (IsTriggered(Buttons.LeftStick) || IsTriggered(Buttons.RightStick) || IsTriggered(Keys.R)) { Reset(); } // Allow the user to start and stop the IK simulation if (IsTriggered(Buttons.A) || IsTriggered(Keys.P)) { runSimulation = !runSimulation; } // If the user presses B he/she want's to pause and step through // the simulation if (IsTriggered(Buttons.B) || IsTriggered(Keys.Space)) { runSimulation = false; } // Allow the user to toggle single step mode if (IsTriggered(Buttons.Start) || IsTriggered(Keys.Enter)) { singleStep = !singleStep; } // Handle input that will control the cat float moveSpeed = .1f; Vector2 movement = currentGamePadState.ThumbSticks.Left * moveSpeed; if (IsDown(Keys.W)) movement.Y += moveSpeed; if (IsDown(Keys.S)) movement.Y -= moveSpeed; if (IsDown(Keys.A)) movement.X -= moveSpeed; if (IsDown(Keys.D)) movement.X += moveSpeed; // Allow the cat to be moved toward and away from the center float zoom = 0; if (IsDown(Buttons.Y) || IsDown(Keys.Q)) zoom = .008f; if (IsDown(Buttons.X) || IsDown(Keys.E)) zoom = -.008f; // Update the radius and rotation angels of the cat movement.X = -movement.X; cat.Position += new Vector3(movement, zoom * time); // Handle input that will control the camera moveSpeed = .1f; movement = currentGamePadState.ThumbSticks.Right * moveSpeed; if (IsDown(Keys.Up)) movement.Y += moveSpeed; if (IsDown(Keys.Down)) movement.Y -= moveSpeed; if (IsDown(Keys.Left)) movement.X -= moveSpeed; if (IsDown(Keys.Right)) movement.X += moveSpeed; // Allow the camera to be zoomed in and out zoom = 0; zoom += currentGamePadState.Triggers.Right * .01f; zoom -= currentGamePadState.Triggers.Left * .01f; if (IsDown(Keys.Z)) zoom = .007f; if (IsDown(Keys.X)) zoom = -.007f; // Update the rotation angles and radius of the camera cameraRotX += movement.Y * time; cameraRotY += movement.X * time; cameraRadius += zoom * time; } /// <summary> /// Resets everything /// </summary> private void Reset() { cat.Position = new Vector3(-1, .25f, -2); cameraRotX = 0; cameraRotY = 0; cameraRadius = 5; runSimulation = true; singleStep = false; InitializeCylinderChain(); LoadAvatar(); } /// <summary> /// Returns if a button/key was just pressed /// </summary> /// <param name="button">The button to check</param> public bool IsTriggered(Buttons button) { return currentGamePadState.IsButtonDown(button) && !prevGamePadState.IsButtonDown(button); } /// <summary> /// Returns if a button/key was just pressed /// </summary> /// <param name="key">The key to check</param> public bool IsTriggered(Keys key) { return currentKeyboardState.IsKeyDown(key) && !prevKeyboardState.IsKeyDown(key); } /// <summary> /// Returns if a button/key is down /// </summary> public bool IsDown(Buttons button) { return currentGamePadState.IsButtonDown(button); } /// <summary> /// Returns if a button/key is down /// </summary> public bool IsDown(Keys key) { return currentKeyboardState.IsKeyDown(key); } #endregion } #region Entry Point static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (IKSample game = new IKSample()) { game.Run(); } } } #endregion }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics; // Process class using System.ComponentModel; // Win32Exception using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; using System.Management; using System.Management.Automation; using System.Management.Automation.Internal; using System.Diagnostics.CodeAnalysis; using System.Net; using System.IO; using System.Security; using System.Security.Principal; using System.Security.AccessControl; using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { #region Get-HotFix /// <summary> /// Cmdlet for Get-Hotfix Proxy /// </summary> [Cmdlet(VerbsCommon.Get, "HotFix", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135217", RemotingCapability = RemotingCapability.SupportedByCommand)] [OutputType(@"System.Management.ManagementObject#root\cimv2\Win32_QuickFixEngineering")] public sealed class GetHotFixCommand : PSCmdlet, IDisposable { #region Parameters /// <summary> /// Specifies the HotFixID. Unique identifier associated with a particular update. /// </summary> [Parameter(Position = 0, ParameterSetName = "Default")] [ValidateNotNullOrEmpty] [Alias("HFID")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Id { get; set; } /// <summary> /// To search on description of Hotfixes /// </summary> [Parameter(ParameterSetName = "Description")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Description { get; set; } /// <summary> /// Parameter to pass the Computer Name /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Alias("CN", "__Server", "IPAddress")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ComputerName { get; set; } = new string[] { "localhost" }; /// <summary> /// Parameter to pass the Credentials. /// </summary> [Parameter] [Credential] [ValidateNotNullOrEmpty] public PSCredential Credential { get; set; } #endregion Parameters #region Overrides private ManagementObjectSearcher _searchProcess; private bool _inputContainsWildcard = false; /// <summary> /// Get the List of HotFixes installed on the Local Machine. /// </summary> protected override void BeginProcessing() { foreach (string computer in ComputerName) { bool foundRecord = false; StringBuilder QueryString = new StringBuilder(); ConnectionOptions conOptions = ComputerWMIHelper.GetConnectionOptions(AuthenticationLevel.Packet, ImpersonationLevel.Impersonate, this.Credential); ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), conOptions); scope.Connect(); if (Id != null) { QueryString.Append("Select * from Win32_QuickFixEngineering where ("); for (int i = 0; i <= Id.Length - 1; i++) { QueryString.Append("HotFixID= '"); QueryString.Append(Id[i].ToString().Replace("'", "\\'")); QueryString.Append("'"); if (i < Id.Length - 1) QueryString.Append(" Or "); } QueryString.Append(")"); } else { QueryString.Append("Select * from Win32_QuickFixEngineering"); foundRecord = true; } _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(QueryString.ToString())); foreach (ManagementObject obj in _searchProcess.Get()) { if (Description != null) { if (!FilterMatch(obj)) continue; } else { _inputContainsWildcard = true; } // try to translate the SID to a more friendly username // just stick with the SID if anything goes wrong string installed = (string)obj["InstalledBy"]; if (!String.IsNullOrEmpty(installed)) { try { SecurityIdentifier secObj = new SecurityIdentifier(installed); obj["InstalledBy"] = secObj.Translate(typeof(NTAccount)); ; } catch (IdentityNotMappedException) // thrown by SecurityIdentifier.Translate { } catch (SystemException e) // thrown by SecurityIdentifier.constr { CommandsCommon.CheckForSevereException(this, e); } //catch (ArgumentException) // thrown (indirectly) by SecurityIdentifier.constr (on XP only?) //{ catch not needed - this is already caught as SystemException //} //catch (PlatformNotSupportedException) // thrown (indirectly) by SecurityIdentifier.Translate (on Win95 only?) //{ catch not needed - this is already caught as SystemException //} //catch (UnauthorizedAccessException) // thrown (indirectly) by SecurityIdentifier.Translate //{ catch not needed - this is already caught as SystemException //} } WriteObject(obj); foundRecord = true; } if (!foundRecord && !_inputContainsWildcard) { Exception Ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer)); WriteError(new ErrorRecord(Ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null)); } if (_searchProcess != null) { this.Dispose(); } } }//end of BeginProcessing method /// <summary> /// to implement ^C /// </summary> protected override void StopProcessing() { if (_searchProcess != null) { _searchProcess.Dispose(); } } #endregion Overrides #region "Private Methods" private bool FilterMatch(ManagementObject obj) { try { foreach (string desc in Description) { WildcardPattern wildcardpattern = WildcardPattern.Get(desc, WildcardOptions.IgnoreCase); if (wildcardpattern.IsMatch((string)obj["Description"])) { return true; } if (WildcardPattern.ContainsWildcardCharacters(desc)) { _inputContainsWildcard = true; } } } catch (Exception e) { CommandsCommon.CheckForSevereException(this, e); return false; } return false; } #endregion "Private Methods" #region "IDisposable Members" /// <summary> /// Dispose Method /// </summary> public void Dispose() { this.Dispose(true); // Use SuppressFinalize in case a subclass // of this type implements a finalizer. GC.SuppressFinalize(this); } /// <summary> /// Dispose Method. /// </summary> /// <param name="disposing"></param> public void Dispose(bool disposing) { if (disposing) { if (_searchProcess != null) { _searchProcess.Dispose(); } } } #endregion "IDisposable Members" }//end class #endregion }//Microsoft.Powershell.commands
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !MONO namespace NLog.UnitTests.Config { using NLog.Config; using System; using System.IO; using System.Threading; using Xunit; public class ReloadTests : NLogTestBase { [Fact] public void TestNoAutoReload() { string config1 = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "noreload.nlog"); WriteConfigFile(configFilePath, config1); try { LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); Assert.False(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(configFilePath, config2, assertDidReload: false); logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestAutoReloadOnFileChange() { string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string badConfig = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload.nlog"); WriteConfigFile(configFilePath, config1); try { LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); Assert.True(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(configFilePath, badConfig, assertDidReload: false); logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); ChangeAndReloadConfigFile(configFilePath, config2); logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestAutoReloadOnFileMove() { string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload.nlog"); WriteConfigFile(configFilePath, config1); string otherFilePath = Path.Combine(tempPath, "other.nlog"); try { LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Move(configFilePath, otherFilePath); reloadWaiter.WaitForReload(); } logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(otherFilePath, config2); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Move(otherFilePath, configFilePath); reloadWaiter.WaitForReload(); Assert.True(reloadWaiter.DidReload); } logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestAutoReloadOnFileCopy() { string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload.nlog"); WriteConfigFile(configFilePath, config1); string otherFilePath = Path.Combine(tempPath, "other.nlog"); try { LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Delete(configFilePath); reloadWaiter.WaitForReload(); } logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(otherFilePath, config2); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Copy(otherFilePath, configFilePath); File.Delete(otherFilePath); reloadWaiter.WaitForReload(); Assert.True(reloadWaiter.DidReload); } logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestIncludedConfigNoReload() { string mainConfig1 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Info' writeTo='debug' /></rules> </nlog>"; string includedConfig1 = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string includedConfig2 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string includedConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(includedConfigFilePath, includedConfig1); try { LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false); logger.Debug("bbb"); // Assert that mainConfig1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(mainConfigFilePath, mainConfig1); ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2, assertDidReload: false); logger.Debug("ccc"); // Assert that includedConfig1 is still loaded. AssertDebugLastMessage("debug", "ccc"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestIncludedConfigReload() { string mainConfig1 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Info' writeTo='debug' /></rules> </nlog>"; string includedConfig1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string includedConfig2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string includedConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(includedConfigFilePath, includedConfig1); try { LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false); logger.Debug("bbb"); // Assert that mainConfig1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(mainConfigFilePath, mainConfig1); ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2); logger.Debug("ccc"); // Assert that includedConfig2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestMainConfigReload() { string mainConfig1 = @"<nlog autoReload='true'> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog autoReload='true'> <include file='included2.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string included1Config = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string included2Config1 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string included2Config2 = @"<nlog> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(included1ConfigFilePath, included1Config); string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog"); WriteConfigFile(included2ConfigFilePath, included2Config1); try { LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2); logger.Debug("bbb"); // Assert that mainConfig2 is loaded (which refers to included2.nlog). AssertDebugLastMessage("debug", "[bbb]"); ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2); logger.Debug("ccc"); // Assert that included2Config2 is loaded. AssertDebugLastMessage("debug", "(ccc)"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestMainConfigReloadIncludedConfigNoReload() { string mainConfig1 = @"<nlog autoReload='true'> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog autoReload='true'> <include file='included2.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string included1Config = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string included2Config1 = @"<nlog autoReload='false'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string included2Config2 = @"<nlog autoReload='false'> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(included1ConfigFilePath, included1Config); string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog"); WriteConfigFile(included2ConfigFilePath, included2Config1); try { LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2); logger.Debug("bbb"); // Assert that mainConfig2 is loaded (which refers to included2.nlog). AssertDebugLastMessage("debug", "[bbb]"); ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2, assertDidReload: false); logger.Debug("ccc"); // Assert that included2Config1 is still loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestKeepVariablesOnReload() { string config = @"<nlog autoReload='true' keepVariablesOnReload='true'> <variable name='var1' value='' /> <variable name='var2' value='keep_value' /> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload_var.nlog"); WriteConfigFile(configFilePath, config); try { LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); LogManager.Configuration.Variables["var1"] = "new_value"; LogManager.Configuration.Variables["var3"] = "new_value3"; ChangeAndReloadConfigFile(configFilePath, config); Assert.Equal("new_value", LogManager.Configuration.Variables["var1"].OriginalText); Assert.Equal("keep_value", LogManager.Configuration.Variables["var2"].OriginalText); Assert.Equal("new_value3", LogManager.Configuration.Variables["var3"].OriginalText); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestResetVariablesOnReload() { string config = @"<nlog autoReload='true' keepVariablesOnReload='false'> <variable name='var1' value='' /> <variable name='var2' value='keep_value' /> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload_var.nlog"); WriteConfigFile(configFilePath, config); try { LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); LogManager.Configuration.Variables["var1"] = "new_value"; LogManager.Configuration.Variables["var3"] = "new_value3"; ChangeAndReloadConfigFile(configFilePath, config); Assert.Equal("", LogManager.Configuration.Variables["var1"].OriginalText); Assert.Equal("keep_value", LogManager.Configuration.Variables["var2"].OriginalText); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } private static void WriteConfigFile(string configFilePath, string config) { using (StreamWriter writer = File.CreateText(configFilePath)) writer.Write(config); } private static void ChangeAndReloadConfigFile(string configFilePath, string config, bool assertDidReload = true) { using (var reloadWaiter = new ConfigurationReloadWaiter()) { WriteConfigFile(configFilePath, config); reloadWaiter.WaitForReload(); if (assertDidReload) Assert.True(reloadWaiter.DidReload, "Config did not reload."); } } private class ConfigurationReloadWaiter : IDisposable { private CountdownEvent counterEvent = new CountdownEvent(1); public ConfigurationReloadWaiter() { LogManager.ConfigurationReloaded += SignalCounterEvent(counterEvent); } public bool DidReload { get { return counterEvent.CurrentCount == 0; } } public void Dispose() { LogManager.ConfigurationReloaded -= SignalCounterEvent(counterEvent); } public void WaitForReload() { counterEvent.Wait(2000); } private static EventHandler<LoggingConfigurationReloadedEventArgs> SignalCounterEvent(CountdownEvent counterEvent) { return (sender, e) => { if (counterEvent.CurrentCount > 0) counterEvent.Signal(); }; } } } } #endif
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Management; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Security.Principal; using Microsoft.Win32.SafeHandles; namespace DriveProxy.Utils { internal class UserProcess { public static bool IsRunning(string processName, bool forCurrentUserOnly) { try { int processId = Process.GetCurrentProcess().Id; string filename = Process.GetCurrentProcess().Modules[0].FileName; Process[] processes = GetProcessesByName(processName, forCurrentUserOnly); if (processes != null) { foreach (Process t in processes) { try { if (t.Id != processId) { if (t.Modules[0].FileName == filename) { return true; } } } catch { return true; } } } return false; } catch (Exception exception) { Log.Error(exception); return false; } } public static System.Diagnostics.Process[] GetProcessesByName(string processName, bool forCurrentUserOnly) { try { System.Diagnostics.Process[] processes = null; if (forCurrentUserOnly) { processes = UserProcess.GetProcessesByName(processName); } else { processes = System.Diagnostics.Process.GetProcessesByName(processName); } return processes; } catch (Exception exception) { Log.Error(exception); return null; } } public static System.Diagnostics.Process[] GetProcessesByName(string processName) { try { System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(processName); var processList = new List<System.Diagnostics.Process>(); foreach (System.Diagnostics.Process process in processes) { var query = new ObjectQuery("Select * from Win32_Process WHERE ProcessID = " + process.Id); using (var searcher = new ManagementObjectSearcher(query)) { using (ManagementObjectCollection objs = searcher.Get()) { foreach (ManagementObject obj in objs) { try { var owner = new String[2]; try { obj.InvokeMethod("GetOwner", owner); } catch { } if (owner == null || owner.Length == 0) { continue; } string user = owner[0]; if (String.IsNullOrEmpty(user)) { continue; } if (!String.Equals(user, Environment.UserName, StringComparison.CurrentCultureIgnoreCase)) { continue; } string domain = owner[1]; if (String.IsNullOrEmpty(domain)) { continue; } if (!String.Equals(domain, Environment.UserDomainName, StringComparison.CurrentCultureIgnoreCase)) { continue; } object name = obj["Name"]; if (name == null) { continue; } string tempName = name.ToString(); if (String.IsNullOrEmpty(tempName)) { continue; } if (!String.Equals(processName, tempName, StringComparison.CurrentCultureIgnoreCase)) { tempName = System.IO.Path.GetFileNameWithoutExtension(tempName); if (!String.Equals(processName, tempName, StringComparison.CurrentCultureIgnoreCase)) { continue; } } object processId = obj["ProcessID"]; if (processId == null) { continue; } int tempId = 0; if (!int.TryParse(processId.ToString(), out tempId)) { continue; } processList.Add(process); } catch (Exception exception) { Log.Error(exception, false); } } } } } return processList.ToArray(); } catch (Exception exception) { Log.Error(exception); return null; } } public static System.Diagnostics.Process Start(string filePath, bool checkIfAlreadyRunning, string processName, bool forCurrentUserOnly) { try { if (checkIfAlreadyRunning) { System.Diagnostics.Process[] processes = GetProcessesByName(processName, forCurrentUserOnly); if (processes != null && processes.Length > 0) { return processes[0]; } } if (!System.IO.File.Exists(filePath)) { string tempPath = System.Reflection.Assembly.GetEntryAssembly().Location; tempPath = System.IO.Path.GetDirectoryName(tempPath); tempPath = System.IO.Path.Combine(tempPath, filePath); if (System.IO.File.Exists(tempPath)) { filePath = tempPath; } } return System.Diagnostics.Process.Start(filePath); } catch (Exception exception) { Log.Error(exception); return null; } } [SuppressUnmanagedCodeSecurity] private class NativeMethods { public enum SECURITY_IMPERSONATION_LEVEL { SecurityAnonymous, SecurityIdentification, SecurityImpersonation, SecurityDelegation } public enum TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation } public const int GENERIC_ALL_ACCESS = 0x10000000; public const int CREATE_NO_WINDOW = 0x08000000; [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken); [ DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall) ] public static extern bool CloseHandle(IntPtr handle); [ DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall) ] public static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, Int32 dwCreationFlags, IntPtr lpEnvrionment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation); [ DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx") ] public static extern bool DuplicateTokenEx(IntPtr hExistingToken, Int32 dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, Int32 impersonationLevel, Int32 dwTokenType, ref IntPtr phNewToken); public static Process CreateProcessAsUser(string filename, string args) { try { IntPtr hToken = WindowsIdentity.GetCurrent().Token; IntPtr hDupedToken = IntPtr.Zero; var pi = new PROCESS_INFORMATION(); var sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); try { if (!DuplicateTokenEx( hToken, GENERIC_ALL_ACCESS, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hDupedToken )) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = ""; string path = Path.GetFullPath(filename); string dir = Path.GetDirectoryName(path); // Revert to self to create the entire process; not doing this might // require that the currently impersonated user has "Replace a process // level token" rights - we only want our service account to need // that right. using (WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero)) { if (!CreateProcessAsUser( hDupedToken, path, string.Format("\"{0}\" {1}", filename.Replace("\"", "\"\""), args), ref sa, ref sa, false, 0, IntPtr.Zero, dir, ref si, ref pi )) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } return Process.GetProcessById(pi.dwProcessID); } finally { if (pi.hProcess != IntPtr.Zero) { CloseHandle(pi.hProcess); } if (pi.hThread != IntPtr.Zero) { CloseHandle(pi.hThread); } if (hDupedToken != IntPtr.Zero) { CloseHandle(hDupedToken); } } } catch (Exception exception) { Log.Error(exception); return null; } } public static Process CreateProcessAsUser(string filename, string args, IntPtr hToken) { try { IntPtr hDupedToken = IntPtr.Zero; var pi = new PROCESS_INFORMATION(); var sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); try { var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = ""; string path = Path.GetFullPath(filename); string dir = Path.GetDirectoryName(path); if (!CreateProcessAsUser(hToken, path, string.Format("\"{0}\" {1}", filename.Replace("\"", "\"\""), args), ref sa, ref sa, false, 0, IntPtr.Zero, dir, ref si, ref pi)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return Process.GetProcessById(pi.dwProcessID); } finally { if (pi.hProcess != IntPtr.Zero) { CloseHandle(pi.hProcess); } if (pi.hThread != IntPtr.Zero) { CloseHandle(pi.hThread); } if (hDupedToken != IntPtr.Zero) { CloseHandle(hDupedToken); } } } catch (Exception exception) { Log.Error(exception); return null; } } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public readonly IntPtr hProcess; public readonly IntPtr hThread; public readonly Int32 dwProcessID; public readonly Int32 dwThreadID; } [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public Int32 Length; public readonly IntPtr lpSecurityDescriptor; public readonly bool bInheritHandle; } [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO { public Int32 cb; public readonly string lpReserved; public string lpDesktop; public readonly string lpTitle; public readonly Int32 dwX; public readonly Int32 dwY; public readonly Int32 dwXSize; public readonly Int32 dwXCountChars; public readonly Int32 dwYCountChars; public readonly Int32 dwFillAttribute; public readonly Int32 dwFlags; public readonly Int16 wShowWindow; public readonly Int16 cbReserved2; public readonly IntPtr lpReserved2; public readonly IntPtr hStdInput; public readonly IntPtr hStdOutput; public readonly IntPtr hStdError; } } public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeTokenHandle() : base(true) { } [DllImport("kernel32.dll")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr handle); protected override bool ReleaseHandle() { try { return CloseHandle(handle); } catch (Exception exception) { Log.Error(exception); return false; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UnityEngine; namespace XposeCraft.Collections { /// <summary> /// Represents a generic collection of key/value pairs. /// Can be used for serialization purposes, which implies that it can be used during a hot-swap in Unity Editor. /// To use, inherit this generic class to a non-generic version (no need to be public) and annotate [Serializable]. /// Source: https://forum.unity3d.com/threads/finally-a-serializable-dictionary-for-unity-extracted-from-system-collections-generic.335797/ /// </summary> /// <typeparam name="TKey">The type of keys in the dictionary.</typeparam> /// <typeparam name="TValue">The type of values in the dictionary.</typeparam> [Serializable, DebuggerDisplay("Count = {Count}")] public class SerializableDictionary3<TKey, TValue> : IDictionary<TKey, TValue> { [SerializeField, HideInInspector] int[] _buckets; [SerializeField, HideInInspector] int[] _hashCodes; [SerializeField, HideInInspector] int[] _next; [SerializeField, HideInInspector] int _count; [SerializeField, HideInInspector] int _version; [SerializeField, HideInInspector] int _freeList; [SerializeField, HideInInspector] int _freeCount; [SerializeField, HideInInspector] TKey[] _keys; [SerializeField, HideInInspector] TValue[] _values; readonly IEqualityComparer<TKey> _comparer; // Mainly for debugging purposes - to get the key-value pairs display public Dictionary<TKey, TValue> AsDictionary { get { return new Dictionary<TKey, TValue>(this); } } public int Count { get { return _count - _freeCount; } } public TValue this[TKey key, TValue defaultValue] { get { int index = FindIndex(key); if (index >= 0) return _values[index]; return defaultValue; } } public TValue this[TKey key] { get { int index = FindIndex(key); if (index >= 0) return _values[index]; throw new KeyNotFoundException(key.ToString()); } set { Insert(key, value, false); } } public SerializableDictionary3() : this(0, null) { } public SerializableDictionary3(int capacity) : this(capacity, null) { } public SerializableDictionary3(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public SerializableDictionary3(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) throw new ArgumentOutOfRangeException("capacity"); Initialize(capacity); _comparer = (comparer ?? EqualityComparer<TKey>.Default); } public SerializableDictionary3(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public SerializableDictionary3(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this((dictionary != null) ? dictionary.Count : 0, comparer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); foreach (KeyValuePair<TKey, TValue> current in dictionary) Add(current.Key, current.Value); } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < _count; i++) { if (_hashCodes[i] >= 0 && _values[i] == null) return true; } } else { var defaultComparer = EqualityComparer<TValue>.Default; for (int i = 0; i < _count; i++) { if (_hashCodes[i] >= 0 && defaultComparer.Equals(_values[i], value)) return true; } } return false; } public bool ContainsKey(TKey key) { return FindIndex(key) >= 0; } public void Clear() { if (_count <= 0) return; for (int i = 0; i < _buckets.Length; i++) _buckets[i] = -1; Array.Clear(_keys, 0, _count); Array.Clear(_values, 0, _count); Array.Clear(_hashCodes, 0, _count); Array.Clear(_next, 0, _count); _freeList = -1; _count = 0; _freeCount = 0; _version++; } public void Add(TKey key, TValue value) { Insert(key, value, true); } private void Resize(int newSize, bool forceNewHashCodes) { int[] bucketsCopy = new int[newSize]; for (int i = 0; i < bucketsCopy.Length; i++) bucketsCopy[i] = -1; var keysCopy = new TKey[newSize]; var valuesCopy = new TValue[newSize]; var hashCodesCopy = new int[newSize]; var nextCopy = new int[newSize]; Array.Copy(_values, 0, valuesCopy, 0, _count); Array.Copy(_keys, 0, keysCopy, 0, _count); Array.Copy(_hashCodes, 0, hashCodesCopy, 0, _count); Array.Copy(_next, 0, nextCopy, 0, _count); if (forceNewHashCodes) { for (int i = 0; i < _count; i++) { if (hashCodesCopy[i] != -1) hashCodesCopy[i] = (_comparer.GetHashCode(keysCopy[i]) & 2147483647); } } for (int i = 0; i < _count; i++) { int index = hashCodesCopy[i] % newSize; nextCopy[i] = bucketsCopy[index]; bucketsCopy[index] = i; } _buckets = bucketsCopy; _keys = keysCopy; _values = valuesCopy; _hashCodes = hashCodesCopy; _next = nextCopy; } private void Resize() { Resize(PrimeHelper.ExpandPrime(_count), false); } public bool Remove(TKey key) { if (key == null) throw new ArgumentNullException("key"); int hash = _comparer.GetHashCode(key) & 2147483647; int index = hash % _buckets.Length; int num = -1; for (int i = _buckets[index]; i >= 0; i = _next[i]) { if (_hashCodes[i] == hash && _comparer.Equals(_keys[i], key)) { if (num < 0) _buckets[index] = _next[i]; else _next[num] = _next[i]; _hashCodes[i] = -1; _next[i] = _freeList; _keys[i] = default(TKey); _values[i] = default(TValue); _freeList = i; _freeCount++; _version++; return true; } num = i; } return false; } private void Insert(TKey key, TValue value, bool add) { if (key == null) throw new ArgumentNullException("key"); if (_buckets == null) Initialize(0); int hash = _comparer.GetHashCode(key) & 2147483647; int index = hash % _buckets.Length; int num1 = 0; for (int i = _buckets[index]; i >= 0; i = _next[i]) { if (_hashCodes[i] == hash && _comparer.Equals(_keys[i], key)) { if (add) throw new ArgumentException("Key already exists: " + key); _values[i] = value; _version++; return; } num1++; } int num2; if (_freeCount > 0) { num2 = _freeList; _freeList = _next[num2]; _freeCount--; } else { if (_count == _keys.Length) { Resize(); index = hash % _buckets.Length; } num2 = _count; _count++; } _hashCodes[num2] = hash; _next[num2] = _buckets[index]; _keys[num2] = key; _values[num2] = value; _buckets[index] = num2; _version++; //if (num3 > 100 && HashHelpers.IsWellKnownEqualityComparer(comparer)) //{ // comparer = (IEqualityComparer<TKey>)HashHelpers.GetRandomizedEqualityComparer(comparer); // Resize(entries.Length, true); //} } private void Initialize(int capacity) { int prime = PrimeHelper.GetPrime(capacity); _buckets = new int[prime]; for (int i = 0; i < _buckets.Length; i++) _buckets[i] = -1; _keys = new TKey[prime]; _values = new TValue[prime]; _hashCodes = new int[prime]; _next = new int[prime]; _freeList = -1; } private int FindIndex(TKey key) { if (key == null) throw new ArgumentNullException("key"); if (_buckets != null) { int hash = _comparer.GetHashCode(key) & 2147483647; for (int i = _buckets[hash % _buckets.Length]; i >= 0; i = _next[i]) { if (_hashCodes[i] == hash && _comparer.Equals(_keys[i], key)) return i; } } return -1; } public bool TryGetValue(TKey key, out TValue value) { int index = FindIndex(key); if (index >= 0) { value = _values[index]; return true; } value = default(TValue); return false; } private static class PrimeHelper { public static readonly int[] Primes = { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; public static bool IsPrime(int candidate) { if ((candidate & 1) != 0) { int num = (int) Math.Sqrt(candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } public static int GetPrime(int min) { if (min < 0) throw new ArgumentException("min < 0"); for (int i = 0; i < Primes.Length; i++) { int prime = Primes[i]; if (prime >= min) return prime; } for (int i = min | 1; i < 2147483647; i += 2) { if (IsPrime(i) && (i - 1) % 101 != 0) return i; } return min; } public static int ExpandPrime(int oldSize) { int num = 2 * oldSize; if (num > 2146435069 && 2146435069 > oldSize) { return 2146435069; } return GetPrime(num); } } public ICollection<TKey> Keys { get { return _keys.Take(Count).ToArray(); } } public ICollection<TValue> Values { get { return _values.Take(Count).ToArray(); } } public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } public bool Contains(KeyValuePair<TKey, TValue> item) { int index = FindIndex(item.Key); return index >= 0 && EqualityComparer<TValue>.Default.Equals(_values[index], item.Value); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < 0 || index > array.Length) throw new ArgumentOutOfRangeException( string.Format("index = {0} array.Length = {1}", index, array.Length)); if (array.Length - index < Count) throw new ArgumentException(string.Format( "The number of elements in the dictionary ({0}) is greater than the available space from index to the end of the destination array {1}.", Count, array.Length)); for (int i = 0; i < _count; i++) { if (_hashCodes[i] >= 0) array[index++] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]); } } public bool IsReadOnly { get { return false; } } public bool Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>> { private readonly SerializableDictionary3<TKey, TValue> _dictionary3; private int _version; private int _index; private KeyValuePair<TKey, TValue> _current; public KeyValuePair<TKey, TValue> Current { get { return _current; } } internal Enumerator(SerializableDictionary3<TKey, TValue> dictionary3) { _dictionary3 = dictionary3; _version = dictionary3._version; _current = default(KeyValuePair<TKey, TValue>); _index = 0; } public bool MoveNext() { if (_version != _dictionary3._version) throw new InvalidOperationException( string.Format("Enumerator version {0} != Dictionary version {1}", _version, _dictionary3._version)); while (_index < _dictionary3._count) { if (_dictionary3._hashCodes[_index] >= 0) { _current = new KeyValuePair<TKey, TValue>(_dictionary3._keys[_index], _dictionary3._values[_index]); _index++; return true; } _index++; } _index = _dictionary3._count + 1; _current = default(KeyValuePair<TKey, TValue>); return false; } void IEnumerator.Reset() { if (_version != _dictionary3._version) throw new InvalidOperationException( string.Format("Enumerator version {0} != Dictionary version {1}", _version, _dictionary3._version)); _index = 0; _current = default(KeyValuePair<TKey, TValue>); } object IEnumerator.Current { get { return Current; } } public void Dispose() { } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; namespace Firebase.Database.Query { /// <summary> /// Query extensions providing linq like syntax for firebase server methods. /// </summary> public static class QueryExtensions { /// <summary> /// Adds an auth parameter to the query. /// </summary> /// <param name="node"> The child. </param> /// <param name="token"> The auth token. </param> /// <returns> The <see cref="AuthQuery"/>. </returns> internal static AuthQuery WithAuth(this FirebaseQuery node, string token) { return node.WithAuth(() => token); } /// <summary> /// Appends print=silent to save bandwidth. /// </summary> /// <param name="node"> The child. </param> /// <returns> The <see cref="SilentQuery"/>. </returns> internal static SilentQuery Silent(this FirebaseQuery node) { return new SilentQuery(node, node.Client); } /// <summary> /// Appends shallow=true to the url parameters. This cannot be used with any other filtering parameters. /// See https://firebase.google.com/docs/database/rest/retrieve-data /// </summary> /// <param name="node"> The child. </param> /// <returns> The <see cref="ShallowQuery"/>. </returns> public static ShallowQuery Shallow(this ChildQuery node) { return new ShallowQuery(node, node.Client); } /// <summary> /// References a sub child of the existing node. /// </summary> /// <param name="node"> The child. </param> /// <param name="path"> The path of sub child. </param> /// <returns> The <see cref="ChildQuery"/>. </returns> public static ChildQuery Child(this ChildQuery node, string path) { return node.Child(() => path); } /// <summary> /// Order data by given <paramref name="propertyName"/>. Note that this is used mainly for following filtering queries and due to firebase implementation /// the data may actually not be ordered. /// </summary> /// <param name="child"> The child. </param> /// <param name="propertyName"> The property name. </param> /// <returns> The <see cref="OrderQuery"/>. </returns> public static OrderQuery OrderBy(this ChildQuery child, string propertyName) { return child.OrderBy(() => propertyName); } /// <summary> /// Instructs firebase to send data greater or equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery StartAt(this ParameterQuery child, string value) { return child.StartAt(() => value); } /// <summary> /// Instructs firebase to send data lower or equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EndAt(this ParameterQuery child, string value) { return child.EndAt(() => value); } /// <summary> /// Instructs firebase to send data equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EqualTo(this ParameterQuery child, string value) { return child.EqualTo(() => value); } /// <summary> /// Instructs firebase to send data greater or equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery StartAt(this ParameterQuery child, double value) { return child.StartAt(() => value); } /// <summary> /// Instructs firebase to send data lower or equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EndAt(this ParameterQuery child, double value) { return child.EndAt(() => value); } /// <summary> /// Instructs firebase to send data equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EqualTo(this ParameterQuery child, double value) { return child.EqualTo(() => value); } /// <summary> /// Instructs firebase to send data greater or equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery StartAt(this ParameterQuery child, long value) { return child.StartAt(() => value); } /// <summary> /// Instructs firebase to send data lower or equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EndAt(this ParameterQuery child, long value) { return child.EndAt(() => value); } /// <summary> /// Instructs firebase to send data equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EqualTo(this ParameterQuery child, long value) { return child.EqualTo(() => value); } /// <summary> /// Instructs firebase to send data equal to the <paramref name="value"/>. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <param name="value"> Value to start at. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EqualTo(this ParameterQuery child, bool value) { return child.EqualTo(() => value); } /// <summary> /// Instructs firebase to send data equal to null. This must be preceded by an OrderBy query. /// </summary> /// <param name="child"> Current node. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery EqualTo(this ParameterQuery child) { return child.EqualTo(() => null); } /// <summary> /// Limits the result to first <paramref name="count"/> items. /// </summary> /// <param name="child"> Current node. </param> /// <param name="count"> Number of elements. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery LimitToFirst(this ParameterQuery child, int count) { return child.LimitToFirst(() => count); } /// <summary> /// Limits the result to last <paramref name="count"/> items. /// </summary> /// <param name="child"> Current node. </param> /// <param name="count"> Number of elements. </param> /// <returns> The <see cref="FilterQuery"/>. </returns> public static FilterQuery LimitToLast(this ParameterQuery child, int count) { return child.LimitToLast(() => count); } public static Task PutAsync<T>(this FirebaseQuery query, T obj) { return query.PutAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } public static Task PatchAsync<T>(this FirebaseQuery query, T obj) { return query.PatchAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } public static async Task<FirebaseObject<T>> PostAsync<T>(this FirebaseQuery query, T obj, bool generateKeyOffline = true) { var result = await query.PostAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings), generateKeyOffline).ConfigureAwait(false); return new FirebaseObject<T>(result.Key, obj); } /// <summary> /// Fan out given item to multiple locations at once. See https://firebase.googleblog.com/2015/10/client-side-fan-out-for-data-consistency_73.html for details. /// </summary> /// <typeparam name="T"> Type of object to fan out. </typeparam> /// <param name="query"> Current node. </param> /// <param name="item"> Object to fan out. </param> /// <param name="relativePaths"> Locations where to store the item. </param> public static Task FanOut<T>(this ChildQuery query, T item, params string[] relativePaths) { if (relativePaths == null) { throw new ArgumentNullException(nameof(relativePaths)); } var fanoutObject = new Dictionary<string, T>(relativePaths.Length); foreach (var path in relativePaths) { fanoutObject.Add(path, item); } return query.PatchAsync(fanoutObject); } } }
using System; namespace GuiLabs.Canvas.Controls { #region CaretPositionChanged event public delegate void CaretPositionChangedHandler(CaretPositionChangedEventArgs e); public class CaretPositionChangedEventArgs : EventArgs { public CaretPositionChangedEventArgs( TextBox textControl, int oldPosition, int newPosition) { TextControl = textControl; OldPosition = oldPosition; NewPosition = newPosition; } private int mOldPosition; public int OldPosition { get { return mOldPosition; } set { mOldPosition = value; } } private int mNewPosition; public int NewPosition { get { return mNewPosition; } set { mNewPosition = value; } } private TextBox mTextControl; public TextBox TextControl { get { return mTextControl; } set { mTextControl = value; } } } #endregion public partial class TextBox { #region Events public event CaretPositionChangedHandler CaretPositionChanged; protected void RaiseCaretPositionChanged(int oldPosition, int newPosition) { if (CaretPositionChanged != null) { CaretPositionChangedEventArgs e = new CaretPositionChangedEventArgs( this, oldPosition, newPosition); CaretPositionChanged(e); } } #endregion #region Selection private int SelectionStartPos = 0; public int SelectionStart { get { return System.Math.Min(SelectionStartPos, CaretPosition); } } public int SelectionLength { get { return System.Math.Abs(SelectionStartPos - CaretPosition); } } public int SelectionEnd { get { return System.Math.Max(SelectionStartPos, CaretPosition); } } public void SetSelection(int selStart, int selLength) { int length = this.TextLength; if ( selStart >= 0 && selStart < length && selLength > 0 && selStart + selLength <= length) { SelectionStartPos = selStart; CaretPosition = selStart + selLength; } } /// <summary> /// The selection is between SelectionStartPos and CaretPosition /// </summary> public void ResetSelection() { SelectionStartPos = CaretPosition; } public bool HasSelection { get { return SelectionStartPos != CaretPosition; } } #endregion #region Caret position public void SetCaretPosition(int newPosition) { CaretPosition = newPosition; ResetSelection(); } private int mCaretPosition = 0; /// <summary> /// Can be 0 for the leftmost position, and /// equal to Text.Length for the rightmost position. /// </summary> public int CaretPosition { get { return mCaretPosition; } set { if (mCaretPosition != value) { int oldValue = mCaretPosition; mCaretPosition = value; VerifyCaretPosition(); if (mCaretPosition != oldValue) { RaiseCaretPositionChanged(oldValue, mCaretPosition); } } } } protected void VerifyCaretPosition() { if (mCaretPosition > TextLength) { mCaretPosition = TextLength; } else if (mCaretPosition < 0) { mCaretPosition = 0; } } /// <summary> /// Returns the substring from the beginning of the textbox to the caret. /// </summary> public string TextBeforeCaret { get { return this.Text.Substring(0, CaretPosition); } } /// <summary> /// Returns the substring from the caret to the end of the textbox. /// </summary> public string TextAfterCaret { get { return this.Text.Substring(CaretPosition); } } /// <summary> /// The text from the beginning of the textbox to the starting point of the selection. /// If nothing is selected, from the beginning to the current caret position. /// </summary> public string TextBeforeSelection { get { if (this.SelectionLength == 0) { return TextBeforeCaret; } else { return this.Text.Substring(0, SelectionStart); } } } /// <summary> /// The text from the end of the selection to the end of the textbox. /// If nothing is selected, from the caret position to the end. /// </summary> public string TextAfterSelection { get { if (this.SelectionLength == 0) { return TextAfterCaret; } else { return this.Text.Substring(SelectionEnd); } } } /// <summary> /// Returns the current selected text or string.Empty if none is selected. /// The text can be selected even if the textbox doesn't have the focus. /// </summary> public string SelectionText { get { if (this.SelectionLength == 0) { return string.Empty; } else { return this.Text.Substring(this.SelectionStart, this.SelectionLength); } } } /// <summary> /// Returns if the caret is currently at the beginning of the textbox. /// </summary> public bool CaretIsAtBeginning { get { return this.CaretPosition == 0; } } /// <summary> /// Returns if the caret is currently at the end of the textbox. /// </summary> public bool CaretIsAtEnd { get { return this.CaretPosition == this.TextLength; } } public void SetCaretToBeginning() { this.SetCaretPosition(0); } public void SetCaretToEnd() { this.SetCaretPosition(this.TextLength); } #endregion } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Params.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Params { /// <java-name> /// org/apache/http/client/params/AuthPolicy /// </java-name> [Dot42.DexImport("org/apache/http/client/params/AuthPolicy", AccessFlags = 49)] public sealed partial class AuthPolicy /* scope: __dot42__ */ { /// <summary> /// <para>The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes). </para> /// </summary> /// <java-name> /// NTLM /// </java-name> [Dot42.DexImport("NTLM", "Ljava/lang/String;", AccessFlags = 25)] public const string NTLM = "NTLM"; /// <summary> /// <para>Digest authentication scheme as defined in RFC2617. </para> /// </summary> /// <java-name> /// DIGEST /// </java-name> [Dot42.DexImport("DIGEST", "Ljava/lang/String;", AccessFlags = 25)] public const string DIGEST = "Digest"; /// <summary> /// <para>Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported) </para> /// </summary> /// <java-name> /// BASIC /// </java-name> [Dot42.DexImport("BASIC", "Ljava/lang/String;", AccessFlags = 25)] public const string BASIC = "Basic"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal AuthPolicy() /* MethodBuilder.Create */ { } } /// <summary> /// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/ClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the class name of the default org.apache.http.conn.ClientConnectionManager </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// CONNECTION_MANAGER_FACTORY_CLASS_NAME /// </java-name> [Dot42.DexImport("CONNECTION_MANAGER_FACTORY_CLASS_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name"; /// <summary> /// <para>Defines the factory to create a default org.apache.http.conn.ClientConnectionManager. </para><para>This parameters expects a value of type org.apache.http.conn.ClientConnectionManagerFactory. </para> /// </summary> /// <java-name> /// CONNECTION_MANAGER_FACTORY /// </java-name> [Dot42.DexImport("CONNECTION_MANAGER_FACTORY", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object"; /// <summary> /// <para>Defines whether redirects should be handled automatically </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// HANDLE_REDIRECTS /// </java-name> [Dot42.DexImport("HANDLE_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string HANDLE_REDIRECTS = "http.protocol.handle-redirects"; /// <summary> /// <para>Defines whether relative redirects should be rejected. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// REJECT_RELATIVE_REDIRECT /// </java-name> [Dot42.DexImport("REJECT_RELATIVE_REDIRECT", "Ljava/lang/String;", AccessFlags = 25)] public const string REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; /// <summary> /// <para>Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_REDIRECTS /// </java-name> [Dot42.DexImport("MAX_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_REDIRECTS = "http.protocol.max-redirects"; /// <summary> /// <para>Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// ALLOW_CIRCULAR_REDIRECTS /// </java-name> [Dot42.DexImport("ALLOW_CIRCULAR_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)] public const string ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; /// <summary> /// <para>Defines whether authentication should be handled automatically. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// HANDLE_AUTHENTICATION /// </java-name> [Dot42.DexImport("HANDLE_AUTHENTICATION", "Ljava/lang/String;", AccessFlags = 25)] public const string HANDLE_AUTHENTICATION = "http.protocol.handle-authentication"; /// <summary> /// <para>Defines the name of the cookie specification to be used for HTTP state management. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// COOKIE_POLICY /// </java-name> [Dot42.DexImport("COOKIE_POLICY", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_POLICY = "http.protocol.cookie-policy"; /// <summary> /// <para>Defines the virtual host name. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// VIRTUAL_HOST /// </java-name> [Dot42.DexImport("VIRTUAL_HOST", "Ljava/lang/String;", AccessFlags = 25)] public const string VIRTUAL_HOST = "http.virtual-host"; /// <summary> /// <para>Defines the request headers to be sent per default with each request. </para><para>This parameter expects a value of type java.util.Collection. The collection is expected to contain org.apache.http.Headers. </para> /// </summary> /// <java-name> /// DEFAULT_HEADERS /// </java-name> [Dot42.DexImport("DEFAULT_HEADERS", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_HEADERS = "http.default-headers"; /// <summary> /// <para>Defines the default host. The default value will be used if the target host is not explicitly specified in the request URI. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// DEFAULT_HOST /// </java-name> [Dot42.DexImport("DEFAULT_HOST", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_HOST = "http.default-host"; } /// <summary> /// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/ClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537)] public partial interface IClientPNames /* scope: __dot42__ */ { } /// <summary> /// <para>An adaptor for accessing HTTP client parameters in HttpParams.</para><para><para></para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/HttpClientParams /// </java-name> [Dot42.DexImport("org/apache/http/client/params/HttpClientParams", AccessFlags = 33)] public partial class HttpClientParams /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpClientParams() /* MethodBuilder.Create */ { } /// <java-name> /// isRedirecting /// </java-name> [Dot42.DexImport("isRedirecting", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsRedirecting(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setRedirecting /// </java-name> [Dot42.DexImport("setRedirecting", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetRedirecting(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// isAuthenticating /// </java-name> [Dot42.DexImport("isAuthenticating", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setAuthenticating /// </java-name> [Dot42.DexImport("setAuthenticating", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// getCookiePolicy /// </java-name> [Dot42.DexImport("getCookiePolicy", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// setCookiePolicy /// </java-name> [Dot42.DexImport("setCookiePolicy", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params, string cookiePolicy) /* MethodBuilder.Create */ { } } /// <java-name> /// org/apache/http/client/params/CookiePolicy /// </java-name> [Dot42.DexImport("org/apache/http/client/params/CookiePolicy", AccessFlags = 49)] public sealed partial class CookiePolicy /* scope: __dot42__ */ { /// <summary> /// <para>The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents. </para> /// </summary> /// <java-name> /// BROWSER_COMPATIBILITY /// </java-name> [Dot42.DexImport("BROWSER_COMPATIBILITY", "Ljava/lang/String;", AccessFlags = 25)] public const string BROWSER_COMPATIBILITY = "compatibility"; /// <summary> /// <para>The Netscape cookie draft compliant policy. </para> /// </summary> /// <java-name> /// NETSCAPE /// </java-name> [Dot42.DexImport("NETSCAPE", "Ljava/lang/String;", AccessFlags = 25)] public const string NETSCAPE = "netscape"; /// <summary> /// <para>The RFC 2109 compliant policy. </para> /// </summary> /// <java-name> /// RFC_2109 /// </java-name> [Dot42.DexImport("RFC_2109", "Ljava/lang/String;", AccessFlags = 25)] public const string RFC_2109 = "rfc2109"; /// <summary> /// <para>The RFC 2965 compliant policy. </para> /// </summary> /// <java-name> /// RFC_2965 /// </java-name> [Dot42.DexImport("RFC_2965", "Ljava/lang/String;", AccessFlags = 25)] public const string RFC_2965 = "rfc2965"; /// <summary> /// <para>The default 'best match' policy. </para> /// </summary> /// <java-name> /// BEST_MATCH /// </java-name> [Dot42.DexImport("BEST_MATCH", "Ljava/lang/String;", AccessFlags = 25)] public const string BEST_MATCH = "best-match"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal CookiePolicy() /* MethodBuilder.Create */ { } } /// <java-name> /// org/apache/http/client/params/ClientParamBean /// </java-name> [Dot42.DexImport("org/apache/http/client/params/ClientParamBean", AccessFlags = 33)] public partial class ClientParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ClientParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionManagerFactoryClassName /// </java-name> [Dot42.DexImport("setConnectionManagerFactoryClassName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetConnectionManagerFactoryClassName(string factory) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionManagerFactory /// </java-name> [Dot42.DexImport("setConnectionManagerFactory", "(Lorg/apache/http/conn/ClientConnectionManagerFactory;)V", AccessFlags = 1)] public virtual void SetConnectionManagerFactory(global::Org.Apache.Http.Conn.IClientConnectionManagerFactory factory) /* MethodBuilder.Create */ { } /// <java-name> /// setHandleRedirects /// </java-name> [Dot42.DexImport("setHandleRedirects", "(Z)V", AccessFlags = 1)] public virtual void SetHandleRedirects(bool handle) /* MethodBuilder.Create */ { } /// <java-name> /// setRejectRelativeRedirect /// </java-name> [Dot42.DexImport("setRejectRelativeRedirect", "(Z)V", AccessFlags = 1)] public virtual void SetRejectRelativeRedirect(bool reject) /* MethodBuilder.Create */ { } /// <java-name> /// setMaxRedirects /// </java-name> [Dot42.DexImport("setMaxRedirects", "(I)V", AccessFlags = 1)] public virtual void SetMaxRedirects(int maxRedirects) /* MethodBuilder.Create */ { } /// <java-name> /// setAllowCircularRedirects /// </java-name> [Dot42.DexImport("setAllowCircularRedirects", "(Z)V", AccessFlags = 1)] public virtual void SetAllowCircularRedirects(bool allow) /* MethodBuilder.Create */ { } /// <java-name> /// setHandleAuthentication /// </java-name> [Dot42.DexImport("setHandleAuthentication", "(Z)V", AccessFlags = 1)] public virtual void SetHandleAuthentication(bool handle) /* MethodBuilder.Create */ { } /// <java-name> /// setCookiePolicy /// </java-name> [Dot42.DexImport("setCookiePolicy", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetCookiePolicy(string policy) /* MethodBuilder.Create */ { } /// <java-name> /// setVirtualHost /// </java-name> [Dot42.DexImport("setVirtualHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetVirtualHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { } /// <java-name> /// setDefaultHeaders /// </java-name> [Dot42.DexImport("setDefaultHeaders", "(Ljava/util/Collection;)V", AccessFlags = 1, Signature = "(Ljava/util/Collection<Lorg/apache/http/Header;>;)V")] public virtual void SetDefaultHeaders(global::Java.Util.ICollection<global::Org.Apache.Http.IHeader> headers) /* MethodBuilder.Create */ { } /// <java-name> /// setDefaultHost /// </java-name> [Dot42.DexImport("setDefaultHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetDefaultHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ClientParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Collected parameter names for the HttpClient module. This interface combines the parameter definitions of the HttpClient module and all dependency modules or informational units. It does not define additional parameter names, but references other interfaces defining parameter names. <br></br> This interface is meant as a navigation aid for developers. When referring to parameter names, you should use the interfaces in which the respective constants are actually defined.</para><para><para></para><title>Revision:</title><para>576078 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/params/AllClientPNames /// </java-name> [Dot42.DexImport("org/apache/http/client/params/AllClientPNames", AccessFlags = 1537)] public partial interface IAllClientPNames : global::Org.Apache.Http.Params.ICoreConnectionPNames, global::Org.Apache.Http.Params.ICoreProtocolPNames, global::Org.Apache.Http.Client.Params.IClientPNames, global::Org.Apache.Http.Auth.Params.IAuthPNames, global::Org.Apache.Http.Cookie.Params.ICookieSpecPNames, global::Org.Apache.Http.Conn.Params.IConnConnectionPNames, global::Org.Apache.Http.Conn.Params.IConnManagerPNames, global::Org.Apache.Http.Conn.Params.IConnRoutePNames /* scope: __dot42__ */ { } }
using System; using System.IO; using System.Net; using System.Xml; using Google.GData.Client; using Google.GData.Extensions.Apps; namespace Google.GData.Apps { /// <summary> /// The AppsException class defines an error resulting from /// a Google Apps provisioning request. /// </summary> public class AppsException : GDataRequestException { private string errorCode; private string invalidInput; private string reason; #region Defined Google Apps error codes /// <summary> /// Google Apps error indicating that the request failed /// for an unknown reason. /// </summary> public const string UnknownError = "1000"; /// <summary> /// Google Apps error indicating that the request instructs /// Google to create a new user but uses the username of an /// account that was deleted in the previous five days. /// </summary> public const string UserDeletedRecently = "1100"; /// <summary> /// Google Apps error indicating that the user identified in /// the request is suspended. /// </summary> public const string UserSuspended = "1101"; /// <summary> /// Google Apps error indicating that the specified domain has /// already reached its quota of user accounts. /// </summary> public const string DomainUserLimitExceeded = "1200"; /// <summary> /// Google Apps error indicating that the specified domain has /// already reached its quota of aliases. Aliases include /// nicknames and email lists. /// </summary> public const string DomainAliasLimitExceeded = "1201"; /// <summary> /// Google Apps error indicating that Google has suspended the /// specified domain's access to Google Apps. /// </summary> public const string DomainSuspended = "1202"; /// <summary> /// Google Apps error indicating that a particular feature /// is not available for the domain. /// </summary> public const string DomainFeatureUnavailable = "1203"; /// <summary> /// Google Apps error indicating that the request instructs /// Google to create an entity that already exists. /// </summary> public const string EntityExists = "1300"; /// <summary> /// Google Apps error indicating that the request asks Google /// to retrieve an entity that does not exist. /// </summary> public const string EntityDoesNotExist = "1301"; /// <summary> /// Google Apps error indicating that the request instructs /// Google to create an entity with a reserved name, such as /// "abuse" or "postmaster". /// </summary> public const string EntityNameIsReserved = "1302"; /// <summary> /// Google Apps error indicating that the request provides an /// invalid name for a requested resource. /// </summary> public const string EntityNameNotValid = "1303"; /// <summary> /// Google Apps error indicating that the value in the API request /// for the user's first name, or given name, contains unaccepted /// characters. /// </summary> public const string InvalidGivenName = "1400"; /// <summary> /// Google Apps error indicating that the value in the API request /// for the user's surname, or family name, contains unaccepted /// characters. /// </summary> public const string InvalidFamilyName = "1401"; /// <summary> /// Google Apps error indicating that the value in the API request /// for the user's password contains an invalid number of characters /// or unaccepted characters. /// </summary> public const string InvalidPassword = "1402"; /// <summary> /// Google Apps error indicating that the value in the API request /// for the user's username contains unaccepted characters. /// </summary> public const string InvalidUsername = "1403"; /// <summary> /// Google Apps error indicating that the specified password /// hash function name is not supported. /// </summary> public const string InvalidHashFunctionName = "1404"; /// <summary> /// Google Apps error indicating that the password specified /// does not comply with the hash function specified. /// </summary> public const string InvalidHashDigestLength = "1405"; /// <summary> /// Google Apps error indicating that the email address /// specified is not valid. /// </summary> public const string InvalidEmailAddress = "1406"; /// <summary> /// Google Apps error indicating that the query parameter value /// specified is not valid. /// </summary> public const string InvalidQueryParameterValue = "1407"; /// <summary> /// Google Apps error indicating that the request instructs Google /// to add users to an email list, but that list has already reached /// the maximum number of subscribers. /// </summary> public const string TooManyRecipientsOnEmailList = "1500"; #endregion /// <summary> /// Constructs a new AppsException with no properties set. /// </summary> public AppsException() : base() { errorCode = null; invalidInput = null; reason = null; } /// <summary> /// Constructs a new AppsException to be parsed from the specified /// GDataRequestException. /// </summary> /// <param name="e"></param> /// <seealso cref="ParseAppsException(GDataRequestException)"/> public AppsException(GDataRequestException e) : base("A Google Apps error occurred.", e) { this.errorCode = null; this.invalidInput = null; this.reason = null; } /// <summary> /// Constructs a new AppsException with the specified properties. /// </summary> /// <param name="errorCode">the value of the ErrorCode property</param> /// <param name="invalidInput">the value of the InvalidInput property</param> /// <param name="reason">the value of the Reason property</param> public AppsException(string errorCode, string invalidInput, string reason) : base("Google Apps error: " + errorCode + ". Invalid input: " + invalidInput + ". Reason: " + reason) { this.errorCode = errorCode; this.invalidInput = invalidInput; this.reason = reason; } /// <summary> /// Accessor for ErrorCode. This property specifies the /// type of error that caused an API request to fail. /// </summary> public string ErrorCode { get { return errorCode; } set { errorCode = value; } } /// <summary> /// Accessor for InvalidInput. This property contains the /// data that caused an API response to fail; it may not be /// provided for all error types. /// </summary> public string InvalidInput { get { return invalidInput; } set { invalidInput = value; } } /// <summary> /// Accessor for Reason. This property contains a short /// explanation of the error that occurred. /// </summary> public string Reason { get { return reason; } set { reason = value; } } /// <summary> /// Parses a GDataRequestException, which wraps the HTTP /// error responses, into an AppsException. /// </summary> /// <param name="e">the GDataRequestException to parse</param> /// <returns>a new AppsException object. The object's ErrorCode, /// InvalidInput and Reason properties will be set if the XML /// in the HTTP response could be parsed, or null otherwise.</returns> public static AppsException ParseAppsException(GDataRequestException e) { AppsException result = null; if (e == null) return (null); if (e.ResponseString == null) return (null); try { XmlReader reader = new XmlTextReader(e.ResponseString, XmlNodeType.Document, null); // now find the ErrorElement while (reader.Read()) if (reader.NodeType == XmlNodeType.Element && reader.LocalName == AppsNameTable.AppsError) { result = new AppsException(e); result.ErrorCode = reader.GetAttribute(AppsNameTable.AppsErrorErrorCode); result.InvalidInput = reader.GetAttribute(AppsNameTable.AppsErrorInvalidInput); result.Reason = reader.GetAttribute(AppsNameTable.AppsErrorReason); break; } } catch (XmlException) { } return result; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { /// <summary> /// The representation of a project to both the project factory and workspace API. /// </summary> /// <remarks> /// Due to the number of interfaces this object must implement, all interface implementations /// are in a separate files. Methods that are shared across multiple interfaces (which are /// effectively methods that just QI from one interface to another), are implemented here. /// </remarks> [ExcludeFromCodeCoverage] internal abstract partial class CSharpProjectShim : CSharpProject { /// <summary> /// This member is used to store a raw array of warning numbers, which is needed to properly implement /// ICSCompilerConfig.GetWarnNumbers. Read the implementation of that function for more details. /// </summary> private readonly IntPtr _warningNumberArrayPointer; private ICSharpProjectRoot _projectRoot; private OutputKind _outputKind = OutputKind.DynamicallyLinkedLibrary; private Platform _platform = Platform.AnyCpu; private string _mainTypeName; private object[] _options = new object[(int)CompilerOptions.LARGEST_OPTION_ID]; public CSharpProjectShim( ICSharpProjectRoot projectRoot, VisualStudioProjectTracker projectTracker, Func<ProjectId, IVsReportExternalErrors> reportExternalErrorCreatorOpt, string projectSystemName, IVsHierarchy hierarchy, IServiceProvider serviceProvider, MiscellaneousFilesWorkspace miscellaneousFilesWorkspaceOpt, VisualStudioWorkspaceImpl visualStudioWorkspaceOpt, HostDiagnosticUpdateSource hostDiagnosticUpdateSourceOpt) : base(projectTracker, reportExternalErrorCreatorOpt, projectSystemName, hierarchy, serviceProvider, miscellaneousFilesWorkspaceOpt, visualStudioWorkspaceOpt, hostDiagnosticUpdateSourceOpt) { _projectRoot = projectRoot; _warningNumberArrayPointer = Marshal.AllocHGlobal(0); } protected override void InitializeOptions() { // Ensure the default options are set up ResetAllOptions(); base.InitializeOptions(); } public override void Disconnect() { _projectRoot = null; base.Disconnect(); } private string GetIdForErrorCode(int errorCode) { return "CS" + errorCode.ToString("0000"); } protected override CSharpCompilationOptions CreateCompilationOptions() { IDictionary<string, ReportDiagnostic> ruleSetSpecificDiagnosticOptions = null; // Get options from the ruleset file, if any, first. That way project-specific // options can override them. ReportDiagnostic? ruleSetGeneralDiagnosticOption = null; if (this.ruleSet != null) { ruleSetGeneralDiagnosticOption = this.ruleSet.GetGeneralDiagnosticOption(); ruleSetSpecificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(this.ruleSet.GetSpecificDiagnosticOptions()); } else { ruleSetSpecificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(); } UpdateRuleSetError(ruleSet); ReportDiagnostic generalDiagnosticOption; var warningsAreErrors = GetNullableBooleanOption(CompilerOptions.OPTID_WARNINGSAREERRORS); if (warningsAreErrors.HasValue) { generalDiagnosticOption = warningsAreErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default; } else if (ruleSetGeneralDiagnosticOption.HasValue) { generalDiagnosticOption = ruleSetGeneralDiagnosticOption.Value; } else { generalDiagnosticOption = ReportDiagnostic.Default; } // Start with the rule set options IDictionary<string, ReportDiagnostic> diagnosticOptions = new Dictionary<string, ReportDiagnostic>(ruleSetSpecificDiagnosticOptions); // Update the specific options based on the general settings if (warningsAreErrors.HasValue && warningsAreErrors.Value == true) { foreach (var pair in ruleSetSpecificDiagnosticOptions) { if (pair.Value == ReportDiagnostic.Warn) { diagnosticOptions[pair.Key] = ReportDiagnostic.Error; } } } // Update the specific options based on the specific settings foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNASERRORLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Error; } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNNOTASERRORLIST)) { ReportDiagnostic ruleSetOption; if (ruleSetSpecificDiagnosticOptions.TryGetValue(diagnosticID, out ruleSetOption)) { diagnosticOptions[diagnosticID] = ruleSetOption; } else { diagnosticOptions[diagnosticID] = ReportDiagnostic.Default; } } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_NOWARNLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Suppress; } Platform platform; if (!Enum.TryParse(GetStringOption(CompilerOptions.OPTID_PLATFORM, ""), ignoreCase: true, result: out platform)) { platform = Platform.AnyCpu; } int warningLevel; if (!int.TryParse(GetStringOption(CompilerOptions.OPTID_WARNINGLEVEL, defaultValue: ""), out warningLevel)) { warningLevel = 4; } string projectDirectory = this.ContainingDirectoryPathOpt; // TODO: #r support, should it include bin path? var referenceSearchPaths = ImmutableArray<string>.Empty; // TODO: #load support var sourceSearchPaths = ImmutableArray<string>.Empty; MetadataReferenceResolver referenceResolver; if (Workspace != null) { referenceResolver = new WorkspaceMetadataFileReferenceResolver( Workspace.CurrentSolution.Services.MetadataService, new RelativePathResolver(referenceSearchPaths, projectDirectory)); } else { // can only happen in tests referenceResolver = null; } // TODO: appConfigPath: GetFilePathOption(CompilerOptions.OPTID_FUSIONCONFIG), bug #869604 return new CSharpCompilationOptions( allowUnsafe: GetBooleanOption(CompilerOptions.OPTID_UNSAFE), checkOverflow: GetBooleanOption(CompilerOptions.OPTID_CHECKED), concurrentBuild: false, cryptoKeyContainer: GetStringOption(CompilerOptions.OPTID_KEYNAME, defaultValue: null), cryptoKeyFile: GetFilePathRelativeOption(CompilerOptions.OPTID_KEYFILE), delaySign: GetNullableBooleanOption(CompilerOptions.OPTID_DELAYSIGN), generalDiagnosticOption: generalDiagnosticOption, mainTypeName: _mainTypeName, moduleName: GetStringOption(CompilerOptions.OPTID_MODULEASSEMBLY, defaultValue: null), optimizationLevel: GetBooleanOption(CompilerOptions.OPTID_OPTIMIZATIONS) ? OptimizationLevel.Release : OptimizationLevel.Debug, outputKind: _outputKind, platform: platform, specificDiagnosticOptions: diagnosticOptions, warningLevel: warningLevel, xmlReferenceResolver: new XmlFileResolver(projectDirectory), sourceReferenceResolver: new SourceFileResolver(sourceSearchPaths, projectDirectory), metadataReferenceResolver: referenceResolver, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default, strongNameProvider: new DesktopStrongNameProvider(GetStrongNameKeyPaths())); } private IEnumerable<string> ParseWarningCodes(CompilerOptions compilerOptions) { Contract.ThrowIfFalse(compilerOptions == CompilerOptions.OPTID_NOWARNLIST || compilerOptions == CompilerOptions.OPTID_WARNASERRORLIST || compilerOptions == CompilerOptions.OPTID_WARNNOTASERRORLIST); foreach (var warning in GetStringOption(compilerOptions, defaultValue: "").Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries)) { int warningId; var warningStringID = warning; if (int.TryParse(warning, out warningId)) { warningStringID = GetIdForErrorCode(warningId); } yield return warningStringID; } } private bool? GetNullableBooleanOption(CompilerOptions optionID) { return (bool?)_options[(int)optionID]; } private bool GetBooleanOption(CompilerOptions optionID) { return GetNullableBooleanOption(optionID).GetValueOrDefault(defaultValue: false); } private string GetFilePathRelativeOption(CompilerOptions optionID) { var path = GetStringOption(optionID, defaultValue: null); if (string.IsNullOrEmpty(path)) { return null; } var directory = this.ContainingDirectoryPathOpt; if (!string.IsNullOrEmpty(directory)) { return FileUtilities.ResolveRelativePath(path, directory); } return null; } private string GetStringOption(CompilerOptions optionID, string defaultValue) { string value = (string)_options[(int)optionID]; if (string.IsNullOrEmpty(value)) { return defaultValue; } else { return value; } } protected override CSharpParseOptions CreateParseOptions() { var symbols = GetStringOption(CompilerOptions.OPTID_CCSYMBOLS, defaultValue: "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); DocumentationMode documentationMode = DocumentationMode.Parse; if (GetStringOption(CompilerOptions.OPTID_XML_DOCFILE, defaultValue: null) != null) { documentationMode = DocumentationMode.Diagnose; } var languageVersion = CompilationOptionsConversion.GetLanguageVersion(GetStringOption(CompilerOptions.OPTID_COMPATIBILITY, defaultValue: "")) ?? CSharpParseOptions.Default.LanguageVersion; return new CSharpParseOptions( languageVersion: languageVersion, preprocessorSymbols: symbols.AsImmutable(), documentationMode: documentationMode); } ~CSharpProjectShim() { // Free the unmanaged memory we allocated in the constructor Marshal.FreeHGlobal(_warningNumberArrayPointer); // Free any entry point strings. if (_startupClasses != null) { foreach (var @class in _startupClasses) { Marshal.FreeHGlobal(@class); } } } internal bool CanCreateFileCodeModelThroughProject(string fileName) { return _projectRoot.CanCreateFileCodeModel(fileName); } internal object CreateFileCodeModelThroughProject(string fileName) { var iid = VSConstants.IID_IUnknown; return _projectRoot.CreateFileCodeModel(fileName, ref iid); } } }
///<summary> ///HTTP Method: GET ///Access: public string ResetNotification( ) { RestRequest request = new RestRequest($"/Notification/Reset/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetCareer( ) { RestRequest request = new RestRequest($"/Content/Careers/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetCareers( ) { RestRequest request = new RestRequest($"/Content/Careers/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="head"></param> ///</summary> public string GetContentById( object head ) { RestRequest request = new RestRequest($"/Content/GetContentById/{param1}/{param2}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("head, head"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="head"></param> ///</summary> public string GetContentByTagAndType( object head ) { RestRequest request = new RestRequest($"/Content/GetContentByTagAndType/{param1}/{param2}/{param3}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("head, head"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetContentType( ) { RestRequest request = new RestRequest($"/Content/GetContentType/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetDestinyContent( ) { RestRequest request = new RestRequest($"/Content/Site/Destiny/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetDestinyContentV2( ) { RestRequest request = new RestRequest($"/Content/Site/Destiny/V2/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetFeaturedArticle( ) { RestRequest request = new RestRequest($"/Content/Site/Featured/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetHomepageContent( ) { RestRequest request = new RestRequest($"/Content/Site/Homepage/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetHomepageContentV2( ) { RestRequest request = new RestRequest($"/Content/Site/Homepage/V2/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetJobs( ) { RestRequest request = new RestRequest($"/Content/Site/Jobs/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="itemsperpage"></param> ///<param name="currentpage">The current page to return. Starts at 1.</param> ///</summary> public string GetNews( object itemsperpage, object currentpage ) { RestRequest request = new RestRequest($"/Content/Site/News/{param1}/{param2}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("itemsperpage, itemsperpage");request.AddParameter("currentpage, currentpage"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetPromoWidget( ) { RestRequest request = new RestRequest($"/Content/Site/Destiny/Promo/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetPublications( ) { RestRequest request = new RestRequest($"/Content/Site/Publications/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="searchtext"></param> ///</summary> public string SearchCareers( object searchtext ) { RestRequest request = new RestRequest($"/Content/Careers/Search/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("searchtext, searchtext"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="head"></param> ///<param name="currentpage">The current page to return. Starts at 1.</param> ///<param name="itemsperpage"></param> ///</summary> public string SearchContentByTagAndType( object head, object currentpage, object itemsperpage ) { RestRequest request = new RestRequest($"/Content/SearchContentByTagAndType/{param1}/{param2}/{param3}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("head, head");request.AddParameter("currentpage, currentpage");request.AddParameter("itemsperpage, itemsperpage"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private ///<param name="head"></param> ///</summary> public string SearchContentEx( object head ) { RestRequest request = new RestRequest($"/Content/SearchEx/{param1}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("head, head"); IRestResponse response = client.Execute(request); return response.Response; }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Runtime.InteropServices; namespace Platform.Support.Windows { #if !INTEROP internal static class Propsys #else public static class Propsys #endif { [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int InitPropVariantFromPropVariantVectorElem([In] ref PropVariant propvarIn, uint iElem, [Out] out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint InitPropVariantFromFileTime([In] ref System.Runtime.InteropServices.ComTypes.FILETIME pftIn, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.I4)] public static extern int PropVariantGetElementCount([In] ref PropVariant propVar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetBooleanElem([In] ref PropVariant propVar, [In]uint iElem, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetInt16Elem([In] ref PropVariant propVar, [In] uint iElem, [Out] out short pnVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetUInt16Elem([In] ref PropVariant propVar, [In] uint iElem, [Out] out ushort pnVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetInt32Elem([In] ref PropVariant propVar, [In] uint iElem, [Out] out int pnVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetUInt32Elem([In] ref PropVariant propVar, [In] uint iElem, [Out] out uint pnVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetInt64Elem([In] ref PropVariant propVar, [In] uint iElem, [Out] out Int64 pnVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetUInt64Elem([In] ref PropVariant propVar, [In] uint iElem, [Out] out UInt64 pnVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetDoubleElem([In] ref PropVariant propVar, [In] uint iElem, [Out] out double pnVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetFileTimeElem([In] ref PropVariant propVar, [In] uint iElem, [Out, MarshalAs(UnmanagedType.Struct)] out System.Runtime.InteropServices.ComTypes.FILETIME pftVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void PropVariantGetStringElem([In] ref PropVariant propVar, [In] uint iElem, [Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszVal); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromBooleanVector([In, Out] bool[] prgf, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromInt16Vector([In, Out] Int16[] prgn, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromUInt16Vector([In, Out] UInt16[] prgn, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromInt32Vector([In, Out] Int32[] prgn, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromUInt32Vector([In, Out] UInt32[] prgn, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromInt64Vector([In, Out] Int64[] prgn, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromUInt64Vector([In, Out] UInt64[] prgn, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromDoubleVector([In, Out] double[] prgn, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromFileTimeVector([In, Out] System.Runtime.InteropServices.ComTypes.FILETIME[] prgft, uint cElems, out PropVariant ppropvar); [DllImport(ExternDll.Propsys, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void InitPropVariantFromStringVector([In, Out] string[] prgsz, uint cElems, out PropVariant ppropvar); } /// <summary> /// Represents the OLE struct PROPVARIANT. /// This class is intended for internal use only. /// </summary> /// <remarks> /// Must call Clear when finished to avoid memory leaks. If you get the value of /// a VT_UNKNOWN prop, an implicit AddRef is called, thus your reference will /// be active even after the PropVariant struct is cleared. /// Correct usage: /// /// PropVariant propVar; /// GetProp(out propVar); /// try /// { /// object value = propVar.Value; /// } /// finally { propVar.Clear(); } /// /// Originally sourced from http://blogs.msdn.com/adamroot/pages/interop-with-propvariants-in-net.aspx /// and modified to support additional types including vectors and ability to set values /// </remarks> #if !INTEROP [StructLayout(LayoutKind.Sequential)] internal struct PropVariant #else [StructLayout(LayoutKind.Sequential)] public struct PropVariant #endif { #region Fields // The layout of these elements needs to be maintained. // // NOTE: We could use LayoutKind.Explicit, but we want // to maintain that the IntPtr may be 8 bytes on // 64-bit architectures, so we'll let the CLR keep // us aligned. // // This is actually a VarEnum value, but the VarEnum type // requires 4 bytes instead of the expected 2. private ushort valueType; // Reserved Fields private ushort wReserved1; private ushort wReserved2; private ushort wReserved3; // In order to allow x64 compat, we need to allow for // expansion of the IntPtr. However, the BLOB struct // uses a 4-byte int, followed by an IntPtr, so // although the valueData field catches most pointer values, // we need an additional 4-bytes to get the BLOB // pointer. The valueDataExt field provides this, as well as // the last 4-bytes of an 8-byte value on 32-bit // architectures. private IntPtr valueData; private Int32 valueDataExt; #endregion Fields #region public Methods private void ZeroOut() { valueType = (ushort)VarEnum.VT_EMPTY; wReserved1 = wReserved2 = wReserved3 = 0; valueData = IntPtr.Zero; valueDataExt = 0; } public PropVariant(uint value) : this() { ZeroOut(); SetUInt(value); } public PropVariant(int value) : this() { ZeroOut(); SetInt(value); } public PropVariant(bool value) : this() { ZeroOut(); SetBool(value); } public PropVariant(string value) : this() { if (value == null) throw new ArgumentNullException("value"); ZeroOut(); SetString(value); } public PropVariant(object value) : this() { if (value == null) throw new ArgumentNullException("value"); ZeroOut(); SetIUnknown(value); } /// <summary> /// Creates a PropVariant from an object /// </summary> /// <param name="value">The object containing the data.</param> /// <returns>An initialized PropVariant</returns> public static PropVariant FromObject(object value) { PropVariant propVar = new PropVariant(); if (value == null) { propVar.Clear(); return propVar; } if (value.GetType() == typeof(string)) { //Strings require special consideration, because they cannot be empty as well if (String.IsNullOrEmpty(value as string) || String.IsNullOrEmpty((value as string).Trim())) throw new ArgumentException("String argument cannot be null or empty."); propVar.SetString(value as string); } else if (value.GetType() == typeof(bool?)) { propVar.SetBool((value as bool?).Value); } else if (value.GetType() == typeof(bool)) { propVar.SetBool((bool)value); } else if (value.GetType() == typeof(byte?)) { propVar.SetByte((value as byte?).Value); } else if (value.GetType() == typeof(byte)) { propVar.SetByte((byte)value); } else if (value.GetType() == typeof(sbyte?)) { propVar.SetSByte((value as sbyte?).Value); } else if (value.GetType() == typeof(sbyte)) { propVar.SetSByte((sbyte)value); } else if (value.GetType() == typeof(short?)) { propVar.SetShort((value as short?).Value); } else if (value.GetType() == typeof(short)) { propVar.SetShort((short)value); } else if (value.GetType() == typeof(ushort?)) { propVar.SetUShort((value as ushort?).Value); } else if (value.GetType() == typeof(ushort)) { propVar.SetUShort((ushort)value); } else if (value.GetType() == typeof(int?)) { propVar.SetInt((value as int?).Value); } else if (value.GetType() == typeof(int)) { propVar.SetInt((int)value); } else if (value.GetType() == typeof(uint?)) { propVar.SetUInt((value as uint?).Value); } else if (value.GetType() == typeof(uint)) { propVar.SetUInt((uint)value); } else if (value.GetType() == typeof(long?)) { propVar.SetLong((value as long?).Value); } else if (value.GetType() == typeof(long)) { propVar.SetLong((long)value); } else if (value.GetType() == typeof(ulong?)) { propVar.SetULong((value as ulong?).Value); } else if (value.GetType() == typeof(ulong)) { propVar.SetULong((ulong)value); } else if (value.GetType() == typeof(double?)) { propVar.SetDouble((value as double?).Value); } else if (value.GetType() == typeof(double)) { propVar.SetDouble((double)value); } else if (value.GetType() == typeof(float?)) { propVar.SetDouble((double)((value as float?).Value)); } else if (value.GetType() == typeof(float)) { propVar.SetDouble((double)(float)value); } else if (value.GetType() == typeof(DateTime?)) { propVar.SetDateTime((value as DateTime?).Value); } else if (value.GetType() == typeof(DateTime)) { propVar.SetDateTime((DateTime)value); } else if (value.GetType() == typeof(string[])) { propVar.SetStringVector((value as string[])); } else if (value.GetType() == typeof(short[])) { propVar.SetShortVector((value as short[])); } else if (value.GetType() == typeof(ushort[])) { propVar.SetUShortVector((value as ushort[])); } else if (value.GetType() == typeof(int[])) { propVar.SetIntVector((value as int[])); } else if (value.GetType() == typeof(uint[])) { propVar.SetUIntVector((value as uint[])); } else if (value.GetType() == typeof(long[])) { propVar.SetLongVector((value as long[])); } else if (value.GetType() == typeof(ulong[])) { propVar.SetULongVector((value as ulong[])); } else if (value.GetType() == typeof(DateTime[])) { propVar.SetDateTimeVector((value as DateTime[])); } else if (value.GetType() == typeof(bool[])) { propVar.SetBoolVector((value as bool[])); } else { throw new ArgumentException("This Value type is not supported."); } return propVar; } public bool IsNull() { return (VarType == VarEnum.VT_EMPTY || VarType == VarEnum.VT_NULL); } public void SetError() { if (!IsNull()) Clear(); valueType = (ushort)VarEnum.VT_ERROR; } public bool IsError() { return (VarType == VarEnum.VT_ERROR); } /// <summary> /// Called to clear the PropVariant's referenced and local memory. /// </summary> /// <remarks> /// You must call Clear to avoid memory leaks. /// </remarks> public void Clear() { // Can't pass "this" by ref, so make a copy to call PropVariantClear with PropVariant var = this; Ole32.PropVariantClear(ref var); // Since we couldn't pass "this" by ref, we need to clear the member fields manually // NOTE: PropVariantClear already freed heap data for us, so we are just setting // our references to null. valueType = (ushort)VarEnum.VT_EMPTY; wReserved1 = wReserved2 = wReserved3 = 0; valueData = IntPtr.Zero; valueDataExt = 0; } /// <summary> /// Set a string value /// </summary> /// <param name="value">The new value to set.</param> public void SetString(string value) { valueType = (ushort)VarEnum.VT_LPWSTR; valueData = Marshal.StringToCoTaskMemUni(value); } /// <summary> /// Set a string vector /// </summary> /// <param name="value">The new value to set.</param> public void SetStringVector(string[] value) { PropVariant propVar; Propsys.InitPropVariantFromStringVector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set a bool vector /// </summary> /// <param name="value">The new value to set.</param> public void SetBoolVector(bool[] value) { PropVariant propVar; Propsys.InitPropVariantFromBooleanVector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set a short vector /// </summary> /// <param name="value">The new value to set.</param> public void SetShortVector(short[] value) { PropVariant propVar; Propsys.InitPropVariantFromInt16Vector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set a short vector /// </summary> /// <param name="value">The new value to set.</param> public void SetUShortVector(ushort[] value) { PropVariant propVar; Propsys.InitPropVariantFromUInt16Vector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set an int vector /// </summary> /// <param name="value">The new value to set.</param> public void SetIntVector(int[] value) { PropVariant propVar; Propsys.InitPropVariantFromInt32Vector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set an uint vector /// </summary> /// <param name="value">The new value to set.</param> public void SetUIntVector(uint[] value) { PropVariant propVar; Propsys.InitPropVariantFromUInt32Vector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set a long vector /// </summary> /// <param name="value">The new value to set.</param> public void SetLongVector(long[] value) { PropVariant propVar; Propsys.InitPropVariantFromInt64Vector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set a ulong vector /// </summary> /// <param name="value">The new value to set.</param> public void SetULongVector(ulong[] value) { PropVariant propVar; Propsys.InitPropVariantFromUInt64Vector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set a double vector /// </summary> /// <param name="value">The new value to set.</param> public void SetDoubleVector(double[] value) { PropVariant propVar; Propsys.InitPropVariantFromDoubleVector(value, (uint)value.Length, out propVar); CopyData(propVar); } /// <summary> /// Set a DateTime vector /// </summary> /// <param name="value">The new value to set.</param> public void SetDateTimeVector(DateTime[] value) { System.Runtime.InteropServices.ComTypes.FILETIME[] fileTimeArr = new System.Runtime.InteropServices.ComTypes.FILETIME[value.Length]; for (int i = 0; i < value.Length; i++) { fileTimeArr[i] = DateTimeTotFileTime(value[i]); } PropVariant propVar; Propsys.InitPropVariantFromFileTimeVector(fileTimeArr, (uint)fileTimeArr.Length, out propVar); CopyData(propVar); } /// <summary> /// Set an IUnknown value /// </summary> /// <param name="value">The new value to set.</param> public void SetIUnknown(object value) { valueType = (ushort)VarEnum.VT_UNKNOWN; valueData = Marshal.GetIUnknownForObject(value); } /// <summary> /// Set a bool value /// </summary> /// <param name="value">The new value to set.</param> public void SetBool(bool value) { valueType = (ushort)VarEnum.VT_BOOL; valueData = (value == true) ? (IntPtr)(-1) : (IntPtr)0; } /// <summary> /// Set a DateTime value /// </summary> /// <param name="value">The new value to set.</param> public void SetDateTime(DateTime value) { valueType = (ushort)VarEnum.VT_FILETIME; PropVariant propVar; System.Runtime.InteropServices.ComTypes.FILETIME ft = DateTimeTotFileTime(value); Propsys.InitPropVariantFromFileTime(ref ft, out propVar); CopyData(propVar); } /// <summary> /// Set a safe array value /// </summary> /// <param name="array">The new value to set.</param> public void SetSafeArray(Array array) { const ushort vtUnknown = 13; IntPtr psa = OleAut32.SafeArrayCreateVector(vtUnknown, 0, (uint)array.Length); IntPtr pvData = OleAut32.SafeArrayAccessData(psa); try // to remember to release lock on data { for (int i = 0; i < array.Length; ++i) { object obj = array.GetValue(i); IntPtr punk = (obj != null) ? Marshal.GetIUnknownForObject(obj) : IntPtr.Zero; Marshal.WriteIntPtr(pvData, i * IntPtr.Size, punk); } } finally { OleAut32.SafeArrayUnaccessData(psa); } this.valueType = (ushort)VarEnum.VT_ARRAY | (ushort)VarEnum.VT_UNKNOWN; this.valueData = psa; } /// <summary> /// Set a byte value /// </summary> /// <param name="value">The new value to set.</param> public void SetByte(byte value) { valueType = (ushort)VarEnum.VT_UI1; valueData = (IntPtr)value; } /// <summary> /// Set a sbyte value /// </summary> /// <param name="value">The new value to set.</param> public void SetSByte(sbyte value) { valueType = (ushort)VarEnum.VT_I1; valueData = (IntPtr)value; } /// <summary> /// Set a short value /// </summary> /// <param name="value">The new value to set.</param> public void SetShort(short value) { valueType = (ushort)VarEnum.VT_I2; valueData = (IntPtr)value; } /// <summary> /// Set an unsigned short value /// </summary> /// <param name="value">The new value to set.</param> public void SetUShort(ushort value) { valueType = (ushort)VarEnum.VT_UI2; valueData = (IntPtr)value; } /// <summary> /// Set an int value /// </summary> /// <param name="value">The new value to set.</param> public void SetInt(int value) { valueType = (ushort)VarEnum.VT_I4; valueData = (IntPtr)value; } /// <summary> /// Set an unsigned int value /// </summary> /// <param name="value">The new value to set.</param> public void SetUInt(uint value) { valueType = (ushort)VarEnum.VT_UI4; valueData = (IntPtr)(int)value; } /// <summary> /// Set a decimal value /// </summary> /// <param name="value">The new value to set.</param> public void SetDecimal(decimal value) { int[] bits = Decimal.GetBits(value); valueData = (IntPtr)bits[0]; valueDataExt = bits[1]; wReserved3 = (ushort)(bits[2] >> 16); wReserved2 = (ushort)(bits[2] & 0x0000FFFF); wReserved1 = (ushort)(bits[3] >> 16); valueType = (ushort)VarEnum.VT_DECIMAL; } /// <summary> /// Set a long /// </summary> /// <param name="value">The new value to set.</param> public void SetLong(long value) { long[] valueArr = new long[] { value }; PropVariant propVar; Propsys.InitPropVariantFromInt64Vector(valueArr, 1, out propVar); CreatePropVariantFromVectorElement(propVar); } /// <summary> /// Set a ulong /// </summary> /// <param name="value">The new value to set.</param> public void SetULong(ulong value) { PropVariant propVar; ulong[] valueArr = new ulong[] { value }; Propsys.InitPropVariantFromUInt64Vector(valueArr, 1, out propVar); CreatePropVariantFromVectorElement(propVar); } /// <summary> /// Set a double /// </summary> /// <param name="value">The new value to set.</param> public void SetDouble(double value) { double[] valueArr = new double[] { value }; PropVariant propVar; Propsys.InitPropVariantFromDoubleVector(valueArr, 1, out propVar); CreatePropVariantFromVectorElement(propVar); } /// <summary> /// Sets the value type to empty /// </summary> public void SetEmptyValue() { valueType = (ushort)VarEnum.VT_EMPTY; } /// <summary> /// Checks if this has an empty or null value /// </summary> /// <returns></returns> public bool IsNullOrEmpty { get { return (valueType == (ushort)VarEnum.VT_EMPTY || valueType == (ushort)VarEnum.VT_NULL); } } #endregion public Methods #region public Properties /// <summary> /// Gets or sets the variant type. /// </summary> public VarEnum VarType { get { return (VarEnum)valueType; } set { valueType = (ushort)value; } } /// <summary> /// Gets the variant value. /// </summary> public object Value { get { switch ((VarEnum)valueType) { case VarEnum.VT_I1: return cVal; case VarEnum.VT_UI1: return bVal; case VarEnum.VT_I2: return iVal; case VarEnum.VT_UI2: return uiVal; case VarEnum.VT_I4: case VarEnum.VT_INT: return lVal; case VarEnum.VT_UI4: case VarEnum.VT_UINT: return ulVal; case VarEnum.VT_I8: return hVal; case VarEnum.VT_UI8: return uhVal; case VarEnum.VT_R4: return fltVal; case VarEnum.VT_R8: return dblVal; case VarEnum.VT_BOOL: return boolVal; case VarEnum.VT_ERROR: return scode; case VarEnum.VT_CY: return cyVal; case VarEnum.VT_DATE: return date; case VarEnum.VT_FILETIME: return DateTime.FromFileTime(hVal); case VarEnum.VT_BSTR: return Marshal.PtrToStringBSTR(valueData); case VarEnum.VT_BLOB: return GetBlobData(); case VarEnum.VT_LPSTR: return Marshal.PtrToStringAnsi(valueData); case VarEnum.VT_LPWSTR: return Marshal.PtrToStringUni(valueData); case VarEnum.VT_UNKNOWN: return Marshal.GetObjectForIUnknown(valueData); case VarEnum.VT_DISPATCH: return Marshal.GetObjectForIUnknown(valueData); case VarEnum.VT_DECIMAL: return decVal; case VarEnum.VT_ARRAY | VarEnum.VT_UNKNOWN: return CrackSingleDimSafeArray(valueData); case (VarEnum.VT_VECTOR | VarEnum.VT_LPWSTR): return GetStringVector(); case (VarEnum.VT_VECTOR | VarEnum.VT_I2): return GetVector<Int16>(); case (VarEnum.VT_VECTOR | VarEnum.VT_UI2): return GetVector<UInt16>(); case (VarEnum.VT_VECTOR | VarEnum.VT_I4): return GetVector<Int32>(); case (VarEnum.VT_VECTOR | VarEnum.VT_UI4): return GetVector<UInt32>(); case (VarEnum.VT_VECTOR | VarEnum.VT_I8): return GetVector<Int64>(); case (VarEnum.VT_VECTOR | VarEnum.VT_UI8): return GetVector<UInt64>(); case (VarEnum.VT_VECTOR | VarEnum.VT_R8): return GetVector<Double>(); case (VarEnum.VT_VECTOR | VarEnum.VT_BOOL): return GetVector<Boolean>(); case (VarEnum.VT_VECTOR | VarEnum.VT_FILETIME): return GetVector<DateTime>(); default: // if the value cannot be marshaled return null; } } } #endregion public Properties #region PropVariant Simple Data types sbyte cVal // CHAR cVal; { get { return (sbyte)GetDataBytes()[0]; } } byte bVal // UCHAR bVal; { get { return GetDataBytes()[0]; } } short iVal // SHORT iVal; { get { return BitConverter.ToInt16(GetDataBytes(), 0); } } ushort uiVal // USHORT uiVal; { get { return BitConverter.ToUInt16(GetDataBytes(), 0); } } int lVal // LONG lVal; { get { return BitConverter.ToInt32(GetDataBytes(), 0); } } uint ulVal // ULONG ulVal; { get { return BitConverter.ToUInt32(GetDataBytes(), 0); } } long hVal // LARGE_INTEGER hVal; { get { return BitConverter.ToInt64(GetDataBytes(), 0); } } ulong uhVal // ULARGE_INTEGER uhVal; { get { return BitConverter.ToUInt64(GetDataBytes(), 0); } } float fltVal // FLOAT fltVal; { get { return BitConverter.ToSingle(GetDataBytes(), 0); } } double dblVal // DOUBLE dblVal; { get { return BitConverter.ToDouble(GetDataBytes(), 0); } } bool boolVal // VARIANT_BOOL boolVal; { get { return (iVal == 0 ? false : true); } } int scode // SCODE scode; { get { return lVal; } } decimal cyVal // CY cyVal; { get { return decimal.FromOACurrency(hVal); } } DateTime date // DATE date; { get { return DateTime.FromOADate(dblVal); } } Decimal decVal // Decimal value { get { int[] bits = new int[4]; bits[0] = (int)valueData; bits[1] = valueDataExt; bits[2] = (wReserved3 << 16) | wReserved2; bits[3] = (wReserved1 << 16); return new decimal(bits); } } #endregion PropVariant Simple Data types #region Private Methods private void CopyData(PropVariant propVar) { this.valueType = propVar.valueType; this.valueData = propVar.valueData; this.valueDataExt = propVar.valueDataExt; } private void CreatePropVariantFromVectorElement(PropVariant propVar) { //Copy the first vector element to a new PropVariant CopyData(propVar); Propsys.InitPropVariantFromPropVariantVectorElem(ref this, 0, out propVar); //Overwrite the existing data CopyData(propVar); } private static long FileTimeToDateTime(ref System.Runtime.InteropServices.ComTypes.FILETIME val) { return (((long)val.dwHighDateTime) << 32) + val.dwLowDateTime; } private static System.Runtime.InteropServices.ComTypes.FILETIME DateTimeTotFileTime(DateTime value) { long hFT = value.ToFileTime(); System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME(); ft.dwLowDateTime = (int)(hFT & 0xFFFFFFFF); ft.dwHighDateTime = (int)(hFT >> 32); return ft; } private object GetBlobData() { byte[] blobData = new byte[lVal]; IntPtr pBlobData; if (IntPtr.Size == 4) { pBlobData = new IntPtr(valueDataExt); } else if (IntPtr.Size == 8) { // In this case, we need to derive a pointer at offset 12, // because the size of the blob is represented as a 4-byte int // but the pointer is immediately after that. pBlobData = new IntPtr( (Int64)(BitConverter.ToInt32(GetDataBytes(), sizeof(int))) + (Int64)(BitConverter.ToInt32(GetDataBytes(), 2 * sizeof(int)) << 32)); } else { throw new NotSupportedException(); } Marshal.Copy(pBlobData, blobData, 0, lVal); return blobData; } private Array GetVector<T>() where T : struct { int count = Propsys.PropVariantGetElementCount(ref this); if (count <= 0) return null; Array arr = new T[count]; for (uint i = 0; i < count; i++) { if (typeof(T) == typeof(Int16)) { short val; Propsys.PropVariantGetInt16Elem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(UInt16)) { ushort val; Propsys.PropVariantGetUInt16Elem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(Int32)) { int val; Propsys.PropVariantGetInt32Elem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(UInt32)) { uint val; Propsys.PropVariantGetUInt32Elem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(Int64)) { long val; Propsys.PropVariantGetInt64Elem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(UInt64)) { ulong val; Propsys.PropVariantGetUInt64Elem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(DateTime)) { System.Runtime.InteropServices.ComTypes.FILETIME val; Propsys.PropVariantGetFileTimeElem(ref this, i, out val); long fileTime = FileTimeToDateTime(ref val); arr.SetValue(DateTime.FromFileTime(fileTime), i); } else if (typeof(T) == typeof(Boolean)) { bool val; Propsys.PropVariantGetBooleanElem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(Double)) { double val; Propsys.PropVariantGetDoubleElem(ref this, i, out val); arr.SetValue(val, i); } else if (typeof(T) == typeof(String)) { string val; Propsys.PropVariantGetStringElem(ref this, i, out val); arr.SetValue(val, i); } } return arr; } // A string requires a special case because it's not a struct or value type private string[] GetStringVector() { int count = Propsys.PropVariantGetElementCount(ref this); if (count <= 0) return null; string[] strArr = new string[count]; for (uint i = 0; i < count; i++) { Propsys.PropVariantGetStringElem(ref this, i, out strArr[i]); } return strArr; } /// <summary> /// Gets a byte array containing the data bits of the struct. /// </summary> /// <returns>A byte array that is the combined size of the data bits.</returns> private byte[] GetDataBytes() { byte[] ret = new byte[IntPtr.Size + sizeof(int)]; if (IntPtr.Size == 4) BitConverter.GetBytes(valueData.ToInt32()).CopyTo(ret, 0); else if (IntPtr.Size == 8) BitConverter.GetBytes(valueData.ToInt64()).CopyTo(ret, 0); BitConverter.GetBytes(valueDataExt).CopyTo(ret, IntPtr.Size); return ret; } private Array CrackSingleDimSafeArray(IntPtr psa) { uint cDims = OleAut32.SafeArrayGetDim(psa); if (cDims != 1) throw new ArgumentException("Multi-dimensional SafeArrays not supported."); int lBound = OleAut32.SafeArrayGetLBound(psa, 1U); int uBound = OleAut32.SafeArrayGetUBound(psa, 1U); int n = uBound - lBound + 1; // uBound is inclusive object[] array = new object[n]; for (int i = lBound; i <= uBound; ++i) { array[i] = OleAut32.SafeArrayGetElement(psa, ref i); } return array; } public PropVariant Clone() { // Can't pass "this" by ref, so make a bitwise copy on the stack, to call API with PropVariant var = this; PropVariant clone; Ole32.PropVariantCopy(out clone, ref var); return clone; } public static PropVariant Empty { get { PropVariant empty = new PropVariant(); empty.valueType = (ushort)VarEnum.VT_EMPTY; empty.wReserved1 = empty.wReserved2 = empty.wReserved3 = 0; //empty.p = IntPtr.Zero; //empty.p2 = 0; return empty; } } #endregion Private Methods } #if !INTEROP [StructLayout(LayoutKind.Sequential)] internal class PropVariantRef #else [StructLayout(LayoutKind.Sequential)] public class PropVariantRef #endif { public PropVariant PropVariant; public static PropVariantRef From(PropVariant value) { PropVariantRef obj = new PropVariantRef(); obj.PropVariant = value; return obj; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Text; using System.Threading.Tasks; namespace System.IO { internal sealed class SyncTextWriter : TextWriter, IDisposable { private readonly object _methodLock = new object(); internal readonly TextWriter _out; internal static SyncTextWriter GetSynchronizedTextWriter(TextWriter writer) { Debug.Assert(writer != null); return writer as SyncTextWriter ?? new SyncTextWriter(writer); } internal SyncTextWriter(TextWriter t) : base(t.FormatProvider) { _out = t; } public override Encoding Encoding { get { return _out.Encoding; } } public override IFormatProvider FormatProvider { get { return _out.FormatProvider; } } public override String NewLine { get { lock (_methodLock) { return _out.NewLine; } } set { lock (_methodLock) { _out.NewLine = value; } } } protected override void Dispose(bool disposing) { if (disposing) { lock (_methodLock) { // Explicitly pick up a potentially methodimpl'ed Dispose ((IDisposable)_out).Dispose(); } } } public override void Flush() { lock (_methodLock) { _out.Flush(); } } public override void Write(char value) { lock (_methodLock) { _out.Write(value); } } public override void Write(char[] buffer) { lock (_methodLock) { _out.Write(buffer); } } public override void Write(char[] buffer, int index, int count) { lock (_methodLock) { _out.Write(buffer, index, count); } } public override void Write(bool value) { lock (_methodLock) { _out.Write(value); } } public override void Write(int value) { lock (_methodLock) { _out.Write(value); } } public override void Write(uint value) { lock (_methodLock) { _out.Write(value); } } public override void Write(long value) { lock (_methodLock) { _out.Write(value); } } public override void Write(ulong value) { lock (_methodLock) { _out.Write(value); } } public override void Write(float value) { lock (_methodLock) { _out.Write(value); } } public override void Write(double value) { lock (_methodLock) { _out.Write(value); } } public override void Write(Decimal value) { lock (_methodLock) { _out.Write(value); } } public override void Write(String value) { lock (_methodLock) { _out.Write(value); } } public override void Write(Object value) { lock (_methodLock) { _out.Write(value); } } public override void Write(String format, Object[] arg) { lock (_methodLock) { _out.Write(format, arg); } } public override void WriteLine() { lock (_methodLock) { _out.WriteLine(); } } public override void WriteLine(char value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(decimal value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(char[] buffer) { lock (_methodLock) { _out.WriteLine(buffer); } } public override void WriteLine(char[] buffer, int index, int count) { lock (_methodLock) { _out.WriteLine(buffer, index, count); } } public override void WriteLine(bool value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(int value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(uint value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(long value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(ulong value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(float value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(double value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(String value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(Object value) { lock (_methodLock) { _out.WriteLine(value); } } public override void WriteLine(String format, Object[] arg) { lock (_methodLock) { _out.WriteLine(format, arg); } } // // On SyncTextWriter all APIs should run synchronously, even the async ones. // public override Task WriteAsync(char value) { Write(value); return Task.CompletedTask; } public override Task WriteAsync(String value) { Write(value); return Task.CompletedTask; } public override Task WriteAsync(char[] buffer, int index, int count) { Write(buffer, index, count); return Task.CompletedTask; } public override Task WriteLineAsync(char value) { WriteLine(value); return Task.CompletedTask; } public override Task WriteLineAsync(String value) { WriteLine(value); return Task.CompletedTask; } public override Task WriteLineAsync(char[] buffer, int index, int count) { WriteLine(buffer, index, count); return Task.CompletedTask; } public override Task FlushAsync() { Flush(); return Task.CompletedTask; } } }
// 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.Sql { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// RestorePointsOperations operations. /// </summary> internal partial class RestorePointsOperations : IServiceOperations<SqlManagementClient>, IRestorePointsOperations { /// <summary> /// Initializes a new instance of the RestorePointsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RestorePointsOperations(SqlManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SqlManagementClient /// </summary> public SqlManagementClient Client { get; private set; } /// <summary> /// Gets a list of database restore points. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database to get available restore points. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<RestorePoint>>> ListByDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (databaseName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "databaseName"); } string apiVersion = "2014-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByDatabase", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/restorePoints").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<RestorePoint>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RestorePoint>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using Invio.Xunit; using Xunit; namespace Invio.Immutable { [UnitTest] public sealed class PropertyValueImplTests { private Random random { get; } public PropertyValueImplTests() { this.random = new Random(); } [Fact] public void GetPropertyValueImpl_NullPropertyName() { // Arrange var fake = this.NextFake(); // Act var exception = Record.Exception( () => fake.GetPropertyValue(null) ); // Assert Assert.IsType<ArgumentNullException>(exception); } [Fact] public void GetPropertyValueImpl_NonExistentProperty() { // Arrange var fake = this.NextFake(); const string propertyName = "ThisPropertyDoesNotExist"; // Act var exception = Record.Exception( () => fake.GetPropertyValue(propertyName) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"The '{propertyName}' property was not found." + Environment.NewLine + "Parameter name: propertyName", exception.Message ); } [Fact] public void GetPropertyValueImpl_CaseInsensitivePropertyName() { // Arrange var fake = this.NextFake(); // Act var actualValue = fake.GetPropertyValue(nameof(Fake.StringProperty).ToLower()); // Assert Assert.Equal(fake.StringProperty, actualValue); } [Fact] public void GetPropertyValueImpl_NullValue() { // Arrange var fake = this.NextFake().SetStringProperty(null); // Act var value = fake.GetPropertyValue(nameof(Fake.StringProperty)); // Assert Assert.Null(value); } [Fact] public void GetPropertyValueImpl_NonNullValue() { // Arrange const int number = 42; var fake = this.NextFake().SetNumber(number); // Act var value = fake.GetPropertyValue(nameof(Fake.Number)); // Assert Assert.Equal(number, value); } [Fact] public void SetPropertyValueImpl_NullPropertyName() { // Arrange var fake = this.NextFake(); // Act var exception = Record.Exception( () => fake.SetPropertyValue(null, 5) ); // Assert Assert.IsType<ArgumentNullException>(exception); } [Fact] public void SetPropertyValueImpl_NonExistentProperty() { // Arrange var fake = this.NextFake(); const string propertyName = "ThisPropertyDoesNotExist"; // Act var exception = Record.Exception( () => fake.SetPropertyValue(propertyName, 5) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"The '{propertyName}' property was not found." + Environment.NewLine + "Parameter name: propertyName", exception.Message ); } [Fact] public void SetPropertyValueImpl_InvalidValueType_Null() { // Arrange var fake = this.NextFake(); var propertyName = nameof(Fake.Number); // Act var exception = Record.Exception( () => fake.SetPropertyValue(propertyName, null) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"Unable to assign the value (null) to the '{propertyName}' property." + Environment.NewLine + "Parameter name: value", exception.Message ); } [Fact] public void SetPropertyValueImpl_InvalidPropertyType_NonNull() { // Arrange var fake = this.NextFake(); var propertyName = nameof(Fake.Number); const string value = "foo"; // Act var exception = Record.Exception( () => fake.SetPropertyValue(propertyName, value) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"Unable to assign the value ({value}) to the '{propertyName}' property." + Environment.NewLine + "Parameter name: value", exception.Message ); } [Fact] public void SetPropertyValueImpl_CaseInsensitivePropertyName() { // Arrange var original = this.NextFake(); var propertyName = nameof(Fake.Number).ToUpper(); const int number = 5; // Act var updated = original.SetPropertyValue(propertyName, number); // Assert Assert.Equal(number, updated.Number); } [Fact] public void SetPropertyValueImpl_NullableProperty() { // Arrange var fake = this.NextFake(); var propertyName = nameof(Fake.NullableDateTime); // Act var updated = fake.SetPropertyValue(propertyName, null); // Assert Assert.Null(updated.NullableDateTime); } [Fact] public void SetPropertyValuesImpl_Null() { // Arrange var fake = this.NextFake(); // Act var exception = Record.Exception( () => fake.SetPropertyValues(null) ); // Assert Assert.IsType<ArgumentNullException>(exception); } [Fact] public void SetPropertyValuesImpl_Empty() { // Arrange var original = this.NextFake(); var propertyValues = ImmutableDictionary<string, object>.Empty; // Act var result = original.SetPropertyValues(propertyValues); // Assert Assert.Equal(original, result); } [Fact] public void SetPropertyValuesImpl_NonExistentProperty() { // Arrange var fake = this.NextFake(); const string propertyName = "ThisPropertyDoesNotExist"; var propertyValues = ImmutableDictionary<string, object> .Empty .Add(propertyName, 5); // Act var exception = Record.Exception( () => fake.SetPropertyValues(propertyValues) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"The '{propertyName}' property was not found." + Environment.NewLine + "Parameter name: propertyValues", exception.Message ); } [Fact] public void SetPropertyValuesImpl_RedundantPropertyAssignments() { // Arrange var fake = this.NextFake(); var propertyValues = ImmutableDictionary<string, object> .Empty .Add(nameof(Fake.Number).ToUpper(), 5) .Add(nameof(Fake.Number).ToLower(), 5); // Act var exception = Record.Exception( () => fake.SetPropertyValues(propertyValues) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"The '{nameof(Fake.Number)}' property was specified more than once." + Environment.NewLine + "Parameter name: propertyValues", exception.Message, ignoreCase: true ); } [Fact] public void SetPropertyValuesImpl_CaseInsensitivePropertyNames() { // Arrange var original = this.NextFake(); var propertyName = nameof(Fake.Number).ToUpper(); const int number = 5; var propertyValues = ImmutableDictionary<string, object> .Empty .Add(propertyName, number); // Act var updated = original.SetPropertyValues(propertyValues); // Assert Assert.Equal(number, updated.Number); } [Fact] public void SetPropertyValuesImpl_InvalidValueType_Null() { // Arrange var fake = this.NextFake(); var propertyValues = ImmutableDictionary<string, object> .Empty .Add(nameof(Fake.Number), null); // Act var exception = Record.Exception( () => fake.SetPropertyValues(propertyValues) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"Unable to assign the value (null) to the 'Number' property." + Environment.NewLine + "Parameter name: propertyValues", exception.Message ); } [Fact] public void SetPropertyValuesImpl_InvalidPropertyType_NonNull() { // Arrange var fake = this.NextFake(); var propertyValues = ImmutableDictionary<string, object> .Empty .Add(nameof(Fake.Number), "foo"); // Act var exception = Record.Exception( () => fake.SetPropertyValues(propertyValues) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"Unable to assign the value (foo) to the 'Number' property." + Environment.NewLine + "Parameter name: propertyValues", exception.Message ); } [Fact] public void SetPropertyValuesImpl_MultipleProperties() { // Arrange var original = this.NextFake(); const int assignedNumber = 5; const string assignedString = "Foo"; var propertyValues = ImmutableDictionary<string, object> .Empty .Add(nameof(Fake.Number), assignedNumber) .Add(nameof(Fake.StringProperty), assignedString); // Act var updated = original.SetPropertyValues(propertyValues); // Assert Assert.Equal(assignedNumber, updated.Number); Assert.Equal(assignedString, updated.StringProperty); Assert.Equal(original.NullableDateTime, updated.NullableDateTime); } private Fake NextFake() { return new Fake( this.random.Next(), Guid.NewGuid().ToString("N"), this.random.Next(2) == 0 ? (DateTime?)null : (DateTime?)new DateTime(this.random.Next(), DateTimeKind.Utc) ); } private class Fake : ImmutableBase<Fake> { public int Number { get; } public String StringProperty { get; } public DateTime? NullableDateTime { get; } public Fake( int number, String stringProperty, DateTime? nullableDateTime) { this.Number = number; this.StringProperty = stringProperty; this.NullableDateTime = nullableDateTime; } public object GetPropertyValue(String propertyName) { return this.GetPropertyValueImpl(propertyName); } public Fake SetPropertyValue(String propertyName, object value) { return this.SetPropertyValueImpl(propertyName, value); } public Fake SetPropertyValues(IDictionary<string, object> propertyValues) { return this.SetPropertyValuesImpl(propertyValues); } public Fake SetNumber(int number) { return this.SetPropertyValueImpl(nameof(Number), number); } public Fake SetStringProperty(string stringProperty) { return this.SetPropertyValueImpl(nameof(StringProperty), stringProperty); } public Fake SetNullableDateTime(DateTime? nullable) { return this.SetPropertyValueImpl(nameof(NullableDateTime), nullable); } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// ProductSupplierItem (editable child object).<br/> /// This is a generated <see cref="ProductSupplierItem"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="ProductSupplierColl"/> collection. /// </remarks> [Serializable] public partial class ProductSupplierItem : BusinessBase<ProductSupplierItem> { #region Static Fields private static int _lastId; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="ProductSupplierId"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> ProductSupplierIdProperty = RegisterProperty<int>(p => p.ProductSupplierId, "Product Supplier Id"); /// <summary> /// Gets the Product Supplier Id. /// </summary> /// <value>The Product Supplier Id.</value> public int ProductSupplierId { get { return GetProperty(ProductSupplierIdProperty); } } /// <summary> /// Maintains metadata about <see cref="SupplierId"/> property. /// </summary> public static readonly PropertyInfo<int> SupplierIdProperty = RegisterProperty<int>(p => p.SupplierId, "Supplier Id"); /// <summary> /// Gets or sets the Supplier Id. /// </summary> /// <value>The Supplier Id.</value> public int SupplierId { get { return GetProperty(SupplierIdProperty); } set { SetProperty(SupplierIdProperty, value); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductSupplierItem"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductSupplierItem() { // 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="ProductSupplierItem"/> object properties. /// </summary> [RunLocal] protected override void Child_Create() { LoadProperty(ProductSupplierIdProperty, System.Threading.Interlocked.Decrement(ref _lastId)); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="ProductSupplierItem"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Child_Fetch(SafeDataReader dr) { // Value properties LoadProperty(ProductSupplierIdProperty, dr.GetInt32("ProductSupplierId")); LoadProperty(SupplierIdProperty, dr.GetInt32("SupplierId")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Inserts a new <see cref="ProductSupplierItem"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(ProductEdit parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false)) { using (var cmd = new SqlCommand("dbo.AddProductSupplierItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductId", parent.ProductId).DbType = DbType.Guid; cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@SupplierId", ReadProperty(SupplierIdProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(ProductSupplierIdProperty, (int) cmd.Parameters["@ProductSupplierId"].Value); } } } /// <summary> /// Updates in the database all changes made to the <see cref="ProductSupplierItem"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false)) { using (var cmd = new SqlCommand("dbo.UpdateProductSupplierItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SupplierId", ReadProperty(SupplierIdProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="ProductSupplierItem"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false)) { using (var cmd = new SqlCommand("dbo.DeleteProductSupplierItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class output by Measure-Object /// </summary> public abstract class MeasureInfo { /// <summary> /// /// property name /// /// </summary> public string Property { get; set; } = null; } /// <summary> /// Class output by Measure-Object /// </summary> public sealed class GenericMeasureInfo : MeasureInfo { /// <summary> /// default ctor /// </summary> public GenericMeasureInfo() { Average = Sum = Maximum = Minimum = null; } /// <summary> /// /// Keeping track of number of objects with a certain property /// /// </summary> public int Count { get; set; } /// <summary> /// /// The average of property values /// /// </summary> public double? Average { get; set; } /// <summary> /// /// The sum of property values /// /// </summary> public double? Sum { get; set; } /// <summary> /// /// The max of property values /// /// </summary> public double? Maximum { get; set; } /// <summary> /// /// The min of property values /// /// </summary> public double? Minimum { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> /// <remarks> /// This class is created for fixing "Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo" /// bug (Win8:343911). /// GenericMeasureInfo class is shipped with PowerShell V2. Fixing this bug requires, changing the type of /// Maximum and Minimum properties which would be a breaking change. Hence created a new class to not /// have an appcompat issues with PS V2. /// </remarks> public sealed class GenericObjectMeasureInfo : MeasureInfo { /// <summary> /// default ctor /// </summary> public GenericObjectMeasureInfo() { Average = Sum = null; Maximum = Minimum = null; } /// <summary> /// /// Keeping track of number of objects with a certain property /// /// </summary> public int Count { get; set; } /// <summary> /// /// The average of property values /// /// </summary> public double? Average { get; set; } /// <summary> /// /// The sum of property values /// /// </summary> public double? Sum { get; set; } /// <summary> /// /// The max of property values /// /// </summary> public object Maximum { get; set; } /// <summary> /// /// The min of property values /// /// </summary> public object Minimum { get; set; } } /// <summary> /// Class output by Measure-Object /// </summary> public sealed class TextMeasureInfo : MeasureInfo { /// <summary> /// default ctor /// </summary> public TextMeasureInfo() { Lines = Words = Characters = null; } /// <summary> /// /// Keeping track of number of objects with a certain property /// /// </summary> public int? Lines { get; set; } /// <summary> /// /// The average of property values /// /// </summary> public int? Words { get; set; } /// <summary> /// /// The sum of property values /// /// </summary> public int? Characters { get; set; } } /// <summary> /// measure object cmdlet /// </summary> [Cmdlet(VerbsDiagnostic.Measure, "Object", DefaultParameterSetName = GenericParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113349", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(GenericMeasureInfo), typeof(TextMeasureInfo), typeof(GenericObjectMeasureInfo))] public sealed class MeasureObjectCommand : PSCmdlet { /// <summary> /// Dictionary to be used by Measure-Object implementation /// Keys are strings. Keys are compared with OrdinalIgnoreCase. /// </summary> /// <typeparam name="V">Value type.</typeparam> private class MeasureObjectDictionary<V> : Dictionary<string, V> where V : new() { /// <summary> /// default ctor /// </summary> internal MeasureObjectDictionary() : base(StringComparer.OrdinalIgnoreCase) { } /// <summary> /// Attempt to look up the value associated with the /// the specified key. If a value is not found, associate /// the key with a new value created via the value type's /// default constructor. /// </summary> /// <param name="key">The key to look up</param> /// <returns> /// The existing value, or a newly-created value. /// </returns> public V EnsureEntry(string key) { V val; if (!TryGetValue(key, out val)) { val = new V(); this[key] = val; } return val; } } /// <summary> /// Convenience class to track statistics without having /// to maintain two sets of MeasureInfo and constantly checking /// what mode we're in. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private class Statistics { // Common properties internal int count = 0; // Generic/Numeric statistics internal double sum = 0.0; internal object max = null; internal object min = null; // Text statistics internal int characters = 0; internal int words = 0; internal int lines = 0; } /// <summary> /// default constructor /// </summary> public MeasureObjectCommand() : base() { } #region Command Line Switches #region Common parameters in both sets /// <summary> /// incoming object /// </summary> /// <value></value> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } = AutomationNull.Value; /// <summary> /// Properties to be examined /// </summary> /// <value></value> [ValidateNotNullOrEmpty] [Parameter(Position = 0)] public string[] Property { get; set; } = null; #endregion Common parameters in both sets /// <summary> /// Set to true is Sum is to be returned /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Sum { get { return _measureSum; } set { _measureSum = value; } } private bool _measureSum; /// <summary> /// Set to true is Average is to be returned /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Average { get { return _measureAverage; } set { _measureAverage = value; } } private bool _measureAverage; /// <summary> /// Set to true is Max is to be returned /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Maximum { get { return _measureMax; } set { _measureMax = value; } } private bool _measureMax; /// <summary> /// Set to true is Min is to be returned /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Minimum { get { return _measureMin; } set { _measureMin = value; } } private bool _measureMin; #region TextMeasure ParameterSet /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Line { get { return _measureLines; } set { _measureLines = value; } } private bool _measureLines = false; /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Word { get { return _measureWords; } set { _measureWords = value; } } private bool _measureWords = false; /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Character { get { return _measureCharacters; } set { _measureCharacters = value; } } private bool _measureCharacters = false; /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter IgnoreWhiteSpace { get { return _ignoreWhiteSpace; } set { _ignoreWhiteSpace = value; } } private bool _ignoreWhiteSpace; #endregion TextMeasure ParameterSet #endregion Command Line Switches /// <summary> /// Which parameter set the Cmdlet is in. /// </summary> private bool IsMeasuringGeneric { get { return String.Compare(ParameterSetName, GenericParameterSet, StringComparison.Ordinal) == 0; } } /// <summary> /// Collect data about each record that comes in. /// Side effects: Updates totalRecordCount. /// </summary> protected override void ProcessRecord() { if (InputObject == null || InputObject == AutomationNull.Value) { return; } _totalRecordCount++; if (Property == null) AnalyzeValue(null, InputObject.BaseObject); else AnalyzeObjectProperties(InputObject); } /// <summary> /// Analyze an object on a property-by-property basis instead /// of as a simple value. /// Side effects: Updates statistics. /// <param name="inObj">The object to analyze.</param> /// </summary> private void AnalyzeObjectProperties(PSObject inObj) { // Keep track of which properties are counted for an // input object so that repeated properties won't be // counted twice. MeasureObjectDictionary<object> countedProperties = new MeasureObjectDictionary<object>(); // First iterate over the user-specified list of // properties... foreach (string p in Property) { MshExpression expression = new MshExpression(p); List<MshExpression> resolvedNames = expression.ResolveNames(inObj); if (resolvedNames == null || resolvedNames.Count == 0) { // Insert a blank entry so we can track // property misses in EndProcessing. if (!expression.HasWildCardCharacters) { string propertyName = expression.ToString(); _statistics.EnsureEntry(propertyName); } continue; } // Each property value can potentially refer // to multiple properties via globbing. Iterate over // the actual property names. foreach (MshExpression resolvedName in resolvedNames) { string propertyName = resolvedName.ToString(); // skip duplicated properties if (countedProperties.ContainsKey(propertyName)) { continue; } List<MshExpressionResult> tempExprRes = resolvedName.GetValues(inObj); if (tempExprRes == null || tempExprRes.Count == 0) { // Shouldn't happen - would somehow mean // that the property went away between when // we resolved it and when we tried to get its // value. continue; } AnalyzeValue(propertyName, tempExprRes[0].Result); // Remember resolved propertyNames that have been counted countedProperties[propertyName] = null; } } } /// <summary> /// Analyze a value for generic/text statistics. /// Side effects: Updates statistics. May set nonNumericError. /// <param name="propertyName">The property this value corresponds to.</param> /// <param name="objValue">The value to analyze.</param> /// </summary> private void AnalyzeValue(string propertyName, object objValue) { if (propertyName == null) propertyName = thisObject; Statistics stat = _statistics.EnsureEntry(propertyName); // Update common properties. stat.count++; if (_measureCharacters || _measureWords || _measureLines) { string strValue = (objValue == null) ? "" : objValue.ToString(); AnalyzeString(strValue, stat); } if (_measureAverage || _measureSum) { double numValue = 0.0; if (!LanguagePrimitives.TryConvertTo(objValue, out numValue)) { _nonNumericError = true; ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue), "NonNumericInputObject", ErrorCategory.InvalidType, objValue); WriteError(errorRecord); return; } AnalyzeNumber(numValue, stat); } // Win8:343911 Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo if (_measureMin) { stat.min = Compare(objValue, stat.min, true); } if (_measureMax) { stat.max = Compare(objValue, stat.max, false); } } /// <summary> /// Compare is a helper function used to find the min/max between the supplied input values. /// </summary> /// <param name="objValue"> /// Current input value. /// </param> /// <param name="statMinOrMaxValue"> /// Current minimum or maximum value in the statistics. /// </param> /// <param name="isMin"> /// Indicates if minimum or maximum value has to be found. /// If true is passed in then the minimum of the two values would be returned. /// If false is passed in then maximum of the two values will be returned.</param> /// <returns></returns> private object Compare(object objValue, object statMinOrMaxValue, bool isMin) { object currentValue = objValue; object statValue = statMinOrMaxValue; int factor = isMin ? 1 : -1; double temp; currentValue = ((objValue != null) && LanguagePrimitives.TryConvertTo<double>(objValue, out temp)) ? temp : currentValue; statValue = ((statValue != null) && LanguagePrimitives.TryConvertTo<double>(statValue, out temp)) ? temp : statValue; if (currentValue != null && statValue != null && !currentValue.GetType().Equals(statValue.GetType())) { currentValue = PSObject.AsPSObject(currentValue).ToString(); statValue = PSObject.AsPSObject(statValue).ToString(); } if ((statValue == null) || ((LanguagePrimitives.Compare(statValue, currentValue, false, CultureInfo.CurrentCulture) * factor) > 0)) { return objValue; } return statMinOrMaxValue; } /// <summary> /// Class contains util static functions /// </summary> private static class TextCountUtilities { /// <summary> /// count chars in inStr /// </summary> /// <param name="inStr">string whose chars are counted</param> /// <param name="ignoreWhiteSpace">true to discount white space</param> /// <returns>number of chars in inStr</returns> internal static int CountChar(string inStr, bool ignoreWhiteSpace) { if (String.IsNullOrEmpty(inStr)) { return 0; } if (!ignoreWhiteSpace) { return inStr.Length; } int len = 0; foreach (char c in inStr) { if (!char.IsWhiteSpace(c)) { len++; } } return len; } /// <summary> /// count words in inStr /// </summary> /// <param name="inStr">string whose words are counted</param> /// <returns>number of words in inStr</returns> internal static int CountWord(string inStr) { if (String.IsNullOrEmpty(inStr)) { return 0; } int wordCount = 0; bool wasAWhiteSpace = true; foreach (char c in inStr) { if (char.IsWhiteSpace(c)) { wasAWhiteSpace = true; } else { if (wasAWhiteSpace) { wordCount++; } wasAWhiteSpace = false; } } return wordCount; } /// <summary> /// count lines in inStr /// </summary> /// <param name="inStr">string whose lines are counted</param> /// <returns>number of lines in inStr</returns> internal static int CountLine(string inStr) { if (String.IsNullOrEmpty(inStr)) { return 0; } int numberOfLines = 0; foreach (char c in inStr) { if (c == '\n') { numberOfLines++; } } // 'abc\nd' has two lines // but 'abc\n' has one line if (inStr[inStr.Length - 1] != '\n') { numberOfLines++; } return numberOfLines; } } /// <summary> /// Update text statistics. /// <param name="strValue">The text to analyze.</param> /// <param name="stat">The Statistics object to update.</param> /// </summary> private void AnalyzeString(string strValue, Statistics stat) { if (_measureCharacters) stat.characters += TextCountUtilities.CountChar(strValue, _ignoreWhiteSpace); if (_measureWords) stat.words += TextCountUtilities.CountWord(strValue); if (_measureLines) stat.lines += TextCountUtilities.CountLine(strValue); } /// <summary> /// Update number statistics. /// <param name="numValue">The number to analyze.</param> /// <param name="stat">The Statistics object to update.</param> /// </summary> private void AnalyzeNumber(double numValue, Statistics stat) { if (_measureSum || _measureAverage) stat.sum += numValue; } /// <summary> /// WriteError when a property is not found /// </summary> /// <param name="propertyName">The missing property.</param> /// <param name="errorId">The error ID to write.</param> private void WritePropertyNotFoundError(string propertyName, string errorId) { Diagnostics.Assert(Property != null, "no property and no InputObject should have been addressed"); ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("Property"), errorId, ErrorCategory.InvalidArgument, null); errorRecord.ErrorDetails = new ErrorDetails( this, "MeasureObjectStrings", "PropertyNotFound", propertyName); WriteError(errorRecord); } /// <summary> /// Output collected statistics. /// Side effects: Updates statistics. Writes objects to stream. /// </summary> protected override void EndProcessing() { // Fix for 917114: If Property is not set, // and we aren't passed any records at all, // output 0s to emulate wc behavior. if (_totalRecordCount == 0 && Property == null) { _statistics.EnsureEntry(thisObject); } foreach (string propertyName in _statistics.Keys) { Statistics stat = _statistics[propertyName]; if (stat.count == 0 && Property != null) { // Why are there two different ids for this error? string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; WritePropertyNotFoundError(propertyName, errorId); continue; } MeasureInfo mi = null; if (IsMeasuringGeneric) { double temp; if ((stat.min == null || LanguagePrimitives.TryConvertTo<double>(stat.min, out temp)) && (stat.max == null || LanguagePrimitives.TryConvertTo<double>(stat.max, out temp))) { mi = CreateGenericMeasureInfo(stat, true); } else { mi = CreateGenericMeasureInfo(stat, false); } } else mi = CreateTextMeasureInfo(stat); // Set common properties. if (Property != null) mi.Property = propertyName; WriteObject(mi); } } /// <summary> /// Create a MeasureInfo object for generic stats. /// <param name="stat">The statistics to use.</param> /// <returns>A new GenericMeasureInfo object.</returns> /// </summary> /// <param name="shouldUseGenericMeasureInfo"></param> private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGenericMeasureInfo) { double? sum = null; double? average = null; object max = null; object min = null; if (!_nonNumericError) { if (_measureSum) sum = stat.sum; if (_measureAverage && stat.count > 0) average = stat.sum / stat.count; } if (_measureMax) { if (shouldUseGenericMeasureInfo && (stat.max != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.max, out temp); max = temp; } else { max = stat.max; } } if (_measureMin) { if (shouldUseGenericMeasureInfo && (stat.min != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.min, out temp); min = temp; } else { min = stat.min; } } if (shouldUseGenericMeasureInfo) { GenericMeasureInfo gmi = new GenericMeasureInfo(); gmi.Count = stat.count; gmi.Sum = sum; gmi.Average = average; if (null != max) { gmi.Maximum = (double)max; } if (null != min) { gmi.Minimum = (double)min; } return gmi; } else { GenericObjectMeasureInfo gomi = new GenericObjectMeasureInfo(); gomi.Count = stat.count; gomi.Sum = sum; gomi.Average = average; gomi.Maximum = max; gomi.Minimum = min; return gomi; } } /// <summary> /// Create a MeasureInfo object for text stats. /// <param name="stat">The statistics to use.</param> /// <returns>A new TextMeasureInfo object.</returns> /// </summary> private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) { TextMeasureInfo tmi = new TextMeasureInfo(); if (_measureCharacters) tmi.Characters = stat.characters; if (_measureWords) tmi.Words = stat.words; if (_measureLines) tmi.Lines = stat.lines; return tmi; } /// <summary> /// The observed statistics keyed by property name. If /// Property is not set, then the key used will be the /// value of thisObject. /// </summary> private MeasureObjectDictionary<Statistics> _statistics = new MeasureObjectDictionary<Statistics>(); /// <summary> /// Whether or not a numeric conversion error occurred. /// If true, then average/sum will not be output. /// </summary> private bool _nonNumericError = false; /// <summary> /// The total number of records encountered. /// </summary> private int _totalRecordCount = 0; /// <summary> /// Parameter set name for measuring objects. /// </summary> private const string GenericParameterSet = "GenericMeasure"; /// <summary> /// Parameter set name for measuring text. /// </summary> private const string TextParameterSet = "TextMeasure"; /// <summary> /// Key that statistics are stored under when Property is not set. /// </summary> private const string thisObject = "$_"; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/bigtable/admin/v2/instance.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Bigtable.Admin.V2 { /// <summary>Holder for reflection information generated from google/bigtable/admin/v2/instance.proto</summary> public static partial class InstanceReflection { #region Descriptor /// <summary>File descriptor for google/bigtable/admin/v2/instance.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static InstanceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cidnb29nbGUvYmlndGFibGUvYWRtaW4vdjIvaW5zdGFuY2UucHJvdG8SGGdv", "b2dsZS5iaWd0YWJsZS5hZG1pbi52MhocZ29vZ2xlL2FwaS9hbm5vdGF0aW9u", "cy5wcm90bxolZ29vZ2xlL2JpZ3RhYmxlL2FkbWluL3YyL2NvbW1vbi5wcm90", "byKeAQoISW5zdGFuY2USDAoEbmFtZRgBIAEoCRIUCgxkaXNwbGF5X25hbWUY", "AiABKAkSNwoFc3RhdGUYAyABKA4yKC5nb29nbGUuYmlndGFibGUuYWRtaW4u", "djIuSW5zdGFuY2UuU3RhdGUiNQoFU3RhdGUSEwoPU1RBVEVfTk9UX0tOT1dO", "EAASCQoFUkVBRFkQARIMCghDUkVBVElORxACIo4CCgdDbHVzdGVyEgwKBG5h", "bWUYASABKAkSEAoIbG9jYXRpb24YAiABKAkSNgoFc3RhdGUYAyABKA4yJy5n", "b29nbGUuYmlndGFibGUuYWRtaW4udjIuQ2x1c3Rlci5TdGF0ZRITCgtzZXJ2", "ZV9ub2RlcxgEIAEoBRJDChRkZWZhdWx0X3N0b3JhZ2VfdHlwZRgFIAEoDjIl", "Lmdvb2dsZS5iaWd0YWJsZS5hZG1pbi52Mi5TdG9yYWdlVHlwZSJRCgVTdGF0", "ZRITCg9TVEFURV9OT1RfS05PV04QABIJCgVSRUFEWRABEgwKCENSRUFUSU5H", "EAISDAoIUkVTSVpJTkcQAxIMCghESVNBQkxFRBAEQm4KHGNvbS5nb29nbGUu", "YmlndGFibGUuYWRtaW4udjJCDUluc3RhbmNlUHJvdG9QAVo9Z29vZ2xlLmdv", "bGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9iaWd0YWJsZS9hZG1pbi92", "MjthZG1pbmIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Bigtable.Admin.V2.CommonReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bigtable.Admin.V2.Instance), global::Google.Bigtable.Admin.V2.Instance.Parser, new[]{ "Name", "DisplayName", "State" }, null, new[]{ typeof(global::Google.Bigtable.Admin.V2.Instance.Types.State) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bigtable.Admin.V2.Cluster), global::Google.Bigtable.Admin.V2.Cluster.Parser, new[]{ "Name", "Location", "State", "ServeNodes", "DefaultStorageType" }, null, new[]{ typeof(global::Google.Bigtable.Admin.V2.Cluster.Types.State) }, null) })); } #endregion } #region Messages /// <summary> /// A collection of Bigtable [Tables][google.bigtable.admin.v2.Table] and /// the resources that serve them. /// All tables in an instance are served from a single /// [Cluster][google.bigtable.admin.v2.Cluster]. /// </summary> public sealed partial class Instance : pb::IMessage<Instance> { private static readonly pb::MessageParser<Instance> _parser = new pb::MessageParser<Instance>(() => new Instance()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Instance> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.V2.InstanceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Instance() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Instance(Instance other) : this() { name_ = other.name_; displayName_ = other.displayName_; state_ = other.state_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Instance Clone() { return new Instance(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// @OutputOnly /// The unique name of the instance. Values are of the form /// projects/&lt;project>/instances/[a-z][a-z0-9\\-]+[a-z0-9] /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "display_name" field.</summary> public const int DisplayNameFieldNumber = 2; private string displayName_ = ""; /// <summary> /// The descriptive name for this instance as it appears in UIs. /// Can be changed at any time, but should be kept globally unique /// to avoid confusion. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string DisplayName { get { return displayName_; } set { displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "state" field.</summary> public const int StateFieldNumber = 3; private global::Google.Bigtable.Admin.V2.Instance.Types.State state_ = 0; /// <summary> /// /// The current state of the instance. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Bigtable.Admin.V2.Instance.Types.State State { get { return state_; } set { state_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Instance); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Instance other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (DisplayName != other.DisplayName) return false; if (State != other.State) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode(); if (State != 0) hash ^= State.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (DisplayName.Length != 0) { output.WriteRawTag(18); output.WriteString(DisplayName); } if (State != 0) { output.WriteRawTag(24); output.WriteEnum((int) State); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (DisplayName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName); } if (State != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Instance other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.DisplayName.Length != 0) { DisplayName = other.DisplayName; } if (other.State != 0) { State = other.State; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { DisplayName = input.ReadString(); break; } case 24: { state_ = (global::Google.Bigtable.Admin.V2.Instance.Types.State) input.ReadEnum(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Instance message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Possible states of an instance. /// </summary> public enum State { /// <summary> /// The state of the instance could not be determined. /// </summary> [pbr::OriginalName("STATE_NOT_KNOWN")] NotKnown = 0, /// <summary> /// The instance has been successfully created and can serve requests /// to its tables. /// </summary> [pbr::OriginalName("READY")] Ready = 1, /// <summary> /// The instance is currently being created, and may be destroyed /// if the creation process encounters an error. /// </summary> [pbr::OriginalName("CREATING")] Creating = 2, } } #endregion } /// <summary> /// A resizable group of nodes in a particular cloud location, capable /// of serving all [Tables][google.bigtable.admin.v2.Table] in the parent /// [Instance][google.bigtable.admin.v2.Instance]. /// </summary> public sealed partial class Cluster : pb::IMessage<Cluster> { private static readonly pb::MessageParser<Cluster> _parser = new pb::MessageParser<Cluster>(() => new Cluster()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Cluster> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.V2.InstanceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Cluster() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Cluster(Cluster other) : this() { name_ = other.name_; location_ = other.location_; state_ = other.state_; serveNodes_ = other.serveNodes_; defaultStorageType_ = other.defaultStorageType_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Cluster Clone() { return new Cluster(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// @OutputOnly /// The unique name of the cluster. Values are of the form /// projects/&lt;project>/instances/&lt;instance>/clusters/[a-z][-a-z0-9]* /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "location" field.</summary> public const int LocationFieldNumber = 2; private string location_ = ""; /// <summary> /// @CreationOnly /// The location where this cluster's nodes and storage reside. For best /// performance, clients should be located as close as possible to this cluster. /// Currently only zones are supported, e.g. projects/*/locations/us-central1-b /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Location { get { return location_; } set { location_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "state" field.</summary> public const int StateFieldNumber = 3; private global::Google.Bigtable.Admin.V2.Cluster.Types.State state_ = 0; /// <summary> /// @OutputOnly /// The current state of the cluster. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Bigtable.Admin.V2.Cluster.Types.State State { get { return state_; } set { state_ = value; } } /// <summary>Field number for the "serve_nodes" field.</summary> public const int ServeNodesFieldNumber = 4; private int serveNodes_; /// <summary> /// The number of nodes allocated to this cluster. More nodes enable higher /// throughput and more consistent performance. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int ServeNodes { get { return serveNodes_; } set { serveNodes_ = value; } } /// <summary>Field number for the "default_storage_type" field.</summary> public const int DefaultStorageTypeFieldNumber = 5; private global::Google.Bigtable.Admin.V2.StorageType defaultStorageType_ = 0; /// <summary> /// @CreationOnly /// The type of storage used by this cluster to serve its /// parent instance's tables, unless explicitly overridden. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Bigtable.Admin.V2.StorageType DefaultStorageType { get { return defaultStorageType_; } set { defaultStorageType_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Cluster); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Cluster other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Location != other.Location) return false; if (State != other.State) return false; if (ServeNodes != other.ServeNodes) return false; if (DefaultStorageType != other.DefaultStorageType) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Location.Length != 0) hash ^= Location.GetHashCode(); if (State != 0) hash ^= State.GetHashCode(); if (ServeNodes != 0) hash ^= ServeNodes.GetHashCode(); if (DefaultStorageType != 0) hash ^= DefaultStorageType.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Location.Length != 0) { output.WriteRawTag(18); output.WriteString(Location); } if (State != 0) { output.WriteRawTag(24); output.WriteEnum((int) State); } if (ServeNodes != 0) { output.WriteRawTag(32); output.WriteInt32(ServeNodes); } if (DefaultStorageType != 0) { output.WriteRawTag(40); output.WriteEnum((int) DefaultStorageType); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Location.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Location); } if (State != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State); } if (ServeNodes != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ServeNodes); } if (DefaultStorageType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DefaultStorageType); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Cluster other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Location.Length != 0) { Location = other.Location; } if (other.State != 0) { State = other.State; } if (other.ServeNodes != 0) { ServeNodes = other.ServeNodes; } if (other.DefaultStorageType != 0) { DefaultStorageType = other.DefaultStorageType; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { Location = input.ReadString(); break; } case 24: { state_ = (global::Google.Bigtable.Admin.V2.Cluster.Types.State) input.ReadEnum(); break; } case 32: { ServeNodes = input.ReadInt32(); break; } case 40: { defaultStorageType_ = (global::Google.Bigtable.Admin.V2.StorageType) input.ReadEnum(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Cluster message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Possible states of a cluster. /// </summary> public enum State { /// <summary> /// The state of the cluster could not be determined. /// </summary> [pbr::OriginalName("STATE_NOT_KNOWN")] NotKnown = 0, /// <summary> /// The cluster has been successfully created and is ready to serve requests. /// </summary> [pbr::OriginalName("READY")] Ready = 1, /// <summary> /// The cluster is currently being created, and may be destroyed /// if the creation process encounters an error. /// A cluster may not be able to serve requests while being created. /// </summary> [pbr::OriginalName("CREATING")] Creating = 2, /// <summary> /// The cluster is currently being resized, and may revert to its previous /// node count if the process encounters an error. /// A cluster is still capable of serving requests while being resized, /// but may exhibit performance as if its number of allocated nodes is /// between the starting and requested states. /// </summary> [pbr::OriginalName("RESIZING")] Resizing = 3, /// <summary> /// The cluster has no backing nodes. The data (tables) still /// exist, but no operations can be performed on the cluster. /// </summary> [pbr::OriginalName("DISABLED")] Disabled = 4, } } #endregion } #endregion } #endregion Designer generated code
// 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.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; namespace System.Reflection.Runtime.BindingFlagSupport { // // This class exists for desktop compatibility. If one uses an api such as Type.GetProperty(string) to retrieve a member // from a base class, the desktop returns a special MemberInfo object that is blocked from seeing or invoking private // set or get methods on that property. That is, the type used to find the member is part of that member's object identity. // internal sealed class InheritedPropertyInfo : PropertyInfo { private readonly PropertyInfo _underlyingPropertyInfo; private readonly Type _reflectedType; internal InheritedPropertyInfo(PropertyInfo underlyingPropertyInfo, Type reflectedType) { // If the reflectedType is the declaring type, the caller should have used the original PropertyInfo. // This assert saves us from having to check this throughout. Debug.Assert(!(reflectedType.Equals(underlyingPropertyInfo.DeclaringType)), "reflectedType must be a proper base type of (and not equal to) underlyingPropertyInfo.DeclaringType."); _underlyingPropertyInfo = underlyingPropertyInfo; _reflectedType = reflectedType; return; } public sealed override PropertyAttributes Attributes { get { return _underlyingPropertyInfo.Attributes; } } public sealed override bool CanRead { get { return GetMethod != null; } } public sealed override bool CanWrite { get { return SetMethod != null; } } public sealed override ParameterInfo[] GetIndexParameters() { return _underlyingPropertyInfo.GetIndexParameters(); } public sealed override Type PropertyType { get { return _underlyingPropertyInfo.PropertyType; } } public sealed override Type DeclaringType { get { return _underlyingPropertyInfo.DeclaringType; } } public sealed override String Name { get { return _underlyingPropertyInfo.Name; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { return _underlyingPropertyInfo.CustomAttributes; } } public sealed override bool Equals(Object obj) { InheritedPropertyInfo other = obj as InheritedPropertyInfo; if (other == null) { return false; } if (!(_underlyingPropertyInfo.Equals(other._underlyingPropertyInfo))) { return false; } if (!(_reflectedType.Equals(other._reflectedType))) { return false; } return true; } public sealed override int GetHashCode() { int hashCode = _reflectedType.GetHashCode(); hashCode ^= _underlyingPropertyInfo.GetHashCode(); return hashCode; } public sealed override Object GetConstantValue() { return _underlyingPropertyInfo.GetConstantValue(); } public sealed override MethodInfo GetMethod { get { MethodInfo accessor = _underlyingPropertyInfo.GetMethod; return Filter(accessor); } } public sealed override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { if (GetMethod == null) { throw new ArgumentException(SR.Arg_GetMethNotFnd); } return _underlyingPropertyInfo.GetValue(obj, invokeAttr, binder, index, culture); } public sealed override Module Module { get { return _underlyingPropertyInfo.Module; } } public sealed override String ToString() { return _underlyingPropertyInfo.ToString(); } public sealed override MethodInfo SetMethod { get { MethodInfo accessor = _underlyingPropertyInfo.SetMethod; return Filter(accessor); } } public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { if (SetMethod == null) { throw new ArgumentException(SR.Arg_SetMethNotFnd); } _underlyingPropertyInfo.SetValue(obj, value, invokeAttr, binder, index, culture); } public sealed override MemberTypes MemberType { get { return MemberTypes.Property; } } public sealed override MethodInfo[] GetAccessors(bool nonPublic) { MethodInfo[] accessors = _underlyingPropertyInfo.GetAccessors(nonPublic); MethodInfo[] survivors = new MethodInfo[accessors.Length]; int numSurvivors = 0; for (int i = 0; i < accessors.Length; i++) { MethodInfo survivor = Filter(accessors[i]); if (survivor != null) { survivors[numSurvivors++] = survivor; } } Array.Resize(ref survivors, numSurvivors); return survivors; } public sealed override MethodInfo GetGetMethod(bool nonPublic) { MethodInfo accessor = _underlyingPropertyInfo.GetGetMethod(nonPublic); return Filter(accessor); } public sealed override MethodInfo GetSetMethod(bool nonPublic) { MethodInfo accessor = _underlyingPropertyInfo.GetSetMethod(nonPublic); return Filter(accessor); } public sealed override object[] GetCustomAttributes(bool inherit) { return _underlyingPropertyInfo.GetCustomAttributes(inherit); } public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { return _underlyingPropertyInfo.GetCustomAttributes(attributeType, inherit); } public sealed override bool IsDefined(Type attributeType, bool inherit) { return _underlyingPropertyInfo.IsDefined(attributeType, inherit); } public sealed override Type ReflectedType { get { return _underlyingPropertyInfo.ReflectedType; } } public sealed override IList<CustomAttributeData> GetCustomAttributesData() { return _underlyingPropertyInfo.GetCustomAttributesData(); } public sealed override Type[] GetOptionalCustomModifiers() { return _underlyingPropertyInfo.GetOptionalCustomModifiers(); } public sealed override object GetRawConstantValue() { return _underlyingPropertyInfo.GetRawConstantValue(); } public sealed override Type[] GetRequiredCustomModifiers() { return _underlyingPropertyInfo.GetRequiredCustomModifiers(); } public sealed override int MetadataToken { get { return _underlyingPropertyInfo.MetadataToken; } } #if DEBUG public sealed override object GetValue(object obj, object[] index) { return base.GetValue(obj, index); } public sealed override void SetValue(object obj, object value, object[] index) { base.SetValue(obj, value, index); } #endif private MethodInfo Filter(MethodInfo accessor) { // // For desktop compat, hide inherited accessors that are marked private. // // Q: Why don't we also hide cross-assembly "internal" accessors? // A: That inconsistency is also desktop-compatible. // if (accessor == null || accessor.IsPrivate) { return null; } return accessor; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; namespace MvvmScarletToolkit { public static class DependencyObjectExtensions { public static IEnumerable<DependencyObject> GetVisualDescendants(this DependencyObject visual) { if (visual is null) { yield break; } for (var i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++) { var child = VisualTreeHelper.GetChild(visual, i); yield return child; foreach (var subChild in GetVisualDescendants(child)) { yield return subChild; } } } public static DependencyObject? FindTopMostParent(this DependencyObject dependencyObject) { while (dependencyObject != null) { var isVisual = dependencyObject is Visual || dependencyObject is Visual3D; dependencyObject = isVisual ? VisualTreeHelper.GetParent(dependencyObject) : LogicalTreeHelper.GetParent(dependencyObject); } return default; } public static T? FindParent<T>(this DependencyObject dependencyObject) where T : DependencyObject { while (dependencyObject != null) { if (dependencyObject is T result) { return result; } var isVisual = dependencyObject is Visual || dependencyObject is Visual3D; dependencyObject = isVisual ? VisualTreeHelper.GetParent(dependencyObject) : LogicalTreeHelper.GetParent(dependencyObject); } return default; } public static T? FindVisualChildBreadthFirst<T>(this DependencyObject dependencyObject) where T : DependencyObject { return dependencyObject.FindVisualChildrenBreadthFirst<T>(null).FirstOrDefault(); } public static IEnumerable<T> FindVisualChildrenBreadthFirst<T>(this DependencyObject dependencyObject) where T : DependencyObject { return dependencyObject.FindVisualChildrenBreadthFirst<T>(null); } /// <summary> /// Gets all children of the specified visual in the visual tree recursively. /// </summary> /// <param name="dependencyObject">The visual to get the visual children for.</param> /// <returns>All children of the specified visual in the visual tree recursively.</returns> public static IEnumerable<T> FindVisualChildrenBreadthFirst<T>(this DependencyObject dependencyObject, Func<T, bool>? filter = null) where T : DependencyObject { if (dependencyObject is null) { yield break; } var count = VisualTreeHelper.GetChildrenCount(dependencyObject); var children = new DependencyObject[count]; for (var i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(dependencyObject, i); children[i] = child; if (child is T result && filter?.Invoke(result) != false) { yield return result; } } for (var i = 0; i < count; i++) { var child = children[i]; foreach (var grandchild in child.FindVisualChildrenBreadthFirst(filter)) { yield return grandchild; } } } /// <summary> /// Gets all children of the specified visual in the visual tree recursively including itself. /// </summary> /// <param name="dependencyObject">The visual to get the visual children for.</param> /// <returns>All children of the specified visual in the visual tree recursively including itself.</returns> public static IEnumerable<T> FindVisualChildrenBreadthFirstOrSelf<T>(this DependencyObject dependencyObject, Func<T, bool>? filter = null) where T : DependencyObject { if (dependencyObject is T self && filter?.Invoke(self) != false) { yield return self; } foreach (var child in dependencyObject.FindVisualChildrenBreadthFirst<T>(filter)) { yield return child; } } public static T? FindVisualChildDepthFirst<T>(this DependencyObject dependencyObject) where T : DependencyObject { return dependencyObject.FindVisualChildrenDepthFirst<T>(null).FirstOrDefault(); } public static IEnumerable<T> FindVisualChildrenDepthFirst<T>(this DependencyObject dependencyObject) where T : DependencyObject { return dependencyObject.FindVisualChildrenDepthFirst<T>(null); } /// <summary> /// Gets all children of the specified visual in the visual tree recursively. /// </summary> /// <param name="dependencyObject">The visual to get the visual children for.</param> /// <returns>All children of the specified visual in the visual tree recursively.</returns> public static IEnumerable<T> FindVisualChildrenDepthFirst<T>(this DependencyObject dependencyObject, Func<T, bool>? filter = null) where T : DependencyObject { if (dependencyObject is null) { yield break; } for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++) { var child = VisualTreeHelper.GetChild(dependencyObject, i); if (child is T result && filter?.Invoke(result) != false) { yield return result; } foreach (var grandchild in child.FindVisualChildrenDepthFirst(filter)) { yield return grandchild; } } } /// <summary> /// Gets all children of the specified visual in the visual tree recursively including itself. /// </summary> /// <param name="dependencyObject">The visual to get the visual children for.</param> /// <returns>All children of the specified visual in the visual tree recursively including itself.</returns> public static IEnumerable<T> FindVisualChildrenDepthFirstOrSelf<T>(this DependencyObject dependencyObject, Func<T, bool>? filter = null) where T : DependencyObject { if (dependencyObject is T self && filter?.Invoke(self) != false) { yield return self; } foreach (var child in dependencyObject.FindVisualChildrenDepthFirst<T>(filter)) { yield return child; } } /// <summary> /// emulates wpf default behavior for looking up datatemplates based on a given type /// </summary> public static DataTemplate? FindDataTemplateFor(this DependencyObject container, Type type) { return (container as FrameworkElement)?.FindDataTemplateFor(type); } /// <summary> /// emulates wpf default behavior for looking up datatemplates based on a given type /// </summary> public static DataTemplate? FindDataTemplateFor(this FrameworkElement container, Type type) { return container?.FindResource(new DataTemplateKey(type)) as DataTemplate; } } }
using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Threading; using Microsoft.Win32.SafeHandles; /// <summary> /// Use to coordinate values between different appdomain/process/terminal/users. /// </summary> internal partial class ProcessValueCoordinator : IDisposable { /// <summary>Prefix for the named shared memory file.</summary> private const string SharedMemoryName = @"Global\DPRuntimeMemory_"; /// <summary>Prefix for the named shared semaphore.</summary> private const string SemaphoreName = @"Global\DPRuntimeSemaphore_"; /// <summary>The size fo the shared memory file.</summary> private const uint BufferSize = 128; /// <summary>The named shared semaphaore.</summary> private Semaphore semaphore; /// <summary>The named shared memory file.</summary> private SafeFileMappingHandle sharedMemoryHandle; /// <summary>The mapped view of the shared memory file.</summary> private SafeMapViewOfFileHandle sharedMemoryMap; /// <summary>Create a syncronized shared memory file</summary> /// <param name="name">The suffix of the shared memory file and semaphore.</param> public ProcessValueCoordinator(string name) { if (String.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(name); } bool created = false; this.semaphore = new Semaphore(1, 1, SemaphoreName + name, out created); this.sharedMemoryHandle = Win32Native.CreateFileMapping(new SafeFileHandle(IntPtr.Zero, false), IntPtr.Zero, FileMapProtection.PageReadWrite, 0, BufferSize, SharedMemoryName + name); this.sharedMemoryMap = Win32Native.MapViewOfFile(this.sharedMemoryHandle, FileMapAccess.FileMapAllAccess, 0, 0, BufferSize); } /// <summary>Specifies the page protection of the file mapping object.</summary> [Flags] private enum FileMapProtection : uint { // PageReadonly = 0x02, // PageWriteCopy = 0x08, // PageExecuteRead = 0x20, // PageExecuteReadWrite = 0x40, // SectionCommit = 0x8000000, // SectionImage = 0x1000000, // SectionNoCache = 0x10000000, // SectionReserve = 0x4000000, /// <summary>Allows views to be mapped for read-only, copy-on-write, or read/write access.</summary> PageReadWrite = 0x04, } /// <summary>The type of access to a file mapping object, which determines the protection of the pages.</summary> [Flags] private enum FileMapAccess : uint { // FileMapCopy = 0x0001, // FileMapWrite = 0x0002, // FileMapRead = 0x0004, // fileMapExecute = 0x0020, /// <summary>A read/write view of the file is mapped.</summary> FileMapAllAccess = 0x001f, } /// <summary>Dispose of the native resources.</summary> public void Dispose() { Util.Dispose(ref this.sharedMemoryMap); Util.Dispose(ref this.sharedMemoryHandle); Util.Dispose(ref this.semaphore); } /// <summary>Read/Write the first integer in the syncronized shared memory</summary> /// <param name="action">Delegate that takes the value read from shared memory and returns the value to write to shared memory.</param> /// <returns>The value written to shared memory.</returns> public int Operate(Func<int, int> action) { if (null == action) { throw new ArgumentNullException("action"); } return this.Operate(Marshal.ReadInt32, action, Marshal.WriteInt32, 0); } /// <summary>Method to syncronize the shared memory.</summary> /// <typeparam name="T">The TypeOf the value type structure being read/write in shared memory.</typeparam> /// <param name="read">Delegate to read from shared memory.</param> /// <param name="action">Delegate that takes the value read from shared memory and returns the value to write to shared memory.</param> /// <param name="write">Delegate to write to shared memory.</param> /// <param name="offset">Byte offset in the shared memory buffer.</param> /// <returns>The value written to shared memory.</returns> public T Operate<T>(Func<IntPtr, int, T> read, Func<T, T> action, Action<IntPtr, int, T> write, int offset) where T : struct { if ((offset < 0) || (BufferSize < (offset + Marshal.SizeOf(typeof(T))))) { throw new ArgumentOutOfRangeException("offset"); } T current = default(T); Semaphore local = this.semaphore; SafeMapViewOfFileHandle handle = this.sharedMemoryMap; if ((null != local) && (null != handle)) { bool waitSuccess = false; RuntimeHelpers.PrepareConstrainedRegions(); try { if (WaitOne(local, UInt32.MaxValue, ref waitSuccess)) { bool memorySuccess = false; RuntimeHelpers.PrepareConstrainedRegions(); try { handle.DangerousAddRef(ref memorySuccess); IntPtr memory = handle.DangerousGetHandle(); write(memory, offset, current = action(read(memory, offset))); } finally { if (memorySuccess) { handle.DangerousRelease(); } } } } finally { if (waitSuccess) { local.Release(); } } } return current; } /// <summary>Reliable WaitOne</summary> /// <param name="waitHandle">object to wait on</param> /// <param name="millisecondsTimeout">The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled.</param> /// <param name="signaled">True if signaled, false if timeout.</param> /// <returns>Returns the <paramref name="signaled"/> value.</returns> /// <exception cref="AbandonedMutexException">If mutex was abandoned.</exception> [SecurityCritical] private static bool WaitOne(WaitHandle waitHandle, uint millisecondsTimeout, ref bool signaled) { signaled = false; SafeWaitHandle safeWaitHandle = waitHandle.SafeWaitHandle; RuntimeHelpers.PrepareConstrainedRegions(); try { // the default usage of local.WaitOne() can get interrupted on return // meaning we may successfully be signalled, but not know we should release // this solves that problem by waiting inside a reliability block that won't be interrupted } finally { switch (Win32Native.WaitForSingleObject(safeWaitHandle, millisecondsTimeout)) { case Win32Native.WaitObject0: signaled = true; break; case Win32Native.WaitAbandoned: throw new AbandonedMutexException(); case Win32Native.WaitTimeout: signaled = false; break; case Win32Native.WaitFailed: Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); break; } } return signaled; } /// <summary>Win32 native methods</summary> [SecurityCritical, SuppressUnmanagedCodeSecurity] private static class Win32Native { /// <summary>name of the file with win32 methods</summary> internal const string Kernel32 = "kernel32.dll"; /// <summary> /// The specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread and the mutex state is set to nonsignaled. /// </summary> internal const UInt32 WaitAbandoned = 0x00000080; /// <summary> /// The state of the specified object is signaled. /// </summary> internal const UInt32 WaitObject0 = 0x00000000; /// <summary> /// The time-out interval elapsed, and the object's state is nonsignaled. /// </summary> internal const UInt32 WaitTimeout = 0x00000102; /// <summary> /// The function has failed. /// </summary> internal const UInt32 WaitFailed = 0xFFFFFFFF; /// <summary> /// Creates or opens a named or unnamed file mapping object for a specified file. /// </summary> /// <param name="handle"> /// A handle to the file from which to create a file mapping object. /// If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a size for the file mapping object in the dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this scenario, CreateFileMapping creates a file mapping object of a specified size that is backed by the system paging file instead of by a file in the file system. /// </param> /// <param name="attributes">A pointer to a SECURITY_ATTRIBUTES structure that determines whether a returned handle can be inherited by child processes.</param> /// <param name="protect">Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection.</param> /// <param name="maximumSizeHigh">The high-order DWORD of the maximum size of the file mapping object.</param> /// <param name="maximumSizeLow">The low-order DWORD of the maximum size of the file mapping object.</param> /// <param name="name">The name of the file mapping object.</param> /// <returns>If the function succeeds, the return value is a handle to the newly created file mapping object.</returns> [DllImport(Kernel32, CharSet = CharSet.Auto, SetLastError = true)] internal static extern SafeFileMappingHandle CreateFileMapping(SafeFileHandle handle, IntPtr attributes, FileMapProtection protect, uint maximumSizeHigh, uint maximumSizeLow, string name); /// <summary> /// Maps a view of a file mapping into the address space of a calling process. /// </summary> /// <param name="handle">A handle to a file mapping object. The CreateFileMapping and OpenFileMapping functions return this handle.</param> /// <param name="desiredAccess">The type of access to a file mapping object, which determines the protection of the pages.</param> /// <param name="fileOffsetHigh">A high-order DWORD of the file offset where the view begins.</param> /// <param name="fileOffsetLow">A low-order DWORD of the file offset where the view is to begin. The combination of the high and low offsets must specify an offset within the file mapping. They must also match the memory allocation granularity of the system. That is, the offset must be a multiple of the allocation granularity. To obtain the memory allocation granularity of the system, use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure.</param> /// <param name="numberOfBytesToMap">The number of bytes of a file mapping to map to the view. All bytes must be within the maximum size specified by CreateFileMapping. If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping.</param> /// <returns>If the function succeeds, the return value is the starting address of the mapped view.</returns> [DllImport(Kernel32, SetLastError = true, ExactSpelling = true)] internal static extern SafeMapViewOfFileHandle MapViewOfFile(SafeFileMappingHandle handle, FileMapAccess desiredAccess, uint fileOffsetHigh, uint fileOffsetLow, uint numberOfBytesToMap); /// <summary> /// Unmaps a mapped view of a file from the calling process's address space. /// </summary> /// <param name="baseAddress"> /// A pointer to the base address of the mapped view of a file that is to be unmapped. This /// value must be identical to the value returned by a previous call to the MapViewOfFile /// or MapViewOfFileEx function. /// </param> /// <returns>If the function succeeds, the return value is nonzero.</returns> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport(Kernel32, ExactSpelling = true)] internal static extern bool UnmapViewOfFile(IntPtr baseAddress); /// <summary> /// Waits until the specified object is in the signaled state, an I/O completion routine or /// asynchronous procedure call (APC) is queued to the thread, or the time-out interval elapses. /// </summary> /// <param name="handle">A handle to the object.</param> /// <param name="milliseconds"> /// The time-out interval, in milliseconds. If a nonzero value is specified, the function waits /// until the object is signaled or the interval elapses. If dwMilliseconds is zero, the /// function does not enter a wait state if the object is not signaled; it always returns /// immediately. If dwMilliseconds is INFINITE, the function will return only when the object is /// signaled. /// </param> /// <returns>If the function succeeds, the return value indicates the event that caused the function to return.</returns> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport(Kernel32)] internal static extern uint WaitForSingleObject(SafeWaitHandle handle, uint milliseconds); /// <summary>Closes an open object handle.</summary> /// <param name="handle">A valid handle to an open object.</param> /// <returns>If the function succeeds, the return value is true.</returns> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport(Kernel32, SetLastError = true)] internal static extern bool CloseHandle(IntPtr handle); } /// <summary>Safe handle for CreateFileMapping</summary> [SecurityCritical] private sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid { /// <summary>default constructor</summary> [SecurityCritical] internal SafeFileMappingHandle() : base(true) { } /// <summary>specific constructor</summary> /// <param name="handle">handle</param> /// <param name="ownsHandle">ownership</param> [SecurityCritical] internal SafeFileMappingHandle(IntPtr handle, bool ownsHandle) : base(ownsHandle) { this.SetHandle(handle); } /// <summary>critical release</summary> /// <returns>true if released</returns> [SecurityCritical] protected override bool ReleaseHandle() { return Win32Native.CloseHandle(this.handle); } } /// <summary>Safe handle for MapViewOfFile</summary> [SecurityCritical] private sealed class SafeMapViewOfFileHandle : SafeHandleZeroOrMinusOneIsInvalid { /// <summary>default constructor</summary> [SecurityCritical] internal SafeMapViewOfFileHandle() : base(true) { } /// <summary>specific constructor</summary> /// <param name="handle">handle</param> /// <param name="ownsHandle">ownership</param> [SecurityCritical] internal SafeMapViewOfFileHandle(IntPtr handle, bool ownsHandle) : base(ownsHandle) { this.SetHandle(handle); } /// <summary>critical release</summary> /// <returns>true if released</returns> [SecurityCritical] protected override bool ReleaseHandle() { return Win32Native.UnmapViewOfFile(handle); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Xml; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Discovery; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Plugin; using Apache.Ignite.Core.Transactions; using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter; /// <summary> /// Grid configuration. /// </summary> public class IgniteConfiguration { /// <summary> /// Default initial JVM memory in megabytes. /// </summary> public const int DefaultJvmInitMem = -1; /// <summary> /// Default maximum JVM memory in megabytes. /// </summary> public const int DefaultJvmMaxMem = -1; /// <summary> /// Default metrics expire time. /// </summary> public static readonly TimeSpan DefaultMetricsExpireTime = TimeSpan.MaxValue; /// <summary> /// Default metrics history size. /// </summary> public const int DefaultMetricsHistorySize = 10000; /// <summary> /// Default metrics log frequency. /// </summary> public static readonly TimeSpan DefaultMetricsLogFrequency = TimeSpan.FromMilliseconds(60000); /// <summary> /// Default metrics update frequency. /// </summary> public static readonly TimeSpan DefaultMetricsUpdateFrequency = TimeSpan.FromMilliseconds(2000); /// <summary> /// Default network timeout. /// </summary> public static readonly TimeSpan DefaultNetworkTimeout = TimeSpan.FromMilliseconds(5000); /// <summary> /// Default network retry delay. /// </summary> public static readonly TimeSpan DefaultNetworkSendRetryDelay = TimeSpan.FromMilliseconds(1000); /// <summary> /// Default failure detection timeout. /// </summary> public static readonly TimeSpan DefaultFailureDetectionTimeout = TimeSpan.FromSeconds(10); /// <summary> /// Default failure detection timeout. /// </summary> public static readonly TimeSpan DefaultClientFailureDetectionTimeout = TimeSpan.FromSeconds(30); /** */ private TimeSpan? _metricsExpireTime; /** */ private int? _metricsHistorySize; /** */ private TimeSpan? _metricsLogFrequency; /** */ private TimeSpan? _metricsUpdateFrequency; /** */ private int? _networkSendRetryCount; /** */ private TimeSpan? _networkSendRetryDelay; /** */ private TimeSpan? _networkTimeout; /** */ private bool? _isDaemon; /** */ private bool? _isLateAffinityAssignment; /** */ private bool? _clientMode; /** */ private TimeSpan? _failureDetectionTimeout; /** */ private TimeSpan? _clientFailureDetectionTimeout; /// <summary> /// Default network retry count. /// </summary> public const int DefaultNetworkSendRetryCount = 3; /// <summary> /// Default late affinity assignment mode. /// </summary> public const bool DefaultIsLateAffinityAssignment = true; /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class. /// </summary> public IgniteConfiguration() { JvmInitialMemoryMb = DefaultJvmInitMem; JvmMaxMemoryMb = DefaultJvmMaxMem; } /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class. /// </summary> /// <param name="configuration">The configuration to copy.</param> public IgniteConfiguration(IgniteConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var marsh = BinaryUtils.Marshaller; configuration.Write(marsh.StartMarshal(stream)); stream.SynchronizeOutput(); stream.Seek(0, SeekOrigin.Begin); ReadCore(marsh.StartUnmarshal(stream)); } CopyLocalProperties(configuration); } /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration" /> class from a reader. /// </summary> /// <param name="binaryReader">The binary reader.</param> /// <param name="baseConfig">The base configuration.</param> internal IgniteConfiguration(IBinaryRawReader binaryReader, IgniteConfiguration baseConfig) { Debug.Assert(binaryReader != null); Debug.Assert(baseConfig != null); CopyLocalProperties(baseConfig); Read(binaryReader); } /// <summary> /// Writes this instance to a writer. /// </summary> /// <param name="writer">The writer.</param> internal void Write(BinaryWriter writer) { Debug.Assert(writer != null); // Simple properties writer.WriteBooleanNullable(_clientMode); writer.WriteIntArray(IncludedEventTypes == null ? null : IncludedEventTypes.ToArray()); writer.WriteTimeSpanAsLongNullable(_metricsExpireTime); writer.WriteIntNullable(_metricsHistorySize); writer.WriteTimeSpanAsLongNullable(_metricsLogFrequency); writer.WriteTimeSpanAsLongNullable(_metricsUpdateFrequency); writer.WriteIntNullable(_networkSendRetryCount); writer.WriteTimeSpanAsLongNullable(_networkSendRetryDelay); writer.WriteTimeSpanAsLongNullable(_networkTimeout); writer.WriteString(WorkDirectory); writer.WriteString(Localhost); writer.WriteBooleanNullable(_isDaemon); writer.WriteBooleanNullable(_isLateAffinityAssignment); writer.WriteTimeSpanAsLongNullable(_failureDetectionTimeout); writer.WriteTimeSpanAsLongNullable(_clientFailureDetectionTimeout); // Cache config var caches = CacheConfiguration; if (caches == null) writer.WriteInt(0); else { writer.WriteInt(caches.Count); foreach (var cache in caches) cache.Write(writer); } // Discovery config var disco = DiscoverySpi; if (disco != null) { writer.WriteBoolean(true); var tcpDisco = disco as TcpDiscoverySpi; if (tcpDisco == null) throw new InvalidOperationException("Unsupported discovery SPI: " + disco.GetType()); tcpDisco.Write(writer); } else writer.WriteBoolean(false); // Communication config var comm = CommunicationSpi; if (comm != null) { writer.WriteBoolean(true); var tcpComm = comm as TcpCommunicationSpi; if (tcpComm == null) throw new InvalidOperationException("Unsupported communication SPI: " + comm.GetType()); tcpComm.Write(writer); } else writer.WriteBoolean(false); // Binary config if (BinaryConfiguration != null) { writer.WriteBoolean(true); if (BinaryConfiguration.CompactFooterInternal != null) { writer.WriteBoolean(true); writer.WriteBoolean(BinaryConfiguration.CompactFooter); } else { writer.WriteBoolean(false); } // Name mapper. var mapper = BinaryConfiguration.NameMapper as BinaryBasicNameMapper; writer.WriteBoolean(mapper != null && mapper.IsSimpleName); } else { writer.WriteBoolean(false); } // User attributes var attrs = UserAttributes; if (attrs == null) writer.WriteInt(0); else { writer.WriteInt(attrs.Count); foreach (var pair in attrs) { writer.WriteString(pair.Key); writer.Write(pair.Value); } } // Atomic if (AtomicConfiguration != null) { writer.WriteBoolean(true); writer.WriteInt(AtomicConfiguration.AtomicSequenceReserveSize); writer.WriteInt(AtomicConfiguration.Backups); writer.WriteInt((int) AtomicConfiguration.CacheMode); } else writer.WriteBoolean(false); // Tx if (TransactionConfiguration != null) { writer.WriteBoolean(true); writer.WriteInt(TransactionConfiguration.PessimisticTransactionLogSize); writer.WriteInt((int) TransactionConfiguration.DefaultTransactionConcurrency); writer.WriteInt((int) TransactionConfiguration.DefaultTransactionIsolation); writer.WriteLong((long) TransactionConfiguration.DefaultTimeout.TotalMilliseconds); writer.WriteInt((int) TransactionConfiguration.PessimisticTransactionLogLinger.TotalMilliseconds); } else writer.WriteBoolean(false); // Event storage if (EventStorageSpi == null) { writer.WriteByte(0); } else if (EventStorageSpi is NoopEventStorageSpi) { writer.WriteByte(1); } else { var memEventStorage = EventStorageSpi as MemoryEventStorageSpi; if (memEventStorage == null) { throw new IgniteException(string.Format( "Unsupported IgniteConfiguration.EventStorageSpi: '{0}'. " + "Supported implementations: '{1}', '{2}'.", EventStorageSpi.GetType(), typeof(NoopEventStorageSpi), typeof(MemoryEventStorageSpi))); } writer.WriteByte(2); memEventStorage.Write(writer); } if (MemoryConfiguration != null) { writer.WriteBoolean(true); MemoryConfiguration.Write(writer); } else { writer.WriteBoolean(false); } // Plugins (should be last) if (PluginConfigurations != null) { var pos = writer.Stream.Position; writer.WriteInt(0); // reserve count var cnt = 0; foreach (var cfg in PluginConfigurations) { if (cfg.PluginConfigurationClosureFactoryId != null) { writer.WriteInt(cfg.PluginConfigurationClosureFactoryId.Value); cfg.WriteBinary(writer); cnt++; } } writer.Stream.WriteInt(pos, cnt); } else { writer.WriteInt(0); } } /// <summary> /// Validates this instance and outputs information to the log, if necessary. /// </summary> internal void Validate(ILogger log) { Debug.Assert(log != null); var ccfg = CacheConfiguration; if (ccfg != null) { foreach (var cfg in ccfg) cfg.Validate(log); } } /// <summary> /// Reads data from specified reader into current instance. /// </summary> /// <param name="r">The binary reader.</param> private void ReadCore(IBinaryRawReader r) { // Simple properties _clientMode = r.ReadBooleanNullable(); IncludedEventTypes = r.ReadIntArray(); _metricsExpireTime = r.ReadTimeSpanNullable(); _metricsHistorySize = r.ReadIntNullable(); _metricsLogFrequency = r.ReadTimeSpanNullable(); _metricsUpdateFrequency = r.ReadTimeSpanNullable(); _networkSendRetryCount = r.ReadIntNullable(); _networkSendRetryDelay = r.ReadTimeSpanNullable(); _networkTimeout = r.ReadTimeSpanNullable(); WorkDirectory = r.ReadString(); Localhost = r.ReadString(); _isDaemon = r.ReadBooleanNullable(); _isLateAffinityAssignment = r.ReadBooleanNullable(); _failureDetectionTimeout = r.ReadTimeSpanNullable(); _clientFailureDetectionTimeout = r.ReadTimeSpanNullable(); // Cache config var cacheCfgCount = r.ReadInt(); CacheConfiguration = new List<CacheConfiguration>(cacheCfgCount); for (int i = 0; i < cacheCfgCount; i++) CacheConfiguration.Add(new CacheConfiguration(r)); // Discovery config DiscoverySpi = r.ReadBoolean() ? new TcpDiscoverySpi(r) : null; // Communication config CommunicationSpi = r.ReadBoolean() ? new TcpCommunicationSpi(r) : null; // Binary config if (r.ReadBoolean()) { BinaryConfiguration = BinaryConfiguration ?? new BinaryConfiguration(); if (r.ReadBoolean()) { BinaryConfiguration.CompactFooter = r.ReadBoolean(); } if (r.ReadBoolean()) { BinaryConfiguration.NameMapper = BinaryBasicNameMapper.SimpleNameInstance; } } // User attributes UserAttributes = Enumerable.Range(0, r.ReadInt()) .ToDictionary(x => r.ReadString(), x => r.ReadObject<object>()); // Atomic if (r.ReadBoolean()) { AtomicConfiguration = new AtomicConfiguration { AtomicSequenceReserveSize = r.ReadInt(), Backups = r.ReadInt(), CacheMode = (CacheMode) r.ReadInt() }; } // Tx if (r.ReadBoolean()) { TransactionConfiguration = new TransactionConfiguration { PessimisticTransactionLogSize = r.ReadInt(), DefaultTransactionConcurrency = (TransactionConcurrency) r.ReadInt(), DefaultTransactionIsolation = (TransactionIsolation) r.ReadInt(), DefaultTimeout = TimeSpan.FromMilliseconds(r.ReadLong()), PessimisticTransactionLogLinger = TimeSpan.FromMilliseconds(r.ReadInt()) }; } // Event storage switch (r.ReadByte()) { case 1: EventStorageSpi = new NoopEventStorageSpi(); break; case 2: EventStorageSpi = MemoryEventStorageSpi.Read(r); break; } if (r.ReadBoolean()) { MemoryConfiguration = new MemoryConfiguration(r); } } /// <summary> /// Reads data from specified reader into current instance. /// </summary> /// <param name="binaryReader">The binary reader.</param> private void Read(IBinaryRawReader binaryReader) { ReadCore(binaryReader); // Misc IgniteHome = binaryReader.ReadString(); JvmInitialMemoryMb = (int) (binaryReader.ReadLong()/1024/2014); JvmMaxMemoryMb = (int) (binaryReader.ReadLong()/1024/2014); // Local data (not from reader) JvmDllPath = Process.GetCurrentProcess().Modules.OfType<ProcessModule>() .Single(x => string.Equals(x.ModuleName, IgniteUtils.FileJvmDll, StringComparison.OrdinalIgnoreCase)) .FileName; } /// <summary> /// Copies the local properties (properties that are not written in Write method). /// </summary> private void CopyLocalProperties(IgniteConfiguration cfg) { IgniteInstanceName = cfg.IgniteInstanceName; if (BinaryConfiguration != null && cfg.BinaryConfiguration != null) { BinaryConfiguration.MergeTypes(cfg.BinaryConfiguration); } else if (cfg.BinaryConfiguration != null) { BinaryConfiguration = new BinaryConfiguration(cfg.BinaryConfiguration); } JvmClasspath = cfg.JvmClasspath; JvmOptions = cfg.JvmOptions; Assemblies = cfg.Assemblies; SuppressWarnings = cfg.SuppressWarnings; LifecycleHandlers = cfg.LifecycleHandlers; Logger = cfg.Logger; JvmInitialMemoryMb = cfg.JvmInitialMemoryMb; JvmMaxMemoryMb = cfg.JvmMaxMemoryMb; PluginConfigurations = cfg.PluginConfigurations; AutoGenerateIgniteInstanceName = cfg.AutoGenerateIgniteInstanceName; } /// <summary> /// Gets or sets optional local instance name. /// <para /> /// This name only works locally and has no effect on topology. /// <para /> /// This property is used to when there are multiple Ignite nodes in one process to distinguish them. /// </summary> public string IgniteInstanceName { get; set; } /// <summary> /// Gets or sets a value indicating whether unique <see cref="IgniteInstanceName"/> should be generated. /// <para /> /// Set this to true in scenarios where new node should be started regardless of other nodes present within /// current process. In particular, this setting is useful is ASP.NET and IIS environments, where AppDomains /// are loaded and unloaded within a single process during application restarts. Ignite stops all nodes /// on <see cref="AppDomain"/> unload, however, IIS does not wait for previous AppDomain to unload before /// starting up a new one, which may cause "Ignite instance with this name has already been started" errors. /// This setting solves the issue. /// </summary> public bool AutoGenerateIgniteInstanceName { get; set; } /// <summary> /// Gets or sets optional local instance name. /// <para /> /// This name only works locally and has no effect on topology. /// <para /> /// This property is used to when there are multiple Ignite nodes in one process to distinguish them. /// </summary> [Obsolete("Use IgniteInstanceName instead.")] public string GridName { get { return IgniteInstanceName; } set { IgniteInstanceName = value; } } /// <summary> /// Gets or sets the binary configuration. /// </summary> /// <value> /// The binary configuration. /// </value> public BinaryConfiguration BinaryConfiguration { get; set; } /// <summary> /// Gets or sets the cache configuration. /// </summary> /// <value> /// The cache configuration. /// </value> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<CacheConfiguration> CacheConfiguration { get; set; } /// <summary> /// URL to Spring configuration file. /// <para /> /// Spring configuration is loaded first, then <see cref="IgniteConfiguration"/> properties are applied. /// Null property values do not override Spring values. /// Value-typed properties are tracked internally: if setter was not called, Spring value won't be overwritten. /// <para /> /// This merging happens on the top level only; e. g. if there are cache configurations defined in Spring /// and in .NET, .NET caches will overwrite Spring caches. /// </summary> [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public string SpringConfigUrl { get; set; } /// <summary> /// Path jvm.dll file. If not set, it's location will be determined /// using JAVA_HOME environment variable. /// If path is neither set nor determined automatically, an exception /// will be thrown. /// </summary> public string JvmDllPath { get; set; } /// <summary> /// Path to Ignite home. If not set environment variable IGNITE_HOME will be used. /// </summary> public string IgniteHome { get; set; } /// <summary> /// Classpath used by JVM on Ignite start. /// </summary> public string JvmClasspath { get; set; } /// <summary> /// Collection of options passed to JVM on Ignite start. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<string> JvmOptions { get; set; } /// <summary> /// List of additional .Net assemblies to load on Ignite start. Each item can be either /// fully qualified assembly name, path to assembly to DLL or path to a directory when /// assemblies reside. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<string> Assemblies { get; set; } /// <summary> /// Whether to suppress warnings. /// </summary> public bool SuppressWarnings { get; set; } /// <summary> /// Lifecycle handlers. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<ILifecycleHandler> LifecycleHandlers { get; set; } /// <summary> /// Initial amount of memory in megabytes given to JVM. Maps to -Xms Java option. /// <code>-1</code> maps to JVM defaults. /// Defaults to <see cref="DefaultJvmInitMem"/>. /// </summary> [DefaultValue(DefaultJvmInitMem)] public int JvmInitialMemoryMb { get; set; } /// <summary> /// Maximum amount of memory in megabytes given to JVM. Maps to -Xmx Java option. /// <code>-1</code> maps to JVM defaults. /// Defaults to <see cref="DefaultJvmMaxMem"/>. /// </summary> [DefaultValue(DefaultJvmMaxMem)] public int JvmMaxMemoryMb { get; set; } /// <summary> /// Gets or sets the discovery service provider. /// Null for default discovery. /// </summary> public IDiscoverySpi DiscoverySpi { get; set; } /// <summary> /// Gets or sets the communication service provider. /// Null for default communication. /// </summary> public ICommunicationSpi CommunicationSpi { get; set; } /// <summary> /// Gets or sets a value indicating whether node should start in client mode. /// Client node cannot hold data in the caches. /// </summary> public bool ClientMode { get { return _clientMode ?? default(bool); } set { _clientMode = value; } } /// <summary> /// Gets or sets a set of event types (<see cref="EventType" />) to be recorded by Ignite. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<int> IncludedEventTypes { get; set; } /// <summary> /// Gets or sets the time after which a certain metric value is considered expired. /// </summary> [DefaultValue(typeof(TimeSpan), "10675199.02:48:05.4775807")] public TimeSpan MetricsExpireTime { get { return _metricsExpireTime ?? DefaultMetricsExpireTime; } set { _metricsExpireTime = value; } } /// <summary> /// Gets or sets the number of metrics kept in history to compute totals and averages. /// </summary> [DefaultValue(DefaultMetricsHistorySize)] public int MetricsHistorySize { get { return _metricsHistorySize ?? DefaultMetricsHistorySize; } set { _metricsHistorySize = value; } } /// <summary> /// Gets or sets the frequency of metrics log print out. /// <see cref="TimeSpan.Zero"/> to disable metrics print out. /// </summary> [DefaultValue(typeof(TimeSpan), "00:01:00")] public TimeSpan MetricsLogFrequency { get { return _metricsLogFrequency ?? DefaultMetricsLogFrequency; } set { _metricsLogFrequency = value; } } /// <summary> /// Gets or sets the job metrics update frequency. /// <see cref="TimeSpan.Zero"/> to update metrics on job start/finish. /// Negative value to never update metrics. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:02")] public TimeSpan MetricsUpdateFrequency { get { return _metricsUpdateFrequency ?? DefaultMetricsUpdateFrequency; } set { _metricsUpdateFrequency = value; } } /// <summary> /// Gets or sets the network send retry count. /// </summary> [DefaultValue(DefaultNetworkSendRetryCount)] public int NetworkSendRetryCount { get { return _networkSendRetryCount ?? DefaultNetworkSendRetryCount; } set { _networkSendRetryCount = value; } } /// <summary> /// Gets or sets the network send retry delay. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:01")] public TimeSpan NetworkSendRetryDelay { get { return _networkSendRetryDelay ?? DefaultNetworkSendRetryDelay; } set { _networkSendRetryDelay = value; } } /// <summary> /// Gets or sets the network timeout. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:05")] public TimeSpan NetworkTimeout { get { return _networkTimeout ?? DefaultNetworkTimeout; } set { _networkTimeout = value; } } /// <summary> /// Gets or sets the work directory. /// If not provided, a folder under <see cref="IgniteHome"/> will be used. /// </summary> public string WorkDirectory { get; set; } /// <summary> /// Gets or sets system-wide local address or host for all Ignite components to bind to. /// If provided it will override all default local bind settings within Ignite. /// <para /> /// If <c>null</c> then Ignite tries to use local wildcard address.That means that all services /// will be available on all network interfaces of the host machine. /// <para /> /// It is strongly recommended to set this parameter for all production environments. /// </summary> public string Localhost { get; set; } /// <summary> /// Gets or sets a value indicating whether this node should be a daemon node. /// <para /> /// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs, /// i.e. they are not part of any cluster groups. /// <para /> /// Daemon nodes are used primarily for management and monitoring functionality that is built on Ignite /// and needs to participate in the topology, but also needs to be excluded from the "normal" topology, /// so that it won't participate in the task execution or in-memory data grid storage. /// </summary> public bool IsDaemon { get { return _isDaemon ?? default(bool); } set { _isDaemon = value; } } /// <summary> /// Gets or sets the user attributes for this node. /// <para /> /// These attributes can be retrieved later via <see cref="IClusterNode.GetAttributes"/>. /// Environment variables are added to node attributes automatically. /// NOTE: attribute names starting with "org.apache.ignite" are reserved for internal use. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary<string, object> UserAttributes { get; set; } /// <summary> /// Gets or sets the atomic data structures configuration. /// </summary> public AtomicConfiguration AtomicConfiguration { get; set; } /// <summary> /// Gets or sets the transaction configuration. /// </summary> public TransactionConfiguration TransactionConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating whether late affinity assignment mode should be used. /// <para /> /// On each topology change, for each started cache, partition-to-node mapping is /// calculated using AffinityFunction for cache. When late /// affinity assignment mode is disabled then new affinity mapping is applied immediately. /// <para /> /// With late affinity assignment mode, if primary node was changed for some partition, but data for this /// partition is not rebalanced yet on this node, then current primary is not changed and new primary /// is temporary assigned as backup. This nodes becomes primary only when rebalancing for all assigned primary /// partitions is finished. This mode can show better performance for cache operations, since when cache /// primary node executes some operation and data is not rebalanced yet, then it sends additional message /// to force rebalancing from other nodes. /// <para /> /// Note, that <see cref="ICacheAffinity"/> interface provides assignment information taking late assignment /// into account, so while rebalancing for new primary nodes is not finished it can return assignment /// which differs from assignment calculated by AffinityFunction. /// <para /> /// This property should have the same value for all nodes in cluster. /// <para /> /// If not provided, default value is <see cref="DefaultIsLateAffinityAssignment"/>. /// </summary> [DefaultValue(DefaultIsLateAffinityAssignment)] public bool IsLateAffinityAssignment { get { return _isLateAffinityAssignment ?? DefaultIsLateAffinityAssignment; } set { _isLateAffinityAssignment = value; } } /// <summary> /// Serializes this instance to the specified XML writer. /// </summary> /// <param name="writer">The writer.</param> /// <param name="rootElementName">Name of the root element.</param> public void ToXml(XmlWriter writer, string rootElementName) { IgniteArgumentCheck.NotNull(writer, "writer"); IgniteArgumentCheck.NotNullOrEmpty(rootElementName, "rootElementName"); IgniteConfigurationXmlSerializer.Serialize(this, writer, rootElementName); } /// <summary> /// Serializes this instance to an XML string. /// </summary> public string ToXml() { var sb = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true }; using (var xmlWriter = XmlWriter.Create(sb, settings)) { ToXml(xmlWriter, "igniteConfiguration"); } return sb.ToString(); } /// <summary> /// Deserializes IgniteConfiguration from the XML reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Deserialized instance.</returns> public static IgniteConfiguration FromXml(XmlReader reader) { IgniteArgumentCheck.NotNull(reader, "reader"); return IgniteConfigurationXmlSerializer.Deserialize(reader); } /// <summary> /// Deserializes IgniteConfiguration from the XML string. /// </summary> /// <param name="xml">Xml string.</param> /// <returns>Deserialized instance.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SuppressMessage("Microsoft.Usage", "CA2202: Do not call Dispose more than one time on an object")] public static IgniteConfiguration FromXml(string xml) { IgniteArgumentCheck.NotNullOrEmpty(xml, "xml"); using (var stringReader = new StringReader(xml)) using (var xmlReader = XmlReader.Create(stringReader)) { // Skip XML header. xmlReader.MoveToContent(); return FromXml(xmlReader); } } /// <summary> /// Gets or sets the logger. /// <para /> /// If no logger is set, logging is delegated to Java, which uses the logger defined in Spring XML (if present) /// or logs to console otherwise. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/> /// and <see cref="TcpCommunicationSpi"/>. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:10")] public TimeSpan FailureDetectionTimeout { get { return _failureDetectionTimeout ?? DefaultFailureDetectionTimeout; } set { _failureDetectionTimeout = value; } } /// <summary> /// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/> /// and <see cref="TcpCommunicationSpi"/> for client nodes. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:30")] public TimeSpan ClientFailureDetectionTimeout { get { return _clientFailureDetectionTimeout ?? DefaultClientFailureDetectionTimeout; } set { _clientFailureDetectionTimeout = value; } } /// <summary> /// Gets or sets the configurations for plugins to be started. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<IPluginConfiguration> PluginConfigurations { get; set; } /// <summary> /// Gets or sets the event storage interface. /// <para /> /// Only predefined implementations are supported: /// <see cref="NoopEventStorageSpi"/>, <see cref="MemoryEventStorageSpi"/>. /// </summary> public IEventStorageSpi EventStorageSpi { get; set; } /// <summary> /// Gets or sets the page memory configuration. /// <see cref="MemoryConfiguration"/> for more details. /// </summary> public MemoryConfiguration MemoryConfiguration { get; set; } } }
using DeOps.Interface; namespace DeOps.Services.Mail { partial class ComposeMail { /// <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 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.label1 = new System.Windows.Forms.Label(); this.ToTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.SubjectTextBox = new System.Windows.Forms.TextBox(); this.MessageBody = new DeOps.Interface.TextInput(); this.SendButton = new System.Windows.Forms.Button(); this.ExitButton = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.ListFiles = new System.Windows.Forms.ComboBox(); this.LinkAdd = new System.Windows.Forms.LinkLabel(); this.LinkRemove = new System.Windows.Forms.LinkLabel(); this.AddPersonLink = new System.Windows.Forms.LinkLabel(); this.RemovePersonLink = new System.Windows.Forms.LinkLabel(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(3, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(21, 13); this.label1.TabIndex = 0; this.label1.Text = "To"; // // ToTextBox // this.ToTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ToTextBox.BackColor = System.Drawing.Color.WhiteSmoke; this.ToTextBox.Location = new System.Drawing.Point(52, 6); this.ToTextBox.Name = "ToTextBox"; this.ToTextBox.ReadOnly = true; this.ToTextBox.Size = new System.Drawing.Size(173, 20); this.ToTextBox.TabIndex = 2; this.ToTextBox.Text = "Click Add..."; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(3, 35); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(50, 13); this.label3.TabIndex = 4; this.label3.Text = "Subject"; // // SubjectTextBox // this.SubjectTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.SubjectTextBox.Location = new System.Drawing.Point(52, 32); this.SubjectTextBox.Name = "SubjectTextBox"; this.SubjectTextBox.Size = new System.Drawing.Size(254, 20); this.SubjectTextBox.TabIndex = 5; // // MessageBody // this.MessageBody.AcceptTabs = true; this.MessageBody.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.MessageBody.EnterClears = false; this.MessageBody.IMButtons = false; this.MessageBody.Location = new System.Drawing.Point(6, 85); this.MessageBody.Name = "MessageBody"; this.MessageBody.PlainTextMode = true; this.MessageBody.ReadOnly = false; this.MessageBody.ShowFontStrip = true; this.MessageBody.Size = new System.Drawing.Size(300, 162); this.MessageBody.TabIndex = 6; // // SendButton // this.SendButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.SendButton.Location = new System.Drawing.Point(150, 253); this.SendButton.Name = "SendButton"; this.SendButton.Size = new System.Drawing.Size(75, 23); this.SendButton.TabIndex = 7; this.SendButton.Text = "Send"; this.SendButton.UseVisualStyleBackColor = true; this.SendButton.Click += new System.EventHandler(this.SendButton_Click); // // ExitButton // this.ExitButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.ExitButton.Location = new System.Drawing.Point(231, 253); this.ExitButton.Name = "ExitButton"; this.ExitButton.Size = new System.Drawing.Size(75, 23); this.ExitButton.TabIndex = 8; this.ExitButton.Text = "Cancel"; this.ExitButton.UseVisualStyleBackColor = true; this.ExitButton.Click += new System.EventHandler(this.CancelButton_Click); // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(6, 61); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(32, 13); this.label4.TabIndex = 9; this.label4.Text = "Files"; // // ListFiles // this.ListFiles.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ListFiles.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.ListFiles.FormattingEnabled = true; this.ListFiles.Location = new System.Drawing.Point(130, 58); this.ListFiles.Name = "ListFiles"; this.ListFiles.Size = new System.Drawing.Size(176, 21); this.ListFiles.TabIndex = 10; // // LinkAdd // this.LinkAdd.ActiveLinkColor = System.Drawing.Color.Blue; this.LinkAdd.AutoSize = true; this.LinkAdd.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.LinkAdd.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.LinkAdd.Location = new System.Drawing.Point(49, 61); this.LinkAdd.Name = "LinkAdd"; this.LinkAdd.Size = new System.Drawing.Size(26, 13); this.LinkAdd.TabIndex = 14; this.LinkAdd.TabStop = true; this.LinkAdd.Text = "Add"; this.LinkAdd.VisitedLinkColor = System.Drawing.Color.Blue; this.LinkAdd.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkAdd_LinkClicked); // // LinkRemove // this.LinkRemove.ActiveLinkColor = System.Drawing.Color.Blue; this.LinkRemove.AutoSize = true; this.LinkRemove.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.LinkRemove.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.LinkRemove.Location = new System.Drawing.Point(77, 61); this.LinkRemove.Name = "LinkRemove"; this.LinkRemove.Size = new System.Drawing.Size(46, 13); this.LinkRemove.TabIndex = 13; this.LinkRemove.TabStop = true; this.LinkRemove.Text = "Remove"; this.LinkRemove.VisitedLinkColor = System.Drawing.Color.Blue; this.LinkRemove.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkRemove_LinkClicked); // // AddPersonLink // this.AddPersonLink.ActiveLinkColor = System.Drawing.Color.Blue; this.AddPersonLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.AddPersonLink.AutoSize = true; this.AddPersonLink.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.AddPersonLink.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.AddPersonLink.Location = new System.Drawing.Point(231, 9); this.AddPersonLink.Name = "AddPersonLink"; this.AddPersonLink.Size = new System.Drawing.Size(26, 13); this.AddPersonLink.TabIndex = 15; this.AddPersonLink.TabStop = true; this.AddPersonLink.Text = "Add"; this.AddPersonLink.VisitedLinkColor = System.Drawing.Color.Blue; this.AddPersonLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.BrowseTo_LinkClicked); // // RemovePersonLink // this.RemovePersonLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.RemovePersonLink.AutoSize = true; this.RemovePersonLink.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.RemovePersonLink.Location = new System.Drawing.Point(259, 9); this.RemovePersonLink.Name = "RemovePersonLink"; this.RemovePersonLink.Size = new System.Drawing.Size(47, 13); this.RemovePersonLink.TabIndex = 16; this.RemovePersonLink.TabStop = true; this.RemovePersonLink.Text = "Remove"; this.RemovePersonLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.RemovePersonLink_LinkClicked); // // ComposeMail // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.RemovePersonLink); this.Controls.Add(this.AddPersonLink); this.Controls.Add(this.LinkAdd); this.Controls.Add(this.LinkRemove); this.Controls.Add(this.ListFiles); this.Controls.Add(this.label4); this.Controls.Add(this.ExitButton); this.Controls.Add(this.SendButton); this.Controls.Add(this.MessageBody); this.Controls.Add(this.SubjectTextBox); this.Controls.Add(this.label3); this.Controls.Add(this.ToTextBox); this.Controls.Add(this.label1); this.Name = "ComposeMail"; this.Size = new System.Drawing.Size(309, 279); this.Load += new System.EventHandler(this.ComposeMail_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox ToTextBox; private System.Windows.Forms.Label label3; public System.Windows.Forms.TextBox SubjectTextBox; public TextInput MessageBody; private System.Windows.Forms.Button SendButton; private System.Windows.Forms.Button ExitButton; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox ListFiles; private System.Windows.Forms.LinkLabel LinkAdd; private System.Windows.Forms.LinkLabel LinkRemove; private System.Windows.Forms.LinkLabel AddPersonLink; private System.Windows.Forms.LinkLabel RemovePersonLink; } }
using System.Globalization; using System.Text; using MySqlConnector.Protocol; using MySqlConnector.Protocol.Payloads; using MySqlConnector.Protocol.Serialization; using MySqlConnector.Utilities; namespace MySqlConnector.Core; internal sealed class TypeMapper { public static TypeMapper Instance { get; } = new(); private TypeMapper() { m_columnTypeMetadata = new(); m_dbTypeMappingsByClrType = new(); m_dbTypeMappingsByDbType = new(); m_columnTypeMetadataLookup = new(StringComparer.OrdinalIgnoreCase); m_mySqlDbTypeToColumnTypeMetadata = new(); // boolean var typeBoolean = AddDbTypeMapping(new(typeof(bool), new[] { DbType.Boolean }, convert: static o => Convert.ToBoolean(o, CultureInfo.InvariantCulture))); AddColumnTypeMetadata(new("TINYINT", typeBoolean, MySqlDbType.Bool, isUnsigned: false, length: 1, columnSize: 1, simpleDataTypeName: "BOOL", createFormat: "BOOL")); // integers var typeSbyte = AddDbTypeMapping(new(typeof(sbyte), new[] { DbType.SByte }, convert: static o => Convert.ToSByte(o, CultureInfo.InvariantCulture))); var typeByte = AddDbTypeMapping(new(typeof(byte), new[] { DbType.Byte }, convert: static o => Convert.ToByte(o, CultureInfo.InvariantCulture))); var typeShort = AddDbTypeMapping(new(typeof(short), new[] { DbType.Int16 }, convert: static o => Convert.ToInt16(o, CultureInfo.InvariantCulture))); var typeUshort = AddDbTypeMapping(new(typeof(ushort), new[] { DbType.UInt16 }, convert: static o => Convert.ToUInt16(o, CultureInfo.InvariantCulture))); var typeInt = AddDbTypeMapping(new(typeof(int), new[] { DbType.Int32 }, convert: static o => Convert.ToInt32(o, CultureInfo.InvariantCulture))); var typeUint = AddDbTypeMapping(new(typeof(uint), new[] { DbType.UInt32 }, convert: static o => Convert.ToUInt32(o, CultureInfo.InvariantCulture))); var typeLong = AddDbTypeMapping(new(typeof(long), new[] { DbType.Int64 }, convert: static o => Convert.ToInt64(o, CultureInfo.InvariantCulture))); var typeUlong = AddDbTypeMapping(new(typeof(ulong), new[] { DbType.UInt64 }, convert: static o => Convert.ToUInt64(o, CultureInfo.InvariantCulture))); AddColumnTypeMetadata(new("TINYINT", typeSbyte, MySqlDbType.Byte, isUnsigned: false)); AddColumnTypeMetadata(new("TINYINT", typeByte, MySqlDbType.UByte, isUnsigned: true, length: 1)); AddColumnTypeMetadata(new("TINYINT", typeByte, MySqlDbType.UByte, isUnsigned: true)); AddColumnTypeMetadata(new("SMALLINT", typeShort, MySqlDbType.Int16, isUnsigned: false)); AddColumnTypeMetadata(new("SMALLINT", typeUshort, MySqlDbType.UInt16, isUnsigned: true)); AddColumnTypeMetadata(new("INT", typeInt, MySqlDbType.Int32, isUnsigned: false)); AddColumnTypeMetadata(new("INT", typeUint, MySqlDbType.UInt32, isUnsigned: true)); AddColumnTypeMetadata(new("MEDIUMINT", typeInt, MySqlDbType.Int24, isUnsigned: false)); AddColumnTypeMetadata(new("MEDIUMINT", typeUint, MySqlDbType.UInt24, isUnsigned: true)); AddColumnTypeMetadata(new("BIGINT", typeLong, MySqlDbType.Int64, isUnsigned: false)); AddColumnTypeMetadata(new("BIGINT", typeUlong, MySqlDbType.UInt64, isUnsigned: true)); AddColumnTypeMetadata(new("BIT", typeUlong, MySqlDbType.Bit)); // decimals var typeDecimal = AddDbTypeMapping(new(typeof(decimal), new[] { DbType.Decimal, DbType.Currency, DbType.VarNumeric }, convert: static o => Convert.ToDecimal(o, CultureInfo.InvariantCulture))); var typeDouble = AddDbTypeMapping(new(typeof(double), new[] { DbType.Double }, convert: static o => Convert.ToDouble(o, CultureInfo.InvariantCulture))); var typeFloat = AddDbTypeMapping(new(typeof(float), new[] { DbType.Single }, convert: static o => Convert.ToSingle(o, CultureInfo.InvariantCulture))); AddColumnTypeMetadata(new("DECIMAL", typeDecimal, MySqlDbType.NewDecimal, createFormat: "DECIMAL({0},{1});precision,scale")); AddColumnTypeMetadata(new("DECIMAL", typeDecimal, MySqlDbType.Decimal)); AddColumnTypeMetadata(new("DOUBLE", typeDouble, MySqlDbType.Double)); AddColumnTypeMetadata(new("FLOAT", typeFloat, MySqlDbType.Float)); // string var typeFixedString = AddDbTypeMapping(new(typeof(string), new[] { DbType.StringFixedLength, DbType.AnsiStringFixedLength }, convert: Convert.ToString!)); var typeString = AddDbTypeMapping(new(typeof(string), new[] { DbType.String, DbType.AnsiString, DbType.Xml }, convert: Convert.ToString!)); AddColumnTypeMetadata(new("VARCHAR", typeString, MySqlDbType.VarChar, createFormat: "VARCHAR({0});size")); AddColumnTypeMetadata(new("VARCHAR", typeString, MySqlDbType.VarString)); AddColumnTypeMetadata(new("CHAR", typeFixedString, MySqlDbType.String, createFormat: "CHAR({0});size")); AddColumnTypeMetadata(new("TINYTEXT", typeString, MySqlDbType.TinyText, columnSize: byte.MaxValue, simpleDataTypeName: "VARCHAR")); AddColumnTypeMetadata(new("TEXT", typeString, MySqlDbType.Text, columnSize: ushort.MaxValue, simpleDataTypeName: "VARCHAR")); AddColumnTypeMetadata(new("MEDIUMTEXT", typeString, MySqlDbType.MediumText, columnSize: 16777215, simpleDataTypeName: "VARCHAR")); AddColumnTypeMetadata(new("LONGTEXT", typeString, MySqlDbType.LongText, columnSize: uint.MaxValue, simpleDataTypeName: "VARCHAR")); AddColumnTypeMetadata(new("ENUM", typeString, MySqlDbType.Enum)); AddColumnTypeMetadata(new("SET", typeString, MySqlDbType.Set)); AddColumnTypeMetadata(new("JSON", typeString, MySqlDbType.JSON)); // binary var typeBinary = AddDbTypeMapping(new(typeof(byte[]), new[] { DbType.Binary })); AddColumnTypeMetadata(new("BLOB", typeBinary, MySqlDbType.Blob, binary: true, columnSize: ushort.MaxValue, simpleDataTypeName: "BLOB")); AddColumnTypeMetadata(new("BINARY", typeBinary, MySqlDbType.Binary, binary: true, simpleDataTypeName: "BLOB", createFormat: "BINARY({0});length")); AddColumnTypeMetadata(new("VARBINARY", typeBinary, MySqlDbType.VarBinary, binary: true, simpleDataTypeName: "BLOB", createFormat: "VARBINARY({0});length")); AddColumnTypeMetadata(new("TINYBLOB", typeBinary, MySqlDbType.TinyBlob, binary: true, columnSize: byte.MaxValue, simpleDataTypeName: "BLOB")); AddColumnTypeMetadata(new("MEDIUMBLOB", typeBinary, MySqlDbType.MediumBlob, binary: true, columnSize: 16777215, simpleDataTypeName: "BLOB")); AddColumnTypeMetadata(new("LONGBLOB", typeBinary, MySqlDbType.LongBlob, binary: true, columnSize: uint.MaxValue, simpleDataTypeName: "BLOB")); // spatial AddColumnTypeMetadata(new("GEOMETRY", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("POINT", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("LINESTRING", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("POLYGON", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("MULTIPOINT", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("MULTILINESTRING", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("MULTIPOLYGON", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("GEOMETRYCOLLECTION", typeBinary, MySqlDbType.Geometry, binary: true)); AddColumnTypeMetadata(new("GEOMCOLLECTION", typeBinary, MySqlDbType.Geometry, binary: true)); // date/time #if NET6_0_OR_GREATER AddDbTypeMapping(new(typeof(DateOnly), new[] { DbType.Date })); #endif var typeDate = AddDbTypeMapping(new(typeof(DateTime), new[] { DbType.Date })); var typeDateTime = AddDbTypeMapping(new(typeof(DateTime), new[] { DbType.DateTime, DbType.DateTime2, DbType.DateTimeOffset })); AddDbTypeMapping(new(typeof(DateTimeOffset), new[] { DbType.DateTimeOffset })); #if NET6_0_OR_GREATER AddDbTypeMapping(new(typeof(TimeOnly), new[] { DbType.Time })); #endif var typeTime = AddDbTypeMapping(new(typeof(TimeSpan), new[] { DbType.Time }, convert: static o => o is string s ? Utility.ParseTimeSpan(Encoding.UTF8.GetBytes(s)) : Convert.ChangeType(o, typeof(TimeSpan), CultureInfo.InvariantCulture))); AddColumnTypeMetadata(new("DATETIME", typeDateTime, MySqlDbType.DateTime)); AddColumnTypeMetadata(new("DATE", typeDate, MySqlDbType.Date)); AddColumnTypeMetadata(new("DATE", typeDate, MySqlDbType.Newdate)); AddColumnTypeMetadata(new("TIME", typeTime, MySqlDbType.Time)); AddColumnTypeMetadata(new("TIMESTAMP", typeDateTime, MySqlDbType.Timestamp)); AddColumnTypeMetadata(new("YEAR", typeInt, MySqlDbType.Year)); // guid var typeGuid = AddDbTypeMapping(new(typeof(Guid), new[] { DbType.Guid }, convert: static o => Guid.Parse(Convert.ToString(o, CultureInfo.InvariantCulture)!))); AddColumnTypeMetadata(new("CHAR", typeGuid, MySqlDbType.Guid, length: 36, simpleDataTypeName: "CHAR(36)", createFormat: "CHAR(36)")); // null var typeNull = AddDbTypeMapping(new(typeof(object), new[] { DbType.Object })); AddColumnTypeMetadata(new("NULL", typeNull, MySqlDbType.Null)); } public IReadOnlyList<ColumnTypeMetadata> GetColumnTypeMetadata() => m_columnTypeMetadata.AsReadOnly(); public ColumnTypeMetadata GetColumnTypeMetadata(MySqlDbType mySqlDbType) => m_mySqlDbTypeToColumnTypeMetadata[mySqlDbType]; public DbType GetDbTypeForMySqlDbType(MySqlDbType mySqlDbType) => m_mySqlDbTypeToColumnTypeMetadata[mySqlDbType].DbTypeMapping.DbTypes[0]; public MySqlDbType GetMySqlDbTypeForDbType(DbType dbType) { foreach (var pair in m_mySqlDbTypeToColumnTypeMetadata) { if (pair.Value.DbTypeMapping.DbTypes.Contains(dbType)) return pair.Key; } return MySqlDbType.VarChar; } private DbTypeMapping AddDbTypeMapping(DbTypeMapping dbTypeMapping) { m_dbTypeMappingsByClrType[dbTypeMapping.ClrType] = dbTypeMapping; if (dbTypeMapping.DbTypes is not null) { foreach (var dbType in dbTypeMapping.DbTypes) m_dbTypeMappingsByDbType[dbType] = dbTypeMapping; } return dbTypeMapping; } private void AddColumnTypeMetadata(ColumnTypeMetadata columnTypeMetadata) { m_columnTypeMetadata.Add(columnTypeMetadata); var lookupKey = columnTypeMetadata.CreateLookupKey(); if (!m_columnTypeMetadataLookup.ContainsKey(lookupKey)) m_columnTypeMetadataLookup.Add(lookupKey, columnTypeMetadata); if (!m_mySqlDbTypeToColumnTypeMetadata.ContainsKey(columnTypeMetadata.MySqlDbType)) m_mySqlDbTypeToColumnTypeMetadata.Add(columnTypeMetadata.MySqlDbType, columnTypeMetadata); } internal DbTypeMapping? GetDbTypeMapping(Type clrType) { if (clrType.IsEnum) clrType = Enum.GetUnderlyingType(clrType); m_dbTypeMappingsByClrType.TryGetValue(clrType, out var dbTypeMapping); return dbTypeMapping; } internal DbTypeMapping? GetDbTypeMapping(DbType dbType) { m_dbTypeMappingsByDbType.TryGetValue(dbType, out var dbTypeMapping); return dbTypeMapping; } public DbTypeMapping? GetDbTypeMapping(string columnTypeName, bool unsigned = false, int length = 0) { return GetColumnTypeMetadata(columnTypeName, unsigned, length)?.DbTypeMapping; } public MySqlDbType GetMySqlDbType(string typeName, bool unsigned, int length) => GetColumnTypeMetadata(typeName, unsigned, length)!.MySqlDbType; private ColumnTypeMetadata? GetColumnTypeMetadata(string columnTypeName, bool unsigned, int length) { if (!m_columnTypeMetadataLookup.TryGetValue(ColumnTypeMetadata.CreateLookupKey(columnTypeName, unsigned, length), out var columnTypeMetadata) && length != 0) m_columnTypeMetadataLookup.TryGetValue(ColumnTypeMetadata.CreateLookupKey(columnTypeName, unsigned, 0), out columnTypeMetadata); return columnTypeMetadata; } public static MySqlDbType ConvertToMySqlDbType(ColumnDefinitionPayload columnDefinition, bool treatTinyAsBoolean, MySqlGuidFormat guidFormat) { var isUnsigned = (columnDefinition.ColumnFlags & ColumnFlags.Unsigned) != 0; switch (columnDefinition.ColumnType) { case ColumnType.Tiny: return treatTinyAsBoolean && columnDefinition.ColumnLength == 1 && !isUnsigned ? MySqlDbType.Bool : isUnsigned ? MySqlDbType.UByte : MySqlDbType.Byte; case ColumnType.Int24: return isUnsigned ? MySqlDbType.UInt24 : MySqlDbType.Int24; case ColumnType.Long: return isUnsigned ? MySqlDbType.UInt32 : MySqlDbType.Int32; case ColumnType.Longlong: return isUnsigned ? MySqlDbType.UInt64 : MySqlDbType.Int64; case ColumnType.Bit: return MySqlDbType.Bit; case ColumnType.String: if (guidFormat == MySqlGuidFormat.Char36 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 36) return MySqlDbType.Guid; if (guidFormat == MySqlGuidFormat.Char32 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 32) return MySqlDbType.Guid; if ((columnDefinition.ColumnFlags & ColumnFlags.Enum) != 0) return MySqlDbType.Enum; if ((columnDefinition.ColumnFlags & ColumnFlags.Set) != 0) return MySqlDbType.Set; goto case ColumnType.VarString; case ColumnType.VarChar: case ColumnType.VarString: case ColumnType.TinyBlob: case ColumnType.Blob: case ColumnType.MediumBlob: case ColumnType.LongBlob: var type = columnDefinition.ColumnType; if (columnDefinition.CharacterSet == CharacterSet.Binary) { if ((guidFormat is MySqlGuidFormat.Binary16 or MySqlGuidFormat.TimeSwapBinary16 or MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16) return MySqlDbType.Guid; return type switch { ColumnType.String => MySqlDbType.Binary, ColumnType.VarString => MySqlDbType.VarBinary, ColumnType.TinyBlob => MySqlDbType.TinyBlob, ColumnType.Blob => MySqlDbType.Blob, ColumnType.MediumBlob => MySqlDbType.MediumBlob, _ => MySqlDbType.LongBlob, }; } return type switch { ColumnType.String => MySqlDbType.String, ColumnType.VarString => MySqlDbType.VarChar, ColumnType.TinyBlob => MySqlDbType.TinyText, ColumnType.Blob => MySqlDbType.Text, ColumnType.MediumBlob => MySqlDbType.MediumText, _ => MySqlDbType.LongText, }; case ColumnType.Json: return MySqlDbType.JSON; case ColumnType.Short: return isUnsigned ? MySqlDbType.UInt16 : MySqlDbType.Int16; case ColumnType.Date: case ColumnType.NewDate: return MySqlDbType.Date; case ColumnType.DateTime: return MySqlDbType.DateTime; case ColumnType.Timestamp: return MySqlDbType.Timestamp; case ColumnType.Time: return MySqlDbType.Time; case ColumnType.Year: return MySqlDbType.Year; case ColumnType.Float: return MySqlDbType.Float; case ColumnType.Double: return MySqlDbType.Double; case ColumnType.Decimal: return MySqlDbType.Decimal; case ColumnType.NewDecimal: return MySqlDbType.NewDecimal; case ColumnType.Geometry: return MySqlDbType.Geometry; case ColumnType.Null: return MySqlDbType.Null; case ColumnType.Enum: return MySqlDbType.Enum; case ColumnType.Set: return MySqlDbType.Set; default: throw new NotImplementedException("ConvertToMySqlDbType for {0} is not implemented".FormatInvariant(columnDefinition.ColumnType)); } } public static ushort ConvertToColumnTypeAndFlags(MySqlDbType dbType, MySqlGuidFormat guidFormat) { var isUnsigned = dbType is MySqlDbType.UByte or MySqlDbType.UInt16 or MySqlDbType.UInt24 or MySqlDbType.UInt32 or MySqlDbType.UInt64; var columnType = dbType switch { MySqlDbType.Bool or MySqlDbType.Byte or MySqlDbType.UByte => ColumnType.Tiny, MySqlDbType.Int16 or MySqlDbType.UInt16 => ColumnType.Short, MySqlDbType.Int24 or MySqlDbType.UInt24 => ColumnType.Int24, MySqlDbType.Int32 or MySqlDbType.UInt32 => ColumnType.Long, MySqlDbType.Int64 or MySqlDbType.UInt64 => ColumnType.Longlong, MySqlDbType.Bit => ColumnType.Bit, MySqlDbType.Guid => (guidFormat is MySqlGuidFormat.Char36 or MySqlGuidFormat.Char32) ? ColumnType.String : ColumnType.Blob, MySqlDbType.Enum or MySqlDbType.Set => ColumnType.String, MySqlDbType.Binary or MySqlDbType.String => ColumnType.String, MySqlDbType.VarBinary or MySqlDbType.VarChar or MySqlDbType.VarString => ColumnType.VarString, MySqlDbType.TinyBlob or MySqlDbType.TinyText => ColumnType.TinyBlob, MySqlDbType.Blob or MySqlDbType.Text => ColumnType.Blob, MySqlDbType.MediumBlob or MySqlDbType.MediumText => ColumnType.MediumBlob, MySqlDbType.LongBlob or MySqlDbType.LongText => ColumnType.LongBlob, MySqlDbType.JSON => ColumnType.Json, // TODO: test MySqlDbType.Date or MySqlDbType.Newdate => ColumnType.Date, MySqlDbType.DateTime => ColumnType.DateTime, MySqlDbType.Timestamp => ColumnType.Timestamp, MySqlDbType.Time => ColumnType.Time, MySqlDbType.Year => ColumnType.Year, MySqlDbType.Float => ColumnType.Float, MySqlDbType.Double => ColumnType.Double, MySqlDbType.Decimal => ColumnType.Decimal, MySqlDbType.NewDecimal => ColumnType.NewDecimal, MySqlDbType.Geometry => ColumnType.Geometry, MySqlDbType.Null => ColumnType.Null, _ => throw new NotImplementedException("ConvertToColumnTypeAndFlags for {0} is not implemented".FormatInvariant(dbType)), }; return (ushort) ((byte) columnType | (isUnsigned ? 0x8000 : 0)); } internal IEnumerable<ColumnTypeMetadata> GetColumnMappings() { return m_columnTypeMetadataLookup.Values.AsEnumerable(); } private readonly List<ColumnTypeMetadata> m_columnTypeMetadata; private readonly Dictionary<Type, DbTypeMapping> m_dbTypeMappingsByClrType; private readonly Dictionary<DbType, DbTypeMapping> m_dbTypeMappingsByDbType; private readonly Dictionary<string, ColumnTypeMetadata> m_columnTypeMetadataLookup; private readonly Dictionary<MySqlDbType, ColumnTypeMetadata> m_mySqlDbTypeToColumnTypeMetadata; }
//------------------------------------------------------------------------------ // <copyright file="HiddenField.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System.ComponentModel; using System.Collections.Specialized; /// <devdoc> /// Inserts a hidden field into the web form. /// </devdoc> [ ControlValueProperty("Value"), DefaultEvent("ValueChanged"), DefaultProperty("Value"), Designer("System.Web.UI.Design.WebControls.HiddenFieldDesigner, " + AssemblyRef.SystemDesign), ParseChildren(true), PersistChildren(false), NonVisualControl(), SupportsEventValidation, ] public class HiddenField : Control, IPostBackDataHandler { private static readonly object EventValueChanged = new object(); [ DefaultValue(false), EditorBrowsable(EditorBrowsableState.Never), ] public override bool EnableTheming { get { return false; } set { throw new NotSupportedException(SR.GetString(SR.NoThemingSupport, this.GetType().Name)); } } [ DefaultValue(""), EditorBrowsable(EditorBrowsableState.Never), ] public override string SkinID { get { return String.Empty; } set { throw new NotSupportedException(SR.GetString(SR.NoThemingSupport, this.GetType().Name)); } } /// <devdoc> /// Gets or sets the value of the hidden field. /// </devdoc> [ Bindable(true), WebCategory("Behavior"), DefaultValue(""), WebSysDescription(SR.HiddenField_Value) ] public virtual string Value { get { string s = (string)ViewState["Value"]; return (s != null) ? s : String.Empty; } set { ViewState["Value"] = value; } } /// <devdoc> /// Raised when the value of the hidden field is changed on the client. /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.HiddenField_OnValueChanged) ] public event EventHandler ValueChanged { add { Events.AddHandler(EventValueChanged, value); } remove { Events.RemoveHandler(EventValueChanged, value); } } protected override ControlCollection CreateControlCollection() { return new EmptyControlCollection(this); } [ EditorBrowsable(EditorBrowsableState.Never), ] public override void Focus() { throw new NotSupportedException(SR.GetString(SR.NoFocusSupport, this.GetType().Name)); } protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { ValidateEvent(UniqueID); string current = Value; string postData = postCollection[postDataKey]; if (!current.Equals(postData, StringComparison.Ordinal)) { Value = postData; return true; } return false; } protected internal override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (SaveValueViewState == false) { ViewState.SetItemDirty("Value", false); } } protected virtual void OnValueChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EventValueChanged]; if (handler != null) { handler(this, e); } } protected virtual void RaisePostDataChangedEvent() { OnValueChanged(EventArgs.Empty); } protected internal override void Render(HtmlTextWriter writer) { string uniqueID = UniqueID; // Make sure we are in a form tag with runat=server. if (Page != null) { Page.VerifyRenderingInServerForm(this); Page.ClientScript.RegisterForEventValidation(uniqueID); } writer.AddAttribute(HtmlTextWriterAttribute.Type, "hidden"); if (uniqueID != null) { writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID); } if (ID != null) { writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); } string s; s = Value; if (s.Length > 0) { writer.AddAttribute(HtmlTextWriterAttribute.Value, s); } writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); } /// <devdoc> /// Determines whether the Value must be stored in view state, to /// optimize the size of the saved state. /// </devdoc> private bool SaveValueViewState { get { // Must be saved when // 1. There is a registered event handler for EventValueChanged // 2. Control is not visible, because the browser's post data will not include this control // 3. The instance is a derived instance, which might be overriding the OnValueChanged method if ((Events[EventValueChanged] != null) || (Visible == false) || (this.GetType() != typeof(HiddenField))) { return true; } return false; } } #region Implementation of IPostBackDataHandler bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) { return LoadPostData(postDataKey, postCollection); } void IPostBackDataHandler.RaisePostDataChangedEvent() { RaisePostDataChangedEvent(); } #endregion } }
/* * 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.Text; using OpenMetaverse; namespace OpenSim.Framework { /// <summary> /// Inventory Item - contains all the properties associated with an individual inventory piece. /// </summary> public class InventoryItemBase : InventoryNodeBase, ICloneable { /// <value> /// The inventory type of the item. This is slightly different from the asset type in some situations. /// </value> public int InvType { get { return m_invType; } set { m_invType = value; } } protected int m_invType; /// <value> /// The folder this item is contained in /// </value> public UUID Folder { get { return m_folder; } set { m_folder = value; } } protected UUID m_folder; /// <value> /// The creator of this item /// </value> public string CreatorId { get { return m_creatorId; } set { m_creatorId = value; if ((m_creatorId == null) || !UUID.TryParse(m_creatorId, out m_creatorIdAsUuid)) m_creatorIdAsUuid = UUID.Zero; } } protected string m_creatorId; /// <value> /// The CreatorId expressed as a UUID. /// </value> public UUID CreatorIdAsUuid { get { if (UUID.Zero == m_creatorIdAsUuid) { UUID.TryParse(CreatorId, out m_creatorIdAsUuid); } return m_creatorIdAsUuid; } } protected UUID m_creatorIdAsUuid = UUID.Zero; /// <summary> /// Extended creator information of the form <profile url>;<name> /// </summary> public string CreatorData // = <profile url>;<name> { get { return m_creatorData; } set { m_creatorData = value; } } protected string m_creatorData = string.Empty; /// <summary> /// Used by the DB layer to retrieve / store the entire user identification. /// The identification can either be a simple UUID or a string of the form /// uuid[;profile_url[;name]] /// </summary> public string CreatorIdentification { get { if (!string.IsNullOrEmpty(m_creatorData)) return m_creatorId + ';' + m_creatorData; else return m_creatorId; } set { if ((value == null) || (value != null && value == string.Empty)) { m_creatorData = string.Empty; return; } if (!value.Contains(";")) // plain UUID { m_creatorId = value; } else // <uuid>[;<endpoint>[;name]] { string name = "Unknown User"; string[] parts = value.Split(';'); if (parts.Length >= 1) m_creatorId = parts[0]; if (parts.Length >= 2) m_creatorData = parts[1]; if (parts.Length >= 3) name = parts[2]; m_creatorData += ';' + name; } } } /// <value> /// The description of the inventory item (must be less than 64 characters) /// </value> public string Description { get { return m_description; } set { m_description = value; } } protected string m_description = String.Empty; /// <value> /// /// </value> public uint NextPermissions { get { return m_nextPermissions; } set { m_nextPermissions = value; } } protected uint m_nextPermissions; /// <value> /// A mask containing permissions for the current owner (cannot be enforced) /// </value> public uint CurrentPermissions { get { return m_currentPermissions; } set { m_currentPermissions = value; } } protected uint m_currentPermissions; /// <value> /// /// </value> public uint BasePermissions { get { return m_basePermissions; } set { m_basePermissions = value; } } protected uint m_basePermissions; /// <value> /// /// </value> public uint EveryOnePermissions { get { return m_everyonePermissions; } set { m_everyonePermissions = value; } } protected uint m_everyonePermissions; /// <value> /// /// </value> public uint GroupPermissions { get { return m_groupPermissions; } set { m_groupPermissions = value; } } protected uint m_groupPermissions; /// <value> /// This is an enumerated value determining the type of asset (eg Notecard, Sound, Object, etc) /// </value> public int AssetType { get { return m_assetType; } set { m_assetType = value; } } protected int m_assetType; /// <value> /// The UUID of the associated asset on the asset server /// </value> public UUID AssetID { get { return m_assetID; } set { m_assetID = value; } } protected UUID m_assetID; /// <value> /// /// </value> public UUID GroupID { get { return m_groupID; } set { m_groupID = value; } } protected UUID m_groupID; /// <value> /// /// </value> public bool GroupOwned { get { return m_groupOwned; } set { m_groupOwned = value; } } protected bool m_groupOwned; /// <value> /// /// </value> public int SalePrice { get { return m_salePrice; } set { m_salePrice = value; } } protected int m_salePrice; /// <value> /// /// </value> public byte SaleType { get { return m_saleType; } set { m_saleType = value; } } protected byte m_saleType; /// <value> /// /// </value> public uint Flags { get { return m_flags; } set { m_flags = value; } } protected uint m_flags; /// <value> /// /// </value> public int CreationDate { get { return m_creationDate; } set { m_creationDate = value; } } protected int m_creationDate = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; public InventoryItemBase() { } public InventoryItemBase(UUID id) { ID = id; } public InventoryItemBase(UUID id, UUID owner) { ID = id; Owner = owner; } public object Clone() { return MemberwiseClone(); } public void ToLLSDxml(StringBuilder lsl) { LLSDxmlEncode.AddMap(lsl); LLSDxmlEncode.AddElem("parent_id", Folder, lsl); LLSDxmlEncode.AddElem("asset_id", AssetID, lsl); LLSDxmlEncode.AddElem("item_id", ID, lsl); LLSDxmlEncode.AddMap("permissions",lsl); LLSDxmlEncode.AddElem("creator_id", CreatorIdAsUuid, lsl); LLSDxmlEncode.AddElem("owner_id", Owner, lsl); LLSDxmlEncode.AddElem("group_id", GroupID, lsl); LLSDxmlEncode.AddElem("base_mask", (int)CurrentPermissions, lsl); LLSDxmlEncode.AddElem("owner_mask", (int)CurrentPermissions, lsl); LLSDxmlEncode.AddElem("group_mask", (int)GroupPermissions, lsl); LLSDxmlEncode.AddElem("everyone_mask", (int)EveryOnePermissions, lsl); LLSDxmlEncode.AddElem("next_owner_mask", (int)NextPermissions, lsl); LLSDxmlEncode.AddElem("is_owner_group", GroupOwned, lsl); LLSDxmlEncode.AddEndMap(lsl); LLSDxmlEncode.AddElem("type", AssetType, lsl); LLSDxmlEncode.AddElem("inv_type", InvType, lsl); LLSDxmlEncode.AddElem("flags", ((int)Flags) & 0xff, lsl); LLSDxmlEncode.AddMap("sale_info",lsl); LLSDxmlEncode.AddElem("sale_price", SalePrice, lsl); LLSDxmlEncode.AddElem("sale_type", SaleType, lsl); LLSDxmlEncode.AddEndMap(lsl); LLSDxmlEncode.AddElem("name", Name, lsl); LLSDxmlEncode.AddElem("desc", Description, lsl); LLSDxmlEncode.AddElem("created_at", CreationDate, lsl); LLSDxmlEncode.AddEndMap(lsl); } } }
using System; using Gtk; using ShadowrunLogic; using ShadowrunCoreContent; using System.Collections.Generic; using ShadowrunGui; public partial class CharacterWindow: Gtk.Window { private List<IManifest<IManifestItem>> rangedWeaponManifests; private List<IManifest<IManifestItem>> meleeWeaponManifests; private List<IManifest<IManifestItem>> attributeManifests; public Character character; public CharacterWindow (): base (Gtk.WindowType.Toplevel) { Build (); rangedWeaponManifests = new List<IManifest<IManifestItem>>(); meleeWeaponManifests = new List<IManifest<IManifestItem>>(); attributeManifests = new List<IManifest<IManifestItem>>(); LoadContentFromManifests(); } public CharacterWindow (Character c): base (Gtk.WindowType.Toplevel) { Build (); rangedWeaponManifests = new List<IManifest<IManifestItem>>(); meleeWeaponManifests = new List<IManifest<IManifestItem>>(); attributeManifests = new List<IManifest<IManifestItem>>(); LoadContentFromManifests(); SetRenderedAttributes(c.attributes); SetRenderedMeleeWeapon(c.meleeWeapon); SetRenderedRangedWeapon(c.rangedWeapon); Bot_Checkbox.Active = c.isBot; } private void LoadContentFromManifests () { rangedWeaponManifests.Add(new ShadowrunCoreContent.RangedWeaponsManifest()); meleeWeaponManifests.Add (new ShadowrunCoreContent.MeleeWeaponsManifest()); attributeManifests.Add(new ShadowrunCoreContent.AttributesManifest()); } #region FormEvents protected void AttributeImport_Click (object sender, EventArgs e) { var attributesImportWindow = new ItemImportWindow(attributeManifests,"Attribute Import"); attributesImportWindow.TransientFor = this; attributesImportWindow.Destroyed+= delegate { if(attributesImportWindow.selectedItem == null) return; var selectedAttributes = (AbstractAttributes)attributesImportWindow.selectedItem; SetRenderedAttributes(selectedAttributes); }; } protected void RangedWeaponImport_Click (object sender, EventArgs e) { var rangedImportWeaponWindow = new ItemImportWindow(rangedWeaponManifests,"Ranged Weapon Import"); rangedImportWeaponWindow.TransientFor = this; rangedImportWeaponWindow.Destroyed+= delegate { if(rangedImportWeaponWindow.selectedItem == null) return; var selectedRangedWeapon = (AbstractRangedWeapon)rangedImportWeaponWindow.selectedItem; SetRenderedRangedWeapon(selectedRangedWeapon); }; } protected void MeleeWeaponImport_Click (object sender, EventArgs e) { var meleeImportWeaponWindow = new ItemImportWindow(meleeWeaponManifests,"Melee Weapon Import"); meleeImportWeaponWindow.TransientFor = this; meleeImportWeaponWindow.Destroyed+= delegate { if(meleeImportWeaponWindow.selectedItem == null) return; var selectedMeleeWeapon = (AbstractMeleeWeapon)meleeImportWeaponWindow.selectedItem; SetRenderedMeleeWeapon(selectedMeleeWeapon); }; } protected void SubmitCharacter_Click (object sender, EventArgs e) { try { this.character = new Character ( attributesFromFormInput (), rangedWeaponFromFormInput (), meleeWeaponFromFormInput (), Bot_Checkbox.Active ); this.Destroy (); } catch (Exception ex) { new MessageWindow("Character Import Window", "Error: " + ex.Message); } } #endregion #region DisplayStuff protected void SetRenderedRangedWeapon (AbstractRangedWeapon r) { RangedWeaponName_Textbox.Text = r.Name (); RangedDamage_Textbox.Text = r.Damage ().ToString (); if (r.DamageType () == DamageType.Stun) RangedStunDamage_Radio.Activate (); else RangedPhysicalDamage_Radio.Activate (); RangedAccuracy_Textbox.Text = r.Accuracy ().ToString (); RangedWeaponAP_Textbox.Text = r.AP ().ToString (); RangedRecoil_Textbox.Text = r.Recoil ().ToString (); var modes = r.FiringModes (); SingleShot_Checkbox.Active = modes.SingleShot; SemiAutomatic_Checkbox.Active = modes.SemiAutomatic; SemiAutomaticBurst_Checkbox.Active = modes.SemiAutomaticBurst; BurstFire_Checkbox.Active = modes.BurstFire; LongBurst_Checkbox.Active = modes.LongBurst; FullAuto_Checkbox.Active = modes.FullAuto; MagSize_Textbox.Text = r.MagSize().ToString(); switch (r.Skill ()) { case RangedWeaponSkills.Archery: Archery_Radio.Activate (); break; case RangedWeaponSkills.Automatics: Automatics_Radio.Activate (); break; case RangedWeaponSkills.HeavyWeapons: HeavyWeapons_Radio.Activate (); break; case RangedWeaponSkills.Longarms: Longarms_Radio.Activate (); break; case RangedWeaponSkills.Pistols: Pistols_Radio.Activate (); break; case RangedWeaponSkills.ThrowingWeapons: ThrowingWeapons_Radio.Activate (); break; } } protected void SetRenderedMeleeWeapon (AbstractMeleeWeapon m) { MeleeWeaponName_Textbox.Text = m.Name (); MeleeAP_Textbox.Text = m.AP ().ToString (); if (m.DamageType () == DamageType.Stun) MeleeStunDamage_Radio.Activate (); else MeleePhysicalDamage_Radio.Activate (); MeleeDamage_Textbox.Text = m.Damage ().ToString (); MeleeAccuracy_Textbox.Text = m.Accuracy().ToString(); switch (m.Skill ()) { case MeleeWeaponSkills.Blades: Blades_Radio.Activate(); break; case MeleeWeaponSkills.Clubs: Clubs_Radio.Activate(); break; case MeleeWeaponSkills.UnarmedCombat: Unarmed_Radio.Activate(); break; } } protected void SetRenderedAttributes(AbstractAttributes a){ this.Armor_Textbox.Text = a.Armor().ToString(); //attributes this.Body_Textbox.Text = a.Body().ToString(); this.Agility_Textbox.Text = a.Agility().ToString(); this.Charisma_Textbox.Text = a.Charisma().ToString(); this.InitiativeDiceCount_Textbox.Text = a.InitiativeDice().ToString(); this.InitiativeModifier_Textbox.Text = a.InitiativeModifier().ToString(); this.Intuition_Textbox.Text = a.Intuition().ToString(); this.Logic_Textbox.Text = a.Logic().ToString(); this.Reaction_Textbox.Text = a.Reaction().ToString(); this.Strength_Textbox.Text = a.Strength().ToString(); this.Willpower_Textbox.Text = a.Willpower().ToString(); this.Name_Textbox.Text = a.Name(); //combat skills this.Archery_Spinbox.Value = a.Archery(); this.AutomaticsSpinbox.Value = a.Automatics(); this.Blades_Spinbox.Value = a.Blades(); this.Clubs_Spinbox.Value = a.Clubs(); this.HeavyWeapons_Spinbox.Value = a.HeavyWeapons(); this.Longarms_Spinbox.Value = a.Longarms(); this.Pistols_Spinbox.Value = a.Pistols(); this.ThrowingWeapons_Spinbox.Value = a.ThrowingWeapons(); this.UnarmedCombat_Spinbox.Value = a.UnarmedCombat(); } protected AbstractAttributes attributesFromFormInput(){ return new CustomAttributes( Int32.Parse(Body_Textbox.Text), Int32.Parse(Agility_Textbox.Text), Int32.Parse(Reaction_Textbox.Text), Int32.Parse(Strength_Textbox.Text), Int32.Parse (Willpower_Textbox.Text), Int32.Parse (Logic_Textbox.Text), Int32.Parse (Intuition_Textbox.Text), Int32.Parse (Charisma_Textbox.Text), Int32.Parse (InitiativeDiceCount_Textbox.Text), Int32.Parse (InitiativeModifier_Textbox.Text), Int32.Parse (Armor_Textbox.Text), Name_Textbox.Text, AttributeType.Custom, (int)Archery_Spinbox.Value, (int)AutomaticsSpinbox.Value, (int)Blades_Spinbox.Value, (int)Clubs_Spinbox.Value, (int)HeavyWeapons_Spinbox.Value, (int)Longarms_Spinbox.Value, (int)Pistols_Spinbox.Value, (int)ThrowingWeapons_Spinbox.Value, (int)UnarmedCombat_Spinbox.Value); } protected RangedFiringModes rangedFiringModesFromFormInput () { RangedFiringModes mode = new RangedFiringModes(); if(BurstFire_Checkbox.Active) mode.BurstFire = true; if(FullAuto_Checkbox.Active) mode.FullAuto = true; if(LongBurst_Checkbox.Active) mode.LongBurst = true; if(SemiAutomatic_Checkbox.Active) mode.SemiAutomatic = true; if(SemiAutomaticBurst_Checkbox.Active) mode.SemiAutomaticBurst = true; if(SingleShot_Checkbox.Active) mode.SingleShot = true; return mode; } protected RangedWeaponSkills rangedWeaponSkillFromFormInput () { if (Archery_Radio.Active) { return RangedWeaponSkills.Archery; } else if (Automatics_Radio.Active) { return RangedWeaponSkills.Automatics; } else if (HeavyWeapons_Radio.Active) { return RangedWeaponSkills.HeavyWeapons; } else if (Longarms_Radio.Active) { return RangedWeaponSkills.Longarms; } else if (Pistols_Radio.Active) { return RangedWeaponSkills.Pistols; } else if (ThrowingWeapons_Radio.Active) { return RangedWeaponSkills.ThrowingWeapons; } else { throw new ArgumentOutOfRangeException(); } } protected AbstractRangedWeapon rangedWeaponFromFormInput () { return new CustomRangedWeapon( Int32.Parse(MeleeDamage_Textbox.Text), (RangedPhysicalDamage_Radio.Active ? DamageType.Physical : DamageType.Stun), Int32.Parse(RangedAccuracy_Textbox.Text), Int32.Parse(RangedWeaponAP_Textbox.Text), rangedFiringModesFromFormInput(), Int32.Parse(this.MagSize_Textbox.Text), RangedWeaponName_Textbox.Text, Int32.Parse(RangedRecoil_Textbox.Text), rangedWeaponSkillFromFormInput()); } protected MeleeWeaponSkills meleeWeaponSkillsFromFormInput () { if (Blades_Radio.Active) { return MeleeWeaponSkills.Blades; } else if (Clubs_Radio.Active) { return MeleeWeaponSkills.Clubs; } else if (Unarmed_Radio.Active) { return MeleeWeaponSkills.UnarmedCombat; } else { throw new ArgumentOutOfRangeException(); } } protected AbstractMeleeWeapon meleeWeaponFromFormInput () { return new CustomMeleeWeapon( Int32.Parse(MeleeDamage_Textbox.Text), (MeleePhysicalDamage_Radio.Active ? DamageType.Physical : DamageType.Stun), Int32.Parse(MeleeAP_Textbox.Text), MeleeWeaponName_Textbox.Text, Int32.Parse(MeleeAccuracy_Textbox.Text), meleeWeaponSkillsFromFormInput()); } #endregion }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using ScrumBasic.Models; namespace ScrumBasic.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20160323074709_Modify_UserStory_Colum")] partial class Modify_UserStory_Colum { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("ScrumBasic.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("ScrumBasic.Models.UserStory", b => { b.Property<string>("ID"); b.Property<string>("Content"); b.Property<DateTime>("CreateTime"); b.Property<int>("ItemTypeCode"); b.Property<int>("Order"); b.Property<int>("Point"); b.Property<int>("Status"); b.HasKey("ID"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("ScrumBasic.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("ScrumBasic.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("ScrumBasic.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// // AddPackagesDialog.cs // // Author: // Matt Ward <[email protected]> // // Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ICSharpCode.PackageManagement; using MonoDevelop.Core; using MonoDevelop.Dnx; using NuGet; using Xwt; using Xwt.Drawing; using PropertyChangedEventArgs = System.ComponentModel.PropertyChangedEventArgs; namespace MonoDevelop.PackageManagement { public partial class AddPackagesDialog { public static readonly string AddPackageDependenciesTitle = GettextCatalog.GetString ("Add NuGet Package Dependencies"); PackagesViewModel viewModel; List<PackageSource> packageSources; DataField<bool> packageHasBackgroundColorField = new DataField<bool> (); DataField<PackageViewModel> packageViewModelField = new DataField<PackageViewModel> (); DataField<Image> packageImageField = new DataField<Image> (); DataField<double> packageCheckBoxAlphaField = new DataField<double> (); const double packageCheckBoxSemiTransarentAlpha = 0.6; ListStore packageStore; PackageCellView packageCellView; TimeSpan searchDelayTimeSpan = TimeSpan.FromMilliseconds (500); IDisposable searchTimer; PackageSource dummyPackageSourceRepresentingConfigureSettingsItem = new PackageSource ("", GettextCatalog.GetString ("Configure Sources...")); ImageLoader imageLoader = new ImageLoader (); bool loadingMessageVisible; List<NuGetPackageToAdd> packagesToAdd = new List<NuGetPackageToAdd> (); public AddPackagesDialog ( AvailablePackagesViewModel viewModel, string title, string initialSearch = null) { this.viewModel = viewModel; Build (); Title = title; UpdatePackageSearchEntryWithInitialText (initialSearch); InitializeListView (); UpdateAddPackagesButton (); ShowLoadingMessage (); LoadViewModel (initialSearch); this.showPrereleaseCheckBox.Clicked += ShowPrereleaseCheckBoxClicked; this.packageSourceComboBox.SelectionChanged += PackageSourceChanged; this.addPackagesButton.Clicked += AddPackagesButtonClicked; this.packageSearchEntry.Changed += PackageSearchEntryChanged; this.packageSearchEntry.Activated += PackageSearchEntryActivated; imageLoader.Loaded += ImageLoaded; } public bool ShowPreferencesForPackageSources { get; private set; } public IEnumerable<NuGetPackageToAdd> PackagesToAdd { get { return packagesToAdd; } } protected override void Dispose (bool disposing) { imageLoader.Loaded -= ImageLoaded; imageLoader.Dispose (); viewModel.PropertyChanged -= ViewModelPropertyChanged; viewModel.Dispose (); DisposeExistingTimer (); base.Dispose (disposing); } void UpdatePackageSearchEntryWithInitialText (string initialSearch) { // packageSearchEntry.Text = initialSearch; // if (!String.IsNullOrEmpty (initialSearch)) { // packageSearchEntry.CursorPosition = initialSearch.Length; // } } public string SearchText { get { return packageSearchEntry.Text; } } void InitializeListView () { packageStore = new ListStore (packageHasBackgroundColorField, packageCheckBoxAlphaField, packageImageField, packageViewModelField); packagesListView.DataSource = packageStore; AddPackageCellViewToListView (); packagesListView.SelectionChanged += PackagesListViewSelectionChanged; packagesListView.RowActivated += PackagesListRowActivated; packagesListView.VerticalScrollControl.ValueChanged += PackagesListViewScrollValueChanged; } void AddPackageCellViewToListView () { packageCellView = new PackageCellView { PackageField = packageViewModelField, HasBackgroundColorField = packageHasBackgroundColorField, CheckBoxAlphaField = packageCheckBoxAlphaField, ImageField = packageImageField, CellWidth = 535 }; var textColumn = new ListViewColumn ("Package", packageCellView); packagesListView.Columns.Add (textColumn); packageCellView.PackageChecked += PackageCellViewPackageChecked; } void ShowLoadingMessage () { UpdateSpinnerLabel (); noPackagesFoundFrame.Visible = false; packagesListView.Visible = false; loadingSpinnerFrame.Visible = true; loadingMessageVisible = true; } void HideLoadingMessage () { loadingSpinnerFrame.Visible = false; packagesListView.Visible = true; noPackagesFoundFrame.Visible = false; loadingMessageVisible = false; } void UpdateSpinnerLabel () { if (String.IsNullOrWhiteSpace (packageSearchEntry.Text)) { loadingSpinnerLabel.Text = GettextCatalog.GetString ("Loading package list..."); } else { loadingSpinnerLabel.Text = GettextCatalog.GetString ("Searching packages..."); } } void ShowNoPackagesFoundMessage () { if (!String.IsNullOrWhiteSpace (packageSearchEntry.Text)) { packagesListView.Visible = false; noPackagesFoundFrame.Visible = true; } } void ShowPrereleaseCheckBoxClicked (object sender, EventArgs e) { viewModel.IncludePrerelease = !viewModel.IncludePrerelease; } void LoadViewModel (string initialSearch) { viewModel.ClearPackagesOnPaging = false; viewModel.SearchTerms = initialSearch; ClearSelectedPackageInformation (); PopulatePackageSources (); viewModel.PropertyChanged += ViewModelPropertyChanged; if (viewModel.SelectedPackageSource != null) { viewModel.ReadPackages (); } else { HideLoadingMessage (); } } void ClearSelectedPackageInformation () { this.packageInfoVBox.Visible = false; } List<PackageSource> PackageSources { get { if (packageSources == null) { packageSources = viewModel.PackageSources.ToList (); } return packageSources; } } void PopulatePackageSources () { foreach (PackageSource packageSource in PackageSources) { AddPackageSourceToComboBox (packageSource); } //AddPackageSourceToComboBox (dummyPackageSourceRepresentingConfigureSettingsItem); packageSourceComboBox.SelectedItem = viewModel.SelectedPackageSource; } void AddPackageSourceToComboBox (PackageSource packageSource) { packageSourceComboBox.Items.Add (packageSource, GetPackageSourceName (packageSource)); } string GetPackageSourceName (PackageSource packageSource) { if (packageSource.IsAggregate ()) { return GettextCatalog.GetString ("All Sources"); } return packageSource.Name; } void PackageSourceChanged (object sender, EventArgs e) { var selectedPackageSource = (PackageSource)packageSourceComboBox.SelectedItem; if (selectedPackageSource == dummyPackageSourceRepresentingConfigureSettingsItem) { ShowPreferencesForPackageSources = true; Close (); } else { viewModel.SelectedPackageSource = selectedPackageSource; } } void PackagesListViewSelectionChanged (object sender, EventArgs e) { try { ShowSelectedPackage (); } catch (Exception ex) { LoggingService.LogError ("Error showing selected package.", ex); ShowErrorMessage (ex.Message); } } void ShowSelectedPackage () { PackageViewModel packageViewModel = GetSelectedPackageViewModel (); if (packageViewModel != null) { ShowPackageInformation (packageViewModel); } else { ClearSelectedPackageInformation (); } UpdateAddPackagesButton (); } PackageViewModel GetSelectedPackageViewModel () { if (packagesListView.SelectedRow != -1) { return packageStore.GetValue (packagesListView.SelectedRow, packageViewModelField); } return null; } void ShowPackageInformation (PackageViewModel packageViewModel) { this.packageNameLabel.Markup = packageViewModel.GetNameMarkup (); this.packageVersionLabel.Text = packageViewModel.Version.ToString (); this.packageAuthor.Text = packageViewModel.GetAuthors (); this.packagePublishedDate.Text = packageViewModel.GetLastPublishedDisplayText (); this.packageDownloads.Text = packageViewModel.GetDownloadCountDisplayText (); this.packageDescription.Text = packageViewModel.Description; this.packageId.Text = packageViewModel.Id; this.packageId.Visible = packageViewModel.HasNoGalleryUrl; ShowUri (this.packageIdLink, packageViewModel.GalleryUrl, packageViewModel.Id); ShowUri (this.packageProjectPageLink, packageViewModel.ProjectUrl); ShowUri (this.packageLicenseLink, packageViewModel.LicenseUrl); this.packageDependenciesListHBox.Visible = packageViewModel.HasDependencies; this.packageDependenciesNoneLabel.Visible = !packageViewModel.HasDependencies; this.packageDependenciesList.Text = packageViewModel.GetPackageDependenciesDisplayText (); this.packageInfoVBox.Visible = true; } void ShowUri (LinkLabel linkLabel, Uri uri, string label) { linkLabel.Text = label; ShowUri (linkLabel, uri); } void ShowUri (LinkLabel linkLabel, Uri uri) { if (uri == null) { linkLabel.Visible = false; } else { linkLabel.Visible = true; linkLabel.Uri = uri; } } void ViewModelPropertyChanged (object sender, PropertyChangedEventArgs e) { try { ShowPackages (); } catch (Exception ex) { LoggingService.LogError ("Error showing packages.", ex); ShowErrorMessage (ex.Message); } } void ShowPackages () { if (viewModel.HasError) { ShowErrorMessage (viewModel.ErrorMessage); } else { ClearErrorMessage (); } if (viewModel.IsLoadingNextPage) { // Show spinner? } else if (viewModel.IsReadingPackages) { ClearPackages (); } else { HideLoadingMessage (); } if (!viewModel.IsLoadingNextPage) { AppendPackagesToListView (); } UpdateAddPackagesButton (); } void ClearPackages () { packageStore.Clear (); ResetPackagesListViewScroll (); UpdatePackageListViewSelectionColor (); ShowLoadingMessage (); ShrinkImageCache (); } void ResetPackagesListViewScroll () { packagesListView.VerticalScrollControl.Value = 0; } void ShowErrorMessage (string message) { errorMessageLabel.Text = message; errorMessageHBox.Visible = true; } void ClearErrorMessage () { errorMessageHBox.Visible = false; errorMessageLabel.Text = ""; } void ShrinkImageCache () { imageLoader.ShrinkImageCache (); } void AppendPackagesToListView () { bool packagesListViewWasEmpty = (packageStore.RowCount == 0); for (int row = packageStore.RowCount; row < viewModel.PackageViewModels.Count; ++row) { PackageViewModel packageViewModel = viewModel.PackageViewModels [row]; AppendPackageToListView (packageViewModel); LoadPackageImage (row, packageViewModel); } if (packagesListViewWasEmpty && (packageStore.RowCount > 0)) { packagesListView.SelectRow (0); } if (!viewModel.IsReadingPackages && (packageStore.RowCount == 0)) { ShowNoPackagesFoundMessage (); } } void AppendPackageToListView (PackageViewModel packageViewModel) { int row = packageStore.AddRow (); packageStore.SetValue (row, packageHasBackgroundColorField, IsOddRow (row)); packageStore.SetValue (row, packageCheckBoxAlphaField, GetPackageCheckBoxAlpha ()); packageStore.SetValue (row, packageViewModelField, packageViewModel); } void LoadPackageImage (int row, PackageViewModel packageViewModel) { if (packageViewModel.HasIconUrl) { // Workaround: Image loading is incorrectly being done on GUI thread // since the wrong synchronization context seems to be used. So // here we switch to a background thread and then back to the GUI thread. Task.Run (() => LoadImage (packageViewModel.IconUrl, row)); } } void LoadImage (Uri iconUrl, int row) { // Put it back on the GUI thread so the correct synchronization context // is used. The image loading will be done on a background thread. Runtime.RunInMainThread (() => imageLoader.LoadFrom (iconUrl, row)); } bool IsOddRow (int row) { return (row % 2) == 0; } double GetPackageCheckBoxAlpha () { if (PackagesCheckedCount == 0) { return packageCheckBoxSemiTransarentAlpha; } return 1; } void ImageLoaded (object sender, ImageLoadedEventArgs e) { if (!e.HasError) { int row = (int)e.State; if (IsValidRowAndUrl (row, e.Uri)) { packageStore.SetValue (row, packageImageField, e.Image); } } } bool IsValidRowAndUrl (int row, Uri uri) { if (row < packageStore.RowCount) { PackageViewModel packageViewModel = packageStore.GetValue (row, packageViewModelField); if (packageViewModel != null) { return uri == packageViewModel.IconUrl; } } return false; } void AddPackagesButtonClicked (object sender, EventArgs e) { try { packagesToAdd = GetPackagesToAdd (); Close (); } catch (Exception ex) { LoggingService.LogError ("Adding packages failed.", ex); ShowErrorMessage (ex.Message); } } List<NuGetPackageToAdd> GetPackagesToAdd () { List<PackageViewModel> packageViewModels = GetSelectedPackageViewModels (); if (packageViewModels.Count > 0) { return GetPackagesToAdd (packageViewModels); } return new List<NuGetPackageToAdd> (); } List<PackageViewModel> GetSelectedPackageViewModels () { List<PackageViewModel> packageViewModels = viewModel.CheckedPackageViewModels.ToList (); if (packageViewModels.Count > 0) { return packageViewModels; } PackageViewModel selectedPackageViewModel = GetSelectedPackageViewModel (); if (selectedPackageViewModel != null) { packageViewModels.Add (selectedPackageViewModel); } return packageViewModels; } List<NuGetPackageToAdd> GetPackagesToAdd (IEnumerable<PackageViewModel> packageViewModels) { return packageViewModels.Select (viewModel => new NuGetPackageToAdd (viewModel)) .ToList (); } void PackageSearchEntryChanged (object sender, EventArgs e) { ClearErrorMessage (); ClearPackages (); UpdateAddPackagesButton (); SearchAfterDelay (); } void SearchAfterDelay () { DisposeExistingTimer (); searchTimer = Application.TimeoutInvoke (searchDelayTimeSpan, Search); } void DisposeExistingTimer () { if (searchTimer != null) { searchTimer.Dispose (); } } bool Search () { viewModel.SearchTerms = this.packageSearchEntry.Text; viewModel.SearchCommand.Execute (null); return false; } void PackagesListRowActivated (object sender, ListViewRowEventArgs e) { if (PackagesCheckedCount > 0) { AddPackagesButtonClicked (sender, e); } else { PackageViewModel packageViewModel = packageStore.GetValue (e.RowIndex, packageViewModelField); packagesToAdd = GetPackagesToAdd (new [] { packageViewModel }); Close (); } } void PackageSearchEntryActivated (object sender, EventArgs e) { if (loadingMessageVisible) return; if (PackagesCheckedCount > 0) { AddPackagesButtonClicked (sender, e); } else { PackageViewModel selectedPackageViewModel = GetSelectedPackageViewModel (); packagesToAdd = GetPackagesToAdd (new [] { selectedPackageViewModel }); Close (); } } void PackagesListViewScrollValueChanged (object sender, EventArgs e) { if (viewModel.IsLoadingNextPage) { return; } if (IsScrollBarNearEnd (packagesListView.VerticalScrollControl)) { if (viewModel.HasNextPage) { viewModel.ShowNextPage (); } } } bool IsScrollBarNearEnd (ScrollControl scrollControl) { double currentValue = scrollControl.Value; double maxValue = scrollControl.UpperValue; double pageSize = scrollControl.PageSize; return (currentValue / (maxValue - pageSize)) > 0.7; } void PackageCellViewPackageChecked (object sender, PackageCellViewEventArgs e) { UpdateAddPackagesButton (); UpdatePackageListViewSelectionColor (); UpdatePackageListViewCheckBoxAlpha (); } void UpdateAddPackagesButton () { if (PackagesCheckedCount > 1) { addPackagesButton.Label = GettextCatalog.GetString ("Add Packages"); } else { if (OlderPackageInstalledThanPackageSelected ()) { addPackagesButton.Label = GettextCatalog.GetString ("Update Package"); } else { addPackagesButton.Label = GettextCatalog.GetString ("Add Package"); } } addPackagesButton.Sensitive = IsAddPackagesButtonEnabled (); } void UpdatePackageListViewSelectionColor () { packageCellView.UseStrongSelectionColor = (PackagesCheckedCount == 0); } void UpdatePackageListViewCheckBoxAlpha () { if (PackagesCheckedCount > 1) return; double alpha = GetPackageCheckBoxAlpha (); for (int row = 0; row < packageStore.RowCount; ++row) { packageStore.SetValue (row, packageCheckBoxAlphaField, alpha); } } bool OlderPackageInstalledThanPackageSelected () { if (PackagesCheckedCount != 0) { return false; } // PackageViewModel selectedPackageViewModel = GetSelectedPackageViewModel (); // if (selectedPackageViewModel != null) { // return selectedPackageViewModel.IsOlderPackageInstalled (); // } return false; } bool IsAddPackagesButtonEnabled () { return !loadingMessageVisible && IsAtLeastOnePackageSelected (); } bool IsAtLeastOnePackageSelected () { return (PackagesCheckedCount) >= 1 || (packagesListView.SelectedRow != -1); } int PackagesCheckedCount { get { return viewModel.CheckedPackageViewModels.Count; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Globalization; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Serialization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Schema { /// <summary> /// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>. /// </summary> public class JsonSchemaGenerator { /// <summary> /// Gets or sets how undefined schemas are handled by the serializer. /// </summary> public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; } private IContractResolver _contractResolver; /// <summary> /// Gets or sets the contract resolver. /// </summary> /// <value>The contract resolver.</value> public IContractResolver ContractResolver { get { if (_contractResolver == null) return DefaultContractResolver.Instance; return _contractResolver; } set { _contractResolver = value; } } private class TypeSchema { public Type Type { get; private set; } public JsonSchema Schema { get; private set;} public TypeSchema(Type type, JsonSchema schema) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(schema, "schema"); Type = type; Schema = schema; } } private JsonSchemaResolver _resolver; private readonly IList<TypeSchema> _stack = new List<TypeSchema>(); private JsonSchema _currentSchema; private JsonSchema CurrentSchema { get { return _currentSchema; } } private void Push(TypeSchema typeSchema) { _currentSchema = typeSchema.Schema; _stack.Add(typeSchema); _resolver.LoadedSchemas.Add(typeSchema.Schema); } private TypeSchema Pop() { TypeSchema popped = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); TypeSchema newValue = _stack.LastOrDefault(); if (newValue != null) { _currentSchema = newValue.Schema; } else { _currentSchema = null; } return popped; } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type) { return Generate(type, new JsonSchemaResolver(), false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver) { return Generate(type, resolver, false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, bool rootSchemaNullable) { return Generate(type, new JsonSchemaResolver(), rootSchemaNullable); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(resolver, "resolver"); _resolver = resolver; return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false); } private string GetTitle(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title)) return containerAttribute.Title; return null; } private string GetDescription(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description)) return containerAttribute.Description; #if !(NETFX_CORE || PORTABLE40 || PORTABLE) DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type); if (descriptionAttribute != null) return descriptionAttribute.Description; #endif return null; } private string GetTypeId(Type type, bool explicitOnly) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id)) return containerAttribute.Id; if (explicitOnly) return null; switch (UndefinedSchemaIdHandling) { case UndefinedSchemaIdHandling.UseTypeName: return type.FullName; case UndefinedSchemaIdHandling.UseAssemblyQualifiedName: return type.AssemblyQualifiedName; default: return null; } } private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) resolvedSchema.Type |= JsonSchemaType.Null; if (required && resolvedSchema.Required != true) resolvedSchema.Required = true; return resolvedSchema; } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) return converterSchema; } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) CurrentSchema.Id = explicitId; if (required) CurrentSchema.Required = true; CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else { switch (contract.ContractType) { case JsonContractType.Object: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract) contract); break; case JsonContractType.Array: CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List<JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } break; case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true)) { CurrentSchema.Enum = new List<JToken>(); EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); } } break; case JsonContractType.String: JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; break; case JsonContractType.Dictionary: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { JsonContract keyContract = ContractResolver.ResolveContract(keyType); // can be converted to a string if (keyContract.ContractType == JsonContractType.Primitive) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } break; #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40) case JsonContractType.Serializable: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract) contract); break; #endif #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE40) case JsonContractType.Dynamic: #endif case JsonContractType.Linq: CurrentSchema.Type = JsonSchemaType.Any; break; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return Pop().Schema; } private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired) { if (valueRequired != Required.Always) return type | JsonSchemaType.Null; return type; } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private void GenerateObjectSchema(Type type, JsonObjectContract contract) { CurrentSchema.Properties = new Dictionary<string, JsonSchema>(); foreach (JsonProperty property in contract.Properties) { if (!property.Ignored) { bool optional = property.NullValueHandling == NullValueHandling.Ignore || HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) || property.ShouldSerialize != null || property.GetIsSpecified != null; JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional); if (property.DefaultValue != null) propertySchema.Default = JToken.FromObject(property.DefaultValue); CurrentSchema.Properties.Add(property.PropertyName, propertySchema); } } if (type.IsSealed()) CurrentSchema.AllowAdditionalProperties = false; } #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40) private void GenerateISerializableContract(Type type, JsonISerializableContract contract) { CurrentSchema.AllowAdditionalProperties = true; } #endif internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag) { // default value is Any if (value == null) return true; bool match = ((value & flag) == flag); if (match) return true; // integer is a subset of float if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float) return true; return false; } private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) { JsonSchemaType schemaType = JsonSchemaType.None; if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) { schemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) type = Nullable.GetUnderlyingType(type); } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); switch (typeCode) { case PrimitiveTypeCode.Empty: case PrimitiveTypeCode.Object: return schemaType | JsonSchemaType.String; #if !(NETFX_CORE || PORTABLE) case PrimitiveTypeCode.DBNull: return schemaType | JsonSchemaType.Null; #endif case PrimitiveTypeCode.Boolean: return schemaType | JsonSchemaType.Boolean; case PrimitiveTypeCode.Char: return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: #if !(PORTABLE || NET35 || NET20 || WINDOWS_PHONE || SILVERLIGHT) case PrimitiveTypeCode.BigInteger: #endif return schemaType | JsonSchemaType.Integer; case PrimitiveTypeCode.Single: case PrimitiveTypeCode.Double: case PrimitiveTypeCode.Decimal: return schemaType | JsonSchemaType.Float; // convert to string? case PrimitiveTypeCode.DateTime: #if !NET20 case PrimitiveTypeCode.DateTimeOffset: #endif return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.String: case PrimitiveTypeCode.Uri: case PrimitiveTypeCode.Guid: case PrimitiveTypeCode.TimeSpan: case PrimitiveTypeCode.Bytes: return schemaType | JsonSchemaType.String; default: throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Linq; using System.Reflection; using Aurora.Framework; using OpenMetaverse; namespace Aurora.Framework { public class EntityManager { protected readonly DoubleKeyDictionary<UUID, uint, UUID> m_child_2_parent_entities = new DoubleKeyDictionary<UUID, uint, UUID>(); protected readonly DoubleKeyDictionary<UUID, uint, ISceneEntity> m_objectEntities = new DoubleKeyDictionary<UUID, uint, ISceneEntity>(); protected readonly Dictionary<UUID, IScenePresence> m_presenceEntities = new Dictionary<UUID, IScenePresence>(); protected readonly List<IScenePresence> m_presenceEntitiesList = new List<IScenePresence>(); protected object m_child_2_parent_entitiesLock = new object(); protected object m_objectEntitiesLock = new object(); protected object m_presenceEntitiesLock = new object(); public virtual int Count { get { return m_objectEntities.Count + this.GetPresenceCount(); } } public virtual bool Add(IEntity entity) { if (entity.LocalId == 0) { MainConsole.Instance.Warn("Entity with 0 localID!"); return false; } try { if (entity is ISceneEntity) { lock (m_child_2_parent_entitiesLock) { foreach (ISceneChildEntity part in (entity as ISceneEntity).ChildrenEntities()) { m_child_2_parent_entities.Remove(part.UUID); m_child_2_parent_entities.Remove(part.LocalId); m_child_2_parent_entities.Add(part.UUID, part.LocalId, entity.UUID); } } lock (m_objectEntitiesLock) m_objectEntities.Add(entity.UUID, entity.LocalId, entity as ISceneEntity); } else { IScenePresence presence = (IScenePresence) entity; lock (m_presenceEntitiesLock) { m_presenceEntitiesList.Add(presence); m_presenceEntities.Add(presence.UUID, presence); } } } catch (Exception e) { MainConsole.Instance.ErrorFormat("Add Entity failed: {0}", e.Message); return false; } return true; } public virtual void Clear() { lock (m_objectEntitiesLock) m_objectEntities.Clear(); lock (m_presenceEntitiesLock) { m_presenceEntitiesList.Clear(); m_presenceEntities.Clear(); } lock (m_child_2_parent_entitiesLock) m_child_2_parent_entities.Clear(); } public virtual bool Remove(IEntity entity) { if (entity == null) return false; try { if (entity is ISceneEntity) { lock (m_child_2_parent_entitiesLock) { //Remove all child entities foreach (ISceneChildEntity part in (entity as ISceneEntity).ChildrenEntities()) { m_child_2_parent_entities.Remove(part.UUID); m_child_2_parent_entities.Remove(part.LocalId); } } lock (m_objectEntitiesLock) { m_objectEntities.Remove(entity.UUID); m_objectEntities.Remove(entity.LocalId); } } else { lock (m_presenceEntitiesLock) { m_presenceEntitiesList.Remove((IScenePresence) entity); m_presenceEntities.Remove(entity.UUID); } } return true; } catch (Exception e) { MainConsole.Instance.ErrorFormat("Remove Entity failed for {0}", entity.UUID, e); return false; } } public virtual List<IScenePresence> GetPresences() { return m_presenceEntitiesList; } public virtual int GetPresenceCount() { return m_presenceEntitiesList.Count; } public virtual IScenePresence[] GetPresences(Vector3 pos, float radius) { lock (m_presenceEntitiesLock) { List<IScenePresence> tmp = new List<IScenePresence>(m_presenceEntities.Count); #if (!ISWIN) foreach (IScenePresence entity in m_presenceEntities.Values) { if ((entity.AbsolutePosition - pos).LengthSquared() < radius * radius) tmp.Add(entity); } #else tmp.AddRange(m_presenceEntities.Values.Where(entity => (entity.AbsolutePosition - pos).LengthSquared() < radius * radius)); #endif return tmp.ToArray(); } } public virtual ISceneEntity[] GetEntities() { lock (m_objectEntitiesLock) { List<ISceneEntity> tmp = new List<ISceneEntity>(m_objectEntities.Count); m_objectEntities.ForEach(tmp.Add); return tmp.ToArray(); } } public virtual ISceneEntity[] GetEntities(Vector3 pos, float radius) { lock (m_objectEntitiesLock) { List<ISceneEntity> tmp = new List<ISceneEntity>(m_objectEntities.Count); m_objectEntities.ForEach(delegate(ISceneEntity entity) { //Add attachments as well, as they might be needed if ((entity.AbsolutePosition - pos).LengthSquared() < radius*radius || entity.IsAttachment) tmp.Add(entity); }); return tmp.ToArray(); } } public virtual bool TryGetPresenceValue(UUID key, out IScenePresence presence) { lock (m_presenceEntitiesLock) { return m_presenceEntities.TryGetValue(key, out presence); } } public virtual bool TryGetValue(UUID key, out IEntity obj) { return InternalTryGetValue(key, true, out obj); } protected virtual bool InternalTryGetValue(UUID key, bool checkRecursive, out IEntity obj) { IScenePresence presence; bool gotit; lock (m_presenceEntitiesLock) gotit = m_presenceEntities.TryGetValue(key, out presence); if (!gotit) { ISceneEntity presence2; lock (m_objectEntitiesLock) gotit = m_objectEntities.TryGetValue(key, out presence2); //Deal with the possibility we may have been asked for a child prim if ((!gotit) && checkRecursive) return TryGetChildPrimParent(key, out obj); else if (gotit) { obj = presence2; return true; } } else if (gotit) { obj = presence; return true; } obj = null; return false; } public virtual bool TryGetValue(uint key, out IEntity obj) { return InternalTryGetValue(key, true, out obj); } protected virtual bool InternalTryGetValue(uint key, bool checkRecursive, out IEntity obj) { ISceneEntity entity; bool gotit; lock (m_objectEntitiesLock) gotit = m_objectEntities.TryGetValue(key, out entity); //Deal with the possibility we may have been asked for a child prim if (!gotit && checkRecursive) return TryGetChildPrimParent(key, out obj); else if (gotit) { obj = entity; return true; } else { obj = null; return false; } } /// <summary> /// Retrives the SceneObjectGroup of this child /// </summary> /// <param name = "childkey"></param> /// <param name = "obj"></param> /// <returns></returns> public virtual bool TryGetChildPrimParent(UUID childkey, out IEntity obj) { UUID ParentKey = UUID.Zero; bool gotit; lock (m_child_2_parent_entitiesLock) gotit = m_child_2_parent_entities.TryGetValue(childkey, out ParentKey); if (gotit) return InternalTryGetValue(ParentKey, false, out obj); obj = null; return false; } /// <summary> /// Retrives the SceneObjectGroup of this child /// </summary> /// <param name = "childkey"></param> /// <param name = "obj"></param> /// <returns></returns> public virtual bool TryGetChildPrimParent(uint childkey, out IEntity obj) { bool gotit; UUID ParentKey = UUID.Zero; lock (m_child_2_parent_entitiesLock) gotit = m_child_2_parent_entities.TryGetValue(childkey, out ParentKey); if (gotit) return InternalTryGetValue(ParentKey, false, out obj); obj = null; return false; } public virtual bool TryGetChildPrim(uint childkey, out ISceneChildEntity child) { child = null; IEntity entity; if (!TryGetChildPrimParent(childkey, out entity)) return false; if (!(entity is ISceneEntity)) return false; child = (entity as ISceneEntity).GetChildPart(childkey); return true; } protected virtual bool TryGetChildPrim(UUID objectID, out ISceneChildEntity childPrim) { childPrim = null; IEntity entity; if (!TryGetChildPrimParent(objectID, out entity)) return false; childPrim = (entity as ISceneEntity).GetChildPart(objectID); return true; } } }
using System; using System.Runtime.InteropServices; using System.IO; using Microsoft.WindowsCE.Forms; using System.Text; using System.Threading; using System.Diagnostics; namespace PlatformAPI.Wave { /// <summary> /// Encapsulates Waveform Audio Interface recording functions and provides a simple /// interface for recording audio. /// </summary> public class WaveIn { /// <summary> /// Create an instance of WaveIn. /// </summary> public WaveIn() { m_msgWindow = new SoundMessageWindow(this); m_file = new WaveFile(); } /// <summary> /// Determine the number of available recording devices. /// </summary> /// <returns>Number of input devices</returns> public uint NumDevices() { return (uint)waveInGetNumDevs(); } /// <summary> /// Get the name of the specified recording device. /// </summary> /// <param name="deviceId">ID of the device</param> /// <param name="prodName">Destination string assigned the name</param> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR GetDeviceName(uint deviceId, ref string prodName) { WAVEINCAPS caps = new WAVEINCAPS(); Wave.MMSYSERR result = waveInGetDevCaps(deviceId, caps, caps.Size); if (result != Wave.MMSYSERR.NOERROR) return result; prodName = caps.szPname; return Wave.MMSYSERR.NOERROR; } /// <summary> /// A block has finished so notify the WaveFile. In a more complicated example, /// this class might maintain an array of WaveFile instances. In such a case, the /// wParam of the message could be passed from the MM_WIM_DATA message. This /// value represents the m_hwi member of the file that caused the message. /// The code might look something like: /// foreach (WaveFile f in m_files) /// { /// if (f.m_hwi.ToInt32() == wParam.ToInt32()) /// { /// f.BlockDone(); /// break; /// } /// } /// </summary> public void BlockDone() { m_file.BlockDone(); } /// <summary> /// Preload the buffers of the record file. /// </summary> /// <param name="maxRecordLength_ms">Maximum record length in milliseconds</param> /// <param name="bufferSize">Size of individual buffers, in bytes</param> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR Preload(int maxRecordLength_ms, int bufferSize) { if (m_file != null) return m_file.Preload(0, m_msgWindow.Hwnd, maxRecordLength_ms, bufferSize); return Wave.MMSYSERR.NOERROR; } /// <summary> /// Stop recording. /// </summary> public void Stop() { if (m_file != null) m_file.Stop(); } /// <summary> /// Start recording. /// </summary> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR Start() { if (m_file != null) return m_file.Start(); return Wave.MMSYSERR.NOERROR; } /// <summary> /// Checks if the recording time is expired. /// </summary> /// <returns>true if not currently recording</returns> public bool Done() { return m_file.Done; } /// <summary> /// Save the WaveFile buffers to the specified file. /// </summary> /// <param name="fileName">Name of destination file</param> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR Save(string fileName) { if (m_file != null) return m_file.Save(fileName); return Wave.MMSYSERR.NOERROR; } /// <summary> /// Clean up any resources allocated by the class. /// </summary> public void Dispose() { m_msgWindow.Dispose(); if (m_file != null) m_file.Dispose(); } /// <summary> /// This function retrieves the number of waveform input devices present in the system. /// </summary> /// <returns>The number of devices indicates success. Zero indicates that no devices are present or that an error occurred.</returns> [DllImport ("coredll.dll")] protected static extern int waveInGetNumDevs(); /// <summary> /// This function closes the specified waveform-audio input device. /// </summary> /// <param name="hwi">Handle to the waveform-audio input device. If the /// function succeeds, the handle is no longer valid after this call.</param> /// <returns>MMSYSERR</returns> [DllImport ("coredll.dll")] protected static extern Wave.MMSYSERR waveInClose(IntPtr hwi); /// <summary> /// This function stops input on a specified waveform input device and resets /// the current position to 0. All pending buffers are marked as done and /// returned to the application. /// </summary> /// <param name="hwi">Handle to the waveform-audio input device.</param> /// <returns>MMSYSERR</returns> [DllImport ("coredll.dll")] protected static extern Wave.MMSYSERR waveInReset(IntPtr hwi); /// <summary> /// This function starts input on the specified waveform input device. /// </summary> /// <param name="hwi">Handle to the waveform-audio input device.</param> /// <returns>MMSYSERR</returns> [DllImport ("coredll.dll")] protected static extern Wave.MMSYSERR waveInStart(IntPtr hwi); /// <summary> /// This function stops waveform input. /// </summary> /// <param name="hwi">Handle to the waveform-audio input device.</param> /// <returns>MMSYSERR</returns> [DllImport ("coredll.dll")] protected static extern Wave.MMSYSERR waveInStop(IntPtr hwi); /// <summary> /// This function retrieves the capabilities of a specified waveform-audio /// input device. /// </summary> /// <param name="uDeviceID">Identifier of the waveform-audio output device. It /// can be either a device identifier or a Handle to an open waveform-audio /// input device.</param> /// <param name="pwic">Pointer to a WAVEINCAPS structure to be filled with /// information about the capabilities of the device.</param> /// <param name="cbwic">Size, in bytes, of the WAVEINCAPS structure.</param> /// <returns>MMSYSERR</returns> [DllImport("coredll.dll")] protected static extern Wave.MMSYSERR waveInGetDevCaps(uint uDeviceID, byte[] pwic, uint cbwic); /// <summary> /// This function opens a specified waveform input device for recording. /// </summary> /// <param name="phwi">Address filled with a handle identifying the open /// waveform-audio input device. Use this handle to identify the device when /// calling other waveform-audio input functions. This parameter can be NULL /// if WAVE_FORMAT_QUERY is specified for fdwOpen.</param> /// <param name="uDeviceID">Identifier of the waveform-audio input device to open. /// It can be either a device identifier or a Handle to an open waveform-audio /// input device. Can also be WAVE_MAPPER.</param> /// <param name="pwfx">Pointer to a WAVEFORMATEX structure that identifies the /// desired format for recording waveform-audio data. You can free this structure /// immediately after waveInOpen returns.</param> /// <param name="dwCallback">Specifies the address of a fixed callback function, /// an event handle, a handle to a window, or the identifier of a thread to be /// called during waveform-audio recording to process messages related to the /// progress of recording. If no callback function is required, this value can be /// zero.</param> /// <param name="dwInstance">Specifies user-instance data passed to the callback /// mechanism. This parameter is not used with the window callback mechanism.</param> /// <param name="fdwOpen">Flags for opening the device.</param> /// <returns>MMSYSERR</returns> [DllImport ("coredll.dll")] private static extern Wave.MMSYSERR waveInOpen(ref IntPtr phwi, uint uDeviceID, Wave.WAVEFORMATEX pwfx, IntPtr dwCallback, uint dwInstance, uint fdwOpen); /// <summary> /// This function prepares a buffer for waveform input. /// </summary> /// <param name="hwi">Handle to the waveform-audio input device.</param> /// <param name="pwh">Pointer to a WAVEHDR structure that identifies the buffer /// to be prepared. The buffer's base address must be aligned with the respect /// to the sample size.</param> /// <param name="cbwh">Size, in bytes, of the WAVEHDR structure.</param> /// <returns></returns> [DllImport ("coredll.dll")] private static extern Wave.MMSYSERR waveInPrepareHeader(IntPtr hwi, Wave.WAVEHDR pwh, uint cbwh); /// <summary> /// This function cleans up the preparation performed by waveInPrepareHeader. /// The function must be called after the device driver fills a data buffer /// and returns it to the application. You must call this function before /// freeing the data buffer. /// </summary> /// <param name="hwi">Handle to the waveform-audio input device.</param> /// <param name="pwh">Pointer to a WAVEHDR structure identifying the buffer to /// be cleaned up.</param> /// <param name="cbwh">Size, in bytes, of the WAVEHDR structure.</param> /// <returns></returns> [DllImport ("coredll.dll")] private static extern Wave.MMSYSERR waveInUnprepareHeader(IntPtr hwi, Wave.WAVEHDR pwh, uint cbwh); /// <summary> /// This function sends an input buffer to the specified waveform-audio input /// device. When the buffer is filled, the application is notified. /// </summary> /// <param name="hwi">Handle to the waveform-audio input device.</param> /// <param name="pwh">Pointer to a WAVEHDR structure that identifies /// the buffer.</param> /// <param name="cbwh">Size, in bytes, of the WAVEHDR structure.</param> /// <returns>MMSYSERR</returns> [DllImport ("coredll.dll")] private static extern Wave.MMSYSERR waveInAddBuffer(IntPtr hwi, Wave.WAVEHDR pwh, uint cbwh); /// <summary> /// Maintain an instance of a MessageWindow that handles audio messages. /// </summary> protected SoundMessageWindow m_msgWindow = null; /// <summary> /// An instance of WaveFile used as the destination for recording audio. /// </summary> protected WaveFile m_file = null; /// <summary> /// Supplies an inteface for creating, recording to, and saving a .wav file. /// </summary> protected class WaveFile : IDisposable { /// <summary> /// Specifies whether or not recording is done. /// </summary> public bool Done { get { return !m_recording; } } /// <summary> /// Preload the buffers and prepare them for recording. /// </summary> /// <param name="curDevice">Device to use for recording</param> /// <param name="hwnd">Handle to a message window that will receive /// audio messages.</param> /// <param name="maxRecordLength_ms">Maximum length of recording</param> /// <param name="bufferSize">Size of buffers to use for recording. New /// buffers are added when needed until the maximum length is reached /// or the recording is stopped.</param> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR Preload(uint curDevice, IntPtr hwnd, int maxRecordLength_ms, int bufferSize) { // Do not allow recording to be interrupted if (m_recording) return Wave.MMSYSERR.ERROR; // If this file is already initialized then start over if (m_inited) { Stop(); FreeWaveBuffers(); } // Create an instance of WAVEINCAPS to check if our desired // format is supported WAVEINCAPS caps = new WAVEINCAPS(); waveInGetDevCaps(0, caps, caps.Size); if ((caps.dwFormats & Wave.WAVE_FORMAT_1S08) == 0) return Wave.MMSYSERR.NOTSUPPORTED; // Initialize a WAVEFORMATEX structure specifying the desired // format m_wfmt = new Wave.WAVEFORMATEX(); m_wfmt.wFormatTag = Wave.WAVEHDR.WAVE_FORMAT_PCM; m_wfmt.wBitsPerSample = 8; m_wfmt.nChannels = 2; m_wfmt.nSamplesPerSec = 11025; m_wfmt.nAvgBytesPerSec = (uint)(m_wfmt.nSamplesPerSec * m_wfmt.nChannels * (m_wfmt.wBitsPerSample / 8)); m_wfmt.nBlockAlign = (ushort)(m_wfmt.wBitsPerSample * m_wfmt.nChannels / 8); // Attempt to open the specified device with the desired wave format Wave.MMSYSERR result = waveInOpen(ref m_hwi, curDevice, m_wfmt, hwnd, 0, Wave.CALLBACK_WINDOW); if (result != Wave.MMSYSERR.NOERROR) return result; if (bufferSize == 0) return Wave.MMSYSERR.ERROR; m_bufferSize = (uint)bufferSize; // Force the buffers to align to nBlockAlign if (m_bufferSize % m_wfmt.nBlockAlign != 0) m_bufferSize += m_wfmt.nBlockAlign - (m_bufferSize % m_wfmt.nBlockAlign); // Determine the number of buffers needed to record the maximum length m_maxDataLength = (uint)(m_wfmt.nAvgBytesPerSec * maxRecordLength_ms / 1000); m_numBlocks = (int)(m_maxDataLength / m_bufferSize); if (m_numBlocks * m_bufferSize < m_maxDataLength) m_numBlocks++; // Allocate the list of buffers m_whdr = new Wave.WAVEHDR[m_numBlocks + 1]; // Allocate and initialize two buffers to start with m_whdr[0] = new Wave.WAVEHDR(); m_whdr[1] = new Wave.WAVEHDR(); result = InitBuffer(0); if (result != Wave.MMSYSERR.NOERROR) return result; result = InitBuffer(1); if (result != Wave.MMSYSERR.NOERROR) return result; m_curBlock = 0; m_inited = true; return Wave.MMSYSERR.NOERROR; } /// <summary> /// Called when the Windows message specifying that a block has finished /// recording is encountered. It is critical that the application stay /// one buffer ahead because at the point this function is called, the system /// has already started writing to the next buffer. /// </summary> public void BlockDone() { m_curBlock++; // If the next block is not the padding buffer at the end of the // recording then initialize another buffer, otherwise stop recording if (m_curBlock < m_numBlocks) { if (m_whdr != null) { InitBuffer(m_curBlock + 1); } } else if (m_curBlock == m_numBlocks) { Stop(); } } /// <summary> /// Initialize a buffer for recording by allocating a data buffer, /// preparing the header, and adding it to the read queue. /// </summary> /// <param name="bufIndex">Index of buffer to allocate</param> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR InitBuffer(int bufIndex) { // Determine the size of the buffer to create uint writeLength = (uint)m_bufferSize; if (bufIndex < m_numBlocks) { uint remainingDataLength = (uint)(m_maxDataLength - bufIndex * m_bufferSize); if (m_bufferSize > remainingDataLength) writeLength = remainingDataLength; } // If the header is not already instanced then instance it if (m_whdr[bufIndex] == null) m_whdr[bufIndex] = new Wave.WAVEHDR(); // Allocate memory if not already allocated Wave.MMSYSERR result = m_whdr[bufIndex].Init(writeLength, false); if (result != Wave.MMSYSERR.NOERROR) return result; // Prepare the header result = waveInPrepareHeader(m_hwi, m_whdr[bufIndex], (uint)Marshal.SizeOf(m_whdr[bufIndex])); if (result != Wave.MMSYSERR.NOERROR) return result; // Put the buffer in the queue return waveInAddBuffer(m_hwi, m_whdr[bufIndex], (uint)Marshal.SizeOf(m_whdr[bufIndex])); } /// <summary> /// Start recording. /// </summary> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR Start() { if (!m_inited || m_recording) return Wave.MMSYSERR.ERROR; Wave.MMSYSERR result = waveInStart(m_hwi); if (result != Wave.MMSYSERR.NOERROR) return result; m_recording = true; return Wave.MMSYSERR.NOERROR; } /// <summary> /// Save the current record buffers to the specified file. /// </summary> /// <param name="fileName">Name of file to be saved</param> /// <returns>MMSYSERR.NOERROR if successful</returns> public Wave.MMSYSERR Save(string fileName) { if (!m_inited) return Wave.MMSYSERR.ERROR; if (m_recording) Stop(); FileStream strm = null; BinaryWriter wrtr = null; try { if (File.Exists(fileName)) { FileInfo fi = new FileInfo(fileName); if ((fi.Attributes & FileAttributes.ReadOnly) != 0) fi.Attributes -= FileAttributes.ReadOnly; strm = new FileStream(fileName, FileMode.Truncate); } else { strm = new FileStream(fileName, FileMode.Create); } if (strm == null) return Wave.MMSYSERR.ERROR; wrtr = new BinaryWriter(strm); if (wrtr == null) return Wave.MMSYSERR.ERROR; // Determine the size of the data, as the total number of bytes // recorded by each buffer uint totalSize = 0; for (int i = 0; i < m_numBlocks; i++) { if (m_whdr[i] != null) totalSize += m_whdr[i].dwBytesRecorded; } int chunkSize = (int)(36 + totalSize); // Write out the header information WriteChars(wrtr, "RIFF"); wrtr.Write(chunkSize); WriteChars(wrtr, "WAVEfmt "); wrtr.Write((int)16); m_wfmt.Write(wrtr); WriteChars(wrtr, "data"); wrtr.Write((int)totalSize); // Write the data recorded to each buffer for (int i = 0; i < m_numBlocks; i++) { if (m_whdr[i] != null) { Wave.MMSYSERR result = m_whdr[i].Write(wrtr); if (result != Wave.MMSYSERR.NOERROR) return result; } } return Wave.MMSYSERR.NOERROR; } finally { FreeWaveBuffers(); if (strm != null) strm.Close(); if (wrtr != null) wrtr.Close(); } } /// <summary> /// Stop recording. After stopping, the buffers are kept until recording /// is restarted or the buffers are saved. /// </summary> public void Stop() { waveInReset(m_hwi); m_recording = false; } /// <summary> /// Clean up any allocated resources. /// </summary> public void Dispose() { Stop(); FreeWaveBuffers(); } /// <summary> /// Current block, or buffer in m_whdr, being written. /// </summary> protected int m_curBlock; /// <summary> /// Maximum number of blocks to be written. /// </summary> protected int m_numBlocks; /// <summary> /// Size of each record buffer. /// </summary> protected uint m_bufferSize; /// <summary> /// Maximum size of all record buffers. /// </summary> protected uint m_maxDataLength; /// <summary> /// Free the buffers allocated for recording. This is not done when /// recording stops because the user needs a chance to save or reject /// the recording before trying again. /// </summary> private void FreeWaveBuffers() { m_inited = false; if (m_whdr != null) { for (int i = 0; i < m_whdr.Length; i++) { if (m_whdr[i] != null) { waveInUnprepareHeader(m_hwi, m_whdr[i], (uint)Marshal.SizeOf(m_whdr[i])); m_whdr[i].Dispose(); m_whdr[i] = null; } } m_whdr = null; } waveInClose(m_hwi); m_hwi = IntPtr.Zero; } /// <summary> /// Write individual characters to the BinaryWriter. This is a helper /// function used by Save. Writing strings does not work because they /// write a length before the characters. /// </summary> /// <param name="wrtr">Destination of write</param> /// <param name="text">Characters to be written</param> private void WriteChars(BinaryWriter wrtr, string text) { for (int i = 0; i < text.Length; i++) { char c = (char)text[i]; wrtr.Write(c); } } protected bool m_recording = false; /// <summary> /// Hardware interface instance for this wave file. /// </summary> protected IntPtr m_hwi = IntPtr.Zero; /// <summary> /// Instance of the WAVEFORMATEX header for this file. /// </summary> protected Wave.WAVEFORMATEX m_wfmt = null; /// <summary> /// Buffers used to store recording information. /// </summary> protected Wave.WAVEHDR[] m_whdr = null; /// <summary> /// Specifies whether the file is inited or not. /// </summary> protected bool m_inited = false; } /// <summary> /// This structure describes the capabilities of a waveform-audio input device. /// typedef struct /// { /// WORD wMid; /// WORD wPid; /// MMVERSION vDriverVersion; /// TCHAR szPname[MAXPNAMELEN]; /// DWORD dwFormats; /// WORD wChannels; /// WORD wReserved1;} /// WAVEINCAPS; /// This structure has an embedded TCHAR array so the managed implementation is /// a byte array with accessors. /// </summary> protected class WAVEINCAPS { public uint Size { get { return (uint)WAVEINCAPS_SIZE; } } /// <summary> /// Manufacturer identifier for the device driver for the waveform-audio /// input device. /// </summary> public ushort wMid { get { return BitConverter.ToUInt16(m_data, 0); } } /// <summary> /// Product identifier for the waveform-audio input device. Product /// identifiers are defined in Manufacturer and Product Identifiers. /// </summary> public ushort wPid { get { return BitConverter.ToUInt16(m_data, 2); } } /// <summary> /// Version number of the device driver for the waveform-audio input device. /// The high-order byte is the major version number, and the low-order byte /// is the minor version number. /// </summary> public uint vDriverVersion { get { return BitConverter.ToUInt32(m_data, 4); } } /// <summary> /// Specifies the standard formats that are supported. It is one or /// a combination of the following flags. /// </summary> public uint dwFormats { get { return BitConverter.ToUInt32(m_data, 72); } } /// <summary> /// Number that specifies whether the device supports mono (1) or stereo (2) /// input. /// </summary> public ushort wChannels { get { return BitConverter.ToUInt16(m_data, 76); } } /// <summary> /// Padding. /// </summary> public ushort wReserved1 { get { return BitConverter.ToUInt16(m_data, 78); } } /// <summary> /// Null-terminated string that contains the product name. /// </summary> public string szPname { get { char[] bytes = new char[32]; for (int i = 0; i < 32; i++) { bytes[i] = (char)BitConverter.ToUInt16(m_data, i * 2 + 8); } return new string(bytes); } } public WAVEINCAPS() { m_data = new byte[WAVEINCAPS_SIZE]; } public static implicit operator byte[](WAVEINCAPS caps) { return caps.m_data; } private const uint WAVEINCAPS_SIZE = 80; private byte[] m_data = null; } /// <summary> /// Defines the MessageWindow used to receive messages from the audio /// system. /// </summary> protected class SoundMessageWindow : MessageWindow { public SoundMessageWindow(WaveIn wi) { m_wi = wi; } protected override void WndProc(ref Message msg) { switch (msg.Msg) { // When this message is encountered, a block is // done recording, so notify the WaveIn instance. case MM_WIM_DATA: { if (m_wi != null) m_wi.BlockDone(); } break; } base.WndProc(ref msg); } public const int MM_WIM_OPEN = 0x3BE; public const int MM_WIM_CLOSE = 0x3BF; public const int MM_WIM_DATA = 0x3C0; // Instance of a recording interface protected WaveIn m_wi = null; } } }
// 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. // /*============================================================================= ** ** ** ** Purpose: synchronization primitive that can also be used for interprocess synchronization ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; using System.Runtime.CompilerServices; using System.Security.Permissions; using System.IO; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; using System.Diagnostics.Contracts; #if FEATURE_MACL using System.Security.AccessControl; #endif [HostProtection(Synchronization=true, ExternalThreading=true)] [ComVisible(true)] public sealed class Mutex : WaitHandle { static bool dummyBool; #if !FEATURE_MACL public class MutexSecurity { } #endif [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public Mutex(bool initiallyOwned, String name, out bool createdNew) : this(initiallyOwned, name, out createdNew, (MutexSecurity)null) { } [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity) { if (name == string.Empty) { // Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on. name = null; } #if !PLATFORM_UNIX if (name != null && System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name)); } #endif Contract.EndContractBlock(); Win32Native.SECURITY_ATTRIBUTES secAttrs = null; #if FEATURE_MACL // For ACL's, get the security descriptor from the MutexSecurity. if (mutexSecurity != null) { secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm(); byte* pSecDescriptor = stackalloc byte[sd.Length]; Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length); secAttrs.pSecurityDescriptor = pSecDescriptor; } #endif CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs); } [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) { if (name == string.Empty) { // Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on. name = null; } #if !PLATFORM_UNIX if (name != null && System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name)); } #endif Contract.EndContractBlock(); CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs); } [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) { RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode); MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(null, false); MutexTryCodeHelper tryCodeHelper = new MutexTryCodeHelper(initiallyOwned, cleanupInfo, name, secAttrs, this); RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(tryCodeHelper.MutexTryCode); RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( tryCode, cleanupCode, cleanupInfo); createdNew = tryCodeHelper.m_newMutex; } internal class MutexTryCodeHelper { bool m_initiallyOwned; MutexCleanupInfo m_cleanupInfo; internal bool m_newMutex; String m_name; [System.Security.SecurityCritical] // auto-generated Win32Native.SECURITY_ATTRIBUTES m_secAttrs; Mutex m_mutex; [System.Security.SecurityCritical] // auto-generated [PrePrepareMethod] internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex) { Contract.Assert(name == null || name.Length != 0); m_initiallyOwned = initiallyOwned; m_cleanupInfo = cleanupInfo; m_name = name; m_secAttrs = secAttrs; m_mutex = mutex; } [System.Security.SecurityCritical] // auto-generated [PrePrepareMethod] internal void MutexTryCode(object userData) { SafeWaitHandle mutexHandle = null; // try block RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (m_initiallyOwned) { m_cleanupInfo.inCriticalRegion = true; #if !FEATURE_CORECLR Thread.BeginThreadAffinity(); Thread.BeginCriticalRegion(); #endif //!FEATURE_CORECLR } } int errorCode = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { errorCode = CreateMutexHandle(m_initiallyOwned, m_name, m_secAttrs, out mutexHandle); } if (mutexHandle.IsInvalid) { mutexHandle.SetHandleAsInvalid(); if (m_name != null) { switch (errorCode) { #if PLATFORM_UNIX case Win32Native.ERROR_FILENAME_EXCED_RANGE: // On Unix, length validation is done by CoreCLR's PAL after converting to utf-8 throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPathComponentLength), "name"); #endif case Win32Native.ERROR_INVALID_HANDLE: throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", m_name)); } } __Error.WinIOError(errorCode, m_name); } m_newMutex = errorCode != Win32Native.ERROR_ALREADY_EXISTS; m_mutex.SetHandleInternal(mutexHandle); m_mutex.hasThreadAffinity = true; } } [System.Security.SecurityCritical] // auto-generated [PrePrepareMethod] private void MutexCleanupCode(Object userData, bool exceptionThrown) { MutexCleanupInfo cleanupInfo = (MutexCleanupInfo) userData; // If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex // on this OS thread before ending our thread affninity. if(!hasThreadAffinity) { if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) { if( cleanupInfo.inCriticalRegion) { Win32Native.ReleaseMutex(cleanupInfo.mutexHandle); } cleanupInfo.mutexHandle.Dispose(); } if( cleanupInfo.inCriticalRegion) { #if !FEATURE_CORECLR Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); #endif } } } internal class MutexCleanupInfo { [System.Security.SecurityCritical] // auto-generated internal SafeWaitHandle mutexHandle; internal bool inCriticalRegion; [System.Security.SecurityCritical] // auto-generated internal MutexCleanupInfo(SafeWaitHandle mutexHandle, bool inCriticalRegion) { this.mutexHandle = mutexHandle; this.inCriticalRegion = inCriticalRegion; } } [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) { } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool) { } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public Mutex() : this(false, null, out dummyBool) { } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private Mutex(SafeWaitHandle handle) { SetHandleInternal(handle); hasThreadAffinity = true; } [System.Security.SecurityCritical] // auto-generated_required public static Mutex OpenExisting(string name) { #if !FEATURE_MACL return OpenExisting(name, (MutexRights) 0); #else // FEATURE_MACL return OpenExisting(name, MutexRights.Modify | MutexRights.Synchronize); #endif // FEATURE_MACL } #if !FEATURE_MACL public enum MutexRights { } #endif [System.Security.SecurityCritical] // auto-generated_required public static Mutex OpenExisting(string name, MutexRights rights) { Mutex result; switch (OpenExistingWorker(name, rights, out result)) { case OpenExistingResult.NameNotFound: throw new WaitHandleCannotBeOpenedException(); case OpenExistingResult.NameInvalid: throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name)); case OpenExistingResult.PathNotFound: __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, name); return result; //never executes default: return result; } } [System.Security.SecurityCritical] // auto-generated_required public static bool TryOpenExisting(string name, out Mutex result) { #if !FEATURE_MACL return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success; #else // FEATURE_MACL return OpenExistingWorker(name, MutexRights.Modify | MutexRights.Synchronize, out result) == OpenExistingResult.Success; #endif // FEATURE_MACL } [System.Security.SecurityCritical] // auto-generated_required public static bool TryOpenExisting(string name, MutexRights rights, out Mutex result) { return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success; } [System.Security.SecurityCritical] private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex result) { if (name == null) { throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName")); } if(name.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); } #if !PLATFORM_UNIX if(System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name)); } #endif Contract.EndContractBlock(); result = null; // To allow users to view & edit the ACL's, call OpenMutex // with parameters to allow us to view & edit the ACL. This will // fail if we don't have permission to view or edit the ACL's. // If that happens, ask for less permissions. #if FEATURE_MACL SafeWaitHandle myHandle = Win32Native.OpenMutex((int) rights, false, name); #else SafeWaitHandle myHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); #endif int errorCode = 0; if (myHandle.IsInvalid) { errorCode = Marshal.GetLastWin32Error(); #if PLATFORM_UNIX if (name != null && errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) { // On Unix, length validation is done by CoreCLR's PAL after converting to utf-8 throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPathComponentLength), nameof(name)); } #endif if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; if (null != name && Win32Native.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; // this is for passed through Win32Native Errors __Error.WinIOError(errorCode,name); } result = new Mutex(myHandle); return OpenExistingResult.Success; } // Note: To call ReleaseMutex, you must have an ACL granting you // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void ReleaseMutex() { if (Win32Native.ReleaseMutex(safeWaitHandle)) { #if !FEATURE_CORECLR Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); #endif } else { #if FEATURE_CORECLR throw new Exception(Environment.GetResourceString("Arg_SynchronizationLockException")); #else throw new ApplicationException(Environment.GetResourceString("Arg_SynchronizationLockException")); #endif // FEATURE_CORECLR } } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) { int errorCode; bool fAffinity = false; while(true) { mutexHandle = Win32Native.CreateMutex(securityAttribute, initiallyOwned, name); errorCode = Marshal.GetLastWin32Error(); if( !mutexHandle.IsInvalid) { break; } if( errorCode == Win32Native.ERROR_ACCESS_DENIED) { // If a mutex with the name already exists, OS will try to open it with FullAccess. // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access. // RuntimeHelpers.PrepareConstrainedRegions(); try { try { } finally { #if !FEATURE_CORECLR Thread.BeginThreadAffinity(); #endif fAffinity = true; } mutexHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); if(!mutexHandle.IsInvalid) { errorCode = Win32Native.ERROR_ALREADY_EXISTS; } else { errorCode = Marshal.GetLastWin32Error(); } } finally { if (fAffinity) { #if !FEATURE_CORECLR Thread.EndThreadAffinity(); #endif } } // There could be a race condition here, the other owner of the mutex can free the mutex, // We need to retry creation in that case. if( errorCode != Win32Native.ERROR_FILE_NOT_FOUND) { if( errorCode == Win32Native.ERROR_SUCCESS) { errorCode = Win32Native.ERROR_ALREADY_EXISTS; } break; } } else { break; } } return errorCode; } #if FEATURE_MACL [System.Security.SecuritySafeCritical] // auto-generated public MutexSecurity GetAccessControl() { return new MutexSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } [System.Security.SecuritySafeCritical] // auto-generated public void SetAccessControl(MutexSecurity mutexSecurity) { if (mutexSecurity == null) throw new ArgumentNullException(nameof(mutexSecurity)); Contract.EndContractBlock(); mutexSecurity.Persist(safeWaitHandle); } #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { 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> /// TopicsOperations operations. /// </summary> public partial interface ITopicsOperations { /// <summary> /// Gets all the topics in a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639388.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBTopic>>> ListByNamespaceWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a topic in the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639409.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a topic resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBTopic>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, SBTopic parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a topic from the specified namespace and resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639404.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a description for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639399.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBTopic>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets authorization rules for a topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBAuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates an authorizatio rule for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720678.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBAuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, SBAuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the specified authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720676.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBAuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a topic authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720677.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates primary or secondary connection strings for the topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720679.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the topics in a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639388.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBTopic>>> ListByNamespaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets authorization rules for a topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBAuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Imms.Abstract; namespace Imms.Implementation { /// <summary> /// Container class for an hashed avl tree, which stores key-value pairs ordered by a hash value. Keys with identical /// hashes are placed in buckets. /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> static partial class HashedAvlTree<TKey, TValue> { /// <summary> /// A node in the hashed AVL tree. /// </summary> internal sealed class Node { /// <summary> /// The singleton that represents an empty node. /// </summary> internal static readonly Node Empty = new Node(true); public readonly bool IsEmpty; /// <summary> /// A bucket containing key-value pairs with identical hashes. /// </summary> private Bucket Bucket; public int Count; private readonly IEqualityComparer<TKey> Eq; /// <summary> /// The hash of this node. /// </summary> public readonly int Hash; private int Height; public Node Left = Empty; private Lineage Lineage; private int NodeCount; public Node Right = Empty; private Node(bool isEmpty = false) { Height = 0; Count = 0; IsEmpty = isEmpty; Eq = FastEquality<TKey>.Default; } private Node(int hash, Bucket bucket, Node left, Node right, IEqualityComparer<TKey> eq, Lineage lin) { Eq = eq; Hash = hash; Bucket = bucket; Left = left; Right = right; Lineage = lin; Height = Math.Max(left.Height, right.Height) + 1; Count = left.Count + right.Count + bucket.Count; NodeCount = left.Count + right.Count; } private int Factor { get { return IsEmpty ? 0 : Left.Height - Right.Height; } } public double CollisionMetric { get { if (IsEmpty) return 0; var total = 0.0; var div = 0; if (!Left.IsEmpty) { total += Left.CollisionMetric; div++; } total += Bucket.Count; div++; if (!Right.IsEmpty) { total += Right.CollisionMetric; div++; } return total / div; } } internal int MaxPossibleHeight { get { return IsEmpty ? 0 : (int) Math.Ceiling(2 * Math.Log(Count, 2f)); } } public IEnumerable<KeyValuePair<TKey, TValue>> Pairs { get { foreach (var bucket in AllBuckets) foreach (var item in bucket.Buckets) yield return Kvp.Of(item.Key, item.Value); } } public IEnumerable<Bucket> AllBuckets { get { var walker = new TreeIterator(this); while (walker.MoveNext()) yield return walker.Current.Bucket; } } private bool IsBalanced { get { return (IsEmpty ? 0 : Left.Height - Right.Height) >= -1 && (IsEmpty ? 0 : Left.Height - Right.Height) <= 1; } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { var iterator = new TreeIterator(this); while (iterator.MoveNext()) { var bucket = iterator.Current.Bucket; while (!bucket.IsEmpty) { yield return Kvp.Of(bucket.Key, bucket.Value); bucket = bucket.Next; } } } public Bucket ByArbitraryOrder(int index) { if (IsEmpty) { throw ImplErrors.Arg_out_of_range("index", index); } if (index < Left.Count) { return Left.ByArbitraryOrder(index); } if (index < Left.Count + Bucket.Count) { return Bucket.ByIndex(index - Left.Count); } return Right.ByArbitraryOrder(index - Left.Count - Bucket.Count); } public Node NewForKvp(int hash, TKey k, TValue v, Lineage lineage) { return new Node(hash, Bucket.FromKvp(k, v, Eq, lineage), Empty, Empty, Eq, lineage); } public static Node WithChildren(Node node, Node left, Node right, Lineage lineage) { if (node.Lineage.AllowMutation(lineage)) { node.Left = left; node.Right = right; node.Height = Math.Max(left.Height, right.Height) + 1; node.Lineage = lineage; node.Count = node.Bucket.Count + left.Count + right.Count; node.NodeCount = left.Count + right.Count; } else node = new Node(node.Hash, node.Bucket, left, right, node.Eq, lineage); return node; } public Node Root_Add(TKey k, TValue v, Lineage lin, IEqualityComparer<TKey> eq, bool overwrite) { if (IsEmpty) { var hash = eq.GetHashCode(k); return new Node(hash, Bucket.FromKvp(k, v, eq, lin), Empty, Empty, eq, lin); } else { var hash = Eq.GetHashCode(k); return AvlAdd(hash, k, v, lin, overwrite); } } public Node Root_Remove(TKey k, Lineage lin) { if (IsEmpty) return this; var hash = Eq.GetHashCode(k); return AvlRemove(hash, k, lin); } public Node WithBucket(Bucket newBucket, Lineage lineage) { if (Lineage.AllowMutation(lineage)) { Bucket = newBucket; Count = Left.Count + Right.Count + newBucket.Count; return this; } return new Node(Hash, newBucket, Left, Right, newBucket.Eq, lineage); } /// <summary> /// Creates a new tree and balances it. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="lineage"></param> /// <returns></returns> private Node AvlBalance(Node left, Node right, Lineage lineage) { var factor = left.Height - right.Height; Node newRoot = null; #if ASSERTS factor.AssertBetween(-2, 2); int oldCount = Bucket.Count + left.Count + right.Count; #endif if (factor == -2) { var rFactor = right.Factor; #if ASSERTS rFactor.AssertBetween(-1, 1); #endif if (rFactor == 1) { var newLeft = WithChildren(this, left, right.Left.Left, lineage); var rootFrom = right.Left; var newRight = WithChildren(right, right.Left.Right, right.Right, lineage); newRoot = WithChildren(rootFrom, newLeft, newRight, lineage); } else { var newLeft = WithChildren(this, left, right.Left, lineage); newRoot = WithChildren(right, newLeft, right.Right, lineage); } } else if (factor == 2) { var lFactor = left.Factor; #if ASSERTS lFactor.AssertBetween(-1, 1); #endif if (lFactor == -1) { var newRight = WithChildren(this, left.Right.Right, right, lineage); var rootFrom = left.Right; var newLeft = WithChildren(left, left.Left, left.Right.Left, lineage); newRoot = WithChildren(rootFrom, newLeft, newRight, lineage); } else { var newRight = WithChildren(this, left.Right, right, lineage); newRoot = WithChildren(left, left.Left, newRight, lineage); } } else newRoot = WithChildren(this, left, right, lineage); #if ASSERTS newRoot.IsBalanced.AssertTrue(); newRoot.Count.AssertEqual(oldCount); #endif return newRoot; } public bool Root_Contains(TKey k) { return Root_Find(k).IsSome; } private Node AvlAdd(int hash, TKey key, TValue value, Lineage lineage, bool overwrite) { #if ASSERTS var initialCount = Count; #endif if (IsEmpty) throw ImplErrors.Invalid_invocation("Empty Node"); Node ret; if (hash < Hash) { var newLeft = Left.IsEmpty ? NewForKvp(hash, key, value, lineage) : Left.AvlAdd(hash, key, value, lineage, overwrite); if (newLeft == null) return null; ret = AvlBalance(newLeft, Right, lineage); } else if (hash > Hash) { var newRight = Right.IsEmpty ? NewForKvp(hash, key, value, lineage) : Right.AvlAdd(hash, key, value, lineage, overwrite); if (newRight == null) return null; ret = AvlBalance(Left, newRight, lineage); } else { var newBucket = Bucket.Add(key, value, lineage, overwrite); if (newBucket == null) return null; ret = WithBucket(newBucket, lineage); } #if ASSERTS ret.Count.AssertEqual(x => x <= initialCount + 1 && x >= initialCount); ret.IsBalanced.AssertTrue(); ret.Root_Contains(key).AssertTrue(); //ret.AllBuckets.Count(b => b.Find(key).IsSome).Is(1); #endif return ret; } private Node ExtractMin(out Node min, Lineage lineage) { if (IsEmpty) throw ImplErrors.Invalid_invocation("EmptyNode"); Node ret; if (!Left.IsEmpty) ret = AvlBalance(Left.ExtractMin(out min, lineage), Right, lineage); else { min = this; ret = Right; } #if ASSERTS ret.IsBalanced.AssertTrue(); #endif return ret; } public override string ToString() { return string.Format("({0}, {1}): {2}", Hash, Bucket, string.Join(", ", Pairs)); } public static Node Concat(Node leftBranch, Node pivot, Node rightBranch, Lineage lin) { var newFactor = leftBranch.Height - rightBranch.Height; Node balanced; #if ASSERTS var leftCount = leftBranch.Count; var rightCount = rightBranch.Count; #endif if (newFactor >= 2) { var newRight = Concat(leftBranch.Right, pivot, rightBranch, lin); balanced = leftBranch.AvlBalance(leftBranch.Left, newRight, lin); } else if (newFactor <= -2) { var newLeft = Concat(leftBranch, pivot, rightBranch.Left, lin); balanced = rightBranch.AvlBalance(newLeft, rightBranch.Right, lin); } else balanced = WithChildren(pivot, leftBranch, rightBranch, lin); #if ASSERTS AssertEx.AssertTrue(balanced.Count == 1 + leftCount + rightCount); AssertEx.AssertTrue(balanced.IsBalanced); #endif return balanced; } public void Split(int pivot, out Node leftBranch, out Node central, out Node rightBranch, Lineage lin) { var myCount = Count; if (IsEmpty) { leftBranch = this; rightBranch = this; central = null; } else if (pivot > Hash) { Node rightL, rightR; Right.Split(pivot, out rightL, out central, out rightR, lin); leftBranch = Concat(Left, this, rightL, lin); rightBranch = rightR; } else if (pivot < Hash) { Node leftL, leftR; Left.Split(pivot, out leftL, out central, out leftR, lin); leftBranch = leftL; rightBranch = Concat(leftR, this, Right, lin); } else { leftBranch = Left; central = this; rightBranch = Right; } #if ASSERTS var totalCount = leftBranch.Count + rightBranch.Count + (central == null ? 0 : 1); totalCount.AssertEqual(myCount); #endif } public static Node Concat(Node left, Node right, Lineage lin) { if (left.IsEmpty) return right; if (right.IsEmpty) return left; Node central; left = left.ExtractMax(out central, lin); return Concat(left, central, right, lin); } public int CountIntersection(Node b) { var count = 0; foreach (var pair in IntersectElements(b)) count += pair.First.Bucket.CountIntersection(pair.Second.Bucket); return count; } public SetRelation RelatesTo(Node other) { var intersectionSize = CountIntersection(other); SetRelation relation = 0; if (intersectionSize == 0) relation |= SetRelation.Disjoint; var containsThis = intersectionSize == Count; var containedInThis = intersectionSize == other.Count; if (containsThis && containedInThis) relation |= SetRelation.Equal; else if (containsThis) relation |= SetRelation.ProperSubsetOf; else if (containedInThis) relation |= SetRelation.ProperSupersetOf; else relation |= SetRelation.None; return relation; } public Node Except<TValue2>(HashedAvlTree<TKey, TValue2>.Node other, Lineage lin, ValueSelector<TKey, TValue, TValue2, Optional<TValue>> subtraction = null) { if (IsEmpty || other.IsEmpty) return this; if (ReferenceEquals(this, other) && subtraction == null) { return Empty; } Node thisLesser, thisGreater; Node central; Split(other.Hash, out thisLesser, out central, out thisGreater, lin); var thisLesserCount = thisLesser.Count; var thisGreaterCount = thisGreater.Count; var exceptLesser = thisLesser.Except(other.Left, lin,subtraction); var exceptBucket = central == null ? null : central.Bucket.Except(other.Bucket, lin, subtraction); var exceptGreater = thisGreater.Except(other.Right, lin, subtraction); var exceptLesserCount = exceptLesser.Count; var exceptGreaterCount = exceptGreater.Count; Node ret; if (exceptBucket == null || exceptBucket.IsEmpty) { ret = Concat(exceptLesser, exceptGreater, lin); } else { ret = Concat(exceptLesser, central.WithBucket(exceptBucket, lin), exceptGreater, lin); } #if ASSERTS AssertEx.AssertTrue(exceptLesserCount <= thisLesserCount); AssertEx.AssertTrue(exceptGreaterCount <= thisGreaterCount); AssertEx.AssertTrue(exceptGreaterCount + exceptLesserCount <= thisLesserCount + thisGreaterCount); AssertEx.AssertTrue(ret.IsBalanced); #endif return ret; } public bool IsSupersetOf(Node other) { if (other.NodeCount > NodeCount) return false; if (other.Count > Count) return false; var iter = new TreeIterator(this); //The idea is tht we go over the nodes in order of hash, from smallest to largest. //If we find a node in `other` that is smaller than the current node in `this //This means that node doesn't exist in `this` at all, so it isn't a superset. return other.ForEachWhileNode(node => { if (!iter.MoveNext()) return false; var cur = iter.Current; if (node.Hash > cur.Hash) { while (node.Hash > iter.Current.Hash) { if (!iter.MoveNext()) { return false; } } cur = iter.Current; } if (node.Hash < cur.Hash) return false; var result = node.Bucket.ForEachWhile((k, v) => cur.Bucket.Find(k).IsSome); return result; }); } public bool IsDisjoint(Node other) { var areDisjoint = true; var iter = other.Pairs.GetEnumerator(); ForEachWhile((k, v) => { if (!iter.MoveNext()) return false; if (Eq.Equals(k, iter.Current.Key)) { areDisjoint = false; return false; } return true; }); return areDisjoint; } public bool ForEachWhileNode(Func<Node, bool> iter) { if (IsEmpty) return true; return Left.ForEachWhileNode(iter) && iter(this) && Right.ForEachWhileNode(iter); } public Node SymDifference(Node b, Lineage lin) { #if ASSERTS var expected = Pairs.Select(x => x.Key).ToHashSet(Eq); expected.SymmetricExceptWith(b.Pairs.Select(x => x.Key)); #endif var ret = Except(b, lin).Union(b.Except(this, lin), lin); #if ASSERTS ret.Pairs.Select(x => x.Key).ToHashSet(Eq).SetEquals(expected).AssertTrue(); #endif return ret; } public Node Union(Node b, Lineage lin, ValueSelector<TKey, TValue, TValue, TValue> collision = null) { if (IsEmpty) return b; if (b.IsEmpty) return this; if (ReferenceEquals(this, b) && collision == null) { return this; } var myCount = Count; var bCount = b.Count; #if ASSERTS var expected = Pairs.Select(x => x.Key).ToHashSet(Eq); var oldContents = b.Pairs.Select(x => x.Key).ToArray(); expected.UnionWith(oldContents); #endif Node aLesser, aGreater; Node centerNode; Split(b.Hash, out aLesser, out centerNode, out aGreater, lin); var unitedLeft = aLesser.Union(b.Left, lin, collision); if (centerNode == null) centerNode = b; else { var newBucket = centerNode.Bucket.Union(b.Bucket, collision, lin); centerNode = centerNode.WithBucket(newBucket, lin); } var unitedRight = aGreater.Union(b.Right, lin, collision); var concated = Concat(unitedLeft, centerNode, unitedRight, lin); #if ASSERTS AssertEx.AssertTrue(concated.Count <= myCount + bCount); AssertEx.AssertTrue(concated.Count >= myCount); AssertEx.AssertTrue(concated.Count >= bCount); AssertEx.AssertTrue(concated.IsBalanced); var hs = concated.Pairs.Select(x => x.Key).ToHashSet(Eq); hs.SetEquals(expected).AssertTrue(); #endif return concated; } public static Node FromSortedList(List<StructTuple<int, Bucket>> sorted, int startIndex, int endIndex, Lineage lineage) { if (startIndex > endIndex) return Empty; var pivotIndex = startIndex + (endIndex - startIndex) / 2; var left = FromSortedList(sorted, startIndex, pivotIndex - 1, lineage); var right = FromSortedList(sorted, pivotIndex + 1, endIndex, lineage); var pivot = sorted[pivotIndex]; return new Node(pivot.First, pivot.Second, left, right, pivot.Second.Eq, lineage); } public IEnumerable<StructTuple<Node, Node>> IntersectElements(Node other) { if (IsEmpty || other.IsEmpty) yield break; var aIterator = new TreeIterator(this); var bIterator = new TreeIterator(other); var success = aIterator.MoveNext(); var pivotInA = true; var pivot = aIterator.Current; while (!aIterator.IsEnded || !bIterator.IsEnded) { var trySeekIn = pivotInA ? bIterator : aIterator; success = trySeekIn.SeekGreaterThan(pivot.Hash); if (!success) break; var maybePivot = trySeekIn.Current; if (maybePivot.Hash == pivot.Hash) { yield return pivotInA ? StructTuple.Create(pivot, maybePivot) : StructTuple.Create(maybePivot, pivot); pivotInA = !pivotInA; trySeekIn = pivotInA ? aIterator : bIterator; success = trySeekIn.MoveNext(); if (!success) break; pivot = trySeekIn.Current; } else { pivot = maybePivot; pivotInA = !pivotInA; //If the pivot was in X, it's now in Y... } } } private bool Debug_Intersect(List<TKey> result, Node other) { var kvps = result.ToHashSet(Eq); var list = new HashSet<TKey>(Eq); foreach (var item in Pairs) if (other.Root_Contains(item.Key)) list.Add(item.Key); var ret = kvps.SetEquals(list); if (!ret) Debugger.Break(); return ret; } public Node Intersect(Node other, Lineage lineage, ValueSelector<TKey, TValue, TValue, TValue> collision = null) { var intersection = IntersectElements(other); var list = new List<StructTuple<int, Bucket>>(); #if ASSERTS var hsMe = AllBuckets.Select(x => x.Key).ToHashSet(Eq); var hsOther = other.AllBuckets.Select(x => x.Key).ToHashSet(Eq); hsMe.IntersectWith(hsOther); #endif foreach (var pair in intersection) { var newBucket = pair.First.Bucket.Intersect(pair.Second.Bucket, lineage, collision); if (!newBucket.IsEmpty) list.Add(StructTuple.Create(pair.First.Hash, newBucket)); } #if ASSERTS var duplicates = list.Select(x => new {x, count = list.Count(y => y.First.Equals(x.First))}).OrderByDescending(x => x.count); list.Count.AssertEqual(x => x <= Count && x <= other.Count); Debug_Intersect(list.SelectMany(x => x.Second.Buckets.Select(y => y.Key)).ToList(), other); #endif return FromSortedList(list, 0, list.Count - 1, lineage); } public Node ExtractMax(out Node max, Lineage lineage) { if (IsEmpty) throw ImplErrors.Invalid_invocation("EmptyNode"); if (!Right.IsEmpty) return AvlBalance(Left, Right.ExtractMax(out max, lineage), lineage); max = this; return Left; } public Optional<TValue> Root_Find(TKey key) { var hash = key.GetHashCode(); return Find(hash, key); } public Optional<KeyValuePair<TKey, TValue>> Root_FindKvp(TKey key) { var hash = key.GetHashCode(); return FindKvp(hash, key); } public Optional<TValue> Find(int hash, TKey key) { var cur = this; while (!cur.IsEmpty) { if (hash < cur.Hash) { cur = cur.Left; } else if (hash > cur.Hash) cur = cur.Right; else return cur.Bucket.Find(key); } return Optional.None; } public Optional<KeyValuePair<TKey, TValue>> FindKvp(int hash, TKey key) { var cur = this; while (!cur.IsEmpty) { if (hash < cur.Hash) { cur = cur.Left; } else if (hash > cur.Hash) cur = cur.Right; else return cur.Bucket.FindKvp(key); } return Optional.None; } public HashedAvlTree<TKey, TValue2>.Node Apply<TValue2>(Func<TKey, TValue, TValue2> selector, Lineage lineage) { if (IsEmpty) return HashedAvlTree<TKey, TValue2>.Node.Empty; var defaultNull = HashedAvlTree<TKey, TValue2>.Node.Empty; var appliedLeft = Left.IsEmpty ? defaultNull : Left.Apply(selector, lineage); var appliedBucket = Bucket.Apply(selector, lineage); var appliedRight = Right.IsEmpty ? defaultNull : Right.Apply(selector, lineage); return new HashedAvlTree<TKey, TValue2>.Node(Hash, appliedBucket, appliedLeft, appliedRight, Eq, lineage); } public bool ForEachWhile(Func<TKey, TValue, bool> act) { if (IsEmpty) return true; return Left.ForEachWhile(act) && Bucket.ForEachWhile(act) && Right.ForEachWhile(act); } private Node AvlErase(Lineage lineage) { var leftEmpty = Left.IsEmpty; var rightEmpty = Right.IsEmpty; if (leftEmpty) return Right; if (rightEmpty) return Left; Node rep; var newRight = Right; var newLeft = Left; if (Left.Height > Right.Height) newRight = Right.ExtractMin(out rep, lineage); else newLeft = Left.ExtractMax(out rep, lineage); return rep.AvlBalance(newLeft, newRight, lineage); } public Node AvlRemove(int hash, TKey key, Lineage lineage) { Node ret; var oldCount = Count; if (IsEmpty) return null; if (hash < Hash) { var newLeft = Left.AvlRemove(hash, key, lineage); if (newLeft == null) return null; ret = AvlBalance(newLeft, Right, lineage); } else if (hash > Hash) { var newRight = Right.AvlRemove(hash, key, lineage); if (newRight == null) return null; ret = AvlBalance(Left, newRight, lineage); } else { var newBucket = Bucket.Remove(key, lineage); if (newBucket == null) return null; ret = !newBucket.IsEmpty ? WithBucket(newBucket, lineage) : AvlErase(lineage); } #if ASSERTS ret.Count.AssertEqual(oldCount - 1); #endif return ret; } } } }
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using CoinSharp.Store; using NUnit.Framework; namespace CoinSharp.Test { [TestFixture] public class WalletTest { private static readonly NetworkParameters _params = NetworkParameters.UnitTests(); private Address _myAddress; private Wallet _wallet; private IBlockStore _blockStore; [SetUp] public void SetUp() { var myKey = new EcKey(); _myAddress = myKey.ToAddress(_params); _wallet = new Wallet(_params); _wallet.AddKey(myKey); _blockStore = new MemoryBlockStore(_params); } [TearDown] public void TearDown() { _blockStore.Dispose(); } [Test] public void BasicSpending() { // We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change. var v1 = Utils.ToNanoCoins(1, 0); var t1 = TestUtils.CreateFakeTx(_params, v1, _myAddress); _wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain); Assert.AreEqual(v1, _wallet.GetBalance()); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent)); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All)); var k2 = new EcKey(); var v2 = Utils.ToNanoCoins(0, 50); var t2 = _wallet.CreateSend(k2.ToAddress(_params), v2); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent)); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All)); // Do some basic sanity checks. Assert.AreEqual(1, t2.Inputs.Count); Assert.AreEqual(_myAddress, t2.Inputs[0].ScriptSig.FromAddress); // We have NOT proven that the signature is correct! _wallet.ConfirmSend(t2); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Pending)); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Spent)); Assert.AreEqual(2, _wallet.GetPoolSize(Wallet.Pool.All)); } [Test] public void SideChain() { // The wallet receives a coin on the main chain, then on a side chain. Only main chain counts towards balance. var v1 = Utils.ToNanoCoins(1, 0); var t1 = TestUtils.CreateFakeTx(_params, v1, _myAddress); _wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain); Assert.AreEqual(v1, _wallet.GetBalance()); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent)); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All)); var v2 = Utils.ToNanoCoins(0, 50); var t2 = TestUtils.CreateFakeTx(_params, v2, _myAddress); _wallet.Receive(t2, null, BlockChain.NewBlockType.SideChain); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Inactive)); Assert.AreEqual(2, _wallet.GetPoolSize(Wallet.Pool.All)); Assert.AreEqual(v1, _wallet.GetBalance()); } [Test] public void Listener() { var fakeTx = TestUtils.CreateFakeTx(_params, Utils.ToNanoCoins(1, 0), _myAddress); var didRun = false; _wallet.CoinsReceived += (sender, e) => { Assert.IsTrue(e.PrevBalance.Equals(0)); Assert.IsTrue(e.NewBalance.Equals(Utils.ToNanoCoins(1, 0))); Assert.AreEqual(e.Tx, fakeTx); Assert.AreEqual(sender, _wallet); didRun = true; }; _wallet.Receive(fakeTx, null, BlockChain.NewBlockType.BestChain); Assert.IsTrue(didRun); } [Test] public void Balance() { // Receive 5 coins then half a coin. var v1 = Utils.ToNanoCoins(5, 0); var v2 = Utils.ToNanoCoins(0, 50); var t1 = TestUtils.CreateFakeTx(_params, v1, _myAddress); var t2 = TestUtils.CreateFakeTx(_params, v2, _myAddress); var b1 = TestUtils.CreateFakeBlock(_params, _blockStore, t1).StoredBlock; var b2 = TestUtils.CreateFakeBlock(_params, _blockStore, t2).StoredBlock; var expected = Utils.ToNanoCoins(5, 50); _wallet.Receive(t1, b1, BlockChain.NewBlockType.BestChain); _wallet.Receive(t2, b2, BlockChain.NewBlockType.BestChain); Assert.AreEqual(expected, _wallet.GetBalance()); // Now spend one coin. var v3 = Utils.ToNanoCoins(1, 0); var spend = _wallet.CreateSend(new EcKey().ToAddress(_params), v3); _wallet.ConfirmSend(spend); // Available and estimated balances should not be the same. We don't check the exact available balance here // because it depends on the coin selection algorithm. Assert.AreEqual(Utils.ToNanoCoins(4, 50), _wallet.GetBalance(Wallet.BalanceType.Estimated)); Assert.IsFalse(_wallet.GetBalance(Wallet.BalanceType.Available).Equals( _wallet.GetBalance(Wallet.BalanceType.Estimated))); // Now confirm the transaction by including it into a block. var b3 = TestUtils.CreateFakeBlock(_params, _blockStore, spend).StoredBlock; _wallet.Receive(spend, b3, BlockChain.NewBlockType.BestChain); // Change is confirmed. We started with 5.50 so we should have 4.50 left. var v4 = Utils.ToNanoCoins(4, 50); Assert.AreEqual(v4, _wallet.GetBalance(Wallet.BalanceType.Available)); } // Intuitively you'd expect to be able to create a transaction with identical inputs and outputs and get an // identical result to the official client. However the signatures are not deterministic - signing the same data // with the same key twice gives two different outputs. So we cannot prove bit-for-bit compatibility in this test // suite. [Test] public void BlockChainCatchup() { var tx1 = TestUtils.CreateFakeTx(_params, Utils.ToNanoCoins(1, 0), _myAddress); var b1 = TestUtils.CreateFakeBlock(_params, _blockStore, tx1).StoredBlock; _wallet.Receive(tx1, b1, BlockChain.NewBlockType.BestChain); // Send 0.10 to somebody else. var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress); // Pretend it makes it into the block chain, our wallet state is cleared but we still have the keys, and we // want to get back to our previous state. We can do this by just not confirming the transaction as // createSend is stateless. var b2 = TestUtils.CreateFakeBlock(_params, _blockStore, send1).StoredBlock; _wallet.Receive(send1, b2, BlockChain.NewBlockType.BestChain); Assert.AreEqual(Utils.BitcoinValueToFriendlystring(_wallet.GetBalance()), "0.90"); // And we do it again after the catch-up. var send2 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress); // What we'd really like to do is prove the official client would accept it .... no such luck unfortunately. _wallet.ConfirmSend(send2); var b3 = TestUtils.CreateFakeBlock(_params, _blockStore, send2).StoredBlock; _wallet.Receive(send2, b3, BlockChain.NewBlockType.BestChain); Assert.AreEqual(Utils.BitcoinValueToFriendlystring(_wallet.GetBalance()), "0.80"); } [Test] public void Balances() { var nanos = Utils.ToNanoCoins(1, 0); var tx1 = TestUtils.CreateFakeTx(_params, nanos, _myAddress); _wallet.Receive(tx1, null, BlockChain.NewBlockType.BestChain); Assert.AreEqual(nanos, tx1.GetValueSentToMe(_wallet, true)); // Send 0.10 to somebody else. var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress); // Re-serialize. var send2 = new Transaction(_params, send1.BitcoinSerialize()); Assert.AreEqual(nanos, send2.GetValueSentFromMe(_wallet)); } [Test] public void Transactions() { // This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly. var tx = TestUtils.CreateFakeTx(_params, Utils.ToNanoCoins(1, 0), _myAddress); // Now add another output (ie, change) that goes to some other address. var someOtherGuy = new EcKey().ToAddress(_params); var output = new TransactionOutput(_params, tx, Utils.ToNanoCoins(0, 5), someOtherGuy); tx.AddOutput(output); // Note that tx is no longer valid: it spends more than it imports. However checking transactions balance // correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all // transactions you can't check they add up. _wallet.Receive(tx, null, BlockChain.NewBlockType.BestChain); // Now the other guy creates a transaction which spends that change. var tx2 = new Transaction(_params); tx2.AddInput(output); tx2.AddOutput(new TransactionOutput(_params, tx2, Utils.ToNanoCoins(0, 5), _myAddress)); // tx2 doesn't send any coins from us, even though the output is in the wallet. Assert.AreEqual(Utils.ToNanoCoins(0, 0), tx2.GetValueSentFromMe(_wallet)); } [Test] public void Bounce() { // This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent // back to us, this isn't considered as a double spend. var coin1 = Utils.ToNanoCoins(1, 0); var coinHalf = Utils.ToNanoCoins(0, 50); // Start by giving us 1 coin. var inbound1 = TestUtils.CreateFakeTx(_params, coin1, _myAddress); _wallet.Receive(inbound1, null, BlockChain.NewBlockType.BestChain); // Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is // in the unspent pool, not pending or spent. Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent)); Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All)); var someOtherGuy = new EcKey().ToAddress(_params); var outbound1 = _wallet.CreateSend(someOtherGuy, coinHalf); _wallet.ConfirmSend(outbound1); _wallet.Receive(outbound1, null, BlockChain.NewBlockType.BestChain); // That other guy gives us the coins right back. var inbound2 = new Transaction(_params); inbound2.AddOutput(new TransactionOutput(_params, inbound2, coinHalf, _myAddress)); inbound2.AddInput(outbound1.Outputs[0]); _wallet.Receive(inbound2, null, BlockChain.NewBlockType.BestChain); Assert.AreEqual(coin1, _wallet.GetBalance()); } [Test] public void FinneyAttack() { // A Finney attack is where a miner includes a transaction spending coins to themselves but does not // broadcast it. When they find a solved block, they hold it back temporarily whilst they buy something with // those same coins. After purchasing, they broadcast the block thus reversing the transaction. It can be // done by any miner for products that can be bought at a chosen time and very quickly (as every second you // withhold your block means somebody else might find it first, invalidating your work). // // Test that we handle ourselves performing the attack correctly: a double spend on the chain moves // transactions from pending to dead. // // Note that the other way around, where a pending transaction sending us coins becomes dead, // isn't tested because today BitCoinJ only learns about such transactions when they appear in the chain. Transaction eventDead = null; Transaction eventReplacement = null; _wallet.DeadTransaction += (sender, e) => { eventDead = e.DeadTx; eventReplacement = e.ReplacementTx; }; // Receive 1 BTC. var nanos = Utils.ToNanoCoins(1, 0); var t1 = TestUtils.CreateFakeTx(_params, nanos, _myAddress); _wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain); // Create a send to a merchant. var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 50)); // Create a double spend. var send2 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 50)); // Broadcast send1. _wallet.ConfirmSend(send1); // Receive a block that overrides it. _wallet.Receive(send2, null, BlockChain.NewBlockType.BestChain); Assert.AreEqual(send1, eventDead); Assert.AreEqual(send2, eventReplacement); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class LambdaAddTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddByteTest(bool useInterpreter) { byte[] values = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddDecimalTest(bool useInterpreter) { decimal[] values = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddDoubleTest(bool useInterpreter) { double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddFloatTest(bool useInterpreter) { float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddIntTest(bool useInterpreter) { int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddLongTest(bool useInterpreter) { long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddShortTest(bool useInterpreter) { short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddUIntTest(bool useInterpreter) { uint[] values = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddULongTest(bool useInterpreter) { ulong[] values = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaAddUShortTest(bool useInterpreter) { ushort[] values = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyAddUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers #region Verify byte private static void VerifyAddByte(byte a, byte b, bool useInterpreter) { byte expected = unchecked((byte)(a + b)); ParameterExpression p0 = Expression.Parameter(typeof(int), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(int), "p1"); // verify with parameters supplied Expression<Func<int>> e1 = Expression.Lambda<Func<int>>( Expression.Invoke( Expression.Lambda<Func<int, int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant((int)a, typeof(int)), Expression.Constant((int)b, typeof(int)) }), Enumerable.Empty<ParameterExpression>()); Func<int> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, unchecked((byte)f1())); // verify with values passed to make parameters Expression<Func<int, int, Func<int>>> e2 = Expression.Lambda<Func<int, int, Func<int>>>( Expression.Lambda<Func<int>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<int, int, Func<int>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, unchecked((byte)f2(a, b)())); // verify with values directly passed Expression<Func<Func<int, int, int>>> e3 = Expression.Lambda<Func<Func<int, int, int>>>( Expression.Invoke( Expression.Lambda<Func<Func<int, int, int>>>( Expression.Lambda<Func<int, int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<int, int, int> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, unchecked((byte)f3(a, b))); // verify as a function generator Expression<Func<Func<int, int, int>>> e4 = Expression.Lambda<Func<Func<int, int, int>>>( Expression.Lambda<Func<int, int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<int, int, int>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, unchecked((byte)f4()(a, b))); // verify with currying Expression<Func<int, Func<int, int>>> e5 = Expression.Lambda<Func<int, Func<int, int>>>( Expression.Lambda<Func<int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<int, Func<int, int>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, unchecked((byte)f5(a)(b))); // verify with one parameter Expression<Func<Func<int, int>>> e6 = Expression.Lambda<Func<Func<int, int>>>( Expression.Invoke( Expression.Lambda<Func<int, Func<int, int>>>( Expression.Lambda<Func<int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant((int)a, typeof(int)) }), Enumerable.Empty<ParameterExpression>()); Func<int, int> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, unchecked((byte)f6(b))); } #endregion #region Verify decimal private static void VerifyAddDecimal(decimal a, decimal b, bool useInterpreter) { bool overflows; decimal expected; try { expected = a + b; overflows = false; } catch (OverflowException) { expected = 0; overflows = true; } ParameterExpression p0 = Expression.Parameter(typeof(decimal), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(decimal), "p1"); // verify with parameters supplied Expression<Func<decimal>> e1 = Expression.Lambda<Func<decimal>>( Expression.Invoke( Expression.Lambda<Func<decimal, decimal, decimal>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal> f1 = e1.Compile(useInterpreter); if (overflows) { Assert.Throws<OverflowException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<decimal, decimal, Func<decimal>>> e2 = Expression.Lambda<Func<decimal, decimal, Func<decimal>>>( Expression.Lambda<Func<decimal>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<decimal, decimal, Func<decimal>> f2 = e2.Compile(useInterpreter); if (overflows) { Assert.Throws<OverflowException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<decimal, decimal, decimal>>> e3 = Expression.Lambda<Func<Func<decimal, decimal, decimal>>>( Expression.Invoke( Expression.Lambda<Func<Func<decimal, decimal, decimal>>>( Expression.Lambda<Func<decimal, decimal, decimal>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<decimal, decimal, decimal> f3 = e3.Compile(useInterpreter)(); if (overflows) { Assert.Throws<OverflowException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<decimal, decimal, decimal>>> e4 = Expression.Lambda<Func<Func<decimal, decimal, decimal>>>( Expression.Lambda<Func<decimal, decimal, decimal>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<decimal, decimal, decimal>> f4 = e4.Compile(useInterpreter); if (overflows) { Assert.Throws<OverflowException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<decimal, Func<decimal, decimal>>> e5 = Expression.Lambda<Func<decimal, Func<decimal, decimal>>>( Expression.Lambda<Func<decimal, decimal>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<decimal, Func<decimal, decimal>> f5 = e5.Compile(useInterpreter); if (overflows) { Assert.Throws<OverflowException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<decimal, decimal>>> e6 = Expression.Lambda<Func<Func<decimal, decimal>>>( Expression.Invoke( Expression.Lambda<Func<decimal, Func<decimal, decimal>>>( Expression.Lambda<Func<decimal, decimal>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(decimal)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal, decimal> f6 = e6.Compile(useInterpreter)(); if (overflows) { Assert.Throws<OverflowException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify double private static void VerifyAddDouble(double a, double b, bool useInterpreter) { double expected = a + b; ParameterExpression p0 = Expression.Parameter(typeof(double), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(double), "p1"); // verify with parameters supplied Expression<Func<double>> e1 = Expression.Lambda<Func<double>>( Expression.Invoke( Expression.Lambda<Func<double, double, double>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double)) }), Enumerable.Empty<ParameterExpression>()); Func<double> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<double, double, Func<double>>> e2 = Expression.Lambda<Func<double, double, Func<double>>>( Expression.Lambda<Func<double>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<double, double, Func<double>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<double, double, double>>> e3 = Expression.Lambda<Func<Func<double, double, double>>>( Expression.Invoke( Expression.Lambda<Func<Func<double, double, double>>>( Expression.Lambda<Func<double, double, double>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<double, double, double> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<double, double, double>>> e4 = Expression.Lambda<Func<Func<double, double, double>>>( Expression.Lambda<Func<double, double, double>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<double, double, double>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<double, Func<double, double>>> e5 = Expression.Lambda<Func<double, Func<double, double>>>( Expression.Lambda<Func<double, double>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<double, Func<double, double>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<double, double>>> e6 = Expression.Lambda<Func<Func<double, double>>>( Expression.Invoke( Expression.Lambda<Func<double, Func<double, double>>>( Expression.Lambda<Func<double, double>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(double)) }), Enumerable.Empty<ParameterExpression>()); Func<double, double> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify float private static void VerifyAddFloat(float a, float b, bool useInterpreter) { float expected = a + b; ParameterExpression p0 = Expression.Parameter(typeof(float), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(float), "p1"); // verify with parameters supplied Expression<Func<float>> e1 = Expression.Lambda<Func<float>>( Expression.Invoke( Expression.Lambda<Func<float, float, float>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float)) }), Enumerable.Empty<ParameterExpression>()); Func<float> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<float, float, Func<float>>> e2 = Expression.Lambda<Func<float, float, Func<float>>>( Expression.Lambda<Func<float>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<float, float, Func<float>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<float, float, float>>> e3 = Expression.Lambda<Func<Func<float, float, float>>>( Expression.Invoke( Expression.Lambda<Func<Func<float, float, float>>>( Expression.Lambda<Func<float, float, float>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<float, float, float> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<float, float, float>>> e4 = Expression.Lambda<Func<Func<float, float, float>>>( Expression.Lambda<Func<float, float, float>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<float, float, float>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<float, Func<float, float>>> e5 = Expression.Lambda<Func<float, Func<float, float>>>( Expression.Lambda<Func<float, float>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<float, Func<float, float>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<float, float>>> e6 = Expression.Lambda<Func<Func<float, float>>>( Expression.Invoke( Expression.Lambda<Func<float, Func<float, float>>>( Expression.Lambda<Func<float, float>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(float)) }), Enumerable.Empty<ParameterExpression>()); Func<float, float> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify int private static void VerifyAddInt(int a, int b, bool useInterpreter) { int expected = unchecked(a + b); ParameterExpression p0 = Expression.Parameter(typeof(int), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(int), "p1"); // verify with parameters supplied Expression<Func<int>> e1 = Expression.Lambda<Func<int>>( Expression.Invoke( Expression.Lambda<Func<int, int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int)) }), Enumerable.Empty<ParameterExpression>()); Func<int> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<int, int, Func<int>>> e2 = Expression.Lambda<Func<int, int, Func<int>>>( Expression.Lambda<Func<int>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<int, int, Func<int>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<int, int, int>>> e3 = Expression.Lambda<Func<Func<int, int, int>>>( Expression.Invoke( Expression.Lambda<Func<Func<int, int, int>>>( Expression.Lambda<Func<int, int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<int, int, int> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<int, int, int>>> e4 = Expression.Lambda<Func<Func<int, int, int>>>( Expression.Lambda<Func<int, int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<int, int, int>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<int, Func<int, int>>> e5 = Expression.Lambda<Func<int, Func<int, int>>>( Expression.Lambda<Func<int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<int, Func<int, int>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<int, int>>> e6 = Expression.Lambda<Func<Func<int, int>>>( Expression.Invoke( Expression.Lambda<Func<int, Func<int, int>>>( Expression.Lambda<Func<int, int>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(int)) }), Enumerable.Empty<ParameterExpression>()); Func<int, int> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify long private static void VerifyAddLong(long a, long b, bool useInterpreter) { long expected = unchecked(a + b); ParameterExpression p0 = Expression.Parameter(typeof(long), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(long), "p1"); // verify with parameters supplied Expression<Func<long>> e1 = Expression.Lambda<Func<long>>( Expression.Invoke( Expression.Lambda<Func<long, long, long>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long)) }), Enumerable.Empty<ParameterExpression>()); Func<long> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<long, long, Func<long>>> e2 = Expression.Lambda<Func<long, long, Func<long>>>( Expression.Lambda<Func<long>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<long, long, Func<long>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<long, long, long>>> e3 = Expression.Lambda<Func<Func<long, long, long>>>( Expression.Invoke( Expression.Lambda<Func<Func<long, long, long>>>( Expression.Lambda<Func<long, long, long>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<long, long, long> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<long, long, long>>> e4 = Expression.Lambda<Func<Func<long, long, long>>>( Expression.Lambda<Func<long, long, long>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<long, long, long>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<long, Func<long, long>>> e5 = Expression.Lambda<Func<long, Func<long, long>>>( Expression.Lambda<Func<long, long>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<long, Func<long, long>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<long, long>>> e6 = Expression.Lambda<Func<Func<long, long>>>( Expression.Invoke( Expression.Lambda<Func<long, Func<long, long>>>( Expression.Lambda<Func<long, long>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(long)) }), Enumerable.Empty<ParameterExpression>()); Func<long, long> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify short private static void VerifyAddShort(short a, short b, bool useInterpreter) { short expected = unchecked((short)(a + b)); ParameterExpression p0 = Expression.Parameter(typeof(short), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(short), "p1"); // verify with parameters supplied Expression<Func<short>> e1 = Expression.Lambda<Func<short>>( Expression.Invoke( Expression.Lambda<Func<short, short, short>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short)) }), Enumerable.Empty<ParameterExpression>()); Func<short> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<short, short, Func<short>>> e2 = Expression.Lambda<Func<short, short, Func<short>>>( Expression.Lambda<Func<short>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<short, short, Func<short>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<short, short, short>>> e3 = Expression.Lambda<Func<Func<short, short, short>>>( Expression.Invoke( Expression.Lambda<Func<Func<short, short, short>>>( Expression.Lambda<Func<short, short, short>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<short, short, short> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<short, short, short>>> e4 = Expression.Lambda<Func<Func<short, short, short>>>( Expression.Lambda<Func<short, short, short>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<short, short, short>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<short, Func<short, short>>> e5 = Expression.Lambda<Func<short, Func<short, short>>>( Expression.Lambda<Func<short, short>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<short, Func<short, short>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<short, short>>> e6 = Expression.Lambda<Func<Func<short, short>>>( Expression.Invoke( Expression.Lambda<Func<short, Func<short, short>>>( Expression.Lambda<Func<short, short>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(short)) }), Enumerable.Empty<ParameterExpression>()); Func<short, short> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify uint private static void VerifyAddUInt(uint a, uint b, bool useInterpreter) { uint expected = unchecked(a + b); ParameterExpression p0 = Expression.Parameter(typeof(uint), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(uint), "p1"); // verify with parameters supplied Expression<Func<uint>> e1 = Expression.Lambda<Func<uint>>( Expression.Invoke( Expression.Lambda<Func<uint, uint, uint>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint)) }), Enumerable.Empty<ParameterExpression>()); Func<uint> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<uint, uint, Func<uint>>> e2 = Expression.Lambda<Func<uint, uint, Func<uint>>>( Expression.Lambda<Func<uint>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<uint, uint, Func<uint>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<uint, uint, uint>>> e3 = Expression.Lambda<Func<Func<uint, uint, uint>>>( Expression.Invoke( Expression.Lambda<Func<Func<uint, uint, uint>>>( Expression.Lambda<Func<uint, uint, uint>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<uint, uint, uint> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<uint, uint, uint>>> e4 = Expression.Lambda<Func<Func<uint, uint, uint>>>( Expression.Lambda<Func<uint, uint, uint>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<uint, uint, uint>> f4 = e4.Compile(useInterpreter); uint f4Result = default(uint); Exception f4Ex = null; try { f4Result = f4()(a, b); } catch (Exception ex) { f4Ex = ex; } // verify with currying Expression<Func<uint, Func<uint, uint>>> e5 = Expression.Lambda<Func<uint, Func<uint, uint>>>( Expression.Lambda<Func<uint, uint>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<uint, Func<uint, uint>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<uint, uint>>> e6 = Expression.Lambda<Func<Func<uint, uint>>>( Expression.Invoke( Expression.Lambda<Func<uint, Func<uint, uint>>>( Expression.Lambda<Func<uint, uint>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(uint)) }), Enumerable.Empty<ParameterExpression>()); Func<uint, uint> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify ulong private static void VerifyAddULong(ulong a, ulong b, bool useInterpreter) { ulong expected = unchecked(a + b); ParameterExpression p0 = Expression.Parameter(typeof(ulong), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ulong), "p1"); // verify with parameters supplied Expression<Func<ulong>> e1 = Expression.Lambda<Func<ulong>>( Expression.Invoke( Expression.Lambda<Func<ulong, ulong, ulong>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<ulong, ulong, Func<ulong>>> e2 = Expression.Lambda<Func<ulong, ulong, Func<ulong>>>( Expression.Lambda<Func<ulong>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ulong, ulong, Func<ulong>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<ulong, ulong, ulong>>> e3 = Expression.Lambda<Func<Func<ulong, ulong, ulong>>>( Expression.Invoke( Expression.Lambda<Func<Func<ulong, ulong, ulong>>>( Expression.Lambda<Func<ulong, ulong, ulong>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ulong, ulong, ulong> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<ulong, ulong, ulong>>> e4 = Expression.Lambda<Func<Func<ulong, ulong, ulong>>>( Expression.Lambda<Func<ulong, ulong, ulong>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ulong, ulong, ulong>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<ulong, Func<ulong, ulong>>> e5 = Expression.Lambda<Func<ulong, Func<ulong, ulong>>>( Expression.Lambda<Func<ulong, ulong>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ulong, Func<ulong, ulong>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<ulong, ulong>>> e6 = Expression.Lambda<Func<Func<ulong, ulong>>>( Expression.Invoke( Expression.Lambda<Func<ulong, Func<ulong, ulong>>>( Expression.Lambda<Func<ulong, ulong>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ulong)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong, ulong> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify ushort private static void VerifyAddUShort(ushort a, ushort b, bool useInterpreter) { ushort expected = unchecked((ushort)(a + b)); ParameterExpression p0 = Expression.Parameter(typeof(ushort), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ushort), "p1"); // verify with parameters supplied Expression<Func<ushort>> e1 = Expression.Lambda<Func<ushort>>( Expression.Invoke( Expression.Lambda<Func<ushort, ushort, ushort>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<ushort, ushort, Func<ushort>>> e2 = Expression.Lambda<Func<ushort, ushort, Func<ushort>>>( Expression.Lambda<Func<ushort>>( Expression.Add(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ushort, ushort, Func<ushort>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<ushort, ushort, ushort>>> e3 = Expression.Lambda<Func<Func<ushort, ushort, ushort>>>( Expression.Invoke( Expression.Lambda<Func<Func<ushort, ushort, ushort>>>( Expression.Lambda<Func<ushort, ushort, ushort>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ushort, ushort, ushort> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<ushort, ushort, ushort>>> e4 = Expression.Lambda<Func<Func<ushort, ushort, ushort>>>( Expression.Lambda<Func<ushort, ushort, ushort>>( Expression.Add(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ushort, ushort, ushort>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<ushort, Func<ushort, ushort>>> e5 = Expression.Lambda<Func<ushort, Func<ushort, ushort>>>( Expression.Lambda<Func<ushort, ushort>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ushort, Func<ushort, ushort>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<ushort, ushort>>> e6 = Expression.Lambda<Func<Func<ushort, ushort>>>( Expression.Invoke( Expression.Lambda<Func<ushort, Func<ushort, ushort>>>( Expression.Lambda<Func<ushort, ushort>>( Expression.Add(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ushort)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort, ushort> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #endregion } }
using System; using System.Collections.Generic; #if SILVERLIGHT using System.Windows.Navigation; #endif using UAuth; namespace UAuthImpl { public class Auth : IAuth { public IOAuth1Authenticator auth1 { get; set; } public IOAuth2Authenticator auth2 { get; set; } #if __ANDROID__ public static Android.App.Activity context; public Auth(Android.App.Activity pContext) { context = pContext; #elif __IOS__ public static MonoTouch.Dialog.DialogViewController dialog; // not sure about static public Auth() { #elif SILVERLIGHT public Auth() { #endif new AccountStoreImpl(); // invoke static constructor auth1 = new OAuth1AuthenticatorImpl(); auth2 = new OAuth2AuthenticatorImpl(); } } public class BaseOAuth2Authenticator : Xamarin.Auth.OAuth2Authenticator { string replacementUrlFormat; public BaseOAuth2Authenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl) : base(clientId, scope, authorizeUrl, redirectUrl) { this.replacementUrlFormat = null; } public BaseOAuth2Authenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl, string replacementUrlFormat) : base(clientId, scope, authorizeUrl, redirectUrl) { this.replacementUrlFormat = replacementUrlFormat; } public BaseOAuth2Authenticator(string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl, GetUsernameAsyncFunc getUsernameAsync = null) : base(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl) { this.replacementUrlFormat = null; // replacementUrlFormat not implemented } protected async override void OnRedirectPageLoaded(Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment) { System.Diagnostics.Debug.WriteLine("OnRedirectPageLoaded url:" + url); foreach (KeyValuePair<string, string> p in query) System.Diagnostics.Debug.WriteLine("query: Key:" + p.Key + " Value:" + p.Value); foreach (KeyValuePair<string, string> p in fragment) System.Diagnostics.Debug.WriteLine("fragment: Key:" + p.Key + " Value:" + p.Value); await System.Threading.Tasks.Task.Delay(2000); // TODO: find another way to pause on redirect page. // Fixes SubstituteRedirectUrlAccessToken issue but just do for every site if (!fragment.Keys.Contains("access_token") && query.Keys.Contains("code")) // fixes missing access_token: GitHub, LinkedIn fragment.Add("access_token", query["code"]); base.OnRedirectPageLoaded(url, query, fragment); } public async override System.Threading.Tasks.Task<Uri> GetInitialUrlAsync() { // just return if no replacement requested if (string.IsNullOrEmpty(replacementUrlFormat)) return await base.GetInitialUrlAsync(); // get base class Uri System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: replacementUrlFormat:" + replacementUrlFormat); Uri uri = await base.GetInitialUrlAsync(); System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: base.uri:" + uri); // need to extract state query string from base Uri because its scope isn't public. string baseUrl = uri.OriginalString; int stateIndex = baseUrl.LastIndexOf("&state="); string requestState = baseUrl.Substring(stateIndex + "&state=".Length); // verify that the base Url is same as our supposedly identical procedure. If not, there must be a code change in a new version of base class. string redoUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}", AuthorizeUrl.AbsoluteUri, Uri.EscapeDataString(ClientId), Uri.EscapeDataString(RedirectUrl.AbsoluteUri), AccessTokenUrl == null ? "token" : "code", Uri.EscapeDataString(Scope), Uri.EscapeDataString(requestState)); if (baseUrl != redoUrl) throw new ArgumentException("GetInitialUrlAsync: Url comparison failure: base: " + baseUrl + " redo:" + redoUrl); // format replacement Uri uri = new Uri(string.Format( replacementUrlFormat, AuthorizeUrl.AbsoluteUri, Uri.EscapeDataString(ClientId), Uri.EscapeDataString(RedirectUrl.AbsoluteUri), AccessTokenUrl == null ? "token" : "code", Uri.EscapeDataString(Scope), Uri.EscapeDataString(requestState))); System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: replacement uri:" + uri); System.Threading.Tasks.TaskCompletionSource<Uri> tcs = new System.Threading.Tasks.TaskCompletionSource<Uri>(); tcs.SetResult(uri); return uri; } } public class OAuth1AuthenticatorImpl : IOAuth1Authenticator { public bool AllowCancel; public event EventHandler<AuthenticatorCompletedEventArgs> Completed; public event EventHandler<AuthenticatorErrorEventArgs> Error; private static readonly System.Threading.Tasks.TaskScheduler UIScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext(); public void OAuth1Authenticator(string consumerKey, string consumerSecret, Uri requestTokenUrl, Uri authorizeUrl, Uri accessTokenUrl, Uri callbackUrl, GetUsernameAsyncFunc getUsernameAsync) { Xamarin.Auth.OAuth1Authenticator auth1 = new Xamarin.Auth.OAuth1Authenticator(consumerKey, consumerSecret, requestTokenUrl, authorizeUrl, accessTokenUrl, callbackUrl, null); // TODO: getUsernameAsync argument not implemented auth1.AllowCancel = AllowCancel; auth1.Completed += (sender, eventArgs) => { Completed(auth1, new AuthenticatorCompletedEventArgs(new Account(eventArgs.Account, eventArgs.Account.Properties, eventArgs.Account.Username))); }; auth1.Error += (sender, eventArgs) => { Error(sender, new AuthenticatorErrorEventArgs(eventArgs.Message, eventArgs.Exception)); }; #if __ANDROID__ Android.Content.Intent intent = auth1.GetUI(Auth.context); Auth.context.StartActivity(intent); #elif __IOS__ UIKit.UIViewController vc = auth1.GetUI(); Auth.dialog.PresentViewController(vc, true, null); #elif SILVERLIGHT Uri uri = auth1.GetUI(); NavigationService.Navigate(uri); #endif } public IOAuth1Request OAuth1Request(string method, Uri url, Dictionary<string, string> parameters, Account account, bool includeMultipartInSignature = false) { Xamarin.Auth.OAuth1Request xrequest = new Xamarin.Auth.OAuth1Request(method, url, parameters, (Xamarin.Auth.Account)account.xAccount, includeMultipartInSignature); return new OAuth1RequestImpl(xrequest); } } public class OAuth1RequestImpl : IOAuth1Request { public Xamarin.Auth.OAuth1Request xrequest; public OAuth1RequestImpl(Xamarin.Auth.OAuth1Request xrequest) { this.xrequest = xrequest; } public System.Threading.Tasks.Task<IResponse> GetResponseAsync() { System.Threading.Tasks.TaskCompletionSource<IResponse> tcs = new System.Threading.Tasks.TaskCompletionSource<IResponse>(); tcs.SetResult(new ResponseImpl(xrequest.GetResponseAsync())); return tcs.Task; } public System.Threading.Tasks.Task<IResponse> GetResponseAsync(System.Threading.CancellationToken cancellationToken) { System.Threading.Tasks.TaskCompletionSource<IResponse> tcs = new System.Threading.Tasks.TaskCompletionSource<IResponse>(); tcs.SetResult(new ResponseImpl(xrequest.GetResponseAsync(cancellationToken))); return tcs.Task; } } public class OAuth2AuthenticatorImpl : IOAuth2Authenticator { public bool AllowCancel; public event EventHandler<AuthenticatorCompletedEventArgs> Completed; public event EventHandler<AuthenticatorErrorEventArgs> Error; private static readonly System.Threading.Tasks.TaskScheduler UIScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext(); public void OAuth2Authenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl) { Xamarin.Auth.OAuth2Authenticator auth2 = new BaseOAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl); auth2.AllowCancel = AllowCancel; auth2.Completed += (sender, eventArgs) => { Completed(auth2, new AuthenticatorCompletedEventArgs(new Account(eventArgs.Account, eventArgs.Account.Properties, eventArgs.Account.Username))); }; auth2.Error += (sender, eventArgs) => { Error(sender, new AuthenticatorErrorEventArgs(eventArgs.Message, eventArgs.Exception)); }; #if __ANDROID__ Android.Content.Intent intent = auth2.GetUI(Auth.context); Auth.context.StartActivity(intent); #elif __IOS__ UIKit.UIViewController vc = auth2.GetUI(); Auth.dialog.PresentViewController(vc, true, null); #elif SILVERLIGHT Uri uri = auth2.GetUI(); NavigationService.Navigate(uri); #endif } public void OAuth2Authenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl, string replacementFormatUrl) { Xamarin.Auth.OAuth2Authenticator auth2 = new BaseOAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl, replacementFormatUrl); auth2.AllowCancel = AllowCancel; auth2.Completed += (sender, eventArgs) => { Completed(auth2, new AuthenticatorCompletedEventArgs(new Account(eventArgs.Account, eventArgs.Account.Properties, eventArgs.Account.Username))); }; auth2.Error += (sender, eventArgs) => { Error(sender, new AuthenticatorErrorEventArgs(eventArgs.Message, eventArgs.Exception)); }; #if __ANDROID__ Android.Content.Intent intent = auth2.GetUI(Auth.context); Auth.context.StartActivity(intent); #elif __IOS__ UIKit.UIViewController vc = auth2.GetUI(); Auth.dialog.PresentViewController(vc, true, null); #elif SILVERLIGHT Uri uri = auth2.GetUI(); NavigationService.Navigate(uri); #endif } public void OAuth2Authenticator(string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl, GetUsernameAsyncFunc getUsernameAsync = null) { Xamarin.Auth.OAuth2Authenticator auth2 = new BaseOAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null); // TODO: getUsernameAsync argument not implemented auth2.AllowCancel = AllowCancel; auth2.Completed += (sender, eventArgs) => { Completed(auth2, new AuthenticatorCompletedEventArgs(new Account(eventArgs.Account, eventArgs.Account.Properties, eventArgs.Account.Username))); }; #if __ANDROID__ Android.Content.Intent intent = auth2.GetUI(Auth.context); Auth.context.StartActivity(intent); #elif __IOS__ UIKit.UIViewController vc = auth2.GetUI(); Auth.dialog.PresentViewController(vc, true, null); #elif SILVERLIGHT Uri uri = auth2.GetUI(); NavigationService.Navigate(uri); #endif } public IOAuth2Request OAuth2Request(string method, Uri url, Dictionary<string, string> parameters, Account account) { Xamarin.Auth.OAuth2Request xrequest = new Xamarin.Auth.OAuth2Request(method, url, parameters, (Xamarin.Auth.Account)account.xAccount); return new OAuth2RequestImpl(xrequest); } } public class OAuth2RequestImpl : IOAuth2Request { public Xamarin.Auth.OAuth2Request xrequest; public OAuth2RequestImpl(Xamarin.Auth.OAuth2Request xrequest) { this.xrequest = xrequest; } public System.Threading.Tasks.Task<IResponse> GetResponseAsync() { System.Threading.Tasks.TaskCompletionSource<IResponse> tcs = new System.Threading.Tasks.TaskCompletionSource<IResponse>(); tcs.SetResult(new ResponseImpl(xrequest.GetResponseAsync())); return tcs.Task; } public System.Threading.Tasks.Task<IResponse> GetResponseAsync(System.Threading.CancellationToken cancellationToken) { System.Threading.Tasks.TaskCompletionSource<IResponse> tcs = new System.Threading.Tasks.TaskCompletionSource<IResponse>(); tcs.SetResult(new ResponseImpl(xrequest.GetResponseAsync(cancellationToken))); return tcs.Task; } public string AccessTokenParameterName { get { return xrequest.AccessTokenParameterName; } set { xrequest.AccessTokenParameterName = value; } } } public class ResponseImpl : IResponse { public System.Threading.Tasks.Task<Xamarin.Auth.Response> xresponse; public ResponseImpl(System.Threading.Tasks.Task<Xamarin.Auth.Response> xresponse) { this.xresponse = xresponse; } public IDictionary<string, string> Headers { get { xresponse.Wait(); return xresponse.Result.Headers; } } public Uri ResponseUri { get { xresponse.Wait(); return xresponse.Result.ResponseUri; } } public int StatusCode { get { xresponse.Wait(); return (int)xresponse.Result.StatusCode; } } // should be Net.HttpStatusCode //public IO.Stream GetResponseStream() { return xresponse.Result.GetResponseStream(); } // not implemented public string GetResponseText() { xresponse.Wait(); return xresponse.Result.GetResponseText(); } } public class AccountStoreImpl : IAccountStore { Xamarin.Auth.AccountStore xAccountStore; static AccountStoreImpl() { AccountStore.xAccountStore = new AccountStoreImpl(); } public IAccountStore xCreate() { #if __ANDROID__ xAccountStore = Xamarin.Auth.AccountStore.Create(Auth.context); // context may be all wrong #elif __IOS__ xAccountStore = Xamarin.Auth.AccountStore.Create(); #elif SILVERLIGHT xAccountStore = Xamarin.Auth.AccountStore.Create(); #endif return this; } public void Delete(Account account, string serviceId) { xAccountStore.Delete((Xamarin.Auth.Account)account.xAccount, serviceId); } public List<Account> FindAccountsForService(string serviceId) { IEnumerable<Xamarin.Auth.Account> xaccounts = xAccountStore.FindAccountsForService(serviceId); List<Account> accounts = new List<Account>(); foreach (Xamarin.Auth.Account xaccount in xaccounts) accounts.Add(new Account(xaccount, xaccount.Properties, xaccount.Username)); return accounts; } public void Save(Account account, string serviceId) { xAccountStore.Save((Xamarin.Auth.Account)account.xAccount, serviceId); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace VkApi.Wrapper.Objects { public class GroupsGroupFull : GroupsGroup { [JsonProperty("market")] public GroupsMarketInfo Market { get; set; } ///<summary> /// Current user's member status ///</summary> [JsonProperty("member_status")] public GroupsGroupFullMemberStatus MemberStatus { get; set; } ///<summary> /// Information whether community is adult ///</summary> [JsonProperty("is_adult")] public int IsAdult { get; set; } ///<summary> /// Information whether community is hidden from current user's newsfeed ///</summary> [JsonProperty("is_hidden_from_feed")] public int IsHiddenFromFeed { get; set; } ///<summary> /// Information whether community is in faves ///</summary> [JsonProperty("is_favorite")] public int IsFavorite { get; set; } ///<summary> /// Information whether current user is subscribed ///</summary> [JsonProperty("is_subscribed")] public int IsSubscribed { get; set; } [JsonProperty("city")] public BaseObject City { get; set; } [JsonProperty("country")] public BaseCountry Country { get; set; } ///<summary> /// Information whether community is verified ///</summary> [JsonProperty("verified")] public int Verified { get; set; } ///<summary> /// Community description ///</summary> [JsonProperty("description")] public String Description { get; set; } ///<summary> /// Community's main wiki page title ///</summary> [JsonProperty("wiki_page")] public String WikiPage { get; set; } ///<summary> /// Community members number ///</summary> [JsonProperty("members_count")] public int MembersCount { get; set; } [JsonProperty("counters")] public GroupsCountersGroup Counters { get; set; } [JsonProperty("cover")] public GroupsCover Cover { get; set; } ///<summary> /// Information whether current user can post on community's wall ///</summary> [JsonProperty("can_post")] public int CanPost { get; set; } ///<summary> /// Information whether current user can see all posts on community's wall ///</summary> [JsonProperty("can_see_all_posts")] public int CanSeeAllPosts { get; set; } ///<summary> /// Type of group, start date of event or category of public page ///</summary> [JsonProperty("activity")] public String Activity { get; set; } ///<summary> /// Fixed post ID ///</summary> [JsonProperty("fixed_post")] public int FixedPost { get; set; } ///<summary> /// Information whether current user can create topic ///</summary> [JsonProperty("can_create_topic")] public int CanCreateTopic { get; set; } ///<summary> /// Information whether current user can upload doc ///</summary> [JsonProperty("can_upload_doc")] public int CanUploadDoc { get; set; } ///<summary> /// Information whether current user can upload story ///</summary> [JsonProperty("can_upload_story")] public int CanUploadStory { get; set; } ///<summary> /// Information whether current user can upload video ///</summary> [JsonProperty("can_upload_video")] public int CanUploadVideo { get; set; } ///<summary> /// Information whether community has photo ///</summary> [JsonProperty("has_photo")] public int HasPhoto { get; set; } ///<summary> /// Community status ///</summary> [JsonProperty("status")] public String Status { get; set; } ///<summary> /// Community's main photo album ID ///</summary> [JsonProperty("main_album_id")] public int MainAlbumId { get; set; } [JsonProperty("links")] public GroupsLinksItem[] Links { get; set; } [JsonProperty("contacts")] public GroupsContactsItem[] Contacts { get; set; } ///<summary> /// Information about wall status in community ///</summary> [JsonProperty("wall")] public int Wall { get; set; } ///<summary> /// Community's website ///</summary> [JsonProperty("site")] public String Site { get; set; } [JsonProperty("main_section")] public GroupsGroupFullMainSection MainSection { get; set; } ///<summary> /// Information whether the community has a "fire" pictogram. ///</summary> [JsonProperty("trending")] public int Trending { get; set; } ///<summary> /// Information whether current user can send a message to community ///</summary> [JsonProperty("can_message")] public int CanMessage { get; set; } ///<summary> /// Information whether community can send a message to current user ///</summary> [JsonProperty("is_messages_blocked")] public int IsMessagesBlocked { get; set; } ///<summary> /// Information whether community can send notifications by phone number to current user ///</summary> [JsonProperty("can_send_notify")] public int CanSendNotify { get; set; } ///<summary> /// Status of replies in community messages ///</summary> [JsonProperty("online_status")] public GroupsOnlineStatus OnlineStatus { get; set; } ///<summary> /// Information whether age limit ///</summary> [JsonProperty("age_limits")] public GroupsGroupFullAgeLimits AgeLimits { get; set; } ///<summary> /// User ban info ///</summary> [JsonProperty("ban_info")] public GroupsGroupBanInfo BanInfo { get; set; } ///<summary> /// Information whether community has installed market app ///</summary> [JsonProperty("has_market_app")] public Boolean HasMarketApp { get; set; } ///<summary> /// Info about addresses in groups ///</summary> [JsonProperty("addresses")] public GroupsAddressesInfo Addresses { get; set; } ///<summary> /// Information whether current user is subscribed to podcasts ///</summary> [JsonProperty("is_subscribed_podcasts")] public Boolean IsSubscribedPodcasts { get; set; } ///<summary> /// Owner in whitelist or not ///</summary> [JsonProperty("can_subscribe_podcasts")] public Boolean CanSubscribePodcasts { get; set; } ///<summary> /// Can subscribe to wall ///</summary> [JsonProperty("can_subscribe_posts")] public Boolean CanSubscribePosts { get; set; } } }
using De.Osthus.Ambeth.Util; using System; using System.Collections; using System.Collections.Generic; namespace De.Osthus.Ambeth.Collections { /// <summary> /// This special kind of HashMap is intended to be used in high-performance concurrent scenarios with many reads and only some single occurences of write /// accesses. To allow extremely high concurrency there is NO lock in read access scenarios. The design pattern to synchronize the reads with the indeed /// synchronized write accesses the internal table-structure well be REPLACED on each write. /// /// Because of this the existing internal object graph will NEVER be modified allowing unsynchronized read access of any amount without performance /// loss. /// </summary> /// <typeparam name="K"></typeparam> public class SmartCopySet<K> : CHashSet<K> { protected readonly Object writeLock = new Object(); public SmartCopySet() : base(0.5f) { // Intended blank } public SmartCopySet(float loadFactor) : base(loadFactor) { // Intended blank } public SmartCopySet(int initialCapacity, float loadFactor) : base(initialCapacity, loadFactor) { // Intended blank } public SmartCopySet(int initialCapacity) : base(initialCapacity) { // Intended blank } public Object GetWriteLock() { return writeLock; } protected TempHashSet<K> CreateCopy() { // Copy existing data in FULLY NEW STRUCTURE SetEntry<K>[] table = this.table; TempHashSet<K> backupSet = new TempHashSet<K>(table.Length, this.loadFactor, delegate(K key, SetEntry<K> entry) { return EqualKeys(key, entry); }, delegate(K key) { return ExtractHash(key); }); for (int a = table.Length; a-- > 0; ) { SetEntry<K> entry = table[a]; while (entry != null) { K key = GetKeyOfEntry(entry); if (key != null) { backupSet.Add(CloneKey(key)); } entry = GetNextEntry(entry); } } return backupSet; } protected void SaveCopy(TempHashSet<K> copy) { // Now the structure contains all necessary data, so we "retarget" the existing table table = copy.GetTable(); threshold = copy.GetThreshold(); size = copy.Count; } protected virtual K CloneKey(K key) { return key; } public override void Clear() { Object writeLock = GetWriteLock(); lock (writeLock) { if (Count == 0) { return; } TempHashSet<K> backupMap = CreateCopy(); backupMap.Clear(); SaveCopy(backupMap); } } public override bool AddAll<S>(IEnumerable<S> coll) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.AddAll(coll)) { return false; } SaveCopy(backupMap); return true; } } public override bool AddAll(IEnumerable coll) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.AddAll(coll)) { return false; } SaveCopy(backupMap); return true; } } public override bool AddAll<S>(S[] array) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.AddAll(array)) { return false; } SaveCopy(backupMap); return true; } } public override bool Add(K key) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.Add(key)) { return false; } SaveCopy(backupMap); return true; } } public override bool Remove(K key) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.Remove(key)) { return false; } SaveCopy(backupMap); return true; } } public override bool RetainAll(IICollection c) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.RetainAll(c)) { return false; } SaveCopy(backupMap); return true; } } public override bool RetainAll(IList c) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.RetainAll(c)) { return false; } SaveCopy(backupMap); return true; } } public override bool RemoveAll(IEnumerable c) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure if (!backupMap.RemoveAll(c)) { return false; } SaveCopy(backupMap); return true; } } public override K RemoveAndGet(K key) { Object writeLock = GetWriteLock(); lock (writeLock) { TempHashSet<K> backupMap = CreateCopy(); // Write new data in the copied structure K existingKey = backupMap.RemoveAndGet(key); SaveCopy(backupMap); return existingKey; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Input; using Eto.Forms; namespace Eto { /// <summary> /// A storage for properties and events of a class /// </summary> /// <remarks> /// This is used by <see cref="Widget"/> object to minimize the footprint of each instance. /// For example, the <see cref="Forms.Control"/> class has around 20 events, each would take up to 4 bytes on a 32 bit /// system for a total overhead of 80 bytes per instance. /// Most of the events won't be handled on most controls, so using a dictionary can dramatically reduce the size. /// /// This can also be used for rarely used properties that do not need to be extremely performant when getting or setting the value. /// </remarks> public class PropertyStore : Dictionary<object, object> { /// <summary> /// Gets the parent object that this property store is attached to /// </summary> /// <remarks> /// This is used to attach/remove events /// </remarks> /// <value>The parent object</value> public object Parent { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Eto.PropertyStore"/> class. /// </summary> /// <param name="parent">Parent to attach the properties to</param> public PropertyStore(object parent) { this.Parent = parent; } /// <summary> /// Gets a value from the property store with the specified key of a concrete type /// </summary> /// <param name="key">Key of the property to get</param> /// <param name="defaultValue">Value to return when the specified property is not found in the dictionary</param> /// <typeparam name="T">The type of property to get.</typeparam> /// <returns>Value of the property with the given key, or <paramref name="defaultValue"/> if not found</returns> public T Get<T>(object key, T defaultValue = default(T)) { object value; return TryGetValue(key, out value) ? (T)value : defaultValue; } /// <summary> /// Gets a value from the property store with the specified key of a concrete type /// </summary> /// <param name="key">Key of the property to get</param> /// <param name="defaultValue">Value to return when the specified property is not found in the dictionary</param> /// <typeparam name="T">The type of property to get.</typeparam> /// <returns>Value of the property with the given key, or <paramref name="defaultValue"/> if not found</returns> public T Get<T>(object key, Func<T> defaultValue) { object value; return TryGetValue(key, out value) ? (T)value : defaultValue(); } /// <summary> /// Gets a value from the property store with the specified key of a concrete type, and creates a new instance if it doesn't exist yet. /// </summary> /// <param name="key">Key of the property to get</param> /// <typeparam name="T">Type type of property to get.</typeparam> /// <returns>Value of the property with the given key, or a new instance if not already added</returns> public T Create<T>(object key) where T: new() { return Create<T>(key, () => new T()); } /// <summary> /// Gets a value from the property store with the specified key of a concrete type, and creates a new instance if it doesn't exist yet. /// </summary> /// <param name="key">Key of the property to get</param> /// <param name="create">Delegate to create the object, if it doesn't already exist</param> /// <typeparam name="T">Type type of property to get.</typeparam> /// <returns>Value of the property with the given key, or a new instance if not already added</returns> public T Create<T>(object key, Func<T> create) { object value; if (!TryGetValue(key, out value)) { value = create(); Add(key, value); } return (T)value; } /// <summary> /// Adds a generic event delegate with the specified key /// </summary> /// <remarks> /// This should be called in an event's add accessor. /// If you are adding a handler-based event, call <see cref="AddHandlerEvent"/> instead, which will automatically /// tell the handler that it needs to be wired up. /// /// You can use any subclass of <see cref="System.EventArgs"/> for the type of event handler /// /// To trigger the event, use <see cref="TriggerEvent{T}"/>. /// </remarks> /// <seealso cref="RemoveEvent"/> /// <seealso cref="AddHandlerEvent"/> /// <example> /// Example implementation of a generic event /// <code> /// static readonly object MySomethingEventKey = new object(); /// /// public event EventHandler&lt;EventArgs&gt; MySomething /// { /// add { Properties.AddEvent(MySomethingEvent, value); } /// remove { Properties.RemoveEvent(MySomethingEvent, value); } /// } /// </code> /// </example> /// <param name="key">Key of the event to add to</param> /// <param name="value">Delegate to add to the event</param> public void AddEvent(object key, Delegate value) { object existingDelegate; if (TryGetValue(key, out existingDelegate)) this[key] = Delegate.Combine((Delegate)existingDelegate, value); else { Add(key, value); } } /// <summary> /// Adds a handler-based event delegate with the specified key /// </summary> /// <remarks> /// This should be called in an event's add accessor. /// This is used for any event that should be triggered by the platform handler. /// This will call <see cref="M:Eto.Widget.IHandler.HandleEvent(string,bool)"/> with the specified <paramref name="key"/> for the /// first subscription to the event. /// /// You can use any subclass of <see cref="System.EventArgs"/> for the type of event handler /// /// To trigger the event, use <see cref="TriggerEvent{T}"/> /// </remarks> /// <example> /// Example implementation of a handler-triggered event /// <code> /// public const string MySomethingEvent = "MyControl.MySomething"; /// /// public event EventHandler&lt;EventArgs&gt; MySomething /// { /// add { Properties.AddHandlerEvent(MySomethingEvent, value); } /// remove { Properties.RemoveHandlerEvent(MySomethingEvent, value); } /// } /// </code> /// </example> /// <param name="key">Key of the event to add to</param> /// <param name="value">Delegate to add to the event</param> public void AddHandlerEvent(string key, Delegate value) { var parentWidget = Parent as Widget; if (parentWidget == null) throw new InvalidOperationException("Parent must subclass Widget"); object existingDelegate; if (TryGetValue(key, out existingDelegate)) this[key] = Delegate.Combine((Delegate)existingDelegate, value); else { if (!EventLookup.IsDefault(parentWidget, key)) { parentWidget.HandleEvent(key); } Add(key, value); } } /// <summary> /// Removes the event delegate with the specified <paramref name="key"/> /// </summary> /// <remarks> /// Use this in the remove accessor of your event. See <see cref="AddEvent"/> and <see cref="AddHandlerEvent"/> /// for examples. /// </remarks> /// <param name="key">Key of the event to remove</param> /// <param name="value">Delegate to remove from the event</param> public void RemoveEvent(object key, Delegate value) { object existingDelegate; if (TryGetValue(key, out existingDelegate)) { this[key] = Delegate.Remove((Delegate)existingDelegate, value); } } /// <summary> /// Triggers an event with the specified key /// </summary> /// <remarks> /// Call this in your OnMyEvent(EventArgs) method to trigger the event if it has been subscribed to. /// This can handle events that have any type of EventArgs. /// </remarks> /// <example> /// This shows how to trigger either a generic event or handler-triggered event: /// <code> /// protected virtual void OnMySomething(EventArgs e) /// { /// Properties.TriggerEvent(MySomethingEventKey, this, e); /// } /// </code> /// </example> /// <param name="key">Key of the generic or handler event</param> /// <param name="sender">Object sending the event (usually 'this')</param> /// <param name="args">Arguments for the event</param> /// <typeparam name="T">Type of the event arguments</typeparam> public void TriggerEvent<T>(object key, object sender, T args) where T: EventArgs { object existingDelegate; if (TryGetValue(key, out existingDelegate) && existingDelegate != null) { ((EventHandler<T>)existingDelegate)(sender, args); } } /// <summary> /// Set the value for the specified property key, removing the value from the dictionary if it is the default value of T. /// </summary> /// <remarks> /// This can be used as an optimized way to set the value in the dictionary as if the value set equal to the <paramref name="defaultValue"/> /// (e.g. null for reference types, false for bool, 0 for int, etc), then it will be removed from the dictionary /// instead of just set to the value, reducing memory usage. /// The <see cref="Get{T}(object,T)"/> should be passed the same default when retrieving the parameter value. /// </remarks> /// <param name="key">Key of the property to set.</param> /// <param name="value">Value for the property.</param> /// <param name="defaultValue">Value of the property when it should be removed from the dictionary. This should match what is passed to <see cref="Get{T}(object,T)"/> when getting the value.</param> /// <typeparam name="T">The type of the property to set.</typeparam> public void Set<T>(object key, T value, T defaultValue = default(T)) { if (Equals(value, defaultValue)) Remove(key); else this[key] = value; } /// <summary> /// Set the value for the specified property key, raising the <paramref name="propertyChanged"/> handler if it has changed. /// </summary> /// <remarks> /// This is useful when creating properties that need to trigger changed events without having to write boilerplate code. /// </remarks> /// <example> /// <code> /// public class MyForm : Form, INotifyPropertyChanged /// { /// static readonly MyPropertyKey = new object(); /// /// public bool MyProperty /// { /// get { return Properties.Get&lt;bool&gt;(MyPropertyKey); } /// set { Properties.Set(MyPropertyKey, value, PropertyChanged); } /// } /// /// public event PropertyChangedEventHandler PropertyChanged; /// } /// </code> /// </example> /// <param name="key">Key of the property to set.</param> /// <param name="value">Value for the property.</param> /// <param name="defaultValue">Default value of the property to compare when removing the key</param> /// <param name="propertyChanged">Property changed event handler to raise if the property value has changed.</param> /// <param name="propertyName">Name of the property, or omit to get the property name from the caller.</param> /// <typeparam name="T">The type of the property to set.</typeparam> /// <returns>true if the property was changed, false if not</returns> #if PCL public bool Set<T>(object key, T value, PropertyChangedEventHandler propertyChanged, T defaultValue = default(T), [CallerMemberName] string propertyName = null) #else public bool Set<T>(object key, T value, PropertyChangedEventHandler propertyChanged, T defaultValue, string propertyName) #endif { var existing = Get<T>(key); if (!Equals(existing, value)) { Set<T>(key, value, defaultValue); if (propertyChanged != null) propertyChanged(Parent, new PropertyChangedEventArgs(propertyName)); return true; } return false; } /// <summary> /// Set the value for the specified property key, calling the <paramref name="propertyChanged"/> delegate if it has changed. /// </summary> /// <remarks> /// This is useful when creating properties that need to trigger changed events without having to write boilerplate code. /// </remarks> /// <example> /// <code> /// public class MyForm : Form /// { /// static readonly MyPropertyKey = new object(); /// /// public bool MyProperty /// { /// get { return Properties.Get&lt;bool&gt;(MyPropertyKey); } /// set { Properties.Set(MyPropertyKey, value, OnMyPropertyChanged); } /// } /// /// public event EventHandler&lt;EventArgs&gt; MyPropertyChanged; /// /// protected virtual void MyPropertyChanged(EventArgs e) /// { /// if (MyPropertyChanged != null) /// MyPropertyChanged(this, e); /// } /// } /// </code> /// </example> /// <param name="key">Key of the property to set.</param> /// <param name="value">Value for the property.</param> /// <param name="defaultValue">Default value of the property to compare when removing the key</param> /// <param name="propertyChanged">Property changed event handler to raise if the property value has changed.</param> /// <typeparam name="T">The type of the property to set.</typeparam> /// <returns>true if the property was changed, false if not</returns> public bool Set<T>(object key, T value, Action propertyChanged, T defaultValue = default(T)) { var existing = Get<T>(key); if (!Equals(existing, value)) { Set<T>(key, value, defaultValue); propertyChanged(); return true; } return false; } class CommandWrapper { readonly Action<EventHandler<EventArgs>> removeExecute; readonly Action<bool> setEnabled; public ICommand Command { get; set; } public CommandWrapper(ICommand command, Action<bool> setEnabled, Action<EventHandler<EventArgs>> addExecute, Action<EventHandler<EventArgs>> removeExecute) { this.Command = command; this.setEnabled = setEnabled; this.removeExecute = removeExecute; addExecute(Command_Execute); SetEnabled(); command.CanExecuteChanged += Command_CanExecuteChanged;; } public void Unregister() { removeExecute(Command_Execute); Command.CanExecuteChanged -= Command_CanExecuteChanged; } void Command_Execute(object sender, EventArgs e) { Command.Execute(null); } void Command_CanExecuteChanged(object sender, EventArgs e) { SetEnabled(); } void SetEnabled() { if (setEnabled != null) setEnabled(Command.CanExecute(null)); } } /// <summary> /// Sets an <see cref="ICommand"/> value for the specified property <paramref name="key"/>. /// </summary> /// <param name="key">Key of the property to set</param> /// <param name="value">Command instance</param> /// <param name="setEnabled">Delegate to set the widget as enabled when the command state changes.</param> /// <param name="addExecute">Delegate to attach the execute event handler when the widget invokes the command.</param> /// <param name="removeExecute">Delegate to detach the execute event handler.</param> /// <seealso cref="GetCommand"/> public void SetCommand(object key, ICommand value, Action<bool> setEnabled, Action<EventHandler<EventArgs>> addExecute, Action<EventHandler<EventArgs>> removeExecute) { var cmd = Get<CommandWrapper>(key); if (cmd != null) { if (ReferenceEquals(cmd.Command, value)) return; cmd.Unregister(); } Set(key, value != null ? new CommandWrapper(value, setEnabled, addExecute, removeExecute) : null); } /// <summary> /// Gets the command instance for the specified property key. /// </summary> /// <returns>The command instance, or null if it is not set.</returns> /// <param name="key">Key of the property to get.</param> /// <seealso cref="SetCommand"/> public ICommand GetCommand(object key) { var cmd = Get<CommandWrapper>(key); return cmd != null ? cmd.Command : null; } } }
//////////////////////////////////////////////////////////////////////////////// // // @module Stan's Assets Commons Lib // @author Osipov Stanislav (Stan's Assets) // @support [email protected] // //////////////////////////////////////////////////////////////////////////////// #if UNITY_EDITOR using UnityEngine; using UnityEditor; using System; using System.Collections; namespace SA.Common.Editor { public static class VersionsManager { //private const string UM_IOS_INSTALATION_MARK = SA.Common.Config.IOS_DESTANATION_PATH + "UM_IOS_INSTALATION_MARK.txt"; //-------------------------------------- // Android Native //-------------------------------------- public static bool Is_AN_Installed { get { return SA.Common.Util.Files.IsFileExists(SA.Common.Config.AN_VERSION_INFO_PATH); } } public static int AN_Version { get { return GetVersionCode(SA.Common.Config.AN_VERSION_INFO_PATH); } } public static int AN_MagorVersion { get { return GetMagorVersionCode(SA.Common.Config.AN_VERSION_INFO_PATH); } } public static string AN_StringVersionId { get { return GetStringVersionId(SA.Common.Config.AN_VERSION_INFO_PATH); } } //-------------------------------------- // Mobile Social //-------------------------------------- public static bool Is_MSP_Installed { get { return SA.Common.Util.Files.IsFileExists(SA.Common.Config.MSP_VERSION_INFO_PATH); } } public static int MSP_Version { get { return GetVersionCode(SA.Common.Config.MSP_VERSION_INFO_PATH); } } public static int MSP_MagorVersion { get { return GetMagorVersionCode(SA.Common.Config.MSP_VERSION_INFO_PATH); } } public static string MSP_StringVersionId { get { return GetStringVersionId(SA.Common.Config.MSP_VERSION_INFO_PATH); } } //-------------------------------------- // Ultimate Mobile //-------------------------------------- public static bool Is_UM_Installed { get { return SA.Common.Util.Files.IsFileExists(SA.Common.Config.UM_VERSION_INFO_PATH); } } public static int UM_Version { get { return GetVersionCode(SA.Common.Config.UM_VERSION_INFO_PATH); } } public static int UM_MagorVersion { get { return GetMagorVersionCode(SA.Common.Config.UM_VERSION_INFO_PATH); } } public static string UM_StringVersionId { get { return GetStringVersionId(SA.Common.Config.UM_VERSION_INFO_PATH); } } //-------------------------------------- // Google Mobile Ad //-------------------------------------- public static bool Is_GMA_Installed { get { return SA.Common.Util.Files.IsFileExists(SA.Common.Config.GMA_VERSION_INFO_PATH); } } public static int GMA_Version { get { return GetVersionCode(SA.Common.Config.GMA_VERSION_INFO_PATH); } } public static int GMA_MagorVersion { get { return GetMagorVersionCode(SA.Common.Config.GMA_VERSION_INFO_PATH); } } public static string GMA_StringVersionId { get { return GetStringVersionId(SA.Common.Config.GMA_VERSION_INFO_PATH); } } //-------------------------------------- // Mobile Native Pop Up //-------------------------------------- public static bool Is_MNP_Installed { get { return SA.Common.Util.Files.IsFileExists(SA.Common.Config.MNP_VERSION_INFO_PATH); } } public static int MNP_Version { get { return GetVersionCode(SA.Common.Config.MNP_VERSION_INFO_PATH); } } public static int MNP_MagorVersion { get { return GetMagorVersionCode(SA.Common.Config.MNP_VERSION_INFO_PATH); } } public static string MNP_StringVersionId { get { return GetStringVersionId(SA.Common.Config.MNP_VERSION_INFO_PATH); } } //-------------------------------------- // IOS Native //-------------------------------------- public static bool Is_ISN_Installed { get { return SA.Common.Util.Files.IsFileExists(SA.Common.Config.ISN_VERSION_INFO_PATH); } } public static int ISN_Version { get { return GetVersionCode(SA.Common.Config.ISN_VERSION_INFO_PATH); } } public static int ISN_MagorVersion { get { return GetMagorVersionCode(SA.Common.Config.ISN_VERSION_INFO_PATH); } } public static string ISN_StringVersionId { get { return GetStringVersionId(SA.Common.Config.ISN_VERSION_INFO_PATH); } } //-------------------------------------- // Utilities //-------------------------------------- public static int ParceMagorVersion(string stringVersionId) { string[] versions = stringVersionId.Split (new char[] {'.', '/'}); int intVersion = Int32.Parse(versions[0]) * 100; return intVersion; } private static int GetMagorVersionCode(string versionFilePath) { string stringVersionId = SA.Common.Util.Files.Read (versionFilePath); return ParceMagorVersion(stringVersionId); } public static int ParceVersion(string stringVersionId) { string[] versions = stringVersionId.Split (new char[] {'.', '/'}); int intVersion = Int32.Parse(versions[0]) * 100 + Int32.Parse(versions[1]) * 10; return intVersion; } private static int GetVersionCode(string versionFilePath) { string stringVersionId = SA.Common.Util.Files.Read (versionFilePath); return ParceVersion(stringVersionId); } private static string GetStringVersionId(string versionFilePath) { if(SA.Common.Util.Files.IsFileExists(versionFilePath)) { return SA.Common.Util.Files.Read (versionFilePath); } else { return "0.0"; } } public static string InstalledPluginsList { get { string allPluginsInstalled = ""; if(SA.Common.Util.Files.IsFolderExists(SA.Common.Config.BUNDLES_PATH)) { string[] bundles = SA.Common.Util.Files.GetFoldersAt (SA.Common.Config.BUNDLES_PATH); foreach(string pluginPath in bundles) { string pluginName = System.IO.Path.GetFileName (pluginPath); allPluginsInstalled = allPluginsInstalled + " (" + pluginName + ")" + "\n"; } } if(SA.Common.Util.Files.IsFolderExists(SA.Common.Config.MODULS_PATH)) { string[] modules = SA.Common.Util.Files.GetFoldersAt (SA.Common.Config.MODULS_PATH); foreach(string pluginPath in modules) { string pluginName = System.IO.Path.GetFileName (pluginPath); allPluginsInstalled = allPluginsInstalled + " (" + pluginName + ")" + "\n"; } } return allPluginsInstalled; } } } } #endif
/* * Naiad ver. 0.5 * 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, MERCHANTABLITY 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.Linq; using System.Text; using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.DataStructures; namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.CollectionTrace { internal class CollectionTraceWithAggregation<S> : CollectionTraceCheckpointable<S> where S : IEquatable<S> { VariableLengthHeap<CollectionTraceWithAggregationIncrement<S>> increments; // stores regions of increments, each corresponding to a time Func<int, int, bool> TimeLessThan; // wraps the "less than" partial order on time indices Func<int, int> UpdateTime; // wraps the reachability-based time advancement Func<Int64, S, S, S> axpy; // (weight, new record, old record) -> newer record Func<S, bool> isZero; // indicates if x is logically zero. OffsetLength cachedIncrementOffset; CollectionTraceWithAggregationIncrement<S> cacheContents; public void ReleaseCache() { if (!cachedIncrementOffset.IsEmpty) { cachedIncrementOffset = new OffsetLength(); cacheContents = new CollectionTraceWithAggregationIncrement<S>(); } } public void Introduce(ref int offsetLength, S element, Int64 weight, int timeIndex) { var ol = new OffsetLength(offsetLength); // internal Introduce uses aggregated element and weight, so should aggregate first Introduce(ref ol, this.axpy(weight, element, default(S)), weight, timeIndex); offsetLength = ol.offsetLength; ReleaseCache(); } void Introduce(ref OffsetLength offsetLength, S element, Int64 weight, int timeIndex) { var handle = EnsureTime(ref offsetLength, timeIndex); var position = 0; while (handle.Array[handle.Offset + position].TimeIndex != timeIndex) position++; if (handle.Array[handle.Offset + position].IsEmpty(isZero)) handle.Array[handle.Offset + position] = new CollectionTraceWithAggregationIncrement<S>(weight, timeIndex, element); else { var incr = handle.Array[handle.Offset + position]; var result = new CollectionTraceWithAggregationIncrement<S>(incr.Weight + weight, timeIndex, axpy(1, element, incr.Value)); handle.Array[handle.Offset + position] = result; } // if the introduction results in an empty region, we need to clean up if (handle.Array[handle.Offset + position].IsEmpty(isZero)) { // drag everything after it down one for (int i = position + 1; i < handle.Length; i++) handle.Array[handle.Offset + i - 1] = handle.Array[handle.Offset + i]; handle.Array[handle.Offset + handle.Length - 1] = new CollectionTraceWithAggregationIncrement<S>(); // if the root element is empty, the list must be empty if (handle.Array[handle.Offset].IsEmpty(isZero)) increments.Release(ref offsetLength); } } void Introduce(ref OffsetLength thisOffsetLength, OffsetLength thatOffsetLength, int scale) { var handle = increments.Dereference(thatOffsetLength); for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty(isZero); i++) { Introduce(ref thisOffsetLength, axpy(scale, handle.Array[handle.Offset + i].Value, default(S)), scale * handle.Array[handle.Offset + i].Weight, handle.Array[handle.Offset + i].TimeIndex); } } Handle<CollectionTraceWithAggregationIncrement<S>> EnsureTime(ref OffsetLength offsetLength, int timeIndex) { var handle = increments.Dereference(offsetLength); for (int i = 0; i < handle.Length; i++) { // if we found the time, it is ensured and we can return if (handle.Array[handle.Offset + i].TimeIndex == timeIndex) return handle; // if we found an empty slot, new it up and return if (handle.Array[handle.Offset + i].IsEmpty(isZero)) { handle.Array[handle.Offset + i] = new CollectionTraceWithAggregationIncrement<S>(timeIndex); return handle; } } // if we didn't find it, and no empty space for it var oldLength = handle.Length; handle = increments.EnsureAllocation(ref offsetLength, handle.Length + 1); handle.Array[handle.Offset + oldLength] = new CollectionTraceWithAggregationIncrement<S>(timeIndex); return handle; } public void IntroduceFrom(ref int thisKeyIndex, ref int thatKeyIndex, bool delete = true) { var ol1 = new OffsetLength(thisKeyIndex); var ol2 = new OffsetLength(thatKeyIndex); if (!ol2.IsEmpty) { Introduce(ref ol1, ol2, 1); thisKeyIndex = ol1.offsetLength; if (delete) ZeroState(ref thatKeyIndex); ReleaseCache(); } } public void SubtractStrictlyPriorDifferences(ref int keyIndex, int timeIndex) { var ol = new OffsetLength(keyIndex); // if there aren't any strictly prior differences we can just return if (ol.IsEmpty) return; var handle = EnsureTime(ref ol, timeIndex); var position = 0; while (handle.Array[handle.Offset + position].TimeIndex != timeIndex) position++; // if the destination time is empty, we can swap in the accumulation (negated) if (!handle.Array[handle.Offset + position].IsEmpty(isZero)) { // swap the accumulation in, and zero out the accumulation (the new correct accumulation for this key). var accum = UpdateAccumulation(ref ol, timeIndex); handle.Array[handle.Offset + position] = new CollectionTraceWithAggregationIncrement<S>(timeIndex).Add(accum, axpy); // we may have ended up with a null acculumation, must clean up if (handle.Array[handle.Offset + position].Weight == 0) { for (int i = position + 1; i < handle.Length; i++) handle.Array[handle.Offset + i - 1] = handle.Array[handle.Offset + i]; handle.Array[handle.Offset + handle.Length - 1] = new CollectionTraceWithAggregationIncrement<S>(); if (handle.Array[handle.Offset].Weight == 0) increments.Release(ref ol); } // important to update the cached accumulation to reflect the emptiness // only do this if the cached accumulation is what we are working with if (cachedIncrementOffset.offsetLength == ol.offsetLength) { cachedIncrementOffset = ol; cacheContents = new CollectionTraceWithAggregationIncrement<S>(timeIndex); } } else throw new Exception("Attemping subtraction from non-empty time; something wrong in Operator logic"); keyIndex = ol.offsetLength; } public void EnumerateCollectionAt(int offsetLength, int timeIndex, NaiadList<Weighted<S>> toFill) { if (toFill.Count == 0) { var temp = new OffsetLength(offsetLength); var accum = UpdateAccumulation(ref temp, timeIndex); if (!accum.IsEmpty(isZero)) toFill.Add(new Weighted<S>(accum.Value, 1)); } else throw new NotImplementedException(); } // no caching at the moment; should do, but need to figure out how... CollectionTraceWithAggregationIncrement<S> UpdateAccumulation(ref OffsetLength ol, int timeIndex) { #if true if (ol.IsEmpty) return new CollectionTraceWithAggregationIncrement<S>(timeIndex); var handle = increments.Dereference(ol); // special-case single element accumulations to avoid unprocessed accumulation dropping processed accumulation if (handle.Length == 1) { if (TimeLessThan(handle.Array[handle.Offset].TimeIndex, timeIndex)) return handle.Array[handle.Offset]; else return new CollectionTraceWithAggregationIncrement<S>(timeIndex); } else #else var handle = increments.Dereference(ol); #endif { // if we have a hit on the cache ... if (ol.offsetLength == cachedIncrementOffset.offsetLength) { for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty(isZero); i++) { if (!handle.Array[handle.Offset + i].IsEmpty(isZero)) { var inNew = TimeLessThan(handle.Array[handle.Offset + i].TimeIndex, timeIndex); var inOld = TimeLessThan(handle.Array[handle.Offset + i].TimeIndex, cacheContents.TimeIndex); if (inOld != inNew) cacheContents.Add(handle.Array[handle.Offset + i], axpy, inOld ? -1 : +1); } } cacheContents.TimeIndex = timeIndex; } else { ReleaseCache(); // blow cache away and start over for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty(isZero); i++) if (TimeLessThan(handle.Array[handle.Offset + i].TimeIndex, timeIndex)) cacheContents.Add(handle.Array[handle.Offset + i], axpy); cachedIncrementOffset = ol; cacheContents.TimeIndex = timeIndex; } return cacheContents; } } public void EnumerateDifferenceAt(int offsetLength, int timeIndex, NaiadList<Weighted<S>> toFill) { if (toFill.Count == 0) { var temp = new OffsetLength(offsetLength); var accum = new CollectionTraceWithAggregationIncrement<S>(); var handle = increments.Dereference(temp); for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty(isZero); i++) if (handle.Array[handle.Offset + i].TimeIndex == timeIndex) accum.Add(handle.Array[handle.Offset + i], axpy); if (!accum.IsEmpty(isZero)) toFill.Add(new Weighted<S>(accum.Value, 1)); } else throw new NotImplementedException(); } HashSet<int> hashSet = new HashSet<int>(); public void EnumerateTimes(int keyIndex, NaiadList<int> timelist) { var ol = new OffsetLength(keyIndex); if (timelist.Count == 0) { var handle = increments.Dereference(ol); for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty(isZero); i++) timelist.Add(handle.Array[handle.Offset + i].TimeIndex); } else { hashSet.Clear(); for (int i = 0; i < timelist.Count; i++) hashSet.Add(timelist.Array[i]); var handle = increments.Dereference(ol); for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty(isZero); i++) { var time = handle.Array[handle.Offset + i].TimeIndex; if (!hashSet.Contains(time)) { timelist.Add(time); hashSet.Add(time); } } } } public int AllocateState() { throw new NotImplementedException(); } public void ReleaseState(ref int keyIndex) { var temp = new OffsetLength(keyIndex); if (!temp.IsEmpty) { increments.Release(ref temp); keyIndex = temp.offsetLength; } ReleaseCache(); } public void ZeroState(ref int keyIndex) { ReleaseState(ref keyIndex); } public bool IsZero(ref int keyIndex) { return keyIndex == 0; } public void EnsureStateIsCurrentWRTAdvancedTimes(ref int offsetLength) { var ol = new OffsetLength(offsetLength); if (!ol.IsEmpty) { var handle = increments.Dereference(ol); for (int i = 0; i < handle.Length; i++) { if (handle.Array[handle.Offset + i].Weight != 0) { handle.Array[handle.Offset + i].TimeIndex = UpdateTime(handle.Array[handle.Offset + i].TimeIndex); for (int j = 0; j < i && !handle.Array[handle.Offset + i].IsEmpty(isZero); j++) { if (handle.Array[handle.Offset + j].TimeIndex == handle.Array[handle.Offset + i].TimeIndex) { handle.Array[handle.Offset + j].Add(handle.Array[handle.Offset + i], axpy); handle.Array[handle.Offset + i] = new CollectionTraceWithAggregationIncrement<S>(); } } } } var position = 0; for (int i = 0; i < handle.Length; i++) if (!handle.Array[handle.Offset + i].IsEmpty(isZero)) { var temp = handle.Array[handle.Offset + i]; handle.Array[handle.Offset + i] = new CollectionTraceWithAggregationIncrement<S>(); handle.Array[handle.Offset + (position++)] = temp; } if (handle.Array[handle.Offset].IsEmpty(isZero)) increments.Release(ref ol); offsetLength = ol.offsetLength; } } public void Release() { } public void Compact() { } public void Checkpoint(NaiadWriter writer) { this.increments.Checkpoint(writer); } public void Restore(NaiadReader reader) { this.ReleaseCache(); this.increments.Restore(reader); } public bool Stateful { get { return true; } } public CollectionTraceWithAggregation(Func<int, int, bool> tCompare, Func<int, int> update, Func<Int64, S, S, S> a, Func<S, bool> isZ) { TimeLessThan = tCompare; UpdateTime = update; axpy = a; isZero = isZ; increments = new VariableLengthHeap<CollectionTraceWithAggregationIncrement<S>>(32); } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; using FILE = System.IO.TextWriter; using i64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using u64 = System.UInt64; using unsigned = System.UIntPtr; using Pgno = System.UInt32; #if !SQLITE_MAX_VARIABLE_NUMBER using ynVar = System.Int16; #else using ynVar = System.Int32; #endif /* ** The yDbMask datatype for the bitmask of all attached databases. */ #if SQLITE_MAX_ATTACHED//>30 // typedef sqlite3_uint64 yDbMask; using yDbMask = System.Int64; #else // typedef unsigned int yDbMask; using yDbMask = System.Int32; #endif namespace System.Data.SQLite { using Op = Sqlite3.VdbeOp; public partial class Sqlite3 { /* ** 2003 September 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for information that is private to the ** VDBE. This information used to all be at the top of the single ** source code file "vdbe.c". When that file became too big (over ** 6000 lines long) it was split up into several smaller files and ** this header information was factored out. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#if !_VDBEINT_H_ //#define _VDBEINT_H_ /// <summary> /// A cursor is a pointer into a single BTree within a database file. /// The cursor can seek to a BTree entry with a particular key, or /// loop over all entries of the Btree. You can also insert new BTree /// entries or retrieve the key or data from the entry that the cursor /// is currently pointing to. /// /// Every cursor that the virtual machine has open is represented by an /// instance of the following structure /// </summary> public class VdbeCursor { /// <summary> /// The cursor structure of the backend /// </summary> public BtCursor pCursor; /// <summary> /// Separate file holding temporary table /// </summary> public Btree pBt; /// <summary> /// Info about index keys needed by index cursors /// </summary> public KeyInfo pKeyInfo; /// <summary> /// Index of cursor database in db->aDb[] (or -1) /// </summary> public int iDb; /// <summary> /// Register holding pseudotable content. /// </summary> public int pseudoTableReg; /// <summary> /// Number of fields in the header /// </summary> public int nField; /// <summary> /// True if zeroed out and ready for reuse /// </summary> public bool zeroed; /// <summary> /// True if lastRowid is valid /// </summary> public bool rowidIsValid; /// <summary> /// True if pointing to first entry /// </summary> public bool atFirst; /// <summary> /// Generate new record numbers semi-randomly /// </summary> public bool useRandomRowid; /// <summary> /// True if pointing to a row with no data /// </summary> public bool nullRow; /// <summary> /// A call to sqlite3BtreeMoveto() is needed /// </summary> public bool deferredMoveto; /// <summary> /// True if a table requiring integer keys /// </summary> public bool isTable; /// <summary> /// True if an index containing keys only - no data /// </summary> public bool isIndex; /// <summary> /// True if the underlying table is BTREE_UNORDERED /// </summary> public bool isOrdered; #if !SQLITE_OMIT_VIRTUALTABLE /// <summary> /// The cursor for a virtual table /// </summary> public sqlite3_vtab_cursor pVtabCursor; /// <summary> /// Module for cursor pVtabCursor /// </summary> public sqlite3_module pModule; #endif /// <summary> /// Sequence counter /// </summary> public i64 seqCount; /// <summary> /// Argument to the deferred sqlite3BtreeMoveto() /// </summary> public i64 movetoTarget; /// <summary> /// Last rowid from a Next or NextIdx operation /// </summary> public i64 lastRowid; /// <summary> /// Result of last sqlite3BtreeMoveto() done by an OP_NotExists or OP_IsUnique opcode on this cursor. /// </summary> public int seekResult; /* Cached information about the header for the data record that the ** cursor is currently pointing to. Only valid if cacheStatus matches ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that ** the cache is out of date. ** ** aRow might point to (ephemeral) data for the current row, or it might ** be NULL. */ /// <summary> /// Cache is valid if this matches Vdbe.cacheCtr /// </summary> public u32 cacheStatus; /// <summary> /// Total number of bytes in the record /// </summary> public Pgno payloadSize; /// <summary> /// Type values for all entries in the record /// </summary> public u32[] aType; /// <summary> /// Cached offsets to the start of each columns data /// </summary> public u32[] aOffset; /// <summary> /// Pointer to Data for the current row, if all on one page /// </summary> public int aRow; public VdbeCursor Copy() { return (VdbeCursor)MemberwiseClone(); } }; /// <summary> /// When a sub-program is executed (OP_Program), a structure of this type /// is allocated to store the current value of the program counter, as /// well as the current memory cell array and various other frame specific /// values stored in the Vdbe struct. When the sub-program is finished, /// these values are copied back to the Vdbe from the VdbeFrame structure, /// restoring the state of the VM to as it was before the sub-program /// began executing. /// /// The memory for a VdbeFrame object is allocated and managed by a memory /// cell in the parent (calling) frame. When the memory cell is deleted or /// overwritten, the VdbeFrame object is not freed immediately. Instead, it /// is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame /// list is deleted when the VM is reset in VdbeHalt(). The reason for doing /// this instead of deleting the VdbeFrame immediately is to avoid recursive /// calls to sqlite3VdbeMemRelease() when the memory cells belonging to the /// child frame are released. /// /// The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is /// set to NULL if the currently executing frame is the main program /// </summary> public class VdbeFrame { /// <summary> /// VM this frame belongs to /// </summary> public Vdbe v; /// <summary> /// Program Counter in parent (calling) frame /// </summary> public int pc; /// <summary> /// Program instructions for parent frame /// </summary> public Op[] aOp; /// <summary> /// Size of aOp array /// </summary> public int nOp; /// <summary> /// Array of memory cells for parent frame /// </summary> public Mem[] aMem; /// <summary> /// Number of entries in aMem /// </summary> public int nMem; /// <summary> /// Array of Vdbe cursors for parent frame /// </summary> public VdbeCursor[] apCsr; /// <summary> /// Number of entries in apCsr /// </summary> public u16 nCursor; /// <summary> /// Copy of SubProgram.token /// </summary> public int token; /// <summary> /// Number of memory cells for child frame /// </summary> public int nChildMem; /// <summary> /// Number of cursors for child frame /// </summary> public int nChildCsr; /// <summary> /// Last insert rowid (sqlite3.lastRowid) /// </summary> public i64 lastRowid; /// <summary> /// Statement changes (Vdbe.nChanges) /// </summary> public int nChange; /// <summary> /// Parent of this frame, or NULL if parent is main /// </summary> public VdbeFrame pParent; /// <summary> /// Array of memory cells for child frame /// </summary> public Mem[] aChildMem; /// <summary> /// Array of cursors for child frame /// </summary> public VdbeCursor[] aChildCsr; }; /* ** A value for VdbeCursor.cacheValid that means the cache is always invalid. */ const int CACHE_STALE = 0; /// <summary> /// Internally, the vdbe manipulates nearly all SQL values as Mem /// structures. Each Mem struct may cache multiple representations (string, /// integer etc.) of the same value /// </summary> public class Mem { /// <summary> /// The associated database connection /// </summary> public sqlite3 db; /// <summary> /// String value /// </summary> public string z; /// <summary> /// Real value /// </summary> public double r; public struct union_ip { #if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL /// <summary> /// First operand /// </summary> public i64 _i; public i64 i { get { return _i; } set { _i = value; } } #else /// <summary> /// Integer value used when MEM_Int is set in flags /// </summary> public i64 i; #endif /// <summary> /// Used when bit MEM_Zero is set in flags /// </summary> public int nZero; /// <summary> /// Used only when flags==MEM_Agg /// </summary> public FuncDef pDef; /// <summary> /// Used only when flags==MEM_RowSet /// </summary> public RowSet pRowSet; /// <summary> /// Used when flags==MEM_Frame /// </summary> public VdbeFrame pFrame; }; public union_ip u; /// <summary> /// BLOB value /// </summary> public byte[] zBLOB; /// <summary> /// Number of characters in string value, excluding '\0' /// </summary> public int n; #if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL /// <summary> /// First operand /// </summary> public u16 _flags; public u16 flags { get { return _flags; } set { _flags = value; } } #else /// <summary> /// Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. /// </summary> public u16 flags; #endif /// <summary> /// One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc /// </summary> public u8 type; /// <summary> /// SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE /// </summary> public u8 enc; #if SQLITE_DEBUG /// <summary> /// This Mem is a shallow copy of pScopyFrom /// </summary> public Mem pScopyFrom; /// <summary> /// So that sizeof(Mem) is a multiple of 8 /// </summary> public object pFiller; #endif /// <summary> /// If not null, call this function to delete Mem.z /// </summary> public dxDel xDel; /// <summary> /// Used when C# overload Z as MEM space /// </summary> public Mem _Mem; /// <summary> /// Used when C# overload Z as Sum context /// </summary> public SumCtx _SumCtx; /// <summary> /// Used when C# overload Z as SubProgram /// </summary> public SubProgram[] _SubProgram; /// <summary> /// Used when C# overload Z as STR context /// </summary> public StrAccum _StrAccum; /// <summary> /// Used when C# overload Z as MD5 context /// </summary> public object _MD5Context; public Mem() { } public Mem(sqlite3 db, string z, double r, int i, int n, u16 flags, u8 type, u8 enc #if SQLITE_DEBUG , Mem pScopyFrom, object pFiller /* pScopyFrom, pFiller */ #endif ) { this.db = db; this.z = z; this.r = r; this.u.i = i; this.n = n; this.flags = flags; #if SQLITE_DEBUG this.pScopyFrom = pScopyFrom; this.pFiller = pFiller; #endif this.type = type; this.enc = enc; } public void CopyTo(ref Mem ct) { if (ct == null) ct = new Mem(); ct.u = u; ct.r = r; ct.db = db; ct.z = z; if (zBLOB == null) ct.zBLOB = null; else { ct.zBLOB = sqlite3Malloc(zBLOB.Length); Buffer.BlockCopy(zBLOB, 0, ct.zBLOB, 0, zBLOB.Length); } ct.n = n; ct.flags = flags; ct.type = type; ct.enc = enc; ct.xDel = xDel; } }; /* One or more of the following flags are set to indicate the validOK ** representations of the value stored in the Mem struct. ** ** If the MEM_Null flag is set, then the value is an SQL NULL value. ** No other flags may be set in this case. ** ** If the MEM_Str flag is set then Mem.z points at a string representation. ** Usually this is encoded in the same unicode encoding as the main ** database (see below for exceptions). If the MEM_Term flag is also ** set, then the string is nul terminated. The MEM_Int and MEM_Real ** flags may coexist with the MEM_Str flag. */ //#define MEM_Null 0x0001 /* Value is NULL */ //#define MEM_Str 0x0002 /* Value is a string */ //#define MEM_Int 0x0004 /* Value is an integer */ //#define MEM_Real 0x0008 /* Value is a real number */ //#define MEM_Blob 0x0010 /* Value is a BLOB */ //#define MEM_RowSet 0x0020 /* Value is a RowSet object */ //#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ //#define MEM_Invalid 0x0080 /* Value is undefined */ //#define MEM_TypeMask 0x00ff /* Mask of type bits */ const int MEM_Null = 0x0001; const int MEM_Str = 0x0002; const int MEM_Int = 0x0004; const int MEM_Real = 0x0008; const int MEM_Blob = 0x0010; const int MEM_RowSet = 0x0020; const int MEM_Frame = 0x0040; const int MEM_Invalid = 0x0080; const int MEM_TypeMask = 0x00ff; /* Whenever Mem contains a valid string or blob representation, one of ** the following flags must be set to determine the memory management ** policy for Mem.z. The MEM_Term flag tells us whether or not the ** string is \000 or \u0000 terminated // */ //#define MEM_Term 0x0200 /* String rep is nul terminated */ //#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */ //#define MEM_Static 0x0800 /* Mem.z points to a static string */ //#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ //#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ //#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ //#if SQLITE_OMIT_INCRBLOB // #undef MEM_Zero // #define MEM_Zero 0x0000 //#endif const int MEM_Term = 0x0200; const int MEM_Dyn = 0x0400; const int MEM_Static = 0x0800; const int MEM_Ephem = 0x1000; const int MEM_Agg = 0x2000; #if !SQLITE_OMIT_INCRBLOB const int MEM_Zero = 0x4000; #else const int MEM_Zero = 0x0000; #endif /* ** Clear any existing type flags from a Mem and replace them with f */ //#define MemSetTypeFlag(p, f) \ // ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) static void MemSetTypeFlag(Mem p, int f) { p.flags = (u16)(p.flags & ~(MEM_TypeMask | MEM_Zero) | f); }// TODO -- Convert back to inline for speed /* ** Return true if a memory cell is not marked as invalid. This macro ** is for use inside Debug.Assert() statements only. */ #if SQLITE_DEBUG //#define memIsValid(M) ((M)->flags & MEM_Invalid)==0 static bool memIsValid( Mem M ) { return ( ( M ).flags & MEM_Invalid ) == 0; } #else static bool memIsValid(Mem M) { return true; } #endif /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains ** additional information about auxiliary information bound to arguments ** of the function. This is used to implement the sqlite3_get_auxdata() ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data ** that can be associated with a constant argument to a function. This ** allows functions such as "regexp" to compile their constant regular ** expression argument once and reused the compiled code for multiple ** invocations. */ public class AuxData { /// <summary> /// Aux data for the i-th argument /// </summary> public object pAux; }; public class VdbeFunc : FuncDef { /// <summary> /// The definition of the function /// </summary> public FuncDef pFunc; /// <summary> /// Number of entries allocated for apAux[] /// </summary> public int nAux; /// <summary> /// One slot for each function argument /// </summary> public AuxData[] apAux = new AuxData[2]; }; /// <summary> /// The "context" argument for a installable function. A pointer to an /// instance of this structure is the first argument to the routines used /// implement the SQL functions. /// /// There is a typedef for this structure in sqlite.h. So all routines, /// even the public interface to SQLite, can use a pointer to this structure. /// But this file is the only place where the internal details of this /// structure are known. /// /// This structure is defined inside of vdbeInt.h because it uses substructures /// (Mem) which are only defined there /// </summary> public class sqlite3_context { /// <summary> /// Pointer to function information. MUST BE FIRST /// </summary> public FuncDef pFunc; /// <summary> /// Auxilary data, if created. /// </summary> public VdbeFunc pVdbeFunc; /// <summary> /// The return value is stored here /// </summary> public Mem s = new Mem(); /// <summary> /// Memory cell used to store aggregate context /// </summary> public Mem pMem; /// <summary> /// Error code returned by the function. /// </summary> public int isError; /// <summary> /// Collating sequence /// </summary> public CollSeq pColl; }; /// <summary> /// An instance of the virtual machine. This structure contains the complete /// state of the virtual machine. /// /// The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() /// is really a pointer to an instance of this structure. /// /// The Vdbe.inVtabMethod variable is set to non-zero for the duration of /// any virtual table method invocations made by the vdbe program. It is /// set to 2 for xDestroy method calls and 1 for all other methods. This /// variable is used for two purposes: to allow xDestroy methods to execute /// "DROP TABLE" statements and to prevent some nasty side effects of /// malloc failure when SQLite is invoked recursively by a virtual table /// method function /// </summary> public class Vdbe { /// <summary> /// The database connection that owns this statement /// </summary> public sqlite3 db; /// <summary> /// Space to hold the virtual machine's program /// </summary> public Op[] aOp; /// <summary> /// The memory locations /// </summary> public Mem[] aMem; /// <summary> /// Arguments to currently executing user function /// </summary> public Mem[] apArg; /// <summary> /// Column names to return /// </summary> public Mem[] aColName; /// <summary> /// Pointer to an array of results /// </summary> public Mem[] pResultSet; /// <summary> /// Number of memory locations currently allocated /// </summary> public int nMem; /// <summary> /// Number of instructions in the program /// </summary> public int nOp; /// <summary> /// Number of slots allocated for aOp[] /// </summary> public int nOpAlloc; /// <summary> /// Number of labels used /// </summary> public int nLabel; /// <summary> /// Number of slots allocated in aLabel[] /// </summary> public int nLabelAlloc; /// <summary> /// Space to hold the labels /// </summary> public int[] aLabel; /// <summary> /// Number of columns in one row of the result set /// </summary> public u16 nResColumn; /// <summary> /// Number of slots in apCsr[] /// </summary> public u16 nCursor; /// <summary> /// Magic number for sanity checking /// </summary> public u32 magic; /// <summary> /// Error message written here /// </summary> public string zErrMsg; /// <summary> /// Linked list of VDBEs with the same Vdbe.db /// </summary> public Vdbe pPrev; /// <summary> /// Linked list of VDBEs with the same Vdbe.db /// </summary> public Vdbe pNext; /// <summary> /// One element of this array for each open cursor /// </summary> public VdbeCursor[] apCsr; /// <summary> /// Values for the OP_Variable opcode. /// </summary> public Mem[] aVar; /// <summary> /// Name of variables /// </summary> public string[] azVar; /// <summary> /// Number of entries in aVar[] /// </summary> public ynVar nVar; /// <summary> /// Number of entries in azVar[] /// </summary> public ynVar nzVar; /// <summary> /// VdbeCursor row cache generation counter /// </summary> public u32 cacheCtr; /// <summary> /// The program counter /// </summary> public int pc; /// <summary> /// Value to return /// </summary> public int rc; /// <summary> /// Recovery action to do in case of an error /// </summary> public u8 errorAction; /// <summary> /// True if EXPLAIN present on SQL command /// </summary> public int explain; /// <summary> /// True to update the change-counter /// </summary> public bool changeCntOn; /// <summary> /// True if the VM needs to be recompiled /// </summary> public bool expired; /// <summary> /// Automatically expire on reset /// </summary> public u8 runOnlyOnce; /// <summary> /// Minimum file format for writable database files /// </summary> public int minWriteFileFormat; /// <summary> /// See comments above /// </summary> public int inVtabMethod; /// <summary> /// True if uses a statement journal /// </summary> public bool usesStmtJournal; /// <summary> /// True for read-only statements /// </summary> public bool readOnly; /// <summary> /// Number of db changes made since last reset /// </summary> public int nChange; /// <summary> /// True if prepared with prepare_v2() /// </summary> public bool isPrepareV2; /// <summary> /// Bitmask of db.aDb[] entries referenced /// </summary> public yDbMask btreeMask; /// <summary> /// Subset of btreeMask that requires a lock /// </summary> public yDbMask lockMask; /// <summary> /// Statement number (or 0 if has not opened stmt) /// </summary> public int iStatement; /// <summary> /// Counters used by sqlite3_stmt_status() /// </summary> public int[] aCounter = new int[3]; #if !SQLITE_OMIT_TRACE /// <summary> /// Time when query started - used for profiling /// </summary> public i64 startTime; #endif /// <summary> /// Number of imm. FK constraints this VM /// </summary> public i64 nFkConstraint; /// <summary> /// Number of def. constraints when stmt started /// </summary> public i64 nStmtDefCons; /// <summary> /// Text of the SQL statement that generated this /// </summary> public string zSql = ""; /// <summary> /// Free this when deleting the vdbe /// </summary> public object pFree; #if SQLITE_DEBUG /// <summary> /// Write an execution trace here, if not NULL /// </summary> public FILE trace; #endif /// <summary> /// Parent frame /// </summary> public VdbeFrame pFrame; /// <summary> /// List of frame objects to free on VM reset /// </summary> public VdbeFrame pDelFrame; /// <summary> /// Number of frames in pFrame list /// </summary> public int nFrame; /// <summary> /// Binding to these vars invalidates VM /// </summary> public u32 expmask; /// <summary> /// Linked list of all sub-programs used by VM /// </summary> public SubProgram pProgram; public Vdbe Copy() { Vdbe cp = (Vdbe)MemberwiseClone(); return cp; } public void CopyTo(Vdbe ct) { ct.db = db; ct.pPrev = pPrev; ct.pNext = pNext; ct.nOp = nOp; ct.nOpAlloc = nOpAlloc; ct.aOp = aOp; ct.nLabel = nLabel; ct.nLabelAlloc = nLabelAlloc; ct.aLabel = aLabel; ct.apArg = apArg; ct.aColName = aColName; ct.nCursor = nCursor; ct.apCsr = apCsr; ct.aVar = aVar; ct.azVar = azVar; ct.nVar = nVar; ct.nzVar = nzVar; ct.magic = magic; ct.nMem = nMem; ct.aMem = aMem; ct.cacheCtr = cacheCtr; ct.pc = pc; ct.rc = rc; ct.errorAction = errorAction; ct.nResColumn = nResColumn; ct.zErrMsg = zErrMsg; ct.pResultSet = pResultSet; ct.explain = explain; ct.changeCntOn = changeCntOn; ct.expired = expired; ct.minWriteFileFormat = minWriteFileFormat; ct.inVtabMethod = inVtabMethod; ct.usesStmtJournal = usesStmtJournal; ct.readOnly = readOnly; ct.nChange = nChange; ct.isPrepareV2 = isPrepareV2; #if !SQLITE_OMIT_TRACE ct.startTime = startTime; #endif ct.btreeMask = btreeMask; ct.lockMask = lockMask; aCounter.CopyTo(ct.aCounter, 0); ct.zSql = zSql; ct.pFree = pFree; #if SQLITE_DEBUG ct.trace = trace; #endif ct.nFkConstraint = nFkConstraint; ct.nStmtDefCons = nStmtDefCons; ct.iStatement = iStatement; ct.pFrame = pFrame; ct.nFrame = nFrame; ct.expmask = expmask; ct.pProgram = pProgram; #if SQLITE_SSE ct.fetchId=fetchId; ct.lru=lru; #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT ct.pLruPrev=pLruPrev; ct.pLruNext=pLruNext; #endif } }; /* ** The following are allowed values for Vdbe.magic */ //#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */ //#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */ //#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */ //#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */ const u32 VDBE_MAGIC_INIT = 0x26bceaa5; /* Building a VDBE program */ const u32 VDBE_MAGIC_RUN = 0xbdf20da3; /* VDBE is ready to execute */ const u32 VDBE_MAGIC_HALT = 0x519c2973; /* VDBE has completed execution */ const u32 VDBE_MAGIC_DEAD = 0xb606c3c8; /* The VDBE has been deallocated */ /* ** Function prototypes */ //void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor); //void sqliteVdbePopStack(Vdbe*,int); //int sqlite3VdbeCursorMoveto(VdbeCursor); //#if (SQLITE_DEBUG) || defined(VDBE_PROFILE) //void sqlite3VdbePrintOp(FILE*, int, Op); //#endif //u32 sqlite3VdbeSerialTypeLen(u32); //u32 sqlite3VdbeSerialType(Mem*, int); //u32sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int); //u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem); //void sqlite3VdbeDeleteAuxData(VdbeFunc*, int); //int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int ); //int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int); //int sqlite3VdbeIdxRowid(sqlite3 *, i64 ); //int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq); //int sqlite3VdbeExec(Vdbe); //int sqlite3VdbeList(Vdbe); //int sqlite3VdbeHalt(Vdbe); //int sqlite3VdbeChangeEncoding(Mem *, int); //int sqlite3VdbeMemTooBig(Mem); //int sqlite3VdbeMemCopy(Mem*, const Mem); //void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); //void sqlite3VdbeMemMove(Mem*, Mem); //int sqlite3VdbeMemNulTerminate(Mem); //int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void()(void)); //void sqlite3VdbeMemSetInt64(Mem*, i64); #if SQLITE_OMIT_FLOATING_POINT //# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 #else //void sqlite3VdbeMemSetDouble(Mem*, double); #endif //void sqlite3VdbeMemSetNull(Mem); //void sqlite3VdbeMemSetZeroBlob(Mem*,int); //void sqlite3VdbeMemSetRowSet(Mem); //int sqlite3VdbeMemMakeWriteable(Mem); //int sqlite3VdbeMemStringify(Mem*, int); //i64 sqlite3VdbeIntValue(Mem); //int sqlite3VdbeMemIntegerify(Mem); //double sqlite3VdbeRealValue(Mem); //void sqlite3VdbeIntegerAffinity(Mem); //int sqlite3VdbeMemRealify(Mem); //int sqlite3VdbeMemNumerify(Mem); //int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem); //void sqlite3VdbeMemRelease(Mem p); //void sqlite3VdbeMemReleaseExternal(Mem p); //int sqlite3VdbeMemFinalize(Mem*, FuncDef); //string sqlite3OpcodeName(int); //int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve); //int sqlite3VdbeCloseStatement(Vdbe *, int); //void sqlite3VdbeFrameDelete(VdbeFrame); //int sqlite3VdbeFrameRestore(VdbeFrame ); //void sqlite3VdbeMemStoreType(Mem *pMem); #if !(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE//>0 //void sqlite3VdbeEnter(Vdbe); //void sqlite3VdbeLeave(Vdbe); #else //# define sqlite3VdbeEnter(X) static void sqlite3VdbeEnter(Vdbe p) { } //# define sqlite3VdbeLeave(X) static void sqlite3VdbeLeave(Vdbe p) { } #endif #if SQLITE_DEBUG //void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem); #endif #if !SQLITE_OMIT_FOREIGN_KEY //int sqlite3VdbeCheckFk(Vdbe *, int); #else //# define sqlite3VdbeCheckFk(p,i) 0 static int sqlite3VdbeCheckFk( Vdbe p, int i ) { return 0; } #endif //int sqlite3VdbeMemTranslate(Mem*, u8); //#if SQLITE_DEBUG // void sqlite3VdbePrintSql(Vdbe); // void sqlite3VdbeMemPrettyPrint(Mem pMem, string zBuf); //#endif //int sqlite3VdbeMemHandleBom(Mem pMem); #if !SQLITE_OMIT_INCRBLOB // int sqlite3VdbeMemExpandBlob(Mem ); #else // #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK static int sqlite3VdbeMemExpandBlob(Mem x) { return SQLITE_OK; } #endif //#endif //* !_VDBEINT_H_) */ } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Controller class for Rem_ExamenPie /// </summary> [System.ComponentModel.DataObject] public partial class RemExamenPieController { // Preload our schema.. RemExamenPie thisSchemaLoad = new RemExamenPie(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public RemExamenPieCollection FetchAll() { RemExamenPieCollection coll = new RemExamenPieCollection(); Query qry = new Query(RemExamenPie.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public RemExamenPieCollection FetchByID(object IdExamenPies) { RemExamenPieCollection coll = new RemExamenPieCollection().Where("idExamenPies", IdExamenPies).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public RemExamenPieCollection FetchByQuery(Query qry) { RemExamenPieCollection coll = new RemExamenPieCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object IdExamenPies) { return (RemExamenPie.Delete(IdExamenPies) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object IdExamenPies) { return (RemExamenPie.Destroy(IdExamenPies) == 1); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int IdEfector,int IdClasificacion,int IdPaciente,DateTime Fecha,string Observacion,int SensibTermica,int SensibAlgesica,int ReflejoPatelar,int ReflejoAquileano,int SignoAbanico,int SensibDiapason,int FuerzaMuscular,int AlteracionesApoyo,int DisminucionMovilidad,int DedosMartillo,int Clinodactilia,int HalluxValgus,int AusenciaVello,int DisminucionPlantar,int Eritroclanosis,int HiperqueatosisPlantar,int HiperqueatosisUnias,int MicosisUnias,string PresenciaLesiones,int? PuntajeNegativo,DateTime? CreatedOn,string CreatedBy,DateTime? ModifiedOn,string ModifiedBy) { RemExamenPie item = new RemExamenPie(); item.IdEfector = IdEfector; item.IdClasificacion = IdClasificacion; item.IdPaciente = IdPaciente; item.Fecha = Fecha; item.Observacion = Observacion; item.SensibTermica = SensibTermica; item.SensibAlgesica = SensibAlgesica; item.ReflejoPatelar = ReflejoPatelar; item.ReflejoAquileano = ReflejoAquileano; item.SignoAbanico = SignoAbanico; item.SensibDiapason = SensibDiapason; item.FuerzaMuscular = FuerzaMuscular; item.AlteracionesApoyo = AlteracionesApoyo; item.DisminucionMovilidad = DisminucionMovilidad; item.DedosMartillo = DedosMartillo; item.Clinodactilia = Clinodactilia; item.HalluxValgus = HalluxValgus; item.AusenciaVello = AusenciaVello; item.DisminucionPlantar = DisminucionPlantar; item.Eritroclanosis = Eritroclanosis; item.HiperqueatosisPlantar = HiperqueatosisPlantar; item.HiperqueatosisUnias = HiperqueatosisUnias; item.MicosisUnias = MicosisUnias; item.PresenciaLesiones = PresenciaLesiones; item.PuntajeNegativo = PuntajeNegativo; item.CreatedOn = CreatedOn; item.CreatedBy = CreatedBy; item.ModifiedOn = ModifiedOn; item.ModifiedBy = ModifiedBy; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int IdExamenPies,int IdEfector,int IdClasificacion,int IdPaciente,DateTime Fecha,string Observacion,int SensibTermica,int SensibAlgesica,int ReflejoPatelar,int ReflejoAquileano,int SignoAbanico,int SensibDiapason,int FuerzaMuscular,int AlteracionesApoyo,int DisminucionMovilidad,int DedosMartillo,int Clinodactilia,int HalluxValgus,int AusenciaVello,int DisminucionPlantar,int Eritroclanosis,int HiperqueatosisPlantar,int HiperqueatosisUnias,int MicosisUnias,string PresenciaLesiones,int? PuntajeNegativo,DateTime? CreatedOn,string CreatedBy,DateTime? ModifiedOn,string ModifiedBy) { RemExamenPie item = new RemExamenPie(); item.MarkOld(); item.IsLoaded = true; item.IdExamenPies = IdExamenPies; item.IdEfector = IdEfector; item.IdClasificacion = IdClasificacion; item.IdPaciente = IdPaciente; item.Fecha = Fecha; item.Observacion = Observacion; item.SensibTermica = SensibTermica; item.SensibAlgesica = SensibAlgesica; item.ReflejoPatelar = ReflejoPatelar; item.ReflejoAquileano = ReflejoAquileano; item.SignoAbanico = SignoAbanico; item.SensibDiapason = SensibDiapason; item.FuerzaMuscular = FuerzaMuscular; item.AlteracionesApoyo = AlteracionesApoyo; item.DisminucionMovilidad = DisminucionMovilidad; item.DedosMartillo = DedosMartillo; item.Clinodactilia = Clinodactilia; item.HalluxValgus = HalluxValgus; item.AusenciaVello = AusenciaVello; item.DisminucionPlantar = DisminucionPlantar; item.Eritroclanosis = Eritroclanosis; item.HiperqueatosisPlantar = HiperqueatosisPlantar; item.HiperqueatosisUnias = HiperqueatosisUnias; item.MicosisUnias = MicosisUnias; item.PresenciaLesiones = PresenciaLesiones; item.PuntajeNegativo = PuntajeNegativo; item.CreatedOn = CreatedOn; item.CreatedBy = CreatedBy; item.ModifiedOn = ModifiedOn; item.ModifiedBy = ModifiedBy; item.Save(UserName); } } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes // and uses the CompactRepositorySelector instead #if !NETCF using System; using System.Collections; using System.Configuration; using System.Reflection; using log4net.Config; using log4net.Util; using log4net.Repository; namespace log4net.Core { /// <summary> /// The default implementation of the <see cref="IRepositorySelector"/> interface. /// </summary> /// <remarks> /// <para> /// Uses attributes defined on the calling assembly to determine how to /// configure the hierarchy for the repository. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class DefaultRepositorySelector : IRepositorySelector { #region Public Events /// <summary> /// Event to notify that a logger repository has been created. /// </summary> /// <value> /// Event to notify that a logger repository has been created. /// </value> /// <remarks> /// <para> /// Event raised when a new repository is created. /// The event source will be this selector. The event args will /// be a <see cref="LoggerRepositoryCreationEventArgs"/> which /// holds the newly created <see cref="ILoggerRepository"/>. /// </para> /// </remarks> public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent { add { m_loggerRepositoryCreatedEvent += value; } remove { m_loggerRepositoryCreatedEvent -= value; } } #endregion Public Events #region Public Instance Constructors /// <summary> /// Creates a new repository selector. /// </summary> /// <param name="defaultRepositoryType">The type of the repositories to create, must implement <see cref="ILoggerRepository"/></param> /// <remarks> /// <para> /// Create an new repository selector. /// The default type for repositories must be specified, /// an appropriate value would be <see cref="log4net.Repository.Hierarchy.Hierarchy"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="defaultRepositoryType"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="defaultRepositoryType"/> does not implement <see cref="ILoggerRepository"/>.</exception> public DefaultRepositorySelector(Type defaultRepositoryType) { if (defaultRepositoryType == null) { throw new ArgumentNullException("defaultRepositoryType"); } // Check that the type is a repository if (! (typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) ) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); } m_defaultRepositoryType = defaultRepositoryType; LogLog.Debug("DefaultRepositorySelector: defaultRepositoryType [" + m_defaultRepositoryType + "]"); } #endregion Public Instance Constructors #region Implementation of IRepositorySelector /// <summary> /// Gets the <see cref="ILoggerRepository"/> for the specified assembly. /// </summary> /// <param name="repositoryAssembly">The assembly use to lookup the <see cref="ILoggerRepository"/>.</param> /// <remarks> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and the repository /// to create can be overridden by specifying the <see cref="log4net.Config.RepositoryAttribute"/> /// attribute on the <paramref name="repositoryAssembly"/>. /// </para> /// <para> /// The default values are to use the <see cref="log4net.Repository.Hierarchy.Hierarchy"/> /// implementation of the <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the repository. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically configured using /// any <see cref="log4net.Config.ConfiguratorAttribute"/> attributes defined on /// the <paramref name="repositoryAssembly"/>. /// </para> /// </remarks> /// <returns>The <see cref="ILoggerRepository"/> for the assembly</returns> /// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception> public ILoggerRepository GetRepository(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } return CreateRepository(repositoryAssembly, m_defaultRepositoryType); } /// <summary> /// Gets the <see cref="ILoggerRepository"/> for the specified repository. /// </summary> /// <param name="repositoryName">The repository to use to lookup the <see cref="ILoggerRepository"/>.</param> /// <returns>The <see cref="ILoggerRepository"/> for the specified repository.</returns> /// <remarks> /// <para> /// Returns the named repository. If <paramref name="repositoryName"/> is <c>null</c> /// a <see cref="ArgumentNullException"/> is thrown. If the repository /// does not exist a <see cref="LogException"/> is thrown. /// </para> /// <para> /// Use <see cref="CreateRepository(string, Type)"/> to create a repository. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryName"/> is <see langword="null" />.</exception> /// <exception cref="LogException"><paramref name="repositoryName"/> does not exist.</exception> public ILoggerRepository GetRepository(string repositoryName) { if (repositoryName == null) { throw new ArgumentNullException("repositoryName"); } lock(this) { // Lookup in map ILoggerRepository rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; if (rep == null) { throw new LogException("Repository [" + repositoryName + "] is NOT defined."); } return rep; } } /// <summary> /// Create a new repository for the assembly specified /// </summary> /// <param name="repositoryAssembly">the assembly to use to create the repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param> /// <returns>The repository created.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and /// the repository to create can be overridden by specifying the /// <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// <paramref name="repositoryAssembly"/>. The default values are to use the /// <paramref name="repositoryType"/> implementation of the /// <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the repository. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically /// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes defined on the <paramref name="repositoryAssembly"/>. /// </para> /// <para> /// If a repository for the <paramref name="repositoryAssembly"/> already exists /// that repository will be returned. An error will not be raised and that /// repository may be of a different type to that specified in <paramref name="repositoryType"/>. /// Also the <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// assembly may be used to override the repository type specified in /// <paramref name="repositoryType"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception> public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) { return CreateRepository(repositoryAssembly, repositoryType, DefaultRepositoryName, true); } /// <summary> /// Creates a new repository for the assembly specified. /// </summary> /// <param name="repositoryAssembly">the assembly to use to create the repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryName">The name to assign to the created repository</param> /// <param name="readAssemblyAttributes">Set to <c>true</c> to read and apply the assembly attributes</param> /// <returns>The repository created.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and /// the repository to create can be overridden by specifying the /// <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// <paramref name="repositoryAssembly"/>. The default values are to use the /// <paramref name="repositoryType"/> implementation of the /// <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the repository. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically /// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes defined on the <paramref name="repositoryAssembly"/>. /// </para> /// <para> /// If a repository for the <paramref name="repositoryAssembly"/> already exists /// that repository will be returned. An error will not be raised and that /// repository may be of a different type to that specified in <paramref name="repositoryType"/>. /// Also the <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// assembly may be used to override the repository type specified in /// <paramref name="repositoryType"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception> public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { // Lookup in map ILoggerRepository rep = m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository; if (rep == null) { // Not found, therefore create LogLog.Debug("DefaultRepositorySelector: Creating repository for assembly [" + repositoryAssembly + "]"); // Must specify defaults string actualRepositoryName = repositoryName; Type actualRepositoryType = repositoryType; if (readAssemblyAttributes) { // Get the repository and type from the assembly attributes GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType); } LogLog.Debug("DefaultRepositorySelector: Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]"); // Lookup the repository in the map (as this may already be defined) rep = m_name2repositoryMap[actualRepositoryName] as ILoggerRepository; if (rep == null) { // Create the repository rep = CreateRepository(actualRepositoryName, actualRepositoryType); if (readAssemblyAttributes) { try { // Look for aliasing attributes LoadAliases(repositoryAssembly, rep); // Look for plugins defined on the assembly LoadPlugins(repositoryAssembly, rep); // Configure the repository using the assembly attributes ConfigureRepository(repositoryAssembly, rep); } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); } } } else { LogLog.Debug("DefaultRepositorySelector: repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]"); if (readAssemblyAttributes) { try { // Look for plugins defined on the assembly LoadPlugins(repositoryAssembly, rep); } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); } } } m_assembly2repositoryMap[repositoryAssembly] = rep; } return rep; } } /// <summary> /// Creates a new repository for the specified repository. /// </summary> /// <param name="repositoryName">The repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>. /// If this param is <see langword="null" /> then the default repository type is used.</param> /// <returns>The new repository.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="GetRepository(string)"/> with the /// same repository specified will return the same repository instance. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryName"/> is <see langword="null" />.</exception> /// <exception cref="LogException"><paramref name="repositoryName"/> already exists.</exception> public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) { if (repositoryName == null) { throw new ArgumentNullException("repositoryName"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { ILoggerRepository rep = null; // First check that the repository does not exist rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; if (rep != null) { throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); } else { // Lookup an alias before trying to create the new repository ILoggerRepository aliasedRepository = m_alias2repositoryMap[repositoryName] as ILoggerRepository; if (aliasedRepository != null) { // Found an alias // Check repository type if (aliasedRepository.GetType() == repositoryType) { // Repository type is compatible LogLog.Debug("DefaultRepositorySelector: Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]"); rep = aliasedRepository; // Store in map m_name2repositoryMap[repositoryName] = rep; } else { // Invalid repository type for alias LogLog.Error("DefaultRepositorySelector: Failed to alias repository [" + repositoryName + "] to existing repository ["+aliasedRepository.Name+"]. Requested repository type ["+repositoryType.FullName+"] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]"); // We now drop through to create the repository without aliasing } } // If we could not find an alias if (rep == null) { LogLog.Debug("DefaultRepositorySelector: Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); // Call the no arg constructor for the repositoryType rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); // Set the name of the repository rep.Name = repositoryName; // Store in map m_name2repositoryMap[repositoryName] = rep; // Notify listeners that the repository has been created OnLoggerRepositoryCreatedEvent(rep); } } return rep; } } /// <summary> /// Test if a named repository exists /// </summary> /// <param name="repositoryName">the named repository to check</param> /// <returns><c>true</c> if the repository exists</returns> /// <remarks> /// <para> /// Test if a named repository exists. Use <see cref="CreateRepository(string, Type)"/> /// to create a new repository and <see cref="GetRepository(string)"/> to retrieve /// a repository. /// </para> /// </remarks> public bool ExistsRepository(string repositoryName) { lock(this) { return m_name2repositoryMap.ContainsKey(repositoryName); } } /// <summary> /// Gets a list of <see cref="ILoggerRepository"/> objects /// </summary> /// <returns>an array of all known <see cref="ILoggerRepository"/> objects</returns> /// <remarks> /// <para> /// Gets an array of all of the repositories created by this selector. /// </para> /// </remarks> public ILoggerRepository[] GetAllRepositories() { lock(this) { ICollection reps = m_name2repositoryMap.Values; ILoggerRepository[] all = new ILoggerRepository[reps.Count]; reps.CopyTo(all, 0); return all; } } #endregion Implementation of IRepositorySelector #region Public Instance Methods /// <summary> /// Aliases a repository to an existing repository. /// </summary> /// <param name="repositoryAlias">The repository to alias.</param> /// <param name="repositoryTarget">The repository that the repository is aliased to.</param> /// <remarks> /// <para> /// The repository specified will be aliased to the repository when created. /// The repository must not already exist. /// </para> /// <para> /// When the repository is created it must utilize the same repository type as /// the repository it is aliased to, otherwise the aliasing will fail. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <para><paramref name="repositoryAlias" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repositoryTarget" /> is <see langword="null" />.</para> /// </exception> public void AliasRepository(string repositoryAlias, ILoggerRepository repositoryTarget) { if (repositoryAlias == null) { throw new ArgumentNullException("repositoryAlias"); } if (repositoryTarget == null) { throw new ArgumentNullException("repositoryTarget"); } lock(this) { // Check if the alias is already set if (m_alias2repositoryMap.Contains(repositoryAlias)) { // Check if this is a duplicate of the current alias if (repositoryTarget != ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias])) { // Cannot redefine existing alias throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined."); } } // Check if the alias is already mapped to a repository else if (m_name2repositoryMap.Contains(repositoryAlias)) { // Check if this is a duplicate of the current mapping if ( repositoryTarget != ((ILoggerRepository)m_name2repositoryMap[repositoryAlias]) ) { // Cannot define alias for already mapped repository throw new InvalidOperationException("Repository [" + repositoryAlias + "] already exists and cannot be aliased to repository [" + repositoryTarget.Name + "]."); } } else { // Set the alias m_alias2repositoryMap[repositoryAlias] = repositoryTarget; } } } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Notifies the registered listeners that the repository has been created. /// </summary> /// <param name="repository">The repository that has been created.</param> /// <remarks> /// <para> /// Raises the <see cref="LoggerRepositoryCreatedEvent"/> event. /// </para> /// </remarks> protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) { LoggerRepositoryCreationEventHandler handler = m_loggerRepositoryCreatedEvent; if (handler != null) { handler(this, new LoggerRepositoryCreationEventArgs(repository)); } } #endregion Protected Instance Methods #region Private Instance Methods /// <summary> /// Gets the repository name and repository type for the specified assembly. /// </summary> /// <param name="assembly">The assembly that has a <see cref="log4net.Config.RepositoryAttribute"/>.</param> /// <param name="repositoryName">in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling.</param> /// <param name="repositoryType">in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly" /> is <see langword="null" />.</exception> private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType) { if (assembly == null) { throw new ArgumentNullException("assembly"); } try { LogLog.Debug("DefaultRepositorySelector: Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); } catch { // Ignore exception from debug call } try { // Look for the RepositoryAttribute on the assembly object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.RepositoryAttribute), false); if (repositoryAttributes == null || repositoryAttributes.Length == 0) { // This is not a problem, but its nice to know what is going on. LogLog.Debug("DefaultRepositorySelector: Assembly [" + assembly + "] does not have a RepositoryAttribute specified."); } else { if (repositoryAttributes.Length > 1) { LogLog.Error("DefaultRepositorySelector: Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence."); } log4net.Config.RepositoryAttribute domAttr = repositoryAttributes[0] as log4net.Config.RepositoryAttribute; if (domAttr == null) { LogLog.Error("DefaultRepositorySelector: Assembly [" + assembly + "] has a RepositoryAttribute but it does not!."); } else { // If the Name property is set then override the default if (domAttr.Name != null) { repositoryName = domAttr.Name; } // If the RepositoryType property is set then override the default if (domAttr.RepositoryType != null) { // Check that the type is a repository if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) { repositoryType = domAttr.RepositoryType; } else { LogLog.Error("DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); } } } } } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Unhandled exception in GetInfoForAssembly", ex); } } /// <summary> /// Configures the repository using information from the assembly. /// </summary> /// <param name="assembly">The assembly containing <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes which define the configuration for the repository.</param> /// <param name="repository">The repository to configure.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { // Sort the ConfiguratorAttributes in priority order Array.Sort(configAttributes); // Delegate to the attribute the job of configuring the repository foreach(log4net.Config.ConfiguratorAttribute configAttr in configAttributes) { if (configAttr != null) { try { configAttr.Configure(assembly, repository); } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Exception calling ["+configAttr.GetType().FullName+"] .Configure method.", ex); } } } } if (repository.Name == DefaultRepositoryName) { // Try to configure the default repository using an AppSettings specified config file // Do this even if the repository has been configured (or claims to be), this allows overriding // of the default config files etc, if that is required. string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch(Exception ex) { LogLog.Warn("DefaultRepositorySelector: Exception getting ApplicationBaseDirectory. appSettings log4net.Config path ["+repositoryConfigFile+"] will be treated as an absolute URI", ex); } // As we are not going to watch the config file it is easiest to just resolve it as a // URI and pass that to the Configurator Uri repositoryConfigUri = null; try { if (applicationBaseDirectory != null) { // Resolve the config path relative to the application base directory URI repositoryConfigUri = new Uri(new Uri(applicationBaseDirectory), repositoryConfigFile); } else { repositoryConfigUri = new Uri(repositoryConfigFile); } } catch(Exception ex) { LogLog.Error("DefaultRepositorySelector: Exception while parsing log4net.Config file path ["+repositoryConfigFile+"]", ex); } if (repositoryConfigUri != null) { LogLog.Debug("DefaultRepositorySelector: Loading configuration for default repository from AppSettings specified Config URI ["+repositoryConfigUri.ToString()+"]"); try { // TODO: Support other types of configurator XmlConfigurator.Configure(repository, repositoryConfigUri); } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Exception calling XmlConfigurator.Configure method with ConfigUri ["+repositoryConfigUri+"]", ex); } } } } } /// <summary> /// Loads the attribute defined plugins on the assembly. /// </summary> /// <param name="assembly">The assembly that contains the attributes.</param> /// <param name="repository">The repository to add the plugins to.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void LoadPlugins(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the PluginAttribute on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.PluginAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { foreach(log4net.Plugin.IPluginFactory configAttr in configAttributes) { try { // Create the plugin and add it to the repository repository.PluginMap.Add(configAttr.CreatePlugin()); } catch(Exception ex) { LogLog.Error("DefaultRepositorySelector: Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex); } } } } /// <summary> /// Loads the attribute defined aliases on the assembly. /// </summary> /// <param name="assembly">The assembly that contains the attributes.</param> /// <param name="repository">The repository to alias to.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void LoadAliases(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the AliasRepositoryAttribute on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.AliasRepositoryAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { foreach(log4net.Config.AliasRepositoryAttribute configAttr in configAttributes) { try { AliasRepository(configAttr.Name, repository); } catch(Exception ex) { LogLog.Error("DefaultRepositorySelector: Failed to alias repository [" + configAttr.Name + "]", ex); } } } } #endregion Private Instance Methods #region Private Static Fields private const string DefaultRepositoryName = "log4net-default-repository"; #endregion Private Static Fields #region Private Instance Fields private readonly Hashtable m_name2repositoryMap = new Hashtable(); private readonly Hashtable m_assembly2repositoryMap = new Hashtable(); private readonly Hashtable m_alias2repositoryMap = new Hashtable(); private readonly Type m_defaultRepositoryType; private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; #endregion Private Instance Fields } } #endif // !NETCF
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Sse2.IsSupported) { using (TestTable<double> doubleTable = new TestTable<double>(new double[2] { 1, -5 }, new double[2])) { var vf = Unsafe.Read<Vector128<double>>(doubleTable.inArrayPtr); Sse2.Store((double*)(doubleTable.outArrayPtr), vf); if (!doubleTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y))) { Console.WriteLine("Sse2 Store failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<long> intTable = new TestTable<long>(new long[2] { 1, -5 }, new long[2])) { var vf = Unsafe.Read<Vector128<long>>(intTable.inArrayPtr); Sse2.Store((long*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on long:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ulong> intTable = new TestTable<ulong>(new ulong[2] { 1, 5 }, new ulong[2])) { var vf = Unsafe.Read<Vector128<ulong>>(intTable.inArrayPtr); Sse2.Store((ulong*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on ulong:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<int> intTable = new TestTable<int>(new int[4] { 1, -5, 100, 0 }, new int[4])) { var vf = Unsafe.Read<Vector128<int>>(intTable.inArrayPtr); Sse2.Store((int*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on int:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<uint> intTable = new TestTable<uint>(new uint[4] { 1, 5, 100, 0 }, new uint[4])) { var vf = Unsafe.Read<Vector128<uint>>(intTable.inArrayPtr); Sse2.Store((uint*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on uint:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<short> intTable = new TestTable<short>(new short[8] { 1, -5, 100, 0, 1, 2, 3, 4 }, new short[8])) { var vf = Unsafe.Read<Vector128<short>>(intTable.inArrayPtr); Sse2.Store((short*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on short:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ushort> intTable = new TestTable<ushort>(new ushort[8] { 1, 5, 100, 0, 1, 2, 3, 4 }, new ushort[8])) { var vf = Unsafe.Read<Vector128<ushort>>(intTable.inArrayPtr); Sse2.Store((ushort*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on ushort:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<sbyte> intTable = new TestTable<sbyte>(new sbyte[16] { 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4 }, new sbyte[16])) { var vf = Unsafe.Read<Vector128<sbyte>>(intTable.inArrayPtr); Sse2.Store((sbyte*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on sbyte:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<byte> intTable = new TestTable<byte>(new byte[16] { 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4 }, new byte[16])) { var vf = Unsafe.Read<Vector128<byte>>(intTable.inArrayPtr); Sse2.Store((byte*)(intTable.outArrayPtr), vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 Store failed on byte:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray; public T[] outArray; public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle; GCHandle outHandle; public TestTable(T[] a, T[] b) { this.inArray = a; this.outArray = b; inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T, T, bool> check) { for (int i = 0; i < inArray.Length; i++) { if (!check(inArray[i], outArray[i])) { return false; } } return true; } public void Dispose() { inHandle.Free(); outHandle.Free(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using YamlDotNet.Serialization; using Microsoft.DocAsCode.Common.EntityMergers; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.DataContracts.ManagedReference; public class MetadataItem : ICloneable { [YamlIgnore] [JsonIgnore] public bool IsInvalid { get; set; } [YamlIgnore] [JsonIgnore] public string RawComment { get; set; } [JsonProperty(Constants.PropertyName.IsEii)] [YamlMember(Alias = Constants.PropertyName.IsEii)] public bool IsExplicitInterfaceImplementation { get; set; } [YamlMember(Alias = "isExtensionMethod")] [JsonProperty("isExtensionMethod")] public bool IsExtensionMethod { get; set; } [YamlMember(Alias = Constants.PropertyName.Id)] [JsonProperty(Constants.PropertyName.Id)] public string Name { get; set; } [YamlMember(Alias = Constants.PropertyName.CommentId)] [JsonProperty(Constants.PropertyName.CommentId)] public string CommentId { get; set; } [YamlMember(Alias = "language")] [JsonProperty("language")] public SyntaxLanguage Language { get; set; } [YamlMember(Alias = "name")] [JsonProperty("name")] public SortedList<SyntaxLanguage, string> DisplayNames { get; set; } [YamlMember(Alias = "nameWithType")] [JsonProperty("nameWithType")] public SortedList<SyntaxLanguage, string> DisplayNamesWithType { get; set; } [YamlMember(Alias = "qualifiedName")] [JsonProperty("qualifiedName")] public SortedList<SyntaxLanguage, string> DisplayQualifiedNames { get; set; } [YamlMember(Alias = "parent")] [JsonProperty("parent")] public MetadataItem Parent { get; set; } [YamlMember(Alias = Constants.PropertyName.Type)] [JsonProperty(Constants.PropertyName.Type)] public MemberType Type { get; set; } [YamlMember(Alias = "assemblies")] [JsonProperty("assemblies")] public List<string> AssemblyNameList { get; set; } [YamlMember(Alias = "namespace")] [JsonProperty("namespace")] public string NamespaceName { get; set; } [YamlMember(Alias = Constants.PropertyName.Source)] [JsonProperty(Constants.PropertyName.Source)] public SourceDetail Source { get; set; } [YamlMember(Alias = Constants.PropertyName.Documentation)] [JsonProperty(Constants.PropertyName.Documentation)] public SourceDetail Documentation { get; set; } public List<LayoutItem> Layout { get; set; } [YamlMember(Alias = "summary")] [JsonProperty("summary")] public string Summary { get; set; } [YamlMember(Alias = "remarks")] [JsonProperty("remarks")] public string Remarks { get; set; } [YamlMember(Alias = "example")] [JsonProperty("example")] public List<string> Examples { get; set; } [YamlMember(Alias = "syntax")] [JsonProperty("syntax")] public SyntaxDetail Syntax { get; set; } [YamlMember(Alias = "overload")] [JsonProperty("overload")] public string Overload { get; set; } [YamlMember(Alias = "overridden")] [JsonProperty("overridden")] public string Overridden { get; set; } [YamlMember(Alias = "exceptions")] [JsonProperty("exceptions")] public List<ExceptionInfo> Exceptions { get; set; } [YamlMember(Alias = "see")] [JsonProperty("see")] public List<LinkInfo> Sees { get; set; } [YamlMember(Alias = "seealso")] [JsonProperty("seealso")] public List<LinkInfo> SeeAlsos { get; set; } [YamlMember(Alias = "inheritance")] [JsonProperty("inheritance")] public List<string> Inheritance { get; set; } [YamlMember(Alias = "derivedClasses")] [JsonProperty("derivedClasses")] public List<string> DerivedClasses { get; set; } [YamlMember(Alias = "implements")] [JsonProperty("implements")] public List<string> Implements { get; set; } [YamlMember(Alias = "inheritedMembers")] [JsonProperty("inheritedMembers")] public List<string> InheritedMembers { get; set; } [YamlMember(Alias = "extensionMethods")] [JsonProperty("extensionMethods")] public List<string> ExtensionMethods { get; set; } [YamlMember(Alias = "attributes")] [JsonProperty("attributes")] [MergeOption(MergeOption.Ignore)] public List<AttributeInfo> Attributes { get; set; } [YamlMember(Alias = "modifiers")] [JsonProperty("modifiers")] public SortedList<SyntaxLanguage, List<string>> Modifiers { get; set; } = new SortedList<SyntaxLanguage, List<string>>(); [YamlMember(Alias = "items")] [JsonProperty("items")] public List<MetadataItem> Items { get; set; } [YamlMember(Alias = "references")] [JsonProperty("references")] public Dictionary<string, ReferenceItem> References { get; set; } [YamlIgnore] [JsonIgnore] public string InheritDoc { get; set; } [YamlIgnore] [JsonIgnore] public TripleSlashCommentModel CommentModel { get; set; } public override string ToString() { return Type + ": " + Name; } public object Clone() { return MemberwiseClone(); } public void CopyInheritedData(MetadataItem src) { if (src == null) throw new ArgumentNullException(nameof(src)); if (Summary == null) Summary = src.Summary; if (Remarks == null) Remarks = src.Remarks; if (Exceptions == null && src.Exceptions != null) Exceptions = src.Exceptions.Select(e => e.Clone()).ToList(); if (Sees == null && src.Sees != null) Sees = src.Sees.Select(s => s.Clone()).ToList(); if (SeeAlsos == null && src.SeeAlsos != null) SeeAlsos = src.SeeAlsos.Select(s => s.Clone()).ToList(); if (Examples == null && src.Examples != null) Examples = new List<string>(src.Examples); if (CommentModel != null && src.CommentModel != null) CommentModel.CopyInheritedData(src.CommentModel); if (Syntax != null && src.Syntax != null) Syntax.CopyInheritedData(src.Syntax); } } }
using Bridge.Contract; using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem.Implementation; using Mono.Cecil; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Bridge.Translator { public partial class Emitter { protected virtual HashSet<string> CreateNamespaces() { var result = new HashSet<string>(); foreach (string typeName in this.TypeDefinitions.Keys) { int index = typeName.LastIndexOf('.'); if (index >= 0) { this.RegisterNamespace(typeName.Substring(0, index), result); } } return result; } protected virtual void RegisterNamespace(string ns, ICollection<string> repository) { if (String.IsNullOrEmpty(ns) || repository.Contains(ns)) { return; } string[] parts = ns.Split('.'); StringBuilder builder = new StringBuilder(); foreach (string part in parts) { if (builder.Length > 0) { builder.Append('.'); } builder.Append(part); string item = builder.ToString(); if (!repository.Contains(item)) { repository.Add(item); } } } public static object ConvertConstant(object value, Expression expression, IEmitter emitter) { try { if (expression.Parent != null) { var rr = emitter.Resolver.ResolveNode(expression, emitter); var conversion = emitter.Resolver.Resolver.GetConversion(expression); var expectedType = emitter.Resolver.Resolver.GetExpectedType(expression); if (conversion.IsNumericConversion && expectedType.IsKnownType(KnownTypeCode.Double) && rr.Type.IsKnownType(KnownTypeCode.Single)) { return (double)(float)value; } } } catch (Exception) { } return value; } public virtual string ToJavaScript(object value) { return JsonConvert.SerializeObject(value, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }); } protected virtual ICSharpCode.NRefactory.CSharp.Attribute GetAttribute(AstNodeCollection<AttributeSection> attributes, string name) { string fullName = name + "Attribute"; foreach (var i in attributes) { foreach (var j in i.Attributes) { if (j.Type.ToString() == name) { return j; } var resolveResult = this.Resolver.ResolveNode(j, this); if (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == fullName) { return j; } } } return null; } public virtual CustomAttribute GetAttribute(IEnumerable<CustomAttribute> attributes, string name) { foreach (var attr in attributes) { if (attr.AttributeType.FullName == name) { return attr; } } return null; } public virtual IAttribute GetAttribute(IEnumerable<IAttribute> attributes, string name) { foreach (var attr in attributes) { if (attr.AttributeType.FullName == name) { return attr; } } return null; } protected virtual bool HasDelegateAttribute(MethodDeclaration method) { return this.GetAttribute(method.Attributes, "Delegate") != null; } public virtual Tuple<bool, bool, string> GetInlineCode(MemberReferenceExpression node) { var member = LiftNullableMember(node); var info = GetInlineCodeFromMember(member, node); return WrapNullableMember(info, member, node); } public virtual Tuple<bool, bool, string> GetInlineCode(InvocationExpression node) { var target = node.Target as MemberReferenceExpression; IMember member = null; if (target != null) { member = LiftNullableMember(target); } var info = GetInlineCodeFromMember(member, node); return WrapNullableMember(info, member, node.Target); } internal Tuple<bool, bool, string> GetInlineCodeFromMember(IMember member, Expression node) { if (member == null) { var resolveResult = this.Resolver.ResolveNode(node, this); var memberResolveResult = resolveResult as MemberResolveResult; if (memberResolveResult == null) { return new Tuple<bool, bool, string>(false, false, null); } member = memberResolveResult.Member; } bool isInlineMethod = this.IsInlineMethod(member); var inlineCode = isInlineMethod ? null : this.GetInline(member); var isStatic = member.IsStatic; if (!string.IsNullOrEmpty(inlineCode) && member is IProperty) { inlineCode = inlineCode.Replace("{value}", "{0}"); } return new Tuple<bool, bool, string>(isStatic, isInlineMethod, inlineCode); } private Tuple<bool, bool, string> WrapNullableMember(Tuple<bool, bool, string> info, IMember member, Expression node) { if (member != null && !string.IsNullOrEmpty(info.Item3)) { IMethod method = (IMethod)member; StringBuilder savedBuilder = this.Output; this.Output = new StringBuilder(); var mrr = new MemberResolveResult(null, member); var argsInfo = new ArgumentsInfo(this, node, mrr); argsInfo.ThisArgument = JS.Vars.T; new InlineArgumentsBlock(this, argsInfo, info.Item3, method, mrr).EmitNullableReference(); string tpl = this.Output.ToString(); this.Output = savedBuilder; if (member.Name == CS.Methods.EQUALS) { tpl = string.Format(JS.Types.SYSTEM_NULLABLE + "." + JS.Funcs.EQUALS + "({{this}}, {{{0}}}, {1})", method.Parameters.First().Name, tpl); } else if (member.Name == CS.Methods.TOSTRING) { tpl = string.Format(JS.Types.SYSTEM_NULLABLE + "." + JS.Funcs.TOSTIRNG + "({{this}}, {0})", tpl); } else if (member.Name == CS.Methods.GETHASHCODE) { tpl = string.Format(JS.Types.SYSTEM_NULLABLE + "." + JS.Funcs.GETHASHCODE + "({{this}}, {0})", tpl); } info = new Tuple<bool, bool, string>(info.Item1, info.Item2, tpl); } return info; } private IMember LiftNullableMember(MemberReferenceExpression target) { var targetrr = this.Resolver.ResolveNode(target.Target, this); IMember member = null; if (targetrr.Type.IsKnownType(KnownTypeCode.NullableOfT)) { string name = null; int count = 0; IType typeArg = null; if (target.MemberName == CS.Methods.TOSTRING || target.MemberName == CS.Methods.GETHASHCODE) { name = target.MemberName; } else if (target.MemberName == CS.Methods.EQUALS) { if (target.Parent is InvocationExpression) { var rr = this.Resolver.ResolveNode(target.Parent, this) as InvocationResolveResult; if (rr != null) { typeArg = rr.Arguments.First().Type; } } name = target.MemberName; count = 1; } if (name != null) { var type = ((ParameterizedType)targetrr.Type).TypeArguments[0]; var methods = type.GetMethods(null, GetMemberOptions.IgnoreInheritedMembers); if (count == 0) { member = methods.FirstOrDefault(m => m.Name == name && m.Parameters.Count == count); } else { member = methods.FirstOrDefault(m => m.Name == name && m.Parameters.Count == count && m.Parameters.First().Type.Equals(typeArg)); if (member == null) { var typeDef = typeArg.GetDefinition(); member = methods.FirstOrDefault(m => m.Name == name && m.Parameters.Count == count && m.Parameters.First().Type.GetDefinition().IsDerivedFrom(typeDef)); } } } } return member; } public virtual bool IsForbiddenInvocation(InvocationExpression node) { var resolveResult = this.Resolver.ResolveNode(node, this); var memberResolveResult = resolveResult as MemberResolveResult; if (memberResolveResult == null) { return false; } var member = memberResolveResult.Member; string attrName = Bridge.Translator.Translator.Bridge_ASSEMBLY + ".InitAttribute"; if (member != null) { var attr = member.Attributes.FirstOrDefault(a => { return a.AttributeType.FullName == attrName; }); if (attr != null) { if (attr.PositionalArguments.Count > 0) { var argExpr = attr.PositionalArguments.First(); if (argExpr.ConstantValue is int) { var value = (InitPosition)argExpr.ConstantValue; if (value > 0) { return true; } } } } } return false; } public virtual IEnumerable<string> GetScript(EntityDeclaration method) { var attr = this.GetAttribute(method.Attributes, Bridge.Translator.Translator.Bridge_ASSEMBLY + ".Script"); return this.GetScriptArguments(attr); } public virtual string GetEntityNameFromAttr(IEntity member, bool setter = false) { var prop = member as IProperty; if (prop != null) { member = setter ? prop.Setter : prop.Getter; } else { var e = member as IEvent; if (e != null) { member = setter ? e.AddAccessor : e.RemoveAccessor; } } if (member == null) { return null; } var attr = Helpers.GetInheritedAttribute(member, Bridge.Translator.Translator.Bridge_ASSEMBLY + ".NameAttribute"); bool isIgnore = member.DeclaringTypeDefinition != null && this.Validator.IsExternalType(member.DeclaringTypeDefinition); string name; if (attr != null) { var value = attr.PositionalArguments.First().ConstantValue; if (value is string) { name = this.GetEntityName(member); if (!isIgnore && member.IsStatic && Helpers.IsReservedStaticName(name, false)) { name = Helpers.ChangeReservedWord(name); } return name; } } return null; } Dictionary<IEntity, NameSemantic> entityNameCache = new Dictionary<IEntity, NameSemantic>(); public virtual NameSemantic GetNameSemantic(IEntity member) { NameSemantic result; if (this.entityNameCache.TryGetValue(member, out result)) { return result; } result = new NameSemantic { Entity = member, Emitter = this }; this.entityNameCache.Add(member, result); return result; } public string GetEntityName(IEntity member) { var semantic = NameSemantic.Create(member, this); semantic.IsObjectLiteral = false; return semantic.Name; } public string GetTypeName(ITypeDefinition type, TypeDefinition typeDefinition) { var semantic = NameSemantic.Create(type, this); semantic.TypeDefinition = typeDefinition; return semantic.Name; } public string GetLiteralEntityName(ICSharpCode.NRefactory.TypeSystem.IEntity member) { var semantic = NameSemantic.Create(member, this); semantic.IsObjectLiteral = true; return semantic.Name; } public virtual string GetEntityName(EntityDeclaration entity) { var rr = this.Resolver.ResolveNode(entity, this) as MemberResolveResult; if (rr != null) { return this.GetEntityName(rr.Member); } return null; } public virtual string GetParameterName(ParameterDeclaration entity) { var name = entity.Name; if (entity.Parent != null && entity.GetParent<SyntaxTree>() != null) { var rr = this.Resolver.ResolveNode(entity, this) as LocalResolveResult; if (rr != null) { var iparam = rr.Variable as IParameter; if (iparam != null && iparam.Attributes != null) { var attr = iparam.Attributes.FirstOrDefault(a => a.AttributeType.FullName == Bridge.Translator.Translator.Bridge_ASSEMBLY + ".NameAttribute"); if (attr != null) { var value = attr.PositionalArguments.First().ConstantValue; if (value is string) { name = value.ToString(); } } } } } if (Helpers.IsReservedWord(this, name)) { name = Helpers.ChangeReservedWord(name); } return name; } public virtual string GetFieldName(FieldDeclaration field) { if (!string.IsNullOrEmpty(field.Name)) { return field.Name; } if (field.Variables.Count > 0) { return field.Variables.First().Name; } return null; } public virtual string GetEventName(EventDeclaration evt) { if (!string.IsNullOrEmpty(evt.Name)) { return evt.Name; } if (evt.Variables.Count > 0) { return evt.Variables.First().Name; } return null; } public Tuple<bool, string> IsGlobalTarget(IMember member) { var attr = this.GetAttribute(member.Attributes, Bridge.Translator.Translator.Bridge_ASSEMBLY + ".GlobalTargetAttribute"); return attr != null ? new Tuple<bool, string>(true, (string)attr.PositionalArguments.First().ConstantValue) : null; } public virtual string GetInline(EntityDeclaration method) { var mrr = this.Resolver.ResolveNode(method, this) as MemberResolveResult; if (mrr != null) { return this.GetInline(mrr.Member); } var attr = this.GetAttribute(method.Attributes, Bridge.Translator.Translator.Bridge_ASSEMBLY + ".Template"); return attr != null && attr.Arguments.Count > 0 ? ((string)((PrimitiveExpression)attr.Arguments.First()).Value) : null; } public virtual string GetInline(IEntity entity) { string attrName = Bridge.Translator.Translator.Bridge_ASSEMBLY + ".TemplateAttribute"; // Moving these two `is` into the end of the methos (where it's actually used) leads // to incorrect JavaScript being generated bool isProp = entity is IProperty; bool isEvent = entity is IEvent; if (entity.SymbolKind == SymbolKind.Property) { var prop = (IProperty)entity; entity = this.IsAssignment ? prop.Setter : prop.Getter; } else if (entity.SymbolKind == SymbolKind.Event) { var ev = (IEvent)entity; entity = this.IsAssignment ? (this.AssignmentType == AssignmentOperatorType.Add ? ev.AddAccessor : ev.RemoveAccessor) : ev.InvokeAccessor; } if (entity != null) { var attr = entity.Attributes.FirstOrDefault(a => { return a.AttributeType.FullName == attrName; }); string inlineCode = null; if (attr != null && entity is IMethod && attr.PositionalArguments.Count == 0 && attr.NamedArguments.Count > 0) { var namedArg = attr.NamedArguments.FirstOrDefault(arg => arg.Key.Name == CS.Attributes.Template.PROPERTY_FN); if (namedArg.Value != null) { inlineCode = namedArg.Value.ConstantValue as string; if (inlineCode != null) { inlineCode = Helpers.DelegateToTemplate(inlineCode, (IMethod) entity, this); } } } if (inlineCode == null) { inlineCode = attr != null && attr.PositionalArguments.Count > 0 ? attr.PositionalArguments[0].ConstantValue.ToString() : null; } if (!string.IsNullOrEmpty(inlineCode) && (isProp || isEvent)) { inlineCode = inlineCode.Replace("{value}", "{0}"); } return inlineCode; } return null; } protected virtual bool IsInlineMethod(IEntity entity) { string attrName = Bridge.Translator.Translator.Bridge_ASSEMBLY + ".TemplateAttribute"; if (entity != null) { var attr = entity.Attributes.FirstOrDefault(a => { return a.AttributeType.FullName == attrName; }); return attr != null && attr.PositionalArguments.Count == 0 && attr.NamedArguments.Count == 0; } return false; } protected virtual IEnumerable<string> GetScriptArguments(ICSharpCode.NRefactory.CSharp.Attribute attr) { if (attr == null) { return null; } var result = new List<string>(); foreach (var arg in attr.Arguments) { string value = ""; if (arg is PrimitiveExpression) { PrimitiveExpression expr = (PrimitiveExpression) arg; value = (string) expr.Value; } else { var rr = this.Resolver.ResolveNode(arg, this) as ConstantResolveResult; if (rr != null && rr.ConstantValue != null) { value = rr.ConstantValue.ToString(); } } result.Add(value); } return result; } public virtual bool IsNativeMember(string fullName) { return fullName.StartsWith(Bridge.Translator.Translator.Bridge_ASSEMBLY_DOT, StringComparison.Ordinal) || fullName.StartsWith("System.", StringComparison.Ordinal); } public virtual bool IsMemberConst(IMember member) { var field = member as IField; if (field != null) { return field.IsConst && member.DeclaringType.Kind != TypeKind.Enum; } return false; } public virtual bool IsInlineConst(IMember member) { bool isConst = IsMemberConst(member); if (isConst) { var attr = this.GetAttribute(member.Attributes, Bridge.Translator.Translator.Bridge_ASSEMBLY + ".InlineConstAttribute"); if (attr != null) { return true; } } return false; } public virtual void InitEmitter() { this.Output = new StringBuilder(); this.Locals = null; this.LocalsStack = null; this.IteratorCount = 0; this.ThisRefCounter = 0; this.Writers = new Stack<IWriter>(); this.IsAssignment = false; this.ResetLevel(); this.IsNewLine = true; this.EnableSemicolon = true; this.Comma = false; this.CurrentDependencies = new List<IPluginDependency>(); } public virtual bool ContainsOnlyOrEmpty(StringBuilder sb, params char[] c) { if (sb == null || sb.Length == 0) { return true; } for (int i = 0; i < sb.Length; i++) { if (!c.Contains(sb[i])) { return false; } } return true; } internal static bool AddOutputItem(List<TranslatorOutputItem> target, string fileName, TranslatorOutputItemContent content, TranslatorOutputKind outputKind, string location = null, string assembly = null) { var fileHelper = new FileHelper(); var outputType = fileHelper.GetOutputType(fileName); TranslatorOutputItem output = null; bool isMinJs = fileHelper.IsMinJS(fileName); var searchName = fileName; if (isMinJs) { searchName = fileHelper.GetNonMinifiedJSFileName(fileName); } output = target.FirstOrDefault(x => string.Compare(x.Name, searchName, StringComparison.InvariantCultureIgnoreCase) == 0); if (output != null) { bool isAdded; if (isMinJs) { isAdded = output.MinifiedVersion == null; output.MinifiedVersion = new TranslatorOutputItem { Name = fileName, OutputType = outputType, OutputKind = outputKind | TranslatorOutputKind.Minified, Location = location, Content = content, IsMinified = true, Assembly = assembly }; } else { isAdded = output.IsEmpty; output.IsEmpty = false; } return isAdded; } output = new TranslatorOutputItem { Name = searchName, OutputType = outputType, OutputKind = outputKind, Location = location, Content = new TranslatorOutputItemContent((string)null), Assembly = assembly }; if (isMinJs) { output.IsEmpty = true; output.MinifiedVersion = new TranslatorOutputItem { Name = fileName, OutputType = outputType, OutputKind = outputKind | TranslatorOutputKind.Minified, Location = location, Content = content, IsMinified = true, Assembly = assembly }; } else { output.Content = content; } target.Add(output); return true; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AlreadyClosedException = Lucene.Net.Store.AlreadyClosedException; using Directory = Lucene.Net.Store.Directory; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; public sealed class StandardDirectoryReader : DirectoryReader { private readonly IndexWriter Writer; private readonly SegmentInfos SegmentInfos; private readonly int TermInfosIndexDivisor; private readonly bool ApplyAllDeletes; /// <summary> /// called only from static open() methods </summary> internal StandardDirectoryReader(Directory directory, AtomicReader[] readers, IndexWriter writer, SegmentInfos sis, int termInfosIndexDivisor, bool applyAllDeletes) : base(directory, readers) { this.Writer = writer; this.SegmentInfos = sis; this.TermInfosIndexDivisor = termInfosIndexDivisor; this.ApplyAllDeletes = applyAllDeletes; } /// <summary> /// called from DirectoryReader.open(...) methods </summary> internal static DirectoryReader Open(Directory directory, IndexCommit commit, int termInfosIndexDivisor) { return (DirectoryReader)new FindSegmentsFileAnonymousInnerClassHelper(directory, termInfosIndexDivisor).Run(commit); } private class FindSegmentsFileAnonymousInnerClassHelper : SegmentInfos.FindSegmentsFile { private new readonly Directory Directory; private readonly int TermInfosIndexDivisor; public FindSegmentsFileAnonymousInnerClassHelper(Directory directory, int termInfosIndexDivisor) : base(directory) { this.Directory = directory; this.TermInfosIndexDivisor = termInfosIndexDivisor; } protected internal override object DoBody(string segmentFileName) { var sis = new SegmentInfos(); sis.Read(Directory, segmentFileName); var readers = new SegmentReader[sis.Size()]; for (int i = sis.Size() - 1; i >= 0; i--) { System.IO.IOException prior = null; bool success = false; try { readers[i] = new SegmentReader(sis.Info(i), TermInfosIndexDivisor, IOContext.READ); success = true; } catch (System.IO.IOException ex) { prior = ex; } finally { if (!success) { IOUtils.CloseWhileHandlingException(prior, readers); } } } return new StandardDirectoryReader(Directory, readers, null, sis, TermInfosIndexDivisor, false); } } /// <summary> /// Used by near real-time search </summary> internal static DirectoryReader Open(IndexWriter writer, SegmentInfos infos, bool applyAllDeletes) { // IndexWriter synchronizes externally before calling // us, which ensures infos will not change; so there's // no need to process segments in reverse order int numSegments = infos.Size(); IList<SegmentReader> readers = new List<SegmentReader>(); Directory dir = writer.Directory; SegmentInfos segmentInfos = (SegmentInfos)infos.Clone(); int infosUpto = 0; bool success = false; try { for (int i = 0; i < numSegments; i++) { // NOTE: important that we use infos not // segmentInfos here, so that we are passing the // actual instance of SegmentInfoPerCommit in // IndexWriter's segmentInfos: SegmentCommitInfo info = infos.Info(i); Debug.Assert(info.Info.Dir == dir); ReadersAndUpdates rld = writer.readerPool.Get(info, true); try { SegmentReader reader = rld.GetReadOnlyClone(IOContext.READ); if (reader.NumDocs > 0 || writer.KeepFullyDeletedSegments) { // Steal the ref: readers.Add(reader); infosUpto++; } else { reader.DecRef(); segmentInfos.Remove(infosUpto); } } finally { writer.readerPool.Release(rld); } } writer.IncRefDeleter(segmentInfos); StandardDirectoryReader result = new StandardDirectoryReader(dir, readers.ToArray(), writer, segmentInfos, writer.Config.ReaderTermsIndexDivisor, applyAllDeletes); success = true; return result; } finally { if (!success) { foreach (SegmentReader r in readers) { try { r.DecRef(); } catch (Exception th) { // ignore any exception that is thrown here to not mask any original // exception. } } } } } /// <summary> /// this constructor is only used for <seealso cref="#doOpenIfChanged(SegmentInfos)"/> </summary> private static DirectoryReader Open(Directory directory, SegmentInfos infos, IList<AtomicReader> oldReaders, int termInfosIndexDivisor) { // we put the old SegmentReaders in a map, that allows us // to lookup a reader using its segment name IDictionary<string, int?> segmentReaders = new Dictionary<string, int?>(); if (oldReaders != null) { // create a Map SegmentName->SegmentReader for (int i = 0, c = oldReaders.Count; i < c; i++) { SegmentReader sr = (SegmentReader)oldReaders[i]; segmentReaders[sr.SegmentName] = Convert.ToInt32(i); } } SegmentReader[] newReaders = new SegmentReader[infos.Size()]; // remember which readers are shared between the old and the re-opened // DirectoryReader - we have to incRef those readers bool[] readerShared = new bool[infos.Size()]; for (int i = infos.Size() - 1; i >= 0; i--) { // find SegmentReader for this segment int? oldReaderIndex; segmentReaders.TryGetValue(infos.Info(i).Info.Name, out oldReaderIndex); if (oldReaderIndex == null) { // this is a new segment, no old SegmentReader can be reused newReaders[i] = null; } else { // there is an old reader for this segment - we'll try to reopen it newReaders[i] = (SegmentReader)oldReaders[(int)oldReaderIndex]; } bool success = false; Exception prior = null; try { SegmentReader newReader; if (newReaders[i] == null || infos.Info(i).Info.UseCompoundFile != newReaders[i].SegmentInfo.Info.UseCompoundFile) { // this is a new reader; in case we hit an exception we can close it safely newReader = new SegmentReader(infos.Info(i), termInfosIndexDivisor, IOContext.READ); readerShared[i] = false; newReaders[i] = newReader; } else { if (newReaders[i].SegmentInfo.DelGen == infos.Info(i).DelGen && newReaders[i].SegmentInfo.FieldInfosGen == infos.Info(i).FieldInfosGen) { // No change; this reader will be shared between // the old and the new one, so we must incRef // it: readerShared[i] = true; newReaders[i].IncRef(); } else { // there are changes to the reader, either liveDocs or DV updates readerShared[i] = false; // Steal the ref returned by SegmentReader ctor: Debug.Assert(infos.Info(i).Info.Dir == newReaders[i].SegmentInfo.Info.Dir); Debug.Assert(infos.Info(i).HasDeletions() || infos.Info(i).HasFieldUpdates()); if (newReaders[i].SegmentInfo.DelGen == infos.Info(i).DelGen) { // only DV updates newReaders[i] = new SegmentReader(infos.Info(i), newReaders[i], newReaders[i].LiveDocs, newReaders[i].NumDocs); } else { // both DV and liveDocs have changed newReaders[i] = new SegmentReader(infos.Info(i), newReaders[i]); } } } success = true; } catch (Exception ex) { prior = ex; } finally { if (!success) { for (i++; i < infos.Size(); i++) { if (newReaders[i] != null) { try { if (!readerShared[i]) { // this is a new subReader that is not used by the old one, // we can close it newReaders[i].Dispose(); } else { // this subReader is also used by the old reader, so instead // closing we must decRef it newReaders[i].DecRef(); } } catch (Exception t) { if (prior == null) { prior = t; } } } } } // throw the first exception IOUtils.ReThrow(prior); } } return new StandardDirectoryReader(directory, newReaders, null, infos, termInfosIndexDivisor, false); } public override string ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append(this.GetType().Name); buffer.Append('('); string segmentsFile = SegmentInfos.SegmentsFileName; if (segmentsFile != null) { buffer.Append(segmentsFile).Append(":").Append(SegmentInfos.Version); } if (Writer != null) { buffer.Append(":nrt"); } foreach (AtomicReader r in GetSequentialSubReaders()) { buffer.Append(' '); buffer.Append(r); } buffer.Append(')'); return buffer.ToString(); } protected internal override DirectoryReader DoOpenIfChanged() { return DoOpenIfChanged((IndexCommit)null); } protected internal override DirectoryReader DoOpenIfChanged(IndexCommit commit) { EnsureOpen(); // If we were obtained by writer.getReader(), re-ask the // writer to get a new reader. if (Writer != null) { return DoOpenFromWriter(commit); } else { return DoOpenNoWriter(commit); } } protected internal override DirectoryReader DoOpenIfChanged(IndexWriter writer, bool applyAllDeletes) { EnsureOpen(); if (writer == this.Writer && applyAllDeletes == this.ApplyAllDeletes) { return DoOpenFromWriter(null); } else { return writer.GetReader(applyAllDeletes); } } private DirectoryReader DoOpenFromWriter(IndexCommit commit) { if (commit != null) { return DoOpenFromCommit(commit); } if (Writer.NrtIsCurrent(SegmentInfos)) { return null; } DirectoryReader reader = Writer.GetReader(ApplyAllDeletes); // If in fact no changes took place, return null: if (reader.Version == SegmentInfos.Version) { reader.DecRef(); return null; } return reader; } private DirectoryReader DoOpenNoWriter(IndexCommit commit) { if (commit == null) { if (Current) { return null; } } else { if (Directory_Renamed != commit.Directory) { throw new System.IO.IOException("the specified commit does not match the specified Directory"); } if (SegmentInfos != null && commit.SegmentsFileName.Equals(SegmentInfos.SegmentsFileName)) { return null; } } return DoOpenFromCommit(commit); } private DirectoryReader DoOpenFromCommit(IndexCommit commit) { return (DirectoryReader)new FindSegmentsFileAnonymousInnerClassHelper2(this, Directory_Renamed).Run(commit); } private class FindSegmentsFileAnonymousInnerClassHelper2 : SegmentInfos.FindSegmentsFile { private readonly StandardDirectoryReader OuterInstance; public FindSegmentsFileAnonymousInnerClassHelper2(StandardDirectoryReader outerInstance, Directory directory) : base(directory) { this.OuterInstance = outerInstance; } protected internal override object DoBody(string segmentFileName) { SegmentInfos infos = new SegmentInfos(); infos.Read(OuterInstance.Directory_Renamed, segmentFileName); return OuterInstance.DoOpenIfChanged(infos); } } internal DirectoryReader DoOpenIfChanged(SegmentInfos infos) { return StandardDirectoryReader.Open(Directory_Renamed, infos, GetSequentialSubReaders().OfType<AtomicReader>().ToList(), TermInfosIndexDivisor); } public override long Version { get { EnsureOpen(); return SegmentInfos.Version; } } public override bool Current { get { EnsureOpen(); if (Writer == null || Writer.Closed) { // Fully read the segments file: this ensures that it's // completely written so that if // IndexWriter.prepareCommit has been called (but not // yet commit), then the reader will still see itself as // current: SegmentInfos sis = new SegmentInfos(); sis.Read(Directory_Renamed); // we loaded SegmentInfos from the directory return sis.Version == SegmentInfos.Version; } else { return Writer.NrtIsCurrent(SegmentInfos); } } } protected internal override void DoClose() { Exception firstExc = null; foreach (AtomicReader r in GetSequentialSubReaders()) { // try to close each reader, even if an exception is thrown try { r.DecRef(); } catch (Exception t) { if (firstExc == null) { firstExc = t; } } } if (Writer != null) { try { Writer.DecRefDeleter(SegmentInfos); } catch (AlreadyClosedException ex) { // this is OK, it just means our original writer was // closed before we were, and this may leave some // un-referenced files in the index, which is // harmless. The next time IW is opened on the // index, it will delete them. } } // throw the first exception IOUtils.ReThrow(firstExc); } public override IndexCommit IndexCommit { get { EnsureOpen(); return new ReaderCommit(SegmentInfos, Directory_Renamed); } } internal sealed class ReaderCommit : IndexCommit { internal string SegmentsFileName_Renamed; internal ICollection<string> Files; internal Directory Dir; internal long Generation_Renamed; internal readonly IDictionary<string, string> UserData_Renamed; internal readonly int SegmentCount_Renamed; internal ReaderCommit(SegmentInfos infos, Directory dir) { SegmentsFileName_Renamed = infos.SegmentsFileName; this.Dir = dir; UserData_Renamed = infos.UserData; Files = infos.Files(dir, true); Generation_Renamed = infos.Generation; SegmentCount_Renamed = infos.Size(); } public override string ToString() { return "DirectoryReader.ReaderCommit(" + SegmentsFileName_Renamed + ")"; } public override int SegmentCount { get { return SegmentCount_Renamed; } } public override string SegmentsFileName { get { return SegmentsFileName_Renamed; } } public override ICollection<string> FileNames { get { return Files; } } public override Directory Directory { get { return Dir; } } public override long Generation { get { return Generation_Renamed; } } public override bool Deleted { get { return false; } } public override IDictionary<string, string> UserData { get { return UserData_Renamed; } } public override void Delete() { throw new NotSupportedException("this IndexCommit does not support deletions"); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.IO; using System.IO.Pipes; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; namespace System.Diagnostics.ProcessTests { public partial class ProcessTest : IDisposable { private const int WaitInMS = 100 * 1000; private const string CoreRunName = "corerun"; private const string TestExeName = "System.Diagnostics.Process.TestConsoleApp.exe"; private const int SuccessExitCode = 100; private Process _process; private List<Process> _processes = new List<Process>(); public ProcessTest() { _process = CreateProcessInfinite(); _process.Start(); } public void Dispose() { // Ensure that there are no open processes with the same name as ProcessName foreach (Process p in _processes) { if (!p.HasExited) { try { p.Kill(); } catch (InvalidOperationException) { } // in case it was never started Assert.True(p.WaitForExit(WaitInMS)); } } } Process CreateProcess(string optionalArgument = ""/*String.Empty is not a constant*/) { Process p = new Process(); _processes.Add(p); p.StartInfo.FileName = CoreRunName; p.StartInfo.Arguments = string.IsNullOrWhiteSpace(optionalArgument) ? TestExeName : TestExeName + " " + optionalArgument; // Profilers / code coverage tools doing coverage of the test process set environment // variables to tell the targeted process what profiler to load. We don't want the child process // to be profiled / have code coverage, so we remove these environment variables for that process // before it's started. p.StartInfo.Environment.Remove("Cor_Profiler"); p.StartInfo.Environment.Remove("Cor_Enable_Profiling"); p.StartInfo.Environment.Remove("CoreClr_Profiler"); p.StartInfo.Environment.Remove("CoreClr_Enable_Profiling"); return p; } Process CreateProcessInfinite() { return CreateProcess("infinite"); } public void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority) { _process.PriorityClass = exPriorityClass; _process.Refresh(); Assert.Equal(priority, _process.BasePriority); } [Fact, PlatformSpecific(PlatformID.Windows)] public void Process_BasePriorityWindows() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { // We are not checking for RealTime case here, as RealTime priority process can // preempt the threads of all other processes, including operating system processes // performing important tasks, which may cause the machine to be unresponsive. //SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24); SetAndCheckBasePriority(ProcessPriorityClass.High, 13); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8); } finally { _process.PriorityClass = originalPriority; } } [Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix public void Process_BasePriorityUnix() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { SetAndCheckBasePriority(ProcessPriorityClass.High, -11); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0); } finally { _process.PriorityClass = originalPriority; } } public void Sleep(double delayInMs) { Task.Delay(TimeSpan.FromMilliseconds(delayInMs)).Wait(); } public void Sleep() { Sleep(50D); } public void StartAndKillProcessWithDelay(Process p) { p.Start(); Sleep(); p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void Process_EnableRaiseEvents() { { bool isExitedInvoked = false; // Test behavior when EnableRaisingEvent = true; // Ensure event is called. Process p = CreateProcessInfinite(); p.EnableRaisingEvents = true; p.Exited += delegate { isExitedInvoked = true; }; StartAndKillProcessWithDelay(p); Assert.True(isExitedInvoked, String.Format("Process_CanRaiseEvents0001: {0}", "isExited Event not called when EnableRaisingEvent is set to true.")); } { bool isExitedInvoked = false; // Check with the default settings (false, events will not be raised) Process p = CreateProcessInfinite(); p.Exited += delegate { isExitedInvoked = true; }; StartAndKillProcessWithDelay(p); Assert.False(isExitedInvoked, String.Format("Process_CanRaiseEvents0002: {0}", "isExited Event called with the default settings for EnableRaiseEvents")); } { bool isExitedInvoked = false; // Same test, this time explicitly set the property to false Process p = CreateProcessInfinite(); p.EnableRaisingEvents = false; p.Exited += delegate { isExitedInvoked = true; }; ; StartAndKillProcessWithDelay(p); Assert.False(isExitedInvoked, String.Format("Process_CanRaiseEvents0003: {0}", "isExited Event called with the EnableRaiseEvents = false")); } } [Fact] public void Process_ExitCode() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, p.ExitCode); } { Process p = CreateProcessInfinite(); StartAndKillProcessWithDelay(p); Assert.NotEqual(0, p.ExitCode); } } [Fact] public void Process_ExitTime() { DateTime timeBeforeProcessStart = DateTime.UtcNow; Process p = CreateProcessInfinite(); StartAndKillProcessWithDelay(p); Assert.True(p.ExitTime.ToUniversalTime() > timeBeforeProcessStart, "Process_ExitTime is incorrect."); } [Fact] public void Process_Id() { if (global::Interop.IsWindows) { Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle)); } else { IEnumerable<int> testProcessIds = Process.GetProcessesByName(CoreRunName).Select(p => p.Id); Assert.Contains(_process.Id, testProcessIds); } } [Fact] public void Process_HasExited() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.HasExited, "Process_HasExited001 failed"); } { Process p = CreateProcessInfinite(); p.Start(); try { Assert.False(p.HasExited, "Process_HasExited002 failed"); } finally { p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } Assert.True(p.HasExited, "Process_HasExited003 failed"); } } [Fact] public void Process_MachineName() { // Checking that the MachineName returns some value. Assert.NotNull(_process.MachineName); } [Fact] public void Process_MainModule() { // Get MainModule property from a Process object ProcessModule mainModule = _process.MainModule; if (!global::Interop.IsOSX) // OS X doesn't currently implement modules support { Assert.NotNull(mainModule); } if (mainModule != null) { Assert.Equal(CoreRunName, Path.GetFileNameWithoutExtension(mainModule.ModuleName)); // Check that the mainModule is present in the modules list. bool foundMainModule = false; if (_process.Modules != null) { foreach (ProcessModule pModule in _process.Modules) { if (String.Equals(Path.GetFileNameWithoutExtension(pModule.ModuleName), CoreRunName, StringComparison.OrdinalIgnoreCase)) { foundMainModule = true; break; } } Assert.True(foundMainModule, "Could not found Module " + mainModule.ModuleName); } } } [Fact] public void Process_MaxWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (global::Interop.IsOSX) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MaxWorkingSet; Assert.True(curValue >= 0); if (global::Interop.IsWindows) { try { _process.MaxWorkingSet = (IntPtr)((int)curValue + 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)max; _process.Refresh(); Assert.Equal(curValue, (int)_process.MaxWorkingSet); } finally { _process.MaxWorkingSet = (IntPtr)curValue; } } } [Fact] public void Process_MinWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (global::Interop.IsOSX) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MinWorkingSet; Assert.True(curValue >= 0); if (global::Interop.IsWindows) { try { _process.MinWorkingSet = (IntPtr)((int)curValue - 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)min; _process.Refresh(); Assert.Equal(curValue, (int)_process.MinWorkingSet); } finally { _process.MinWorkingSet = (IntPtr)curValue; } } } [Fact] public void Process_Modules() { foreach (ProcessModule pModule in _process.Modules) { // Validated that we can get a value for each of the following. Assert.NotNull(pModule); Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress); Assert.NotNull(pModule.FileName); Assert.NotNull(pModule.ModuleName); // Just make sure these don't throw IntPtr addr = pModule.EntryPointAddress; int memSize = pModule.ModuleMemorySize; } } private void AssertNonZeroWindowsZeroUnix(long value) { switch (global::Interop.PlatformDetection.OperatingSystem) { case global::Interop.OperatingSystem.Windows: Assert.NotEqual(0, value); break; default: Assert.Equal(0, value); break; } } [Fact] public void Process_NonpagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64); } [Fact] public void Process_PagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64); } [Fact] public void Process_PagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64); } [Fact] public void Process_PeakPagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64); } [Fact] public void Process_PeakVirtualMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64); } [Fact] public void Process_PeakWorkingSet64() { AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64); } [Fact] public void Process_PrivateMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64); } [Fact] public void Process_ProcessorTime() { Assert.True(_process.UserProcessorTime.TotalSeconds >= 0); Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0); Assert.True(_process.TotalProcessorTime.TotalSeconds >= 0); } [Fact] [PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX public void Process_ProcessorAffinity() { IntPtr curProcessorAffinity = _process.ProcessorAffinity; try { _process.ProcessorAffinity = new IntPtr(0x1); Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity); } finally { _process.ProcessorAffinity = curProcessorAffinity; Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity); } } [Fact] public void Process_PriorityBoostEnabled() { bool isPriorityBoostEnabled = _process.PriorityBoostEnabled; try { _process.PriorityBoostEnabled = true; Assert.True(_process.PriorityBoostEnabled, "Process_PriorityBoostEnabled001 failed"); _process.PriorityBoostEnabled = false; Assert.False(_process.PriorityBoostEnabled, "Process_PriorityBoostEnabled002 failed"); } finally { _process.PriorityBoostEnabled = isPriorityBoostEnabled; } } [Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix public void Process_PriorityClassUnix() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact, PlatformSpecific(PlatformID.Windows)] public void Process_PriorityClassWindows() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact] public void Process_InvalidPriorityClass() { Process p = new Process(); Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; }); } [Fact] public void ProcessProcessName() { Assert.Equal(_process.ProcessName, CoreRunName, StringComparer.OrdinalIgnoreCase); } [Fact] public void Process_SafeHandle() { Assert.False(_process.SafeHandle.IsInvalid); } [Fact] public void Process_SessionId() { uint sessionId; if (global::Interop.IsWindows) { ProcessIdToSessionId((uint)_process.Id, out sessionId); } else { sessionId = (uint)getsid(_process.Id); } Assert.Equal(sessionId, (uint)_process.SessionId); } [DllImport("api-ms-win-core-processthreads-l1-1-0.dll")] internal static extern int GetCurrentProcessId(); [DllImport("libc")] internal static extern int getpid(); [DllImport("libc")] internal static extern int getsid(int pid); [DllImport("api-ms-win-core-processthreads-l1-1-2.dll")] internal static extern bool ProcessIdToSessionId(uint dwProcessId, out uint pSessionId); [Fact] public void Process_GetCurrentProcess() { Process current = Process.GetCurrentProcess(); Assert.NotNull(current); int currentProcessId = global::Interop.IsWindows ? GetCurrentProcessId() : getpid(); Assert.Equal(currentProcessId, current.Id); Assert.Equal(Process.GetProcessById(currentProcessId).ProcessName, Process.GetCurrentProcess().ProcessName); } [Fact] public void Process_GetProcesses() { // Get all the processes running on the machine. Process currentProcess = Process.GetCurrentProcess(); var foundCurrentProcess = (from p in Process.GetProcesses() where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "Process_GetProcesses001 failed"); foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName) where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "Process_GetProcesses002 failed"); } [Fact] public void Process_GetProcessesByName() { // Get the current process using its name Process currentProcess = Process.GetCurrentProcess(); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "Process_GetProcessesByName001 failed"); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "Process_GetProcessesByName001 failed"); } [Fact] public void Process_Environment() { Assert.NotEqual(0, new Process().StartInfo.Environment.Count); ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. var Environment2 = psi.Environment; Assert.NotEqual(Environment2.Count, 0); int CountItems = Environment2.Count; Environment2.Add("NewKey", "NewValue"); Environment2.Add("NewKey2", "NewValue2"); Assert.Equal(CountItems + 2, Environment2.Count); Environment2.Remove("NewKey"); Assert.Equal(CountItems + 1, Environment2.Count); //Exception not thrown with invalid key Assert.Throws<ArgumentException>(() => { Environment2.Add("NewKey2", "NewValue2"); }); //Clear Environment2.Clear(); Assert.Equal(0, Environment2.Count); //ContainsKey Environment2.Add("NewKey", "NewValue"); Environment2.Add("NewKey2", "NewValue2"); Assert.True(Environment2.ContainsKey("NewKey")); if (global::Interop.IsWindows) { Assert.True(Environment2.ContainsKey("newkey")); } Assert.False(Environment2.ContainsKey("NewKey99")); //Iterating string result = null; int index = 0; foreach (string e1 in Environment2.Values) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("NewValueNewValue2", result); result = null; index = 0; foreach (string e1 in Environment2.Keys) { index++; result += e1; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (System.Collections.Generic.KeyValuePair<string, string> e1 in Environment2) { index++; result += e1.Key; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); //Contains Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey", "NewValue"))); if (global::Interop.IsWindows) { Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("nEwKeY", "NewValue"))); } Assert.False(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey99", "NewValue99"))); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>(null, "NewValue99")); } ); Environment2.Add(new System.Collections.Generic.KeyValuePair<string, string>("NewKey98", "NewValue98")); //Indexed string newIndexItem = Environment2["NewKey98"]; Assert.Equal("NewValue98", newIndexItem); //TryGetValue string stringout = null; bool retval = false; retval = Environment2.TryGetValue("NewKey", out stringout); Assert.True(retval); Assert.Equal("NewValue", stringout); if (global::Interop.IsWindows) { retval = Environment2.TryGetValue("NeWkEy", out stringout); Assert.True(retval); Assert.Equal("NewValue", stringout); } stringout = null; retval = false; retval = Environment2.TryGetValue("NewKey99", out stringout); Assert.Equal(null, stringout); Assert.False(retval); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout1 = null; bool retval1 = false; retval1 = Environment2.TryGetValue(null, out stringout1); } ); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { Environment2.Add(null, "NewValue2"); } ); //Invalid Key to add Assert.Throws<ArgumentException>(() => { Environment2.Add("NewKey2", "NewValue2"); } ); //Remove Item Environment2.Remove("NewKey98"); Environment2.Remove("NewKey98"); //2nd occurrence should not assert //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { Environment2.Remove(null); }); //"Exception not thrown with null key" Assert.Throws<System.Collections.Generic.KeyNotFoundException>(() => { string a1 = Environment2["1bB"]; }); Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey2", "NewValue2"))); if (global::Interop.IsWindows) { Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NEWKeY2", "NewValue2"))); } Assert.False(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey2", "newvalue2"))); Assert.False(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("newkey2", "newvalue2"))); //Use KeyValuePair Enumerator var x = Environment2.GetEnumerator(); x.MoveNext(); var y1 = x.Current; Assert.Equal("NewKey NewValue", y1.Key + " " + y1.Value); x.MoveNext(); y1 = x.Current; Assert.Equal("NewKey2 NewValue2", y1.Key + " " + y1.Value); //IsReadonly Assert.False(Environment2.IsReadOnly); Environment2.Add(new System.Collections.Generic.KeyValuePair<string, string>("NewKey3", "NewValue3")); Environment2.Add(new System.Collections.Generic.KeyValuePair<string, string>("NewKey4", "NewValue4")); //CopyTo System.Collections.Generic.KeyValuePair<String, String>[] kvpa = new System.Collections.Generic.KeyValuePair<string, string>[10]; Environment2.CopyTo(kvpa, 0); Assert.Equal("NewKey", kvpa[0].Key); Assert.Equal("NewKey3", kvpa[2].Key); Environment2.CopyTo(kvpa, 6); Assert.Equal("NewKey", kvpa[6].Key); //Exception not thrown with null key Assert.Throws<System.ArgumentOutOfRangeException>(() => { Environment2.CopyTo(kvpa, -1); }); //Exception not thrown with null key Assert.Throws<System.ArgumentException>(() => { Environment2.CopyTo(kvpa, 9); }); //Exception not thrown with null key Assert.Throws<System.ArgumentNullException>(() => { System.Collections.Generic.KeyValuePair<String, String>[] kvpanull = null; Environment2.CopyTo(kvpanull, 0); } ); } [Fact] public void Process_StartInfo() { { Process process = CreateProcessInfinite(); process.Start(); Assert.Equal(CoreRunName, process.StartInfo.FileName); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = CreateProcessInfinite(); process.Start(); Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo())); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = new Process(); process.StartInfo = new ProcessStartInfo(TestExeName); Assert.Equal(TestExeName, process.StartInfo.FileName); } { Process process = new Process(); Assert.Throws<ArgumentNullException>(() => process.StartInfo = null); } { Process process = Process.GetCurrentProcess(); Assert.Throws<System.InvalidOperationException>(() => process.StartInfo); } } [Fact] public void Process_IPC() { Process p = CreateProcess("ipc"); using (var outbound = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) using (var inbound = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)) { p.StartInfo.Arguments += " " + outbound.GetClientHandleAsString() + " " + inbound.GetClientHandleAsString(); p.Start(); outbound.DisposeLocalCopyOfClientHandle(); inbound.DisposeLocalCopyOfClientHandle(); for (byte i = 0; i < 10; i++) { outbound.WriteByte(i); int received = inbound.ReadByte(); Assert.Equal(i, received); } Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, p.ExitCode); } } [Fact] public void ThreadCount() { Assert.True(_process.Threads.Count > 0); using (Process p = Process.GetCurrentProcess()) { Assert.True(p.Threads.Count > 0); } } // [Fact] // uncomment for diagnostic purposes to list processes to console public void ConsoleWriteLineProcesses() { foreach (var p in Process.GetProcesses().OrderBy(p => p.Id)) { Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count); p.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Orleans; using Orleans.Providers.Streams.AzureQueue; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using UnitTests.GrainInterfaces; using UnitTests.StreamingTests; using UnitTests.Tester; namespace Tester.StreamingTests { public abstract class StreamFilteringTestsBase : OrleansTestingBase { protected Guid StreamId; protected string StreamNamespace; protected string streamProviderName; private static readonly TimeSpan timeout = TimeSpan.FromSeconds(30); protected StreamFilteringTestsBase() { StreamId = Guid.NewGuid(); StreamNamespace = Guid.NewGuid().ToString(); } // Test support functions protected async Task Test_Filter_EvenOdd(bool allCheckEven = false) { streamProviderName.Should().NotBeNull("Stream provider name not set."); // Consumers const int numConsumers = 10; var consumers = new IFilteredStreamConsumerGrain[numConsumers]; var promises = new List<Task>(); for (int loopCount = 0; loopCount < numConsumers; loopCount++) { IFilteredStreamConsumerGrain grain = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(Guid.NewGuid()); consumers[loopCount] = grain; bool isEven = allCheckEven || loopCount % 2 == 0; Task promise = grain.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, isEven); promises.Add(promise); } await Task.WhenAll(promises); // Producer IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid()); await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 1, timeout); } // Check initial counts var sb = new StringBuilder(); int[] counts = new int[numConsumers]; for (int i = 0; i < numConsumers; i++) { counts[i] = await consumers[i].GetReceivedCount(); sb.AppendFormat("Baseline count = {0} for consumer {1}", counts[i], i); sb.AppendLine(); } logger.Info(sb.ToString()); // Get producer to send some messages for (int round = 1; round <= 10; round++) { bool roundIsEven = round % 2 == 0; await producer.SendItem(round); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout); } for (int i = 0; i < numConsumers; i++) { bool indexIsEven = i % 2 == 0; int expected = counts[i]; if (roundIsEven) { if (indexIsEven || allCheckEven) expected += 1; } else if (allCheckEven) { // No change to expected counts for odd rounds } else { if (!indexIsEven) expected += 1; } int count = await consumers[i].GetReceivedCount(); logger.Info("Received count = {0} in round {1} for consumer {2}", count, round, i); count.Should().Be(expected, "Expected count in round {0} for consumer {1}", round, i); counts[i] = expected; // Set new baseline } } } protected async Task Test_Filter_BadFunc() { streamProviderName.Should().NotBeNull("Stream provider name not set."); Guid id = Guid.NewGuid(); IFilteredStreamConsumerGrain grain = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id); try { await grain.Ping(); await grain.SubscribeWithBadFunc(id, StreamNamespace, streamProviderName); } catch (AggregateException ae) { Exception exc = ae.GetBaseException(); logger.Info("Got exception " + exc); throw exc; } } protected async Task Test_Filter_TwoObsv_Different() { streamProviderName.Should().NotBeNull("Stream provider name not set."); Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); // Same consumer grain subscribes twice, with two different filters IFilteredStreamConsumerGrain consumer = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id1); await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, false); // Odd IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(id2); await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName); int expectedCount = 1; // Producer always sends first message when it becomes active await producer.SendItem(1); expectedCount++; // One observer receives, the other does not. if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout); } int count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after first send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after first send"); await producer.SendItem(2); expectedCount++; if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 3, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after second send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); await producer.SendItem(3); expectedCount++; if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 4, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after third send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); } protected async Task Test_Filter_TwoObsv_Same() { streamProviderName.Should().NotBeNull("Stream provider name not set."); Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); // Same consumer grain subscribes twice, with two identical filters IFilteredStreamConsumerGrain consumer = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id1); await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(id2); await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName); int expectedCount = 2; // When Producer becomes active, it always sends first message to each subscriber await producer.SendItem(1); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout); } int count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after first send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after first send"); await producer.SendItem(2); expectedCount += 2; if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 3, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after second send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); await producer.SendItem(3); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 4, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after third send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); } } public class StreamFilteringTests_SMS : StreamFilteringTestsBase, IClassFixture<StreamFilteringTests_SMS.Fixture> { public class Fixture : BaseTestClusterFixture { public const string StreamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); options.ClusterConfiguration.AddMemoryStorageProvider("MemoryStore"); options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false); options.ClientConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false); return new TestCluster(options); } } public StreamFilteringTests_SMS() { streamProviderName = Fixture.StreamProvider; } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_Basic() { await Test_Filter_EvenOdd(true); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_EvenOdd() { await Test_Filter_EvenOdd(); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_BadFunc() { await Assert.ThrowsAsync(typeof(ArgumentException), () => Test_Filter_BadFunc()); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_TwoObsv_Different() { await Test_Filter_TwoObsv_Different(); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_TwoObsv_Same() { await Test_Filter_TwoObsv_Same(); } } public class StreamFilteringTests_AQ : StreamFilteringTestsBase, IClassFixture<StreamFilteringTests_AQ.Fixture>, IDisposable { private readonly string deploymentId; public class Fixture : BaseTestClusterFixture { public const string StreamProvider = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); options.ClusterConfiguration.AddMemoryStorageProvider("MemoryStore"); options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.AddAzureQueueStreamProvider(StreamProvider); return new TestCluster(options); } public override void Dispose() { var deploymentId = this.HostedCluster.DeploymentId; base.Dispose(); AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(StreamProvider, deploymentId, StorageTestConstants.DataConnectionString) .Wait(); } } public StreamFilteringTests_AQ(Fixture fixture) { this.deploymentId = fixture.HostedCluster.DeploymentId; streamProviderName = Fixture.StreamProvider; } public virtual void Dispose() { AzureQueueStreamProviderUtils.ClearAllUsedAzureQueues( streamProviderName, this.deploymentId, StorageTestConstants.DataConnectionString).Wait(); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_Basic() { await Test_Filter_EvenOdd(true); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_EvenOdd() { await Test_Filter_EvenOdd(); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_BadFunc() { await Assert.ThrowsAsync(typeof(ArgumentException), () => Test_Filter_BadFunc()); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_TwoObsv_Different() { await Test_Filter_TwoObsv_Different(); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_TwoObsv_Same() { await Test_Filter_TwoObsv_Same(); } } }
/* ==================================================================== 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.HSLF.Model; using NPOI.ddf.EscherProperties; /** * Stores defInition of auto-shapes. * See the Office Drawing 97-2007 Binary Format Specification for details. * * TODO: follow the spec and define all the auto-shapes * * @author Yegor Kozlov */ public class AutoShapes { protected static ShapeOutline[] shapes; /** * Return shape outline by shape type * @param type shape type see {@link ShapeTypes} * * @return the shape outline */ public static ShapeOutline GetShapeOutline(int type){ ShapeOutline outline = shapes[type]; return outline; } /** * Auto-shapes are defined in the [0,21600] coordinate system. * We need to transform it into normal slide coordinates * */ public static java.awt.Shape transform(java.awt.Shape outline, Rectangle2D anchor){ AffineTransform at = new AffineTransform(); at.translate(anchor.GetX(), anchor.GetY()); at.scale( 1.0f/21600*anchor.Width, 1.0f/21600*anchor.Height ); return at.CreateTransformedShape(outline); } static { shapes = new ShapeOutline[255]; shapes[ShapeTypes.Rectangle] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ Rectangle2D path = new Rectangle2D.Float(0, 0, 21600, 21600); return path; } }; shapes[ShapeTypes.RoundRectangle] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); RoundRectangle2D path = new RoundRectangle2D.Float(0, 0, 21600, 21600, adjval, adjval); return path; } }; shapes[ShapeTypes.Ellipse] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ Ellipse2D path = new Ellipse2D.Float(0, 0, 21600, 21600); return path; } }; shapes[ShapeTypes.Diamond] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ GeneralPath path = new GeneralPath(); path.moveTo(10800, 0); path.lineTo(21600, 10800); path.lineTo(10800, 21600); path.lineTo(0, 10800); path.ClosePath(); return path; } }; //m@0,l,21600r21600 shapes[ShapeTypes.IsocelesTriangle] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 10800); GeneralPath path = new GeneralPath(); path.moveTo(adjval, 0); path.lineTo(0, 21600); path.lineTo(21600, 21600); path.ClosePath(); return path; } }; shapes[ShapeTypes.RightTriangle] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ GeneralPath path = new GeneralPath(); path.moveTo(0, 0); path.lineTo(21600, 21600); path.lineTo(0, 21600); path.ClosePath(); return path; } }; shapes[ShapeTypes.Parallelogram] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(adjval, 0); path.lineTo(21600, 0); path.lineTo(21600 - adjval, 21600); path.lineTo(0, 21600); path.ClosePath(); return path; } }; shapes[ShapeTypes.Trapezoid] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(0, 0); path.lineTo(adjval, 21600); path.lineTo(21600 - adjval, 21600); path.lineTo(21600, 0); path.ClosePath(); return path; } }; shapes[ShapeTypes.Hexagon] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(adjval, 0); path.lineTo(21600 - adjval, 0); path.lineTo(21600, 10800); path.lineTo(21600 - adjval, 21600); path.lineTo(adjval, 21600); path.lineTo(0, 10800); path.ClosePath(); return path; } }; shapes[ShapeTypes.Octagon] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 6326); GeneralPath path = new GeneralPath(); path.moveTo(adjval, 0); path.lineTo(21600 - adjval, 0); path.lineTo(21600, adjval); path.lineTo(21600, 21600-adjval); path.lineTo(21600-adjval, 21600); path.lineTo(adjval, 21600); path.lineTo(0, 21600-adjval); path.lineTo(0, adjval); path.ClosePath(); return path; } }; shapes[ShapeTypes.Plus] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(adjval, 0); path.lineTo(21600 - adjval, 0); path.lineTo(21600 - adjval, adjval); path.lineTo(21600, adjval); path.lineTo(21600, 21600-adjval); path.lineTo(21600-adjval, 21600-adjval); path.lineTo(21600-adjval, 21600); path.lineTo(adjval, 21600); path.lineTo(adjval, 21600-adjval); path.lineTo(0, 21600-adjval); path.lineTo(0, adjval); path.lineTo(adjval, adjval); path.ClosePath(); return path; } }; shapes[ShapeTypes.Pentagon] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ GeneralPath path = new GeneralPath(); path.moveTo(10800, 0); path.lineTo(21600, 8259); path.lineTo(21600 - 4200, 21600); path.lineTo(4200, 21600); path.lineTo(0, 8259); path.ClosePath(); return path; } }; shapes[ShapeTypes.DownArrow] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ //m0@0 l@1@0 @1,0 @2,0 @2@0,21600@0,10800,21600xe int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 16200); int adjval2 = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUST2VALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(0, adjval); path.lineTo(adjval2, adjval); path.lineTo(adjval2, 0); path.lineTo(21600-adjval2, 0); path.lineTo(21600-adjval2, adjval); path.lineTo(21600, adjval); path.lineTo(10800, 21600); path.ClosePath(); return path; } }; shapes[ShapeTypes.UpArrow] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ //m0@0 l@1@0 @1,21600@2,21600@2@0,21600@0,10800,xe int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); int adjval2 = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUST2VALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(0, adjval); path.lineTo(adjval2, adjval); path.lineTo(adjval2, 21600); path.lineTo(21600-adjval2, 21600); path.lineTo(21600-adjval2, adjval); path.lineTo(21600, adjval); path.lineTo(10800, 0); path.ClosePath(); return path; } }; shapes[ShapeTypes.Arrow] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ //m@0, l@0@1 ,0@1,0@2@0@2@0,21600,21600,10800xe int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 16200); int adjval2 = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUST2VALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(adjval, 0); path.lineTo(adjval, adjval2); path.lineTo(0, adjval2); path.lineTo(0, 21600-adjval2); path.lineTo(adjval, 21600-adjval2); path.lineTo(adjval, 21600); path.lineTo(21600, 10800); path.ClosePath(); return path; } }; shapes[ShapeTypes.LeftArrow] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ //m@0, l@0@1,21600@1,21600@2@0@2@0,21600,,10800xe int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); int adjval2 = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUST2VALUE, 5400); GeneralPath path = new GeneralPath(); path.moveTo(adjval, 0); path.lineTo(adjval, adjval2); path.lineTo(21600, adjval2); path.lineTo(21600, 21600-adjval2); path.lineTo(adjval, 21600-adjval2); path.lineTo(adjval, 21600); path.lineTo(0, 10800); path.ClosePath(); return path; } }; shapes[ShapeTypes.Can] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ //m10800,qx0@1l0@2qy10800,21600,21600@2l21600@1qy10800,xem0@1qy10800@0,21600@1nfe int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 5400); GeneralPath path = new GeneralPath(); path.Append(new Arc2D.Float(0, 0, 21600, adjval, 0, 180, Arc2D.OPEN), false); path.moveTo(0, adjval/2); path.lineTo(0, 21600 - adjval/2); path.ClosePath(); path.Append(new Arc2D.Float(0, 21600 - adjval, 21600, adjval, 180, 180, Arc2D.OPEN), false); path.moveTo(21600, 21600 - adjval/2); path.lineTo(21600, adjval/2); path.Append(new Arc2D.Float(0, 0, 21600, adjval, 180, 180, Arc2D.OPEN), false); path.moveTo(0, adjval/2); path.ClosePath(); return path; } }; shapes[ShapeTypes.LeftBrace] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ //m21600,qx10800@0l10800@2qy0@11,10800@3l10800@1qy21600,21600e int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 1800); int adjval2 = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUST2VALUE, 10800); GeneralPath path = new GeneralPath(); path.moveTo(21600, 0); path.Append(new Arc2D.Float(10800, 0, 21600, adjval*2, 90, 90, Arc2D.OPEN), false); path.moveTo(10800, adjval); path.lineTo(10800, adjval2 - adjval); path.Append(new Arc2D.Float(-10800, adjval2 - 2*adjval, 21600, adjval*2, 270, 90, Arc2D.OPEN), false); path.moveTo(0, adjval2); path.Append(new Arc2D.Float(-10800, adjval2, 21600, adjval*2, 0, 90, Arc2D.OPEN), false); path.moveTo(10800, adjval2 + adjval); path.lineTo(10800, 21600 - adjval); path.Append(new Arc2D.Float(10800, 21600 - 2*adjval, 21600, adjval*2, 180, 90, Arc2D.OPEN), false); return path; } }; shapes[ShapeTypes.RightBrace] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ //m,qx10800@0 l10800@2qy21600@11,10800@3l10800@1qy,21600e int adjval = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUSTVALUE, 1800); int adjval2 = shape.GetEscherProperty(EscherProperties.GEOMETRY__ADJUST2VALUE, 10800); GeneralPath path = new GeneralPath(); path.moveTo(0, 0); path.Append(new Arc2D.Float(-10800, 0, 21600, adjval*2, 0, 90, Arc2D.OPEN), false); path.moveTo(10800, adjval); path.lineTo(10800, adjval2 - adjval); path.Append(new Arc2D.Float(10800, adjval2 - 2*adjval, 21600, adjval*2, 180, 90, Arc2D.OPEN), false); path.moveTo(21600, adjval2); path.Append(new Arc2D.Float(10800, adjval2, 21600, adjval*2, 90, 90, Arc2D.OPEN), false); path.moveTo(10800, adjval2 + adjval); path.lineTo(10800, 21600 - adjval); path.Append(new Arc2D.Float(-10800, 21600 - 2*adjval, 21600, adjval*2, 270, 90, Arc2D.OPEN), false); return path; } }; shapes[ShapeTypes.StraightConnector1] = new ShapeOutline(){ public java.awt.Shape GetOutline(Shape shape){ return new Line2D.Float(0, 0, 21600, 21600); } }; } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Resources; using System.IO; using System.Drawing; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Caching; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Globalization; using WebsitePanel.Portal; namespace WebsitePanel.WebPortal { public partial class DefaultPage : System.Web.UI.Page { public const string DEFAULT_PAGE = "~/Default.aspx"; public const string PAGE_ID_PARAM = "pid"; public const string CONTROL_ID_PARAM = "ctl"; public const string MODULE_ID_PARAM = "mid"; public const string THEMES_FOLDER = "App_Themes"; public const string IMAGES_FOLDER = "Images"; public const string ICONS_FOLDER = "Icons"; public const string SKINS_FOLDER = "App_Skins"; public const string CONTAINERS_FOLDER = "App_Containers"; public const string CONTENT_PANE_NAME = "ContentPane"; public const string LEFT_PANE_NAME = "LeftPane"; public const string MODULE_TITLE_CONTROL_ID = "lblModuleTitle"; public const string MODULE_ICON_CONTROL_ID = "imgModuleIcon"; public const string DESKTOP_MODULES_FOLDER = "DesktopModules"; protected string CultureCookieName { get { return PortalConfiguration.SiteSettings["CultureCookieName"]; } } private string CurrentPageID { get { string pid = Request[PAGE_ID_PARAM]; if (pid == null) { // get default page pid = PortalConfiguration.SiteSettings["DefaultPage"]; } return pid.ToLower(CultureInfo.InvariantCulture); } } private string ModuleControlID { get { string ctl = Request[CONTROL_ID_PARAM]; if (ctl == null) { ctl = ""; } return ctl.ToLower(CultureInfo.InvariantCulture); } } private int ModuleID { get { string smid = Request[MODULE_ID_PARAM]; if (smid == null) { smid = "0"; } return Int32.Parse(smid); } } public static string GetPageUrl(string pid) { return DefaultPage.DEFAULT_PAGE + "?" + DefaultPage.PAGE_ID_PARAM + "=" + pid; } public static bool IsAccessibleToUser(HttpContext context, IList roles) { foreach (string role in roles) { if (role == "?") return true; if ((role == "*") || ((context.User != null) && context.User.IsInRole(role))) { return true; } } return false; } protected void Page_Load(object sender, EventArgs e) { } protected void Page_PreInit(object sender, EventArgs e) { Theme = PortalThemeProvider.Instance.GetTheme(); } protected void Page_Init(object sender, EventArgs e) { // get page info string pid = CurrentPageID; if(PortalConfiguration.Site.Pages[pid] == null) { ShowError(skinPlaceHolder, String.Format("Page with ID '{0}' is not found", HttpUtility.HtmlEncode(pid))); return; } PortalPage page = PortalConfiguration.Site.Pages[pid]; // check if page is accessible to user if (!IsAccessibleToUser(Context, page.Roles)) { // redirect to login page string returnUrl = Request.RawUrl; Response.Redirect(DEFAULT_PAGE + "?" + PAGE_ID_PARAM + "=" + PortalConfiguration.SiteSettings["LoginPage"] + "&ReturnUrl=" + Server.UrlEncode(returnUrl)); } Title = String.Format("{0} - {1}", PortalConfiguration.SiteSettings["PortalName"], PageTitleProvider.Instance.ProcessPageTitle(GetLocalizedPageTitle(page.Name))); // load skin bool editMode = (ModuleControlID != "" && ModuleID > 0); string skinName = page.SkinSrc; if(!editMode) { // browse skin if (String.IsNullOrEmpty(skinName)) { // load portal skin skinName = PortalConfiguration.SiteSettings["PortalSkin"]; } } else { // edit skin if (!String.IsNullOrEmpty(page.AdminSkinSrc)) skinName = page.AdminSkinSrc; else skinName = PortalConfiguration.SiteSettings["AdminSkin"]; } // load skin control string skinPath = "~/" + SKINS_FOLDER + "/" + this.Theme + "/" + skinName; Control ctrlSkin = null; try { ctrlSkin = LoadControl(skinPath); skinPlaceHolder.Controls.Add(ctrlSkin); } catch (Exception ex) { ShowError(skinPlaceHolder, String.Format("Can't load {0} skin: {1}", skinPath, ex.ToString())); return; } // load page modules if (!editMode) { // browse mode foreach (string paneId in page.ContentPanes.Keys) { // try to find content pane Control ctrlPane = ctrlSkin.FindControl(paneId); if (ctrlPane != null) { // insert modules ContentPane pane = page.ContentPanes[paneId]; foreach (PageModule module in pane.Modules) { if (IsAccessibleToUser(Context, module.ViewRoles)) { // add module if (module.Settings.Contains("UseDefault")) { string useDefault = Convert.ToString(module.Settings["UseDefault"]).ToLower(CultureInfo.InvariantCulture); AddModuleToContentPane(ctrlPane, module, useDefault, editMode); } else AddModuleToContentPane(ctrlPane, module, "", editMode); } } } } } else { // edit mode // find ContentPane Control ctrlPane = ctrlSkin.FindControl(CONTENT_PANE_NAME); if (ctrlPane != null) { // add "edit" module if (PortalConfiguration.Site.Modules.ContainsKey(ModuleID)) AddModuleToContentPane(ctrlPane, PortalConfiguration.Site.Modules[ModuleID], ModuleControlID, editMode); } // find LeftPane ctrlPane = ctrlSkin.FindControl(LEFT_PANE_NAME); if (ctrlPane != null && page.ContentPanes.ContainsKey(LEFT_PANE_NAME)) { ContentPane pane = page.ContentPanes[LEFT_PANE_NAME]; foreach (PageModule module in pane.Modules) { if (IsAccessibleToUser(Context, module.ViewRoles)) { // add module AddModuleToContentPane(ctrlPane, module, "", false); } } } } } protected void Page_PreRender(object sender, EventArgs e) { // Ensure the page's form action attribute is not empty if (Request.RawUrl.Equals("/") == false) return; // Assign default page to avoid ASP.NET 4 issue w/ Extensionless URL Module & Custom HTTP Modules Form.Action = Form.ResolveUrl(DEFAULT_PAGE); } private void AddModuleToContentPane(Control pane, PageModule module, string ctrlKey, bool editMode) { string defId = module.ModuleDefinitionID; if(!PortalConfiguration.ModuleDefinitions.ContainsKey(defId)) { ShowError(pane, String.Format("Module definition '{0}' could not be found", defId)); return; } ModuleDefinition definition = PortalConfiguration.ModuleDefinitions[defId]; ModuleControl control = null; if(String.IsNullOrEmpty(ctrlKey)) control = definition.DefaultControl; else { if(definition.Controls.ContainsKey(ctrlKey)) control = definition.Controls[ctrlKey]; } if(control == null) return; // container string containerName = editMode ? PortalConfiguration.SiteSettings["AdminContainer"] : PortalConfiguration.SiteSettings["PortalContainer"]; if (!editMode && !String.IsNullOrEmpty(module.ContainerSrc)) containerName = module.ContainerSrc; if (editMode && !String.IsNullOrEmpty(module.AdminContainerSrc)) containerName = module.AdminContainerSrc; // load container string containerPath = "~/" + CONTAINERS_FOLDER + "/" + this.Theme + "/" + containerName; Control ctrlContainer = null; try { ctrlContainer = LoadControl(containerPath); } catch (Exception ex) { ShowError(pane, String.Format("Container '{0}' could not be loaded: {1}", containerPath, ex.ToString())); return; } string title = module.Title; if (editMode || String.IsNullOrEmpty(title)) { // get control title title = control.Title; } string iconFile = module.IconFile; if (editMode || String.IsNullOrEmpty(iconFile)) { // get control icon iconFile = control.IconFile; } // set title Label lblModuleTitle = (Label)ctrlContainer.FindControl(MODULE_TITLE_CONTROL_ID); if (lblModuleTitle != null) { lblModuleTitle.Text = GetLocalizedModuleTitle(title); } // set icon System.Web.UI.WebControls.Image imgModuleIcon = (System.Web.UI.WebControls.Image)ctrlContainer.FindControl(MODULE_ICON_CONTROL_ID); if (imgModuleIcon != null) { if (String.IsNullOrEmpty(iconFile)) { imgModuleIcon.Visible = false; } else { string iconPath = "~/" + THEMES_FOLDER + "/" + this.Theme + "/" + ICONS_FOLDER + "/" + iconFile; imgModuleIcon.ImageUrl = iconPath; } } Control contentPane = ctrlContainer.FindControl(CONTENT_PANE_NAME); if (contentPane != null) { string controlName = control.Src; string controlPath = "~/" + DESKTOP_MODULES_FOLDER + "/" + controlName; if (!String.IsNullOrEmpty(controlName)) { PortalControlBase ctrlControl = null; try { ctrlControl = (PortalControlBase)LoadControl(controlPath); ctrlControl.Module = module; ctrlControl.ContainerControl = ctrlContainer; contentPane.Controls.Add(ctrlControl); } catch (Exception ex) { ShowError(contentPane, String.Format("Control '{0}' could not be loaded: {1}", controlPath, ex.ToString())); } } } // add controls to the pane pane.Controls.Add(ctrlContainer); } protected override void InitializeCulture() { HttpCookie localeCrub = Request.Cookies[CultureCookieName]; if (localeCrub != null) { string localeCode = localeCrub.Value; UICulture = localeCode; Culture = localeCode; System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CreateSpecificCulture(localeCode); if (ci != null) { // Reset currency symbol to deal with the existing ISO currency symbol implementation ci.NumberFormat.CurrencySymbol = String.Empty; // Setting up culture System.Threading.Thread.CurrentThread.CurrentCulture = ci; System.Threading.Thread.CurrentThread.CurrentUICulture = ci; } } base.InitializeCulture(); } private void ShowError(Control placeholder, string message) { Label lbl = new Label(); lbl.Text = PortalAntiXSS.Encode("<div style=\"height:300px;overflow:auto;\">" + message.Replace("\n", "<br>") + "</div>"); lbl.ForeColor = Color.Red; lbl.Font.Bold = true; lbl.Font.Size = FontUnit.Point(8); placeholder.Controls.Add(lbl); } public static string GetLocalizedModuleTitle(string moduleName) { string localizedString = GetLocalizedResourceString("Modules", String.Concat("ModuleTitle.", moduleName)); return localizedString != null ? localizedString : moduleName; } public static string GetLocalizedPageTitle(string tabName) { string localizedString = GetLocalizedResourceString("Pages", String.Concat("PageTitle.", tabName)); return localizedString != null ? localizedString : tabName; } public static string GetLocalizedPageName(string tabName) { return GetLocalizedResourceString("Pages", String.Concat("PageName.", tabName)); } private static string GetLocalizedResourceString(string suffix, string key) { List<string> list1 = null; if (suffix == "Pages") { list1 = GetResourceFiles("Pages", "WspLocaleAdapterPages"); } else { list1 = GetResourceFiles("Modules", "WspLocaleAdapterModules"); } string text1 = null; foreach (string text2 in list1) { text1 = GetGlobalLocalizedString(text2, key); if (!String.IsNullOrEmpty(text1)) { return text1; } } return text1; } private static List<string> GetResourceFiles(string suffix, string cacheKey) { List<string> list1 = (List<string>)HttpContext.Current.Cache[cacheKey]; if (list1 == null) { list1 = new List<string>(); string text2 = HttpContext.Current.Server.MapPath("~/App_GlobalResources"); FileInfo[] infoArray1 = new DirectoryInfo(text2).GetFiles("*_" + suffix + ".ascx.resx"); foreach (FileInfo info1 in infoArray1) { list1.Add(info1.Name); } HttpContext.Current.Cache.Insert(cacheKey, list1, new CacheDependency(text2)); } return list1; } public static string GetGlobalLocalizedString(string fileName, string resourceKey) { string className = fileName.Replace(".resx", ""); return (string)HttpContext.GetGlobalResourceObject(className, resourceKey); } } }
using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Lime.Protocol.Listeners; using Lime.Protocol.Network; using Moq; using NUnit.Framework; using Shouldly; using System; namespace Lime.Protocol.UnitTests.Listeners { [TestFixture] public class DataflowChannelListenerTests { protected Mock<IEstablishedReceiverChannel> _channel; protected BlockingCollection<Message> _producedMessages; protected BlockingCollection<Notification> _producedNotifications; protected BlockingCollection<Command> _producedCommands; private BufferBlock<Message> _messageBufferBlock; private BufferBlock<Notification> _notificationBufferBlock; private BufferBlock<Command> _commandBufferBlock; private CancellationTokenSource _cts; [SetUp] public void SetUp() { _channel = new Mock<IEstablishedReceiverChannel>(); _producedMessages = new BlockingCollection<Message>(); _producedNotifications = new BlockingCollection<Notification>(); _producedCommands = new BlockingCollection<Command>(); _channel .Setup(m => m.ReceiveMessageAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken cancellationToken) => _producedMessages.Take(cancellationToken).AsCompletedTask()); _channel .Setup(m => m.ReceiveNotificationAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken cancellationToken) => _producedNotifications.Take(cancellationToken).AsCompletedTask()); _channel .Setup(m => m.ReceiveCommandAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken cancellationToken) => _producedCommands.Take(cancellationToken).AsCompletedTask()); _cts = new CancellationTokenSource(); var options = new DataflowBlockOptions() { CancellationToken = _cts.Token }; _messageBufferBlock = new BufferBlock<Message>(options); _notificationBufferBlock = new BufferBlock<Notification>(options); _commandBufferBlock = new BufferBlock<Command>(options); } [TearDown] public void TearDown() { _cts.Dispose(); _channel = null; _messageBufferBlock = null; _notificationBufferBlock = null; _commandBufferBlock = null; } private DataflowChannelListener GetAndStartTarget() { var target = new DataflowChannelListener(_messageBufferBlock, _notificationBufferBlock, _commandBufferBlock); target.Start(_channel.Object); return target; } [Test] public async Task Start_MessageReceived_SendsToBuffer() { // Arrange var message = Dummy.CreateMessage(Dummy.CreateTextContent()); var target = GetAndStartTarget(); // Act _producedMessages.Add(message); // Assert Message actual = await _messageBufferBlock.ReceiveAsync(); actual.ShouldBe(message); target.Stop(); } [Test] public async Task Start_MultipleMessagesReceived_SendsToBuffer() { // Arrange var messages = new List<Message>(); var count = Dummy.CreateRandomInt(100); for (int i = 0; i < count; i++) { messages.Add( Dummy.CreateMessage(Dummy.CreateTextContent())); } var target = GetAndStartTarget(); // Act foreach (var message in messages) { _producedMessages.Add(message); } // Assert for (int i = 0; i < count; i++) { var actual = await _messageBufferBlock.ReceiveAsync(); messages.ShouldContain(actual); } } [Test] public async Task Start_CompletedMessageBufferBlock_StopsConsumerTask() { // Arrange var message = Dummy.CreateMessage(Dummy.CreateTextContent()); var target = GetAndStartTarget(); // Act _messageBufferBlock.Complete(); _producedMessages.Add(message); // Assert (await target.MessageListenerTask.WithCancellation(_cts.Token)).ShouldBe(message); } [Test] public async Task Start_NotificationReceived_SendsToBuffer() { // Arrange var notification = Dummy.CreateNotification(Event.Received); var target = GetAndStartTarget(); // Act _producedNotifications.Add(notification); // Assert Notification actual = await _notificationBufferBlock.ReceiveAsync(); actual.ShouldBe(notification); target.Stop(); } [Test] public async Task Start_MultipleNotificationsReceived_SendsToBuffer() { // Arrange var notifications = new List<Notification>(); var count = Dummy.CreateRandomInt(100); for (int i = 0; i < count; i++) { notifications.Add( Dummy.CreateNotification(Event.Received)); } var target = GetAndStartTarget(); // Act foreach (var notification in notifications) { _producedNotifications.Add(notification); } // Assert for (int i = 0; i < count; i++) { var actual = await _notificationBufferBlock.ReceiveAsync(); notifications.ShouldContain(actual); } } [Test] public async Task Start_CompletedNotificationBufferBlock_StopsConsumerTask() { // Arrange var notification = Dummy.CreateNotification(Event.Received); var target = GetAndStartTarget(); // Act _notificationBufferBlock.Complete(); _producedNotifications.Add(notification); // Assert (await target.NotificationListenerTask.WithCancellation(_cts.Token)).ShouldBe(notification); } [Test] public async Task Start_CommandReceived_SendsToBuffer() { // Arrange var command = Dummy.CreateCommand(Dummy.CreateTextContent()); var target = GetAndStartTarget(); // Act _producedCommands.Add(command); // Assert Command actual = await _commandBufferBlock.ReceiveAsync(); actual.ShouldBe(command); target.Stop(); } [Test] public async Task Start_MultipleCommandsReceived_SendsToBuffer() { // Arrange var commands = new List<Command>(); var count = Dummy.CreateRandomInt(100); for (int i = 0; i < count; i++) { commands.Add( Dummy.CreateCommand(Dummy.CreateTextContent())); } var target = GetAndStartTarget(); // Act foreach (var command in commands) { _producedCommands.Add(command); } // Assert for (int i = 0; i < count; i++) { var actual = await _commandBufferBlock.ReceiveAsync(); commands.ShouldContain(actual); } } [Test] public async Task Start_CompletedCommandBufferBlock_StopsConsumerTask() { // Arrange var command = Dummy.CreateCommand(Dummy.CreateTextContent()); var target = GetAndStartTarget(); // Act _commandBufferBlock.Complete(); _producedCommands.Add(command); // Assert (await target.CommandListenerTask.WithCancellation(_cts.Token)).ShouldBe(command); } } }
/* Copyright (c) 2004-2009 Deepak Nataraj. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S) AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Collections.Specialized; using System.Xml.Serialization; using System.Diagnostics; using System.Runtime.Remoting; using System.Threading; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using GOBaseLibrary.Interfaces; namespace GOBaseLibrary.Common { /// <summary> /// Represents a concrete node in a graph /// </summary> [Serializable] public class Node : IGraphElement { private String id; private String address; private SerializableDictionary<Node, double> neighborIDCostMap; // cost of edges between the graph elements private List<IGraphElement> groupList; // groups to which the node belongs to private string ip, port; public String Port { get { return port; } set { port = value; } } public String Ip { get { return ip; } set { ip = value; } } private SerializableDictionary<Node, double> NeighborMap { get { return neighborIDCostMap; } set { neighborIDCostMap = value; } } [XmlElement] public String Id { get { return id; } set { id = value; } } /// <summary> /// address contains ip and port separated by a colon /// </summary> [XmlElement] public String Address { get { return address; } set { address = value; string[] ipPort = address.Split(':'); ip = ipPort[0]; port = ipPort[1]; } } public Node() { id = ""; neighborIDCostMap = new SerializableDictionary<Node, double>(); groupList = new List<IGraphElement>(); } public Node(String nID) { id = nID; neighborIDCostMap = new SerializableDictionary<Node, double>(); groupList = new List<IGraphElement>(); } public void printGroupList() { Console.WriteLine("Grouplist: " + groupList); } #region IGraphElement Members /// <summary> /// Join a group /// </summary> /// <param name="group">Group to which the node has to join</param> public void Join(IGraphElement group) { try { if (groupList != null) { groupList.Add(group); } } catch (Exception e) { throw new UseCaseException("340", "Node::Join " + e + ", " + e.StackTrace); } } /// <summary> /// Leave a group /// </summary> /// <param name="group">Group from which the node has to leave</param> public void Leave(IGraphElement group) { try { if (groupList != null) { groupList.Remove(group); } } catch (Exception e) { throw new UseCaseException("360", "Node::Leave " + e + ", " + e.StackTrace); } } /// <summary> /// an element could belong to many groups /// </summary> /// <returns>a list of groups to which the current element belongs to</returns> public List<IGraphElement> GetJoinedGroupList() { return groupList; } /// <summary> /// an element could be connected to many neighboring elements /// </summary> /// <returns>get the neighbors of current element</returns> IDictionary<IGraphElement, double> IGraphElement.GetNeighborList() { try { if (neighborIDCostMap == null || neighborIDCostMap.Count == 0) { return null; } Dictionary<IGraphElement, double> newDict = new Dictionary<IGraphElement, double>(); foreach (KeyValuePair<Node, double> kv in this.neighborIDCostMap) { newDict.Add(kv.Key, kv.Value); } return newDict; } catch (Exception e) { throw new UseCaseException("380", "Node::GetNeighborList " + e + ", " + e.StackTrace); } } public SerializableDictionary<Node, double> getNeighborList() { return (neighborIDCostMap); } /// <summary> /// Add an edge for the neighbor and the cost of reaching it /// </summary> /// <param name="node">neighboring node to add</param> /// <param name="edgeCost">cost of reaching the neighbor</param> public void AddNeighbor(IGraphElement node, double edgeCost) { try { /* * Remove the edge if it already exists */ if (neighborIDCostMap.Keys != null && neighborIDCostMap.ContainsKey(node as Node)) { neighborIDCostMap.Remove(node as Node); } /* * Add the edge */ neighborIDCostMap.Add(node as Node, edgeCost); } catch (Exception e) { throw new UseCaseException("400", "Node::AddNeighbor " + e + ", " + e.StackTrace); } } /// <summary> /// remove an edge for the neighbor /// </summary> /// <param name="node">neighboring node to remove</param> public void RemoveNeighbor(IGraphElement node) { try { neighborIDCostMap.Remove(node as Node); } catch (Exception e) { throw new UseCaseException("420", "Node::RemoveNeighbor " + e + ", " + e.StackTrace); } } public string GetID() { return id; } public void SetID(String nodeId) { id = nodeId; } public double GetEdgeCost(IGraphElement neighbor) { try { return neighborIDCostMap == null || !neighborIDCostMap.ContainsKey(neighbor as Node) ? Constants.INFINITY : neighborIDCostMap[neighbor as Node]; } catch (Exception e) { throw new UseCaseException("440", "Node::GetEdgeCost " + e + ", " + e.StackTrace); } } public void SetEdgeCost(IGraphElement neighbor, double cost) { try { if (neighborIDCostMap != null && neighborIDCostMap.ContainsKey(neighbor as Node)) { neighborIDCostMap[neighbor as Node] = cost; } } catch (Exception e) { throw new UseCaseException("460", "Node::SetEdgeCost " + e + ", " + e.StackTrace); } } public string GetAddress() { return address; } public void SetAddress(String nodeAddress) { address = nodeAddress; string[] ipPort = address.Split(':'); ip = ipPort[0]; port = ipPort[1]; } #endregion /// <summary> /// two elements are considered equal if their IDs match /// </summary> /// <param name="right">element to be compared with 'this' element</param> /// <returns>true if IDs are equal, false otherwise</returns> public override bool Equals(object right) { if (right == null) return false; return this.id == (right as Node).Id; } public override int GetHashCode() { return base.GetHashCode(); } // deep copy in separate memory space public object Clone() { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, this); ms.Position = 0; object obj = bf.Deserialize(ms); ms.Close(); return obj; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// Options for creating and running scripts. /// </summary> public sealed class ScriptOptions { public static readonly ScriptOptions Default = new ScriptOptions( path: "", references: ImmutableArray<MetadataReference>.Empty, namespaces: ImmutableArray<string>.Empty, metadataResolver: RuntimeMetadataReferenceResolver.Default, sourceResolver: SourceFileResolver.Default, isInteractive: true); /// <summary> /// An array of <see cref="MetadataReference"/>s to be added to the script. /// </summary> /// <remarks> /// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>). /// Unresolved references are resolved when the script is about to be executed /// (<see cref="Script.RunAsync(object, CancellationToken)"/>. /// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>. /// </remarks> public ImmutableArray<MetadataReference> MetadataReferences { get; private set; } /// <summary> /// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives. /// </summary> public MetadataReferenceResolver MetadataResolver { get; private set; } /// <summary> /// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive. /// </summary> public SourceReferenceResolver SourceResolver { get; private set; } /// <summary> /// The namespaces automatically imported by the script. /// </summary> public ImmutableArray<string> Namespaces { get; private set; } /// <summary> /// The path to the script source if it originated from a file, empty otherwise. /// </summary> public string Path { get; private set; } /// <summary> /// True if the script is interactive. /// Interactive scripts may contain a final expression whose value is returned when the script is run. /// </summary> public bool IsInteractive { get; private set; } private ScriptOptions( string path, ImmutableArray<MetadataReference> references, ImmutableArray<string> namespaces, MetadataReferenceResolver metadataResolver, SourceReferenceResolver sourceResolver, bool isInteractive) { Debug.Assert(path != null); Debug.Assert(!references.IsDefault); Debug.Assert(!namespaces.IsDefault); Debug.Assert(metadataResolver != null); Debug.Assert(sourceResolver != null); Path = path; MetadataReferences = references; Namespaces = namespaces; MetadataResolver = metadataResolver; SourceResolver = sourceResolver; IsInteractive = isInteractive; } private ScriptOptions(ScriptOptions other) : this(path: other.Path, references: other.MetadataReferences, namespaces: other.Namespaces, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver, isInteractive: other.IsInteractive) { } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Path"/> changed. /// </summary> public ScriptOptions WithPath(string path) => (Path == path) ? this : new ScriptOptions(this) { Path = path ?? "" }; private static MetadataReference CreateUnresolvedReference(string reference) => new UnresolvedMetadataReference(reference, MetadataReferenceProperties.Assembly); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) => MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) => WithReferences(ToImmutableArrayChecked(references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params MetadataReference[] references) => WithReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) => WithReferences(ConcatChecked(MetadataReferences, references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params MetadataReference[] references) => AddReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<Assembly> references) => WithReferences(SelectChecked(references, nameof(references), MetadataReference.CreateFromAssemblyInternal)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params Assembly[] references) => WithReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<Assembly> references) => AddReferences(SelectChecked(references, nameof(references), MetadataReference.CreateFromAssemblyInternal)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(params Assembly[] references) => AddReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<string> references) => WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params string[] references) => WithReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<string> references) => AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params string[] references) => AddReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="MetadataResolver"/> set to the default metadata resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving assembly file names.</param> /// <remarks> /// The default resolver looks up references in specified <paramref name="searchPaths"/>, in NuGet packages and in Global Assembly Cache (if available on the current platform). /// </remarks> public ScriptOptions WithDefaultMetadataResolution(ImmutableArray<string> searchPaths) { var resolver = new RuntimeMetadataReferenceResolver( ToImmutableArrayChecked(searchPaths, nameof(searchPaths)), baseDirectory: null); return new ScriptOptions(this) { MetadataResolver = resolver }; } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="MetadataResolver"/> set to the default metadata resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving assembly file names.</param> /// <remarks> /// The default resolver looks up references in specified <paramref name="searchPaths"/>, in NuGet packages and in Global Assembly Cache (if available on the current platform). /// </remarks> public ScriptOptions WithDefaultMetadataResolution(IEnumerable<string> searchPaths) => WithDefaultMetadataResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="MetadataResolver"/> set to the default metadata resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving assembly file names.</param> /// <remarks> /// The default resolver looks up references in specified <paramref name="searchPaths"/>, in NuGet packages and in Global Assembly Cache (if available on the current platform). /// </remarks> public ScriptOptions WithDefaultMetadataResolution(params string[] searchPaths) => WithDefaultMetadataResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>. /// </summary> public ScriptOptions WithCustomMetadataResolution(MetadataReferenceResolver resolver) => MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="SourceResolver"/> set to the default source resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving script file names.</param> /// <remarks> /// The default resolver looks up scripts in specified <paramref name="searchPaths"/> and in NuGet packages. /// </remarks> public ScriptOptions WithDefaultSourceResolution(ImmutableArray<string> searchPaths) { var resolver = new SourceFileResolver( ToImmutableArrayChecked(searchPaths, nameof(searchPaths)), baseDirectory: null); return new ScriptOptions(this) { SourceResolver = resolver }; } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="SourceResolver"/> set to the default source resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving script file names.</param> /// <remarks> /// The default resolver looks up scripts in specified <paramref name="searchPaths"/> and in NuGet packages. /// </remarks> public ScriptOptions WithDefaultSourceResolution(IEnumerable<string> searchPaths) => WithDefaultSourceResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="SourceResolver"/> set to the default source resolver for the current platform. /// </summary> /// <param name="searchPaths">Directories to be used by the default resolver when resolving script file names.</param> /// <remarks> /// The default resolver looks up scripts in specified <paramref name="searchPaths"/> and in NuGet packages. /// </remarks> public ScriptOptions WithDefaultSourceResolution(params string[] searchPaths) => WithDefaultSourceResolution(searchPaths.AsImmutableOrEmpty()); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>. /// </summary> public ScriptOptions WithCustomSourceResolution(SourceReferenceResolver resolver) => SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the namespaces changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions WithNamespaces(ImmutableArray<string> namespaces) => Namespaces.Equals(namespaces) ? this : new ScriptOptions(this) { Namespaces = CheckImmutableArray(namespaces, nameof(namespaces)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the namespaces changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions WithNamespaces(IEnumerable<string> namespaces) => WithNamespaces(ToImmutableArrayChecked(namespaces, nameof(namespaces))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the namespaces changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions WithNamespaces(params string[] namespaces) => WithNamespaces((IEnumerable<string>)namespaces); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with namespaces added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions AddNamespaces(IEnumerable<string> namespaces) => WithNamespaces(ConcatChecked(Namespaces, namespaces, nameof(namespaces))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with namespaces added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="namespaces"/> is null or contains a null reference.</exception> public ScriptOptions AddNamespaces(params string[] namespaces) => AddNamespaces((IEnumerable<string>)namespaces); /// <summary> /// Create a new <see cref="ScriptOptions"/> with the interactive state specified. /// Interactive scripts may contain a final expression whose value is returned when the script is run. /// </summary> public ScriptOptions WithIsInteractive(bool isInteractive) => IsInteractive == isInteractive ? this : new ScriptOptions(this) { IsInteractive = isInteractive }; #region Parameter Validation private static ImmutableArray<T> CheckImmutableArray<T>(ImmutableArray<T> items, string parameterName) { if (items.IsDefault) { throw new ArgumentNullException(parameterName); } for (int i = 0; i < items.Length; i++) { if (items[i] == null) { throw new ArgumentNullException($"{parameterName}[{i}]"); } } return items; } private static ImmutableArray<T> ToImmutableArrayChecked<T>(IEnumerable<T> items, string parameterName) where T : class { return AddRangeAndFreeChecked(ArrayBuilder<T>.GetInstance(), items, parameterName); } private static ImmutableArray<T> ConcatChecked<T>(ImmutableArray<T> existing, IEnumerable<T> items, string parameterName) where T : class { var builder = ArrayBuilder<T>.GetInstance(); builder.AddRange(existing); return AddRangeAndFreeChecked(builder, items, parameterName); } private static ImmutableArray<T> AddRangeAndFreeChecked<T>(ArrayBuilder<T> builder, IEnumerable<T> items, string parameterName) where T : class { RequireNonNull(items, parameterName); foreach (var item in items) { if (item == null) { builder.Free(); throw new ArgumentNullException($"{parameterName}[{builder.Count}]"); } builder.Add(item); } return builder.ToImmutableAndFree(); } private static IEnumerable<S> SelectChecked<T, S>(IEnumerable<T> items, string parameterName, Func<T, S> selector) where T : class where S : class { RequireNonNull(items, parameterName); return items.Select(item => (item != null) ? selector(item) : null); } private static void RequireNonNull<T>(IEnumerable<T> items, string parameterName) { if (items == null || items is ImmutableArray<T> && ((ImmutableArray<T>)items).IsDefault) { throw new ArgumentNullException(parameterName); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using Xunit; namespace System.Runtime.CompilerServices.Tests { public static partial class RuntimeHelpersTests { [Fact] public static void GetHashCodeTest() { // Int32 RuntimeHelpers.GetHashCode(Object) object obj1 = new object(); int h1 = RuntimeHelpers.GetHashCode(obj1); int h2 = RuntimeHelpers.GetHashCode(obj1); Assert.Equal(h1, h2); object obj2 = new object(); int h3 = RuntimeHelpers.GetHashCode(obj2); Assert.NotEqual(h1, h3); // Could potentially clash but very unlikely int i123 = 123; int h4 = RuntimeHelpers.GetHashCode(i123); Assert.NotEqual(i123.GetHashCode(), h4); int h5 = RuntimeHelpers.GetHashCode(null); Assert.Equal(h5, 0); } public struct TestStruct { public int i1; public int i2; public override bool Equals(object obj) { if (!(obj is TestStruct)) return false; TestStruct that = (TestStruct)obj; return i1 == that.i1 && i2 == that.i2; } public override int GetHashCode() => i1 ^ i2; } [Fact] public static unsafe void GetObjectValue() { // Object RuntimeHelpers.GetObjectValue(Object) TestStruct t = new TestStruct() { i1 = 2, i2 = 4 }; object tOV = RuntimeHelpers.GetObjectValue(t); Assert.Equal(t, (TestStruct)tOV); object o = new object(); object oOV = RuntimeHelpers.GetObjectValue(o); Assert.Equal(o, oOV); int i = 3; object iOV = RuntimeHelpers.GetObjectValue(i); Assert.Equal(i, (int)iOV); } [Fact] public static unsafe void OffsetToStringData() { // RuntimeHelpers.OffsetToStringData char[] expectedValues = new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }; string s = "abcdef"; fixed (char* values = s) // Compiler will use OffsetToStringData with fixed statements { for (int i = 0; i < expectedValues.Length; i++) { Assert.Equal(expectedValues[i], values[i]); } } } [Fact] public static void InitializeArray() { // Void RuntimeHelpers.InitializeArray(Array, RuntimeFieldHandle) char[] expected = new char[] { 'a', 'b', 'c' }; // Compiler will use RuntimeHelpers.InitializeArrary these } [Fact] public static void RunClassConstructor() { RuntimeTypeHandle t = typeof(HasCctor).TypeHandle; RuntimeHelpers.RunClassConstructor(t); Assert.Equal(HasCctorReceiver.S, "Hello"); return; } internal class HasCctor { static HasCctor() { HasCctorReceiver.S = "Hello" + (Guid.NewGuid().ToString().Substring(string.Empty.Length, 0)); // Make sure the preinitialization optimization doesn't eat this. } } internal class HasCctorReceiver { public static string S; } [Fact] public static void PrepareMethod() { foreach (MethodInfo m in typeof(RuntimeHelpersTests).GetMethods()) RuntimeHelpers.PrepareMethod(m.MethodHandle); Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(default(RuntimeMethodHandle))); Assert.ThrowsAny<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(IList).GetMethod("Add").MethodHandle)); } [Fact] public static void PrepareGenericMethod() { Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(default(RuntimeMethodHandle), null)); // // Type instantiations // // Generic definition with instantiation is valid RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle }); // Instantiated method without instantiation is valid RuntimeHelpers.PrepareMethod(typeof(List<int>).GetMethod("Add").MethodHandle, null); // Generic definition without instantiation is invalid Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, null)); // Wrong instantiation Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); // // Method instantiations // // Generic definition with instantiation is valid RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle }); // Instantiated method without instantiation is valid RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize") .MakeGenericMethod(new Type[] { typeof(TestStruct) }).MethodHandle, null); // Generic definition without instantiation is invalid Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, null)); // Wrong instantiation Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); } [Fact] public static void PrepareDelegate() { RuntimeHelpers.PrepareDelegate((Action)(() => { })); RuntimeHelpers.PrepareDelegate((Func<int>)(() => 1) + (Func<int>)(() => 2)); RuntimeHelpers.PrepareDelegate(null); } } public struct Age { public int years; public int months; } public class FixedClass { [FixedAddressValueType] public static Age FixedAge; public static unsafe IntPtr AddressOfFixedAge() { fixed (Age* pointer = &FixedAge) { return (IntPtr)pointer; } } } public static partial class RuntimeHelpersTests { [Fact] public static void FixedAddressValueTypeTest() { // Get addresses of static Age fields. IntPtr fixedPtr1 = FixedClass.AddressOfFixedAge(); // Garbage collection. GC.Collect(3, GCCollectionMode.Forced, true, true); GC.WaitForPendingFinalizers(); // Get addresses of static Age fields after garbage collection. IntPtr fixedPtr2 = FixedClass.AddressOfFixedAge(); Assert.Equal(fixedPtr1, fixedPtr2); } } }
using System; using System.Text; using System.Data.SqlClient; using Sqloogle.Libs.DBDiff.Schema.Events; using Sqloogle.Libs.DBDiff.Schema.Model; using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates.SQLCommands; using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates.Util; using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model; namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates { public class GenerateConstraint { private Generate root; public GenerateConstraint(Generate root) { this.root = root; } private static string AlternateName(string schema, string table) { //var columns = SqlStrings.RemoveBrackets(string.Join("_", this.Columns.Select(c => c.Name))); //var name = string.Format("PK_{0}_{1}_{2}", schema, table, columns); var name = string.Format("PK_{0}_{1}", schema.Replace(" ", "_").Replace("\\", "_"), table.Replace(" ", "_")); var length = Math.Min(name.Length, 128); return name.Substring(0, length); } #region Check Functions... public void FillCheck(Database database, string connectionString) { int parentId = 0; ISchemaBase table = null; using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(ConstraintSQLCommand.GetCheck(database.Info.Version), conn)) { root.RaiseOnReading(new ProgressEventArgs("Reading constraint...", Constants.READING_CONSTRAINTS)); conn.Open(); command.CommandTimeout = 0; using (SqlDataReader reader = command.ExecuteReader()) { Constraint item = null; while (reader.Read()) { root.RaiseOnReadingOne(reader["Name"]); if (parentId != (int)reader["parent_object_id"]) { parentId = (int)reader["parent_object_id"]; if (reader["ObjectType"].ToString().Trim().Equals("U")) table = database.Tables.Find(parentId); else table = database.TablesTypes.Find(parentId); } item = new Constraint(table); item.Id = (int)reader["id"]; item.Name = reader["Name"].ToString(); item.Type = Constraint.ConstraintType.Check; item.Definition = reader["Definition"].ToString(); item.WithNoCheck = (bool)reader["WithCheck"]; item.IsDisabled = (bool)reader["is_disabled"]; item.Owner = reader["Owner"].ToString(); if (database.Options.Ignore.FilterNotForReplication) item.NotForReplication = (bool)reader["is_not_for_replication"]; if (reader["ObjectType"].ToString().Trim().Equals("U")) ((Table)table).Constraints.Add(item); else ((TableType)table).Constraints.Add(item); } } } } } #endregion #region ForeignKey Functions... private static string GetSQLForeignKey() { StringBuilder sql = new StringBuilder(); sql.Append("SELECT FK.object_id, C.user_type_id ,FK.parent_object_id,S.Name AS Owner, S2.Name AS ReferenceOwner, C2.Name AS ColumnName, C2.column_id AS ColumnId, C.name AS ColumnRelationalName, C.column_id AS ColumnRelationalId, T.object_id AS TableRelationalId, FK.Parent_object_id AS TableId, T.Name AS TableRelationalName, FK.Name, FK.is_disabled, FK.is_not_for_replication, FK.is_not_trusted, FK.delete_referential_action, FK.update_referential_action "); sql.Append("FROM sys.foreign_keys FK "); sql.Append("INNER JOIN sys.tables T ON T.object_id = FK.referenced_object_id "); sql.Append("INNER JOIN sys.schemas S2 ON S2.schema_id = T.schema_id "); sql.Append("INNER JOIN sys.foreign_key_columns FKC ON FKC.constraint_object_id = FK.object_id "); sql.Append("INNER JOIN sys.columns C ON C.object_id = FKC.referenced_object_id AND C.column_id = referenced_column_id "); sql.Append("INNER JOIN sys.columns C2 ON C2.object_id = FKC.parent_object_id AND C2.column_id = parent_column_id "); sql.Append("INNER JOIN sys.schemas S ON S.schema_id = FK.schema_id "); sql.Append("ORDER BY FK.parent_object_id, FK.Name, ColumnId"); return sql.ToString(); } private static void FillForeignKey(Database database, string connectionString) { int lastid = 0; int parentId = 0; Table table = null; using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(GetSQLForeignKey(), conn)) { conn.Open(); command.CommandTimeout = 0; using (SqlDataReader reader = command.ExecuteReader()) { Constraint con = null; while (reader.Read()) { if (parentId != (int)reader["parent_object_id"]) { parentId = (int)reader["parent_object_id"]; table = database.Tables.Find(parentId); } if (lastid != (int)reader["object_id"]) { con = new Constraint(table); con.Id = (int)reader["object_id"]; con.Name = reader["Name"].ToString(); con.Type = Constraint.ConstraintType.ForeignKey; con.WithNoCheck = (bool)reader["is_not_trusted"]; con.RelationalTableFullName = "[" + reader["ReferenceOwner"].ToString() + "].[" + reader["TableRelationalName"].ToString() + "]"; con.RelationalTableId = (int)reader["TableRelationalId"]; con.Owner = reader["Owner"].ToString(); con.IsDisabled = (bool)reader["is_disabled"]; con.OnDeleteCascade = (byte)reader["delete_referential_action"]; con.OnUpdateCascade = (byte)reader["update_referential_action"]; if (database.Options.Ignore.FilterNotForReplication) con.NotForReplication = (bool)reader["is_not_for_replication"]; lastid = (int)reader["object_id"]; table.Constraints.Add(con); } ConstraintColumn ccon = new ConstraintColumn(con); ccon.Name = reader["ColumnName"].ToString(); ccon.ColumnRelationalName = reader["ColumnRelationalName"].ToString(); ccon.ColumnRelationalId = (int)reader["ColumnRelationalId"]; ccon.Id = (int)reader["ColumnId"]; ccon.KeyOrder = con.Columns.Count; ccon.ColumnRelationalDataTypeId = (int)reader["user_type_id"]; //table.DependenciesCount++; con.Columns.Add(ccon); } } } } } #endregion #region UniqueKey Functions... private static void FillUniqueKey(Database database, string connectionString) { int lastId = 0; int parentId = 0; bool change = false; ISchemaBase table = null; using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(ConstraintSQLCommand.GetUniqueKey(database.Info.Version), conn)) { conn.Open(); command.CommandTimeout = 0; using (SqlDataReader reader = command.ExecuteReader()) { Constraint con = null; while (reader.Read()) { if (parentId != (int)reader["ID"]) { parentId = (int)reader["ID"]; if (reader["ObjectType"].ToString().Trim().Equals("U")) table = database.Tables.Find(parentId); else table = database.TablesTypes.Find(parentId); change = true; } else change = false; if ((lastId != (int)reader["Index_id"]) || (change)) { con = new Constraint(table); con.Name = reader["Name"].ToString(); con.Owner = (string)reader["Owner"]; con.Id = (int)reader["Index_id"]; con.Type = Constraint.ConstraintType.Unique; con.Index.Id = (int)reader["Index_id"]; con.Index.AllowPageLocks = (bool)reader["allow_page_locks"]; con.Index.AllowRowLocks = (bool)reader["allow_row_locks"]; con.Index.FillFactor = (byte)reader["fill_factor"]; con.Index.IgnoreDupKey = (bool)reader["ignore_dup_key"]; con.Index.IsAutoStatistics = (bool)reader["ignore_dup_key"]; con.Index.IsDisabled = (bool)reader["is_disabled"]; con.Index.IsPadded = (bool)reader["is_padded"]; con.Index.IsPrimaryKey = false; con.Index.IsUniqueKey = true; con.Index.Type = (Index.IndexTypeEnum)(byte)reader["type"]; con.Index.Name = con.Name; if (database.Options.Ignore.FilterTableFileGroup) con.Index.FileGroup = reader["FileGroup"].ToString(); lastId = (int)reader["Index_id"]; if (reader["ObjectType"].ToString().Trim().Equals("U")) ((Table)table).Constraints.Add(con); else ((TableType)table).Constraints.Add(con); } ConstraintColumn ccon = new ConstraintColumn(con); ccon.Name = reader["ColumnName"].ToString(); ccon.IsIncluded = (bool)reader["is_included_column"]; ccon.Order = (bool)reader["is_descending_key"]; ccon.Id = (int)reader["column_id"]; ccon.DataTypeId = (int)reader["user_type_id"]; con.Columns.Add(ccon); } } } } } #endregion #region PrimaryKey Functions... private static void FillPrimaryKey(Database database, string connectionString) { int lastId = 0; int parentId = 0; bool change = false; ISchemaBase table = null; using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(ConstraintSQLCommand.GetPrimaryKey(database.Info.Version, null), conn)) { conn.Open(); command.CommandTimeout = 0; using (SqlDataReader reader = command.ExecuteReader()) { Constraint con = null; while (reader.Read()) { if (parentId != (int)reader["ID"]) { parentId = (int)reader["ID"]; if (reader["ObjectType"].ToString().Trim().Equals("U")) table = database.Tables.Find(parentId); else table = database.TablesTypes.Find(parentId); change = true; } else change = false; if ((lastId != (int)reader["Index_id"]) || (change)) { var name = (string) reader["Name"]; var owner = (string) reader["Owner"]; con = new Constraint(table); con.Id = (int)reader["Index_id"]; con.Name = SqlStrings.HasHexEnding(name) ? AlternateName(owner, con.Parent.Name) : name; con.Owner = owner; con.Type = Constraint.ConstraintType.PrimaryKey; con.Index.Id = (int)reader["Index_id"]; con.Index.AllowPageLocks = (bool)reader["allow_page_locks"]; con.Index.AllowRowLocks = (bool)reader["allow_row_locks"]; con.Index.FillFactor = (byte)reader["fill_factor"]; con.Index.IgnoreDupKey = (bool)reader["ignore_dup_key"]; con.Index.IsAutoStatistics = (bool)reader["ignore_dup_key"]; con.Index.IsDisabled = (bool)reader["is_disabled"]; con.Index.IsPadded = (bool)reader["is_padded"]; con.Index.IsPrimaryKey = true; con.Index.IsUniqueKey = false; con.Index.Type = (Index.IndexTypeEnum)(byte)reader["type"]; con.Index.Name = con.Name; if (database.Options.Ignore.FilterTableFileGroup) con.Index.FileGroup = reader["FileGroup"].ToString(); lastId = (int)reader["Index_id"]; if (reader["ObjectType"].ToString().Trim().Equals("U")) ((Table)table).Constraints.Add(con); else ((TableType)table).Constraints.Add(con); } ConstraintColumn ccon = new ConstraintColumn(con); ccon.Name = (string)reader["ColumnName"]; ccon.IsIncluded = (bool)reader["is_included_column"]; ccon.Order = (bool)reader["is_descending_key"]; ccon.KeyOrder = (byte)reader["key_ordinal"]; ccon.Id = (int)reader["column_id"]; ccon.DataTypeId = (int)reader["user_type_id"]; con.Columns.Add(ccon); } } } } } #endregion public void Fill(Database database, string connectionString) { if (database.Options.Ignore.FilterConstraintPK) FillPrimaryKey(database, connectionString); if (database.Options.Ignore.FilterConstraintFK) FillForeignKey(database, connectionString); if (database.Options.Ignore.FilterConstraintUK) FillUniqueKey(database, connectionString); if (database.Options.Ignore.FilterConstraintCheck) FillCheck(database, connectionString); } } }
//----------------------------------------------------------------------- //<copyright file="GenericsTest.cs" company=""> //TODO: Update copyright text. //</copyright> //----------------------------------------------------------------------- namespace Generics { using System; using System.Collections.Generic; using System.Linq; using System.Text; #region Generic Class Test Code class BaseNodeMultiple<T, U> { T t; U u; public BaseNodeMultiple(T t, U u) { this.t = t; this.u = u; } public void printTypes() { Console.WriteLine(t.GetType()); Console.WriteLine(u.GetType()); } } class Node4<T> : BaseNodeMultiple<T, int> { public Node4(T t, int i) : base(t, i) { } } class Node5<T, U> : BaseNodeMultiple<T, U> { public Node5(T t, U u) : base(t, u) { } } #endregion // type parameter T in angle brackets class GenericList<T> { // The nested class is also generic on T. private class Node { // T used in non-generic constructor. public Node(T t) { next = null; data = t; } private Node next; public Node Next { get { return next; } set { next = value; } } // T as private member data type. private T data; // T as return type of property. public T Data { get { return data; } set { data = value; } } } private Node head; // constructor public GenericList() { head = null; } // T as method parameter type: public void AddHead(T t) { Node n = new Node(t); n.Next = head; head = n; } public IEnumerator<T> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } } // The following method returns the data value stored in the last node in // the list. If the list is empty, the default value for type T is // returned. public T GetLast() { // The value of temp is returned as the value of the method. // The following declaration initializes temp to the appropriate // default value for type T. The default value is returned if the // list is empty. T temp = default(T); Node current = head; while (current != null) { temp = current.Data; current = current.Next; } return temp; } } class NodeItem<T> where T : System.IComparable<T>, new() { } class SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>, new() { } #region Generic Delegate Testing Code class DelegateTestExampleClass : IComparable<DelegateTestExampleClass> { public int CompareTo(DelegateTestExampleClass other) { throw new NotImplementedException(); } } delegate void StackEventHandler<T, U>(T sender, U eventArgs); class DelegateTestStack<T> { public class StackEventArgs : System.EventArgs { } public event StackEventHandler<DelegateTestStack<T>, StackEventArgs> stackEvent; protected virtual void OnStackChanged(StackEventArgs a) { stackEvent(this, a); } } class DelegateTestClass { public void HandleStackChange<T>(DelegateTestStack<T> stack, DelegateTestStack<T>.StackEventArgs args) { } } #endregion public class GenericsTest { /// <summary> /// Test operation on generic delegates /// </summary> private static void DelegateTest() { DelegateTestStack<double> s = new DelegateTestStack<double>(); DelegateTestClass o = new DelegateTestClass(); s.stackEvent += o.HandleStackChange; } /// <summary> /// Swap the contents of the two given generic lists /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list1"></param> /// <param name="list2"></param> private static void Swap<T>(List<T> list1, List<T> list2) { List<T> list3 = new List<T>(list1); list1.Clear(); list1.AddRange(list2); list2.Clear(); list2.AddRange(list3); } /// <summary> /// Swap the two args if lhs > rhs /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> private static void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T> { T temp; if (lhs.CompareTo(rhs) > 0) { temp = lhs; lhs = rhs; rhs = temp; } } /// <summary> /// Test modification of a generic list /// </summary> /// <param name="intList1"></param> private static void AddToList1(List<int> intList1) { intList1.Add(1); intList1.Add(2); intList1.Add(3); } /// <summary> /// Test the default keyword for two differently typed generic lists /// </summary> private static void DefaultTest() { // Test with an empty list of integers. GenericList<int> gll2 = new GenericList<int>(); int intVal = gll2.GetLast(); // The following line displays 0. System.Console.WriteLine(intVal); // Test with an empty list of strings. GenericList<string> gll4 = new GenericList<string>(); string sVal = gll4.GetLast(); // The following line displays a blank line. System.Console.WriteLine(sVal); } /// <summary> /// Test out parameter in generic methods /// </summary> /// <typeparam name="T"></typeparam> /// <param name="a"></param> /// <param name="b"></param> /// <param name="smaller"></param> private static void PickSmaller<T>(T a, T b, out T smaller) where T : struct, System.IComparable<T> { if (a.CompareTo(b) < 0) { smaller = a; } else { smaller = b; } } private static void OutTest() { int a = 3; int b = -3; int c; PickSmaller<int>(a, b, out c); Console.WriteLine("Smaller of {0} and {1} is {2}", a, b, c); } /// <summary> /// Test generic reference parameters /// </summary> private static void SwapTest() { List<int> l1 = new List<int>(new int[] { 1, 2, 3 }); List<int> l2 = new List<int>(new int[] { 4, 5, 6 }); Console.WriteLine("Before Swap: " + l1[0] + " , " + l2[0]); Swap(l1, l2); Console.WriteLine("After Swap: " + l1[0] + " , " + l2[0]); int a = 5; int b = 4; Console.WriteLine("Before Swap: " + a + " , " + b); SwapIfGreater(ref a, ref b); Console.WriteLine("After Swap: " + a + " , " + b); } public static void Main() { // int is the type argument GenericList<int> list = new GenericList<int>(); for (int x = 0; x < 10; x++) { list.AddHead(x); } foreach (int i in list) { System.Console.Write(i + " "); } System.Console.WriteLine("\nDone"); // Declare a list of type string GenericList<string> list2 = new GenericList<string>(); // Declare a list of type ExampleClass GenericList<DelegateTestExampleClass> list3 = new GenericList<DelegateTestExampleClass>(); Node4<string> n4 = new Node4<string>("hello ", 4); Node5<Node4<string>, Node5<int, int>> n5 = new Node5<Node4<string>, Node5<int, int>>( new Node4<string>("hello", 5), new Node5<int, int>(6, 7)); NodeItem<DelegateTestExampleClass> strNode = new NodeItem<DelegateTestExampleClass>(); SwapTest(); List<int> intList1 = new List<int>(); AddToList1(intList1); DelegateTest(); DefaultTest(); OutTest(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Cognifide.PowerShell.Core.Extensions; using Cognifide.PowerShell.Core.Validation; using Cognifide.PowerShell.Core.VersionDecoupling; using Sitecore.ContentSearch; using Sitecore.ContentSearch.Linq; using Sitecore.ContentSearch.SearchTypes; using Sitecore.ContentSearch.Utilities; using Sitecore.Data; using Sitecore.Data.Items; namespace Cognifide.PowerShell.Commandlets.Data.Search { [Cmdlet(VerbsCommon.Find, "Item")] [OutputType(typeof(Item))] public class FindItemCommand : BaseCommand { public static string[] Indexes { get { return ContentSearchManager.Indexes.Select(i => i.Name).ToArray(); } } [AutocompleteSet("Indexes")] [Parameter(Mandatory = true, Position = 0)] public string Index { get; set; } [Parameter] public SearchCriteria[] Criteria { get; set; } [Parameter] public string Where { get; set; } [Parameter] public object[] WhereValues { get; set; } [Parameter] public string OrderBy { get; set; } [Parameter] public int First { get; set; } [Parameter] public int Last { get; set; } [Parameter] public int Skip { get; set; } protected override void EndProcessing() { string index = string.IsNullOrEmpty(Index) ? "sitecore_master_index" : Index; using (var context = ContentSearchManager.GetIndex(index).CreateSearchContext()) { // get all items in medialibrary var query = context.GetQueryable<SearchResultItem>(); if (!String.IsNullOrEmpty(Where)) { if (this.ParameterVersionSupportThreshold("Where", VersionResolver.SitecoreVersion75)) { query = FilterIfSupported(query); } } if (Criteria != null) foreach (var filter in Criteria) { var criteria = filter; if(criteria.Value == null) continue; var comparer = criteria.CaseSensitive.HasValue && criteria.CaseSensitive.Value ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; switch (criteria.Filter) { case (FilterType.DescendantOf): var ancestorId = string.Empty; if (criteria.Value is Item) { ancestorId = ((Item) criteria.Value).ID.ToShortID().ToString(); } if (ID.IsID(criteria.Value.ToString())) { ancestorId = ((ID) criteria.Value).ToShortID().ToString(); } if (string.IsNullOrEmpty(ancestorId)) { WriteError( new ErrorRecord( new Exception( "The root for DescendantOf criteria has to be an Item or an ID"), "sitecore_find_item_invalid_parameter", ErrorCategory.InvalidArgument, criteria.Value)); return; } query = criteria.Invert ? query.Where(i => !i["_path"].Contains(ancestorId)) : query.Where(i => i["_path"].Contains(ancestorId)); break; case (FilterType.StartsWith): query = criteria.Invert ? query.Where(i => !i[criteria.Field].StartsWith(criteria.StringValue, comparer)) : query.Where(i => i[criteria.Field].StartsWith(criteria.StringValue, comparer)); break; case (FilterType.Contains): if (comparer == StringComparison.OrdinalIgnoreCase && criteria.CaseSensitive.HasValue) { WriteWarning( "Case insensitiveness is not supported on Contains criteria due to platform limitations."); } query = criteria.Invert ? query.Where(i => !i[criteria.Field].Contains(criteria.StringValue)) : query.Where(i => i[criteria.Field].Contains(criteria.StringValue)); break; case (FilterType.EndsWith): query = criteria.Invert ? query.Where(i => i[criteria.Field].EndsWith(criteria.StringValue, comparer)) : query.Where(i => i[criteria.Field].EndsWith(criteria.StringValue, comparer)); break; case (FilterType.Equals): query = criteria.Invert ? query.Where(i => !i[criteria.Field].Equals(criteria.StringValue, comparer)) : query.Where(i => i[criteria.Field].Equals(criteria.StringValue, comparer)); break; case (FilterType.Fuzzy): query = criteria.Invert ? query.Where(i => !i[criteria.Field].Like(criteria.StringValue)) : query.Where(i => i[criteria.Field].Like(criteria.StringValue)); break; case (FilterType.InclusiveRange): case (FilterType.ExclusiveRange): if (!(criteria.Value is string[])) break; var inclusion = (criteria.Filter == FilterType.InclusiveRange) ? Inclusion.Both : Inclusion.None; var pair = (object[])criteria.Value; var left = (pair[0] is DateTime) ? ((DateTime)pair[0]).ToString("yyyyMMdd") : pair[0].ToString(); var right = (pair[1] is DateTime) ? ((DateTime)pair[1]).ToString("yyyyMMdd") : pair[1].ToString(); query = criteria.Invert ? query.Where(i => !i[criteria.Field].Between(left, right, inclusion)) : query.Where(i => i[criteria.Field].Between(left, right, inclusion)); break; } } if (!String.IsNullOrEmpty(OrderBy)) { if (this.ParameterVersionSupportThreshold("OrderBy", VersionResolver.SitecoreVersion75)) { query = OrderIfSupported(query); } } WriteObject(FilterByPosition(query), true); } } private IQueryable<SearchResultItem> FilterIfSupported(IQueryable<SearchResultItem> query) { query = query.Where(Where, WhereValues.BaseArray()); return query; } private IQueryable<SearchResultItem> OrderIfSupported(IQueryable<SearchResultItem> query) { query = query.OrderBy(OrderBy); return query; } private List<SearchResultItem> FilterByPosition(IQueryable<SearchResultItem> query) { var count = query.Count(); var skipEnd = (Last != 0 && First == 0); var skipFirst = skipEnd ? 0 : Skip; var takeFirst = First; if (Last == 0 && First == 0) { takeFirst = count - skipFirst; } var firstObjects = query.Skip(skipFirst).Take(takeFirst); var takenAndSkipped = (skipFirst + takeFirst); if (takenAndSkipped >= count || Last == 0 || (skipEnd && Skip >= (count - takenAndSkipped))) { return firstObjects.ToList(); } var takeAndSkipAtEnd = Last + (skipEnd ? Skip : 0); var skipBeforeEnd = count - takenAndSkipped - takeAndSkipAtEnd; var takeLast = Last; if (skipBeforeEnd >= 0) { // Concat not support by Sitecore. return firstObjects.ToList().Concat(query.Skip(takenAndSkipped + skipBeforeEnd).Take(takeLast)).ToList(); } takeLast += skipBeforeEnd; skipBeforeEnd = 0; // Concat not support by Sitecore. return firstObjects.ToList().Concat(query.Skip(takenAndSkipped + skipBeforeEnd).Take(takeLast)).ToList(); } } public enum FilterType { None, Equals, StartsWith, Contains, EndsWith, DescendantOf, Fuzzy, InclusiveRange, ExclusiveRange } public class SearchCriteria { public FilterType Filter { get; set; } public string Field { get; set; } public object Value { get; set; } public bool? CaseSensitive { get; set; } internal string StringValue { get { return Value.ToString(); } } public bool Invert { get; set; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if false using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Microsoft.Contracts; //This file contains three examples about the use of pointer and what it is necessary to add in the pre and post condition of methods namespace Examples { #region Example n.1 unsafe class StringBuilder { public int m_ChunkLength; // The index in m_BlockChars that repsent the end of the block public char[] m_ChunkChars; // The characters in this block public int m_MaxCapacity; // Limits the size of the stringbuilder (ideally we would remove this). private const int DefaultCapacity = 16; unsafe public StringBuilder(String value, int startIndex, int length, int capacity) { if (capacity < 0) { throw new Exception("capacity"); } if (capacity == 0) { capacity = DefaultCapacity; } //Ensure that capacity > 0 if (length < 0) { throw new Exception("length"); } if (startIndex < 0) { throw new Exception("startIndex"); } if (value == null) { value = String.Empty; } //length >= 0 && startIndex >= 0 && value != null if (startIndex > value.Length - length) { throw new Exception("length"); } if (capacity < length) capacity = length; //length <= capacity && length <= startIndex + value.Length m_ChunkChars = new char[capacity]; //m_ChunkChars.Length = capacity m_ChunkLength = length; //m_ChunkLength >= capacity && m_ChunkLength <= startIndex + value.Length && m_ChunkLength >= 0 m_MaxCapacity = int.MaxValue; fixed (char* sourcePtr = value) //sourcePtr.AllocatedUntil = value.Length ThreadSafeCopy(sourcePtr + startIndex, m_ChunkChars, 0, length); //In this invocation the following relations between parameters hold: //- m_ChunkLength <= startIndex + sourcePtr.AllocatedUntil && m_ChunkLength = length -> length <= startIndex + sourcePtr.AllocatedUntil //- m_ChunkChars.Length=capacity && capacity >= length -> m_ChunkChars.Length >= length //(4) It had to ensure that: //- m_ChunkChars.Length-0 >= length (by 3.a) //- sourcePtr.AllocatedUntil + startIndex >= length (by 3.b) //It holds! } unsafe private static void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count) { Contract.Requires(Contract.WritableBytes(sourcePtr) > (ulong)count); Contract.Required(destination.Length > (ulong)(count + destinationIndex)); //(3) Requires that (a) destination.Length-destinationIndex>= count (by (2)) && (b) sourcePtr.AllocatedUntil >= count (by (1.b)) if (count > 0) { if ((uint)destinationIndex <= (uint)destination.Length && (destinationIndex + count) <= destination.Length) { fixed (char* destinationPtr = &destination[destinationIndex]) //destinationPtr.AllocatedUntil = destination.Length-destinationIndex //(2) It should ensures that destination.Length-destinationIndex>= count //(1) It should ensures that (a) destinationPtr.AllocatedUntil >= count && (b) sourcePtr.AllocatedUntil >= count CopyChars(destinationPtr, sourcePtr, count); } else { BCLDebug.Assert(false, "Thread safety check failed"); throw new Exception("Thread safety exception"); } } } unsafe private static void CopyChars(char* dest, char* source, int count) { Contract.Requires(Contract.WritableBytes(dest) > (ulong)count); Contract.Requires(Contract.WritableBytes(source) > (ulong)count); //Requires dest.AllocatedUntil >= count && source.AllocatedUntil >= count for (int i = 0; i < count; i++) { dest[i] = source[i]; } } } #endregion #region Example n.2 public class Buffer { internal static unsafe int IndexOfByte(byte* src, byte value, int index, int count) {//Requires src.AllocatedUntil>=count+index byte* numPtr = src + index;//numPtr.AllocatedUntil = src.AllocatedUntil-index -> src.AllocatedUntil-index>= count by (1/2/3) while ((((int)numPtr) & 3) != 0) { if (count == 0) { return -1; } if (numPtr[0] == value) { return (int)((long)((numPtr - src) / 1)); } count--; numPtr++; }//(3) Require numPtr.AllocatedUntil >= count uint num = (uint)((value << 8) + value); num = (num << 0x10) + num; while (count > 3) { uint num2 = *((uint*)numPtr); num2 ^= num; uint num3 = 0x7efefeff + num2; num2 ^= uint.MaxValue; num2 ^= num3; if ((num2 & 0x81010100) != 0) { int num4 = (int)((long)((numPtr - src) / 1)); if (numPtr[0] == value) { return num4; } if (numPtr[1] == value) { return (num4 + 1); } if (numPtr[2] == value) { return (num4 + 2); } if (numPtr[3] == value) { return (num4 + 3); } } count -= 4; numPtr += 4; }//(2) Require numPtr.AllocatedUntil >= count while (count > 0) { if (numPtr[0] == value) { return (int)((long)((numPtr - src) / 1)); } count--; numPtr++; }//(1) Require numPtr.AllocatedUntil >= count return -1; } } internal class ByteEqualityComparer : EqualityComparer<byte> { internal override unsafe int IndexOf(byte[] array, byte value, int startIndex, int count) { if (array == null) { throw new ArgumentNullException("array"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count")); } if (count > (array.Length - startIndex)) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); } if (count == 0) { return -1; } //All these if statements guarantee that: array != null && count > 0 && count <= array.Length-startIndex (1) fixed (byte* numRef = array) //numRef.AllocatedUntil = array.Length (2) { //Ensures by (1) and (2) that numRef.AllocatedUntil >=count+startIndex return Buffer.IndexOfByte(numRef, value, startIndex, count); } } } #endregion #region Example n.3 public class MemberInfoCache<T> where T : MemberInfo { private unsafe void PopulateEvents(RuntimeType.RuntimeTypeCache.Filter filter, RuntimeTypeHandle declaringTypeHandle, MetadataImport scope, int* tkAssociates, int cAssociates, Hashtable csEventInfos, List<RuntimeEventInfo> list) { //Require tkAssociates.AllocatedUntil >= cAssociates for (int i = 0; i < cAssociates; i++) { int mdToken = tkAssociates[i]; Utf8String name = scope.GetName(mdToken); if (filter.Match(name)) { bool flag; RuntimeEventInfo item = new RuntimeEventInfo(mdToken, declaringTypeHandle.GetRuntimeType(), this.m_runtimeTypeCache, out flag); if ((declaringTypeHandle.Equals(this.m_runtimeTypeCache.RuntimeTypeHandle) || !flag) && (csEventInfos[item.Name] == null)) { csEventInfos[item.Name] = item; list.Add(item); } } } } private unsafe void PopulateEvents(RuntimeType.RuntimeTypeCache.Filter filter, RuntimeTypeHandle declaringTypeHandle, Hashtable csEventInfos, List<RuntimeEventInfo> list) { int token = declaringTypeHandle.GetToken(); if (!MetadataToken.IsNullToken(token)) { MetadataImport metadataImport = declaringTypeHandle.GetModuleHandle().GetMetadataImport(); int count = metadataImport.EnumEventsCount(token); int* result = stackalloc int[count]; //result.AllocatedUntil = count metadataImport.EnumEvents(token, result, count); this.PopulateEvents(filter, declaringTypeHandle, metadataImport, result, count, csEventInfos, list); //Ensures that result.AllocatedUntil >= count! } } } #endregion } #endif
#region Apache Notice /***************************************************************************** * $Revision: 575913 $ * $LastChangedDate: 2007-09-15 14:43:08 +0200 (sam., 15 sept. 2007) $ * $LastChangedBy: gbayon $ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using IBatisNet.Common.Exceptions; using IBatisNet.Common.Logging; using IBatisNet.Common.Utilities; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.MappedStatements; namespace IBatisNet.DataMapper.Configuration.Cache { /// <summary> /// CacheModel. /// </summary> [Serializable] [XmlRoot("cacheModel", Namespace = "http://ibatis.apache.org/mapping")] public class CacheModel { #region Fields private static IDictionary _lockMap = new HybridDictionary(); [NonSerialized] private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This is used to represent null objects that are returned from the cache so /// that they can be cached, too. /// </summary> [NonSerialized] public readonly static object NULL_OBJECT = new Object(); /// <summary> /// Constant to turn off periodic cache flushes /// </summary> [NonSerialized] public const long NO_FLUSH_INTERVAL = -99999; [NonSerialized] private object _statLock = new Object(); [NonSerialized] private int _requests = 0; [NonSerialized] private int _hits = 0; [NonSerialized] private string _id = string.Empty; [NonSerialized] private ICacheController _controller = null; [NonSerialized] private FlushInterval _flushInterval = null; [NonSerialized] private long _lastFlush = 0; [NonSerialized] private HybridDictionary _properties = new HybridDictionary(); [NonSerialized] private string _implementation = string.Empty; [NonSerialized] private bool _isReadOnly = true; [NonSerialized] private bool _isSerializable = false; #endregion #region Properties /// <summary> /// Identifier used to identify the CacheModel amongst the others. /// </summary> [XmlAttribute("id")] public string Id { get { return _id; } set { if ((value == null) || (value.Length < 1)) throw new ArgumentNullException("The id attribute is mandatory in a cacheModel tag."); _id = value; } } /// <summary> /// Cache controller implementation name. /// </summary> [XmlAttribute("implementation")] public string Implementation { get { return _implementation; } set { if ((value == null) || (value.Length < 1)) throw new ArgumentNullException("The implementation attribute is mandatory in a cacheModel tag."); _implementation = value; } } /// <summary> /// Set the cache controller /// </summary> public ICacheController CacheController { set { _controller = value; } } /// <summary> /// Set or get the flushInterval (in Ticks) /// </summary> [XmlElement("flushInterval", typeof(FlushInterval))] public FlushInterval FlushInterval { get { return _flushInterval; } set { _flushInterval = value; } } /// <summary> /// Specifie how the cache content should be returned. /// If true a deep copy is returned. /// </summary> /// <remarks> /// Combinaison /// IsReadOnly=true/IsSerializable=false : Returned instance of cached object /// IsReadOnly=false/IsSerializable=true : Returned coopy of cached object /// </remarks> public bool IsSerializable { get { return _isSerializable; } set { _isSerializable = value; } } /// <summary> /// Determines if the cache will be used as a read-only cache. /// Tells the cache model that is allowed to pass back a reference to the object /// existing in the cache. /// </summary> /// <remarks> /// The IsReadOnly properties works in conjonction with the IsSerializable propertie. /// </remarks> public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; } } #endregion #region Constructor (s) / Destructor /// <summary> /// Constructor /// </summary> public CacheModel() { _lastFlush = DateTime.Now.Ticks; } #endregion #region Methods /// <summary> /// /// </summary> public void Initialize() { // Initialize FlushInterval _flushInterval.Initialize(); try { if (_implementation == null) { throw new DataMapperException("Error instantiating cache controller for cache named '" + _id + "'. Cause: The class for name '" + _implementation + "' could not be found."); } // Build the CacheController Type type = TypeUtils.ResolveType(_implementation); object[] arguments = new object[0]; _controller = (ICacheController)Activator.CreateInstance(type, arguments); } catch (Exception e) { throw new ConfigurationException("Error instantiating cache controller for cache named '" + _id + ". Cause: " + e.Message, e); } //------------ configure Controller--------------------- try { _controller.Configure(_properties); } catch (Exception e) { throw new ConfigurationException("Error configuring controller named '" + _id + "'. Cause: " + e.Message, e); } } /// <summary> /// Event listener /// </summary> /// <param name="mappedStatement">A MappedStatement on which we listen ExecuteEventArgs event.</param> public void RegisterTriggerStatement(IMappedStatement mappedStatement) { mappedStatement.Execute += new ExecuteEventHandler(FlushHandler); } /// <summary> /// FlushHandler which clear the cache /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FlushHandler(object sender, ExecuteEventArgs e) { if (_logger.IsDebugEnabled) { _logger.Debug("Flush cacheModel named " + _id + " for statement '" + e.StatementName + "'"); } Flush(); } /// <summary> /// Clears all elements from the cache. /// </summary> public void Flush() { _lastFlush = DateTime.Now.Ticks; _controller.Flush(); } /// <summary> /// Adds an item with the specified key and value into cached data. /// Gets a cached object with the specified key. /// </summary> /// <value>The cached object or <c>null</c></value> /// <remarks> /// A side effect of this method is that is may clear the cache /// if it has not been cleared in the flushInterval. /// </remarks> public object this[CacheKey key] { get { lock (this) { if (_lastFlush != NO_FLUSH_INTERVAL && (DateTime.Now.Ticks - _lastFlush > _flushInterval.Interval)) { Flush(); } } object value = null; lock (GetLock(key)) { value = _controller[key]; } if (_isSerializable && !_isReadOnly && (value != NULL_OBJECT && value != null)) { try { MemoryStream stream = new MemoryStream((byte[])value); stream.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); value = formatter.Deserialize(stream); } catch (Exception ex) { throw new IBatisNetException("Error caching serializable object. Be sure you're not attempting to use " + "a serialized cache for an object that may be taking advantage of lazy loading. Cause: " + ex.Message, ex); } } lock (_statLock) { _requests++; if (value != null) { _hits++; } } if (_logger.IsDebugEnabled) { if (value != null) { _logger.Debug(String.Format("Retrieved cached object '{0}' using key '{1}' ", value, key)); } else { _logger.Debug(String.Format("Cache miss using key '{0}' ", key)); } } return value; } set { if (null == value) { value = NULL_OBJECT; } if (_isSerializable && !_isReadOnly && value != NULL_OBJECT) { try { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, value); value = stream.ToArray(); } catch (Exception ex) { throw new IBatisNetException("Error caching serializable object. Cause: " + ex.Message, ex); } } _controller[key] = value; if (_logger.IsDebugEnabled) { _logger.Debug(String.Format("Cache object '{0}' using key '{1}' ", value, key)); } } } /// <summary> /// /// </summary> public double HitRatio { get { if (_requests != 0) { return (double)_hits / (double)_requests; } else { return 0; } } } /// <summary> /// Add a property /// </summary> /// <param name="name">The name of the property</param> /// <param name="value">The value of the property</param> public void AddProperty(string name, string value) { _properties.Add(name, value); } #endregion /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.Synchronized)] public object GetLock(CacheKey key) { int controllerId = HashCodeProvider.GetIdentityHashCode(_controller); int keyHash = key.GetHashCode(); int lockKey = 29 * controllerId + keyHash; object lok = _lockMap[lockKey]; if (lok == null) { lok = lockKey; //might as well use the same object _lockMap[lockKey] = lok; } return lok; } } }
using System.IO; using System.Linq; using System.Threading.Tasks; using Content.Server.Construction.Components; using Content.Server.DoAfter; using Content.Server.Hands.Components; using Content.Server.Storage.Components; using Content.Shared.ActionBlocker; using Content.Shared.Construction; using Content.Shared.Construction.Prototypes; using Content.Shared.Construction.Steps; using Content.Shared.Coordinates; using Content.Shared.Interaction; using Content.Shared.Inventory; using Content.Shared.Popups; using Robust.Shared.Containers; using Robust.Shared.Players; using Robust.Shared.Timing; namespace Content.Server.Construction { public sealed partial class ConstructionSystem { [Dependency] private readonly InventorySystem _inventorySystem = default!; [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!; [Dependency] private readonly ActionBlockerSystem _actionBlocker = default!; // --- WARNING! LEGACY CODE AHEAD! --- // This entire file contains the legacy code for initial construction. // This is bound to be replaced by a better alternative (probably using dummy entities) // but for now I've isolated them in their own little file. This code is largely unchanged. // --- YOU HAVE BEEN WARNED! AAAH! --- private readonly Dictionary<ICommonSession, HashSet<int>> _beingBuilt = new(); private void InitializeInitial() { SubscribeNetworkEvent<TryStartStructureConstructionMessage>(HandleStartStructureConstruction); SubscribeNetworkEvent<TryStartItemConstructionMessage>(HandleStartItemConstruction); } // LEGACY CODE. See warning at the top of the file! private IEnumerable<EntityUid> EnumerateNearby(EntityUid user) { if (EntityManager.TryGetComponent(user, out HandsComponent? hands)) { foreach (var itemComponent in hands?.GetAllHeldItems()!) { if (EntityManager.TryGetComponent(itemComponent.Owner, out ServerStorageComponent? storage)) { foreach (var storedEntity in storage.StoredEntities!) { yield return storedEntity; } } yield return itemComponent.Owner; } } if (_inventorySystem.TryGetContainerSlotEnumerator(user, out var containerSlotEnumerator)) { while (containerSlotEnumerator.MoveNext(out var containerSlot)) { if(!containerSlot.ContainedEntity.HasValue) continue; if (EntityManager.TryGetComponent(containerSlot.ContainedEntity.Value, out ServerStorageComponent? storage)) { foreach (var storedEntity in storage.StoredEntities!) { yield return storedEntity; } } yield return containerSlot.ContainedEntity.Value; } } foreach (var near in EntitySystem.Get<EntityLookupSystem>().GetEntitiesInRange(user!, 2f, LookupFlags.Approximate)) { yield return near; } } // LEGACY CODE. See warning at the top of the file! private async Task<EntityUid?> Construct(EntityUid user, string materialContainer, ConstructionGraphPrototype graph, ConstructionGraphEdge edge, ConstructionGraphNode targetNode) { // We need a place to hold our construction items! var container = ContainerHelpers.EnsureContainer<Container>(user, materialContainer, out var existed); if (existed) { user.PopupMessageCursor(Loc.GetString("construction-system-construct-cannot-start-another-construction")); return null; } var containers = new Dictionary<string, Container>(); var doAfterTime = 0f; // HOLY SHIT THIS IS SOME HACKY CODE. // But I'd rather do this shit than risk having collisions with other containers. Container GetContainer(string name) { if (containers!.ContainsKey(name)) return containers[name]; while (true) { var random = _robustRandom.Next(); var c = ContainerHelpers.EnsureContainer<Container>(user!, random.ToString(), out var existed); if (existed) continue; containers[name] = c; return c; } } void FailCleanup() { foreach (var entity in container!.ContainedEntities.ToArray()) { container.Remove(entity); } foreach (var cont in containers!.Values) { foreach (var entity in cont.ContainedEntities.ToArray()) { cont.Remove(entity); } } // If we don't do this, items are invisible for some fucking reason. Nice. Timer.Spawn(1, ShutdownContainers); } void ShutdownContainers() { container!.Shutdown(); foreach (var c in containers!.Values.ToArray()) { c.Shutdown(); } } var failed = false; var steps = new List<ConstructionGraphStep>(); foreach (var step in edge.Steps) { doAfterTime += step.DoAfter; var handled = false; switch (step) { case MaterialConstructionGraphStep materialStep: foreach (var entity in EnumerateNearby(user)) { if (!materialStep.EntityValid(entity, out var stack)) continue; var splitStack = _stackSystem.Split(entity, materialStep.Amount, user.ToCoordinates(0, 0), stack); if (splitStack == null) continue; if (string.IsNullOrEmpty(materialStep.Store)) { if (!container.Insert(splitStack.Value)) continue; } else if (!GetContainer(materialStep.Store).Insert(splitStack.Value)) continue; handled = true; break; } break; case ArbitraryInsertConstructionGraphStep arbitraryStep: foreach (var entity in EnumerateNearby(user)) { if (!arbitraryStep.EntityValid(entity, EntityManager)) continue; if (string.IsNullOrEmpty(arbitraryStep.Store)) { if (!container.Insert(entity)) continue; } else if (!GetContainer(arbitraryStep.Store).Insert(entity)) continue; handled = true; break; } break; } if (handled == false) { failed = true; break; } steps.Add(step); } if (failed) { user.PopupMessageCursor(Loc.GetString("construction-system-construct-no-materials")); FailCleanup(); return null; } var doAfterArgs = new DoAfterEventArgs(user, doAfterTime) { BreakOnDamage = true, BreakOnStun = true, BreakOnTargetMove = false, BreakOnUserMove = true, NeedHand = false, }; if (await _doAfterSystem.WaitDoAfter(doAfterArgs) == DoAfterStatus.Cancelled) { FailCleanup(); return null; } var newEntityProto = graph.Nodes[edge.Target].Entity; var newEntity = EntityManager.SpawnEntity(newEntityProto, EntityManager.GetComponent<TransformComponent>(user).Coordinates); if (!TryComp(newEntity, out ConstructionComponent? construction)) { _sawmill.Error($"Initial construction does not have a valid target entity! It is missing a ConstructionComponent.\nGraph: {graph.ID}, Initial Target: {edge.Target}, Ent. Prototype: {newEntityProto}\nCreated Entity {ToPrettyString(newEntity)} will be deleted."); Del(newEntity); // Screw you, make proper construction graphs. return null; } // We attempt to set the pathfinding target. SetPathfindingTarget(newEntity, targetNode.Name, construction); // We preserve the containers... foreach (var (name, cont) in containers) { var newCont = ContainerHelpers.EnsureContainer<Container>(newEntity, name); foreach (var entity in cont.ContainedEntities.ToArray()) { cont.ForceRemove(entity); newCont.Insert(entity); } } // We now get rid of all them. ShutdownContainers(); // We have step completed steps! foreach (var step in steps) { foreach (var completed in step.Completed) { completed.PerformAction(newEntity, user, EntityManager); } } // And we also have edge completed effects! foreach (var completed in edge.Completed) { completed.PerformAction(newEntity, user, EntityManager); } return newEntity; } // LEGACY CODE. See warning at the top of the file! private async void HandleStartItemConstruction(TryStartItemConstructionMessage ev, EntitySessionEventArgs args) { if (!_prototypeManager.TryIndex(ev.PrototypeName, out ConstructionPrototype? constructionPrototype)) { _sawmill.Error($"Tried to start construction of invalid recipe '{ev.PrototypeName}'!"); return; } if (!_prototypeManager.TryIndex(constructionPrototype.Graph, out ConstructionGraphPrototype? constructionGraph)) { _sawmill.Error( $"Invalid construction graph '{constructionPrototype.Graph}' in recipe '{ev.PrototypeName}'!"); return; } var startNode = constructionGraph.Nodes[constructionPrototype.StartNode]; var targetNode = constructionGraph.Nodes[constructionPrototype.TargetNode]; var pathFind = constructionGraph.Path(startNode.Name, targetNode.Name); if (args.SenderSession.AttachedEntity is not {Valid: true} user || !Get<ActionBlockerSystem>().CanInteract(user, null)) return; if (!EntityManager.TryGetComponent(user, out HandsComponent? hands)) return; foreach (var condition in constructionPrototype.Conditions) { if (!condition.Condition(user, user.ToCoordinates(0, 0), Direction.South)) return; } if (pathFind == null) throw new InvalidDataException( $"Can't find path from starting node to target node in construction! Recipe: {ev.PrototypeName}"); var edge = startNode.GetEdge(pathFind[0].Name); if (edge == null) throw new InvalidDataException( $"Can't find edge from starting node to the next node in pathfinding! Recipe: {ev.PrototypeName}"); // No support for conditions here! foreach (var step in edge.Steps) { switch (step) { case ToolConstructionGraphStep _: throw new InvalidDataException("Invalid first step for construction recipe!"); } } if (await Construct(user, "item_construction", constructionGraph, edge, targetNode) is {Valid: true} item) hands.PutInHandOrDrop(item); } // LEGACY CODE. See warning at the top of the file! private async void HandleStartStructureConstruction(TryStartStructureConstructionMessage ev, EntitySessionEventArgs args) { if (!_prototypeManager.TryIndex(ev.PrototypeName, out ConstructionPrototype? constructionPrototype)) { _sawmill.Error($"Tried to start construction of invalid recipe '{ev.PrototypeName}'!"); RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack)); return; } if (!_prototypeManager.TryIndex(constructionPrototype.Graph, out ConstructionGraphPrototype? constructionGraph)) { _sawmill.Error($"Invalid construction graph '{constructionPrototype.Graph}' in recipe '{ev.PrototypeName}'!"); RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack)); return; } if (args.SenderSession.AttachedEntity is not {Valid: true} user) { _sawmill.Error($"Client sent {nameof(TryStartStructureConstructionMessage)} with no attached entity!"); return; } if (user.IsInContainer()) { user.PopupMessageCursor(Loc.GetString("construction-system-inside-container")); return; } var startNode = constructionGraph.Nodes[constructionPrototype.StartNode]; var targetNode = constructionGraph.Nodes[constructionPrototype.TargetNode]; var pathFind = constructionGraph.Path(startNode.Name, targetNode.Name); if (_beingBuilt.TryGetValue(args.SenderSession, out var set)) { if (!set.Add(ev.Ack)) { user.PopupMessageCursor(Loc.GetString("construction-system-already-building")); return; } } else { var newSet = new HashSet<int> {ev.Ack}; _beingBuilt[args.SenderSession] = newSet; } foreach (var condition in constructionPrototype.Conditions) { if (!condition.Condition(user, ev.Location, ev.Angle.GetCardinalDir())) { Cleanup(); return; } } void Cleanup() { _beingBuilt[args.SenderSession].Remove(ev.Ack); } if (!_actionBlocker.CanInteract(user, null) || !EntityManager.TryGetComponent(user, out HandsComponent? hands) || hands.GetActiveHandItem == null) { Cleanup(); return; } var mapPos = ev.Location.ToMap(EntityManager); var predicate = GetPredicate(constructionPrototype.CanBuildInImpassable, mapPos); if (!_interactionSystem.InRangeUnobstructed(user, mapPos, predicate: predicate)) { Cleanup(); return; } if (pathFind == null) throw new InvalidDataException($"Can't find path from starting node to target node in construction! Recipe: {ev.PrototypeName}"); var edge = startNode.GetEdge(pathFind[0].Name); if(edge == null) throw new InvalidDataException($"Can't find edge from starting node to the next node in pathfinding! Recipe: {ev.PrototypeName}"); var valid = false; if (hands.GetActiveHandItem?.Owner is not {Valid: true} holding) { Cleanup(); return; } // No support for conditions here! foreach (var step in edge.Steps) { switch (step) { case EntityInsertConstructionGraphStep entityInsert: if (entityInsert.EntityValid(holding, EntityManager)) valid = true; break; case ToolConstructionGraphStep _: throw new InvalidDataException("Invalid first step for item recipe!"); } if (valid) break; } if (!valid) { Cleanup(); return; } if (await Construct(user, (ev.Ack + constructionPrototype.GetHashCode()).ToString(), constructionGraph, edge, targetNode) is not {Valid: true} structure) { Cleanup(); return; } // We do this to be able to move the construction to its proper position in case it's anchored... // Oh wow transform anchoring is amazing wow I love it!!!! var wasAnchored = EntityManager.GetComponent<TransformComponent>(structure).Anchored; EntityManager.GetComponent<TransformComponent>(structure).Anchored = false; EntityManager.GetComponent<TransformComponent>(structure).Coordinates = ev.Location; EntityManager.GetComponent<TransformComponent>(structure).LocalRotation = constructionPrototype.CanRotate ? ev.Angle : Angle.Zero; EntityManager.GetComponent<TransformComponent>(structure).Anchored = wasAnchored; RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack)); Cleanup(); } } }