context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { /// <summary> /// Visual Studio 2013 Light theme. /// </summary> public class VS2013BlueTheme : ThemeBase { /// <summary> /// Applies the specified theme to the dock panel. /// </summary> /// <param name="dockPanel">The dock panel.</param> public override void Apply(DockPanel dockPanel) { if (dockPanel == null) { throw new NullReferenceException("dockPanel"); } Measures.SplitterSize = 6; dockPanel.Extender.DockPaneCaptionFactory = new VS2013LightDockPaneCaptionFactory(); dockPanel.Extender.AutoHideStripFactory = new VS2013LightAutoHideStripFactory(); dockPanel.Extender.AutoHideWindowFactory = new VS2013LightAutoHideWindowFactory(); dockPanel.Extender.DockPaneStripFactory = new VS2013LightDockPaneStripFactory(); dockPanel.Extender.DockPaneSplitterControlFactory = new VS2013LightDockPaneSplitterControlFactory(); dockPanel.Extender.DockWindowSplitterControlFactory = new VS2013LightDockWindowSplitterControlFactory(); dockPanel.Extender.DockWindowFactory = new VS2013LightDockWindowFactory(); dockPanel.Extender.PaneIndicatorFactory = new VS2013LightPaneIndicatorFactory(); dockPanel.Extender.PanelIndicatorFactory = new VS2013LightPanelIndicatorFactory(); dockPanel.Extender.DockOutlineFactory = new VS2013LightDockOutlineFactory(); dockPanel.Skin = CreateVisualStudio2013Light(); } public override void Apply(DockContent dockContent) { if (dockContent == null) return; dockContent.BackColor = Color.FromArgb(0xFF, 214, 219, 233); } private class VS2013LightDockOutlineFactory : DockPanelExtender.IDockOutlineFactory { public DockOutlineBase CreateDockOutline() { return new VS2013LightDockOutline(); } private class VS2013LightDockOutline : DockOutlineBase { public VS2013LightDockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = Color.FromArgb(0xff, 91, 173, 255); DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) { if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = new Region(Rectangle.Empty); } else if (DragForm.Region != null) { DragForm.Region.Dispose(); DragForm.Region = null; } } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = region; } } } private class VS2013LightPanelIndicatorFactory : DockPanelExtender.IPanelIndicatorFactory { public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style) { return new VS2013LightPanelIndicator(style); } private class VS2013LightPanelIndicator : PictureBox, DockPanel.IPanelIndicator { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft_VS2012; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight_VS2012; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop_VS2012; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom_VS2012; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill_VS2012; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_VS2012; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_VS2012; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_VS2012; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_VS2012; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_VS2012; public VS2013LightPanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } } private class VS2013LightPaneIndicatorFactory : DockPanelExtender.IPaneIndicatorFactory { public DockPanel.IPaneIndicator CreatePaneIndicator() { return new VS2013LightPaneIndicator(); } private class VS2013LightPaneIndicator : PictureBox, DockPanel.IPaneIndicator { private static Bitmap _bitmapPaneDiamond = Resources.Dockindicator_PaneDiamond_VS2012; private static Bitmap _bitmapPaneDiamondLeft = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondRight = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondTop = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondBottom = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.Dockindicator_PaneDiamond_Hotspot_VS2012; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex_VS2012; private static DockPanel.HotSpotIndex[] _hotSpots = new[] { new DockPanel.HotSpotIndex(1, 0, DockStyle.Top), new DockPanel.HotSpotIndex(0, 1, DockStyle.Left), new DockPanel.HotSpotIndex(1, 1, DockStyle.Fill), new DockPanel.HotSpotIndex(2, 1, DockStyle.Right), new DockPanel.HotSpotIndex(1, 2, DockStyle.Bottom) }; private GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public VS2013LightPaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } } private class VS2013LightAutoHideWindowFactory : DockPanelExtender.IAutoHideWindowFactory { public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel) { return new VS2012LightAutoHideWindowControl(panel); } } private class VS2013LightDockPaneSplitterControlFactory : DockPanelExtender.IDockPaneSplitterControlFactory { public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane) { return new VS2012LightSplitterControl(pane); } } private class VS2013LightDockWindowSplitterControlFactory : DockPanelExtender.IDockWindowSplitterControlFactory { public SplitterBase CreateSplitterControl() { return new VS2012LightDockWindow.VS2012LightDockWindowSplitterControl(); } } private class VS2013LightDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory { public DockPaneStripBase CreateDockPaneStrip(DockPane pane) { return new VS2013BlueDockPaneStrip(pane); } } private class VS2013LightAutoHideStripFactory : DockPanelExtender.IAutoHideStripFactory { public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) { return new VS2012LightAutoHideStrip(panel); } } private class VS2013LightDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory { public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) { return new VS2012LightDockPaneCaption(pane); } } private class VS2013LightDockWindowFactory : DockPanelExtender.IDockWindowFactory { public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState) { return new VS2012LightDockWindow(dockPanel, dockState); } } public static DockPanelSkin CreateVisualStudio2013Light() { var specialBlue = Color.FromArgb(0xFF, 54, 78, 111); var border = Color.FromArgb(0xFF, 41, 57, 85); var selection = Color.FromArgb(0xFF, 255, 242, 157); var header = Color.FromArgb(0xFF, 77, 96, 130); var hover = Color.FromArgb(0xFF, 155, 167, 183); var dot = Color.FromArgb(80, 170, 220); //var activeTab = specialBlue; var activeTab = selection; var mouseHoverTab = Color.FromArgb(0xFF, 91, 113, 153); var inactiveTab = specialBlue; //var lostFocusTab = Color.FromArgb(0xFF, 204, 206, 219); var lostFocusTab = specialBlue; var skin = new DockPanelSkin(); skin.AutoHideStripSkin.DockStripGradient.StartColor = hover; skin.AutoHideStripSkin.DockStripGradient.EndColor = specialBlue; skin.AutoHideStripSkin.TabGradient.TextColor = Color.White; skin.AutoHideStripSkin.DockStripBackground.StartColor = border; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = border; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = border; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = activeTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = lostFocusTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = inactiveTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.HoverTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.StartColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = border; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = border; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = selection; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = selection; //skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = header; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = header; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = Color.White; return skin; } } }
#region License /* * Copyright 2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Reflection; using System.Xml; using NUnit.Framework; using Spring.Aop.Config; using Spring.Core.IO; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Support; using Spring.Validation; #endregion namespace Spring.Objects.Factory.Xml { /// <summary> /// Unit tests for the XmlObjectDefinitionReader class. /// </summary> /// <author>Rick Evans (.NET)</author> [TestFixture] public class XmlObjectDefinitionReaderTests { [Test] public void Instantiation() { XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader( new DefaultListableObjectFactory()); } [Test] [ExpectedException(typeof(ObjectDefinitionStoreException))] public void LoadObjectDefinitionsWithNullResource() { XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader( new DefaultListableObjectFactory()); reader.LoadObjectDefinitions((string)null); } [Test] [ExpectedException(typeof(ObjectDefinitionStoreException))] public void LoadObjectDefinitionsWithNonExistentResource() { XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader( new DefaultListableObjectFactory()); reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("/dev/null")); } #if NET_2_0 [Test] public void AutoRegistersAllWellknownNamespaceParsers_Common() { string[] namespaces = { "http://www.springframework.net/tx", "http://www.springframework.net/aop", "http://www.springframework.net/db", "http://www.springframework.net/database", "http://www.springframework.net/remoting", "http://www.springframework.net/nms", "http://www.springframework.net/validation", "http://www.springframework.net/nvelocity" }; foreach (string ns in namespaces) { Assert.IsNotNull(NamespaceParserRegistry.GetParser(ns), string.Format("Parser for Namespace {0} could not be auto-registered.", ns)); } } #endif #if NET_3_0 [Test] public void AutoRegistersAllWellknownNamespaceParsers_3_0() { string[] namespaces = { "http://www.springframework.net/wcf" }; foreach (string ns in namespaces) { Assert.IsNotNull(NamespaceParserRegistry.GetParser(ns), string.Format("Parser for Namespace {0} could not be auto-registered.", ns)); } } #endif [Test] [Ignore] //this test cannot co-exist with AutoRegistersAllWellknownNamespaceParsers b/c that test will have already loaded the Spring.Data ass'y public void AutoRegistersWellknownNamespaceParser() { try { Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in loadedAssemblies) { if (assembly.GetName(true).Name.StartsWith("Spring.Data")) { Assert.Fail("Spring.Data is already loaded - this test checks if it gets loaded during xml parsing"); } } NamespaceParserRegistry.Reset(); DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net' xmlns:tx='http://www.springframework.net/tx'> <tx:attribute-driven /> </objects> ")); object apc = of.GetObject(AopNamespaceUtils.AUTO_PROXY_CREATOR_OBJECT_NAME); Assert.NotNull(apc); } finally { NamespaceParserRegistry.Reset(); } } [Test] [ExpectedException(typeof(ObjectDefinitionStoreException))] public void ThrowsOnUnknownNamespaceUri() { NamespaceParserRegistry.Reset(); DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net' xmlns:x='http://www.springframework.net/XXXX'> <x:group id='tripValidator' /> </objects> ")); Assert.Fail(); } [Test] public void WhitespaceValuesArePreservedForValueAttribute() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net'> <object id='test' type='Spring.Objects.TestObject, Spring.Core.Tests'> <property name='name' value=' &#x000a;&#x000d;&#x0009;' /> </object> </objects> ")); Assert.AreEqual(" \n\r\t", ((TestObject)of.GetObject("test")).Name); } [Test] public void WhitespaceValuesResultInEmptyStringForValueElement() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net'> <object id='test2' type='Spring.Objects.TestObject, Spring.Core.Tests'> <property name='name'><value /></property> </object> <object id='test3' type='Spring.Objects.TestObject, Spring.Core.Tests'> <property name='name'><value></value></property> </object> <object id='test4' type='Spring.Objects.TestObject, Spring.Core.Tests'> <property name='name'><value xml:space='default'> &#x000a;&#x000d;&#x0009;</value></property> </object> </objects> ")); Assert.AreEqual(string.Empty, ((TestObject)of.GetObject("test2")).Name); Assert.AreEqual(string.Empty, ((TestObject)of.GetObject("test3")).Name); Assert.AreEqual(string.Empty, ((TestObject)of.GetObject("test4")).Name); } [Test] public void WhitespaceValuesArePreservedForValueElementWhenSpaceIsSetToPreserve() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net'> <object id='test4' type='Spring.Objects.TestObject, Spring.Core.Tests'> <property name='name'><value xml:space='preserve'> &#x000a;&#x000d;&#x0009;</value></property> </object> </objects> ")); Assert.AreEqual(" \n\r\t", ((TestObject)of.GetObject("test4")).Name); } [Test] public void ThrowsObjectDefinitionStoreExceptionOnValidationError() { try { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net'> <INVALIDELEMENT id='test2' type='Spring.Objects.TestObject, Spring.Core.Tests' /> </objects> ")); Assert.Fail(); } catch (ObjectDefinitionStoreException ex) { Assert.IsTrue(ex.Message.IndexOf("Line 3 in XML document from violates the schema.") > -1); } } [Test] public void ThrowsObjectDefinitionStoreExceptionOnInvalidXml() { try { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net'> <object id='test2' type='Spring.Objects.TestObject, Spring.Core.Tests'> </objects> ")); Assert.Fail(); } catch (ObjectDefinitionStoreException ex) { Assert.IsTrue(ex.Message.IndexOf("Line 4 in XML document from is not well formed.") > -1); } } #region ThrowsObjectDefinitionStoreExceptionOnErrorDuringObjectDefinitionRegistration Helper private class TestXmlObjectDefinitionReader : XmlObjectDefinitionReader { public TestXmlObjectDefinitionReader(IObjectDefinitionRegistry registry) : base(registry) { } private class ThrowingObjectDefinitionDocumentReader : IObjectDefinitionDocumentReader { public void RegisterObjectDefinitions(XmlDocument doc, XmlReaderContext readerContext) { throw new TestException("RegisterObjectDefinitions"); } } protected override IObjectDefinitionDocumentReader CreateObjectDefinitionDocumentReader() { return new ThrowingObjectDefinitionDocumentReader(); } } #endregion [Test] [ExpectedException(typeof(ObjectDefinitionStoreException))] public void ThrowsObjectDefinitionStoreExceptionOnErrorDuringObjectDefinitionRegistration() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new TestXmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net'> <object id='test2' type='Spring.Objects.TestObject, Spring.Core.Tests' /> </objects> ")); } [Test] public void ParsesNonDefaultNamespace() { try { NamespaceParserRegistry.Reset(); DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <core:objects xmlns:core='http://www.springframework.net'> <core:object id='test2' type='Spring.Objects.TestObject, Spring.Core.Tests'> <core:property name='Sibling'> <core:object type='Spring.Objects.TestObject, Spring.Core.Tests' /> </core:property> </core:object> </core:objects> ")); TestObject test2 = (TestObject)of.GetObject("test2"); Assert.AreEqual(typeof(TestObject), test2.GetType()); Assert.IsNotNull(test2.Sibling); } finally { NamespaceParserRegistry.Reset(); } } [Test] public void ParsesObjectAttributes() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net'> <object id='test1' type='Spring.Objects.TestObject, Spring.Core.Tests' singleton='false' abstract='true' /> <object id='test2' type='Spring.Objects.TestObject, Spring.Core.Tests' singleton='true' abstract='false' lazy-init='true' autowire='no' dependency-check='simple' depends-on='test1' init-method='init' destroy-method='destroy' /> </objects> ")); AbstractObjectDefinition od1 = (AbstractObjectDefinition)of.GetObjectDefinition("test1"); Assert.IsFalse(od1.IsSingleton); Assert.IsTrue(od1.IsAbstract); Assert.IsFalse(od1.IsLazyInit); AbstractObjectDefinition od2 = (AbstractObjectDefinition)of.GetObjectDefinition("test2"); Assert.IsTrue(od2.IsSingleton); Assert.IsFalse(od2.IsAbstract); Assert.IsTrue(od2.IsLazyInit); Assert.AreEqual(AutoWiringMode.No, od2.AutowireMode); Assert.AreEqual("init", od2.InitMethodName); Assert.AreEqual("destroy", od2.DestroyMethodName); Assert.AreEqual(1, od2.DependsOn.Length); Assert.AreEqual("test1", od2.DependsOn[0]); Assert.AreEqual(DependencyCheckingMode.Simple, od2.DependencyCheck); } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.Collections; using System.IO; using NUnit.Framework; using NPOI.POIFS.FileSystem; using NPOI.Util; using NPOI.POIFS.Storage; using NPOI.POIFS.Properties; using NPOI.POIFS.NIO; namespace TestCases.POIFS.FileSystem { /** * Class to Test POIFSDocumentReader functionality * * @author Marc Johnson */ [TestFixture] public class TestDocumentInputStream { //private DocumentNode _workbook; private DocumentNode _workbook_n; private DocumentNode _workbook_o; private byte[] _workbook_data; private static int _workbook_size = 5000; private static int _buffer_size = 6; public TestDocumentInputStream() { int blocks = (_workbook_size + 511) / 512; _workbook_data = new byte[512 * blocks]; Arrays.Fill(_workbook_data, unchecked((byte)-1)); for (int j = 0; j < _workbook_size; j++) { _workbook_data[j] = (byte)(j * j); } // Create the Old POIFS Version RawDataBlock[] rawBlocks = new RawDataBlock[blocks]; MemoryStream stream = new MemoryStream(_workbook_data); for (int j = 0; j < blocks; j++) { rawBlocks[j] = new RawDataBlock(stream); } OPOIFSDocument document = new OPOIFSDocument("Workbook", rawBlocks, _workbook_size); _workbook_o = new DocumentNode( document.DocumentProperty, new DirectoryNode( new DirectoryProperty("Root Entry"), (POIFSFileSystem)null, null)); // Now create the NPOIFS Version byte[] _workbook_data_only = new byte[_workbook_size]; Array.Copy(_workbook_data, 0, _workbook_data_only, 0, _workbook_size); NPOIFSFileSystem npoifs = new NPOIFSFileSystem(); // Make it easy when debugging to see what isn't the doc byte[] minus1 = new byte[512]; Arrays.Fill(minus1, unchecked((byte)-1)); npoifs.GetBlockAt(-1).Write(minus1); npoifs.GetBlockAt(0).Write(minus1); npoifs.GetBlockAt(1).Write(minus1); // Create the NPOIFS document _workbook_n = (DocumentNode)npoifs.CreateDocument( new MemoryStream(_workbook_data_only), "Workbook" ); } /** * Test constructor * * @exception IOException */ [Test] public void TestConstructor() { DocumentInputStream ostream = new ODocumentInputStream(_workbook_o); DocumentInputStream nstream = new NDocumentInputStream(_workbook_n); Assert.AreEqual(_workbook_size, _workbook_o.Size); Assert.AreEqual(_workbook_size, _workbook_n.Size); Assert.AreEqual(_workbook_size, ostream.Available()); Assert.AreEqual(_workbook_size, nstream.Available()); ostream.Close(); nstream.Close(); } /** * Test Available behavior * * @exception IOException */ [Test] public void TestAvailable() { DocumentInputStream ostream = new DocumentInputStream(_workbook_o); DocumentInputStream nstream = new NDocumentInputStream(_workbook_n); Assert.AreEqual(_workbook_size, ostream.Available()); Assert.AreEqual(_workbook_size, nstream.Available()); ostream.Close(); nstream.Close(); try { ostream.Available(); Assert.Fail("Should have caught IOException"); } catch (InvalidOperationException) { // as expected } try { nstream.Available(); Assert.Fail("Should have caught IOException"); } catch (InvalidOperationException) { // as expected } } /** * Test mark/reset/markSupported. * * @exception IOException */ [Test] public void TestMarkFunctions() { byte[] buffer = new byte[_workbook_size / 5]; byte[] small_buffer = new byte[212]; DocumentInputStream[] streams = new DocumentInputStream[] { new DocumentInputStream(_workbook_o), new NDocumentInputStream(_workbook_n) }; foreach (DocumentInputStream stream in streams) { // Read a fifth of it, and check all's correct stream.Read(buffer); for (int j = 0; j < buffer.Length; j++) { Assert.AreEqual(_workbook_data[j], buffer[j], "Checking byte " + j); } Assert.AreEqual(_workbook_size - buffer.Length, stream.Available()); // Reset, and check the available goes back to being the // whole of the stream stream.Reset(); Assert.AreEqual(_workbook_size, stream.Available()); // Read part of a block stream.Read(small_buffer); for (int j = 0; j < small_buffer.Length; j++) { Assert.AreEqual(_workbook_data[j], small_buffer[j], "Checking byte " + j); } Assert.AreEqual(_workbook_size - small_buffer.Length, stream.Available()); stream.Mark(0); // Read the next part stream.Read(small_buffer); for (int j = 0; j < small_buffer.Length; j++) { Assert.AreEqual(_workbook_data[j + small_buffer.Length], small_buffer[j], "Checking byte " + j); } Assert.AreEqual(_workbook_size - 2 * small_buffer.Length, stream.Available()); // Reset, check it goes back to where it was stream.Reset(); Assert.AreEqual(_workbook_size - small_buffer.Length, stream.Available()); // Read stream.Read(small_buffer); for (int j = 0; j < small_buffer.Length; j++) { Assert.AreEqual(_workbook_data[j + small_buffer.Length], small_buffer[j], "Checking byte " + j); } Assert.AreEqual(_workbook_size - 2 * small_buffer.Length, stream.Available()); // Now read at various points Arrays.Fill(small_buffer, (byte)0); stream.Read(small_buffer, 6, 8); stream.Read(small_buffer, 100, 10); stream.Read(small_buffer, 150, 12); int pos = small_buffer.Length * 2; for (int j = 0; j < small_buffer.Length; j++) { byte exp = 0; if (j >= 6 && j < 6 + 8) { exp = _workbook_data[pos]; pos++; } if (j >= 100 && j < 100 + 10) { exp = _workbook_data[pos]; pos++; } if (j >= 150 && j < 150 + 12) { exp = _workbook_data[pos]; pos++; } Assert.AreEqual(exp, small_buffer[j], "Checking byte " + j); } } // Now repeat it with spanning multiple blocks streams = new DocumentInputStream[] { new DocumentInputStream(_workbook_o), new NDocumentInputStream(_workbook_n) }; foreach (DocumentInputStream stream in streams) { // Read several blocks work buffer = new byte[_workbook_size / 5]; stream.Read(buffer); for (int j = 0; j < buffer.Length; j++) { Assert.AreEqual(_workbook_data[j], buffer[j], "Checking byte " + j); } Assert.AreEqual(_workbook_size - buffer.Length, stream.Available()); // Read all of it again, check it began at the start again stream.Reset(); Assert.AreEqual(_workbook_size, stream.Available()); stream.Read(buffer); for (int j = 0; j < buffer.Length; j++) { Assert.AreEqual(_workbook_data[j], buffer[j], "Checking byte " + j); } // Mark our position, and read another whole buffer stream.Mark(12); stream.Read(buffer); Assert.AreEqual(_workbook_size - (2 * buffer.Length), stream.Available()); for (int j = buffer.Length; j < (2 * buffer.Length); j++) { Assert.AreEqual(_workbook_data[j], buffer[j - buffer.Length], "Checking byte " + j); } // Reset, should go back to only one buffer full read stream.Reset(); Assert.AreEqual(_workbook_size - buffer.Length, stream.Available()); // Read the buffer again stream.Read(buffer); Assert.AreEqual(_workbook_size - (2 * buffer.Length), stream.Available()); for (int j = buffer.Length; j < (2 * buffer.Length); j++) { Assert.AreEqual(_workbook_data[j], buffer[j - buffer.Length], "Checking byte " + j); } Assert.IsTrue(stream.MarkSupported()); } } /** * Test simple Read method * * @exception IOException */ [Test] public void TestReadSingleByte() { DocumentInputStream[] streams = new DocumentInputStream[] { new DocumentInputStream(_workbook_o), new NDocumentInputStream(_workbook_n) }; foreach (DocumentInputStream stream in streams) { int remaining = _workbook_size; // Try and read each byte in turn for (int j = 0; j < _workbook_size; j++) { int b = stream.Read(); Assert.IsTrue(b >= 0, "Checking sign of " + j); Assert.AreEqual(_workbook_data[j], (byte)b, "validating byte " + j); remaining--; Assert.AreEqual( remaining, stream.Available(), "Checking remaining After Reading byte " + j); } // Ensure we fell off the end Assert.AreEqual(-1, stream.Read()); // Check that After close we can no longer read stream.Close(); try { stream.Read(); Assert.Fail("Should have caught IOException"); } catch (IOException) { // as expected } } } /** * Test buffered Read * * @exception IOException */ [Test] public void TestBufferRead() { DocumentInputStream[] streams = new DocumentInputStream[] { new DocumentInputStream(_workbook_o), new NDocumentInputStream(_workbook_n) }; foreach (DocumentInputStream stream in streams) { // Need to give a byte array to read try { stream.Read(null); Assert.Fail("Should have caught NullPointerException"); } catch (NullReferenceException) { // as expected } // test Reading zero length buffer Assert.AreEqual(0, stream.Read(new byte[0])); Assert.AreEqual(_workbook_size, stream.Available()); byte[] buffer = new byte[_buffer_size]; int offset = 0; while (stream.Available() >= buffer.Length) { Assert.AreEqual(_buffer_size, stream.Read(buffer)); for (int j = 0; j < buffer.Length; j++) { Assert.AreEqual( _workbook_data[offset], buffer[j], "in main loop, byte " + offset); offset++; } Assert.AreEqual(_workbook_size - offset, stream.Available(), "offset " + offset); } Assert.AreEqual(_workbook_size % _buffer_size, stream.Available()); Arrays.Fill(buffer, (byte)0); int count = stream.Read(buffer); Assert.AreEqual(_workbook_size % _buffer_size, count); for (int j = 0; j < count; j++) { Assert.AreEqual( _workbook_data[offset], buffer[j], "past main loop, byte " + offset); offset++; } Assert.AreEqual(_workbook_size, offset); for (int j = count; j < buffer.Length; j++) { Assert.AreEqual(0, buffer[j], "Checking remainder, byte " + j); } Assert.AreEqual(-1, stream.Read(buffer)); stream.Close(); try { stream.Read(buffer); Assert.Fail("Should have caught IOException"); } catch (IOException) { // as expected } } } /** * Test complex buffered Read * * @exception IOException */ [Test] public void TestComplexBufferRead() { DocumentInputStream[] streams = new DocumentInputStream[] { new DocumentInputStream(_workbook_o), new NDocumentInputStream(_workbook_n) }; foreach (DocumentInputStream stream in streams) { try { stream.Read(null, 0, 1); Assert.Fail("Should have caught NullPointerException"); } catch (ArgumentException) { // as expected } // test illegal offsets and lengths try { stream.Read(new byte[5], -4, 0); Assert.Fail("Should have caught IndexOutOfBoundsException"); } catch (IndexOutOfRangeException) { // as expected } try { stream.Read(new byte[5], 0, -4); Assert.Fail("Should have caught IndexOutOfBoundsException"); } catch (IndexOutOfRangeException) { // as expected } try { stream.Read(new byte[5], 0, 6); Assert.Fail("Should have caught IndexOutOfBoundsException"); } catch (IndexOutOfRangeException) { // as expected } // test Reading zero Assert.AreEqual(0, stream.Read(new byte[5], 0, 0)); Assert.AreEqual(_workbook_size, stream.Available()); byte[] buffer = new byte[_workbook_size]; int offset = 0; while (stream.Available() >= _buffer_size) { Arrays.Fill(buffer, (byte)0); Assert.AreEqual(_buffer_size, stream.Read(buffer, offset, _buffer_size)); for (int j = 0; j < offset; j++) { Assert.AreEqual(0, buffer[j], "Checking byte " + j); } for (int j = offset; j < (offset + _buffer_size); j++) { Assert.AreEqual(_workbook_data[j], buffer[j], "Checking byte " + j); } for (int j = offset + _buffer_size; j < buffer.Length; j++) { Assert.AreEqual(0, buffer[j], "Checking byte " + j); } offset += _buffer_size; Assert.AreEqual(_workbook_size - offset, stream.Available(), "offset " + offset); } Assert.AreEqual(_workbook_size % _buffer_size, stream.Available()); Arrays.Fill(buffer, (byte)0); int count = stream.Read(buffer, offset, _workbook_size % _buffer_size); Assert.AreEqual(_workbook_size % _buffer_size, count); for (int j = 0; j < offset; j++) { Assert.AreEqual(0, buffer[j], "Checking byte " + j); } for (int j = offset; j < buffer.Length; j++) { Assert.AreEqual(_workbook_data[j], buffer[j], "Checking byte " + j); } Assert.AreEqual(_workbook_size, offset + count); for (int j = count; j < offset; j++) { Assert.AreEqual(0, buffer[j], "byte " + j); } Assert.AreEqual(-1, stream.Read(buffer, 0, 1)); stream.Close(); try { stream.Read(buffer, 0, 1); Assert.Fail("Should have caught IOException"); } catch (IOException) { // as expected } } } /** * Test Skip * * @exception IOException */ [Test] public void TestSkip() { DocumentInputStream[] streams = new DocumentInputStream[] { new DocumentInputStream(_workbook_o), new NDocumentInputStream(_workbook_n) }; foreach (DocumentInputStream stream in streams) { Assert.AreEqual(_workbook_size, stream.Available()); int count = stream.Available(); while (stream.Available() >= _buffer_size) { Assert.AreEqual(_buffer_size, stream.Skip(_buffer_size)); count -= _buffer_size; Assert.AreEqual(count, stream.Available()); } Assert.AreEqual(_workbook_size % _buffer_size, stream.Skip(_buffer_size)); Assert.AreEqual(0, stream.Available()); stream.Reset(); Assert.AreEqual(_workbook_size, stream.Available()); Assert.AreEqual(_workbook_size, stream.Skip(_workbook_size * 2)); Assert.AreEqual(0, stream.Available()); stream.Reset(); Assert.AreEqual(_workbook_size, stream.Available()); Assert.AreEqual(_workbook_size, stream.Skip(2 + (long)Int32.MaxValue)); Assert.AreEqual(0, stream.Available()); } } /** * Test that we can read files at multiple levels down the tree */ [Test] public void TestReadMultipleTreeLevels() { POIDataSamples _samples = POIDataSamples.GetPublisherInstance(); FileStream sample = _samples.GetFile("Sample.pub"); DocumentInputStream stream; NPOIFSFileSystem npoifs = new NPOIFSFileSystem(sample); try { sample = _samples.GetFile("Sample.pub"); OPOIFSFileSystem opoifs = new OPOIFSFileSystem(sample); // Ensure we have what we expect on the root Assert.AreEqual(npoifs, npoifs.Root.NFileSystem); Assert.AreEqual(npoifs, npoifs.Root.FileSystem); Assert.AreEqual(null, npoifs.Root.OFileSystem); Assert.AreEqual(null, opoifs.Root.FileSystem); Assert.AreEqual(opoifs, opoifs.Root.OFileSystem); Assert.AreEqual(null, opoifs.Root.NFileSystem); // Check inside foreach (DirectoryNode root in new DirectoryNode[] { opoifs.Root, npoifs.Root }) { // Top Level Entry top = root.GetEntry("Contents"); Assert.AreEqual(true, top.IsDocumentEntry); stream = root.CreateDocumentInputStream(top); stream.Read(); // One Level Down DirectoryNode escher = (DirectoryNode)root.GetEntry("Escher"); Entry one = escher.GetEntry("EscherStm"); Assert.AreEqual(true, one.IsDocumentEntry); stream = escher.CreateDocumentInputStream(one); stream.Read(); // Two Levels Down DirectoryNode quill = (DirectoryNode)root.GetEntry("Quill"); DirectoryNode quillSub = (DirectoryNode)quill.GetEntry("QuillSub"); Entry two = quillSub.GetEntry("CONTENTS"); Assert.AreEqual(true, two.IsDocumentEntry); stream = quillSub.CreateDocumentInputStream(two); stream.Read(); } } finally { npoifs.Close(); } } } }
// 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 Internal.TypeSystem; using Internal.IL; namespace Internal.IL { // // Corresponds to "I.12.3.2.1 The evaluation stack" in ECMA spec // internal enum StackValueKind { /// <summary>An unknow type.</summary> Unknown, /// <summary>Any signed or unsigned integer values that can be represented as a 32-bit entity.</summary> Int32, /// <summary>Any signed or unsigned integer values that can be represented as a 64-bit entity.</summary> Int64, /// <summary>Underlying platform pointer type represented as an integer of the appropriate size.</summary> NativeInt, /// <summary>Any float value.</summary> Float, /// <summary>A managed pointer.</summary> ByRef, /// <summary>An object reference.</summary> ObjRef, /// <summary>A value type which is not any of the primitive one.</summary> ValueType } internal partial class ILImporter { private BasicBlock[] _basicBlocks; // Maps IL offset to basic block private BasicBlock _currentBasicBlock; private int _currentOffset; private BasicBlock _pendingBasicBlocks; // // IL stream reading // private byte ReadILByte() { return _ilBytes[_currentOffset++]; } private UInt16 ReadILUInt16() { UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } private UInt32 ReadILUInt32() { UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } private int ReadILToken() { return (int)ReadILUInt32(); } private ulong ReadILUInt64() { ulong value = ReadILUInt32(); value |= (((ulong)ReadILUInt32()) << 32); return value; } private unsafe float ReadILFloat() { uint value = ReadILUInt32(); return *(float*)(&value); } private unsafe double ReadILDouble() { ulong value = ReadILUInt64(); return *(double*)(&value); } private void SkipIL(int bytes) { _currentOffset += bytes; } // // Basic block identification // private void FindBasicBlocks() { _basicBlocks = new BasicBlock[_ilBytes.Length]; CreateBasicBlock(0); FindJumpTargets(); FindEHTargets(); } private BasicBlock CreateBasicBlock(int offset) { BasicBlock basicBlock = _basicBlocks[offset]; if (basicBlock == null) { basicBlock = new BasicBlock() { StartOffset = offset }; _basicBlocks[offset] = basicBlock; } return basicBlock; } private void FindJumpTargets() { _currentOffset = 0; while (_currentOffset < _ilBytes.Length) { MarkInstructionBoundary(); ILOpcode opCode = (ILOpcode)ReadILByte(); again: switch (opCode) { case ILOpcode.ldarg_s: case ILOpcode.ldarga_s: case ILOpcode.starg_s: case ILOpcode.ldloc_s: case ILOpcode.ldloca_s: case ILOpcode.stloc_s: case ILOpcode.ldc_i4_s: case ILOpcode.unaligned: SkipIL(1); break; case ILOpcode.ldarg: case ILOpcode.ldarga: case ILOpcode.starg: case ILOpcode.ldloc: case ILOpcode.ldloca: case ILOpcode.stloc: SkipIL(2); break; case ILOpcode.ldc_i4: case ILOpcode.ldc_r4: SkipIL(4); break; case ILOpcode.ldc_i8: case ILOpcode.ldc_r8: SkipIL(8); break; case ILOpcode.jmp: case ILOpcode.call: case ILOpcode.calli: case ILOpcode.callvirt: case ILOpcode.cpobj: case ILOpcode.ldobj: case ILOpcode.ldstr: case ILOpcode.newobj: case ILOpcode.castclass: case ILOpcode.isinst: case ILOpcode.unbox: case ILOpcode.ldfld: case ILOpcode.ldflda: case ILOpcode.stfld: case ILOpcode.ldsfld: case ILOpcode.ldsflda: case ILOpcode.stsfld: case ILOpcode.stobj: case ILOpcode.box: case ILOpcode.newarr: case ILOpcode.ldelema: case ILOpcode.ldelem: case ILOpcode.stelem: case ILOpcode.unbox_any: case ILOpcode.refanyval: case ILOpcode.mkrefany: case ILOpcode.ldtoken: case ILOpcode.ldftn: case ILOpcode.ldvirtftn: case ILOpcode.initobj: case ILOpcode.constrained: case ILOpcode.sizeof_: SkipIL(4); break; case ILOpcode.prefix1: opCode = (ILOpcode)(0x100 + ReadILByte()); goto again; case ILOpcode.br_s: case ILOpcode.leave_s: { int delta = (sbyte)ReadILByte(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); } break; case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: { int delta = (sbyte)ReadILByte(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); CreateBasicBlock(_currentOffset); } break; case ILOpcode.br: case ILOpcode.leave: { int delta = (int)ReadILUInt32(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); } break; case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: { int delta = (int)ReadILUInt32(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); CreateBasicBlock(_currentOffset); } break; case ILOpcode.switch_: { uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); for (uint i = 0; i < count; i++) { int delta = (int)ReadILUInt32(); int target = jmpBase + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); } CreateBasicBlock(_currentOffset); } break; default: continue; } } } private void FindEHTargets() { for (int i = 0; i < _exceptionRegions.Length; i++) { var r = _exceptionRegions[i]; CreateBasicBlock(r.ILRegion.TryOffset).TryStart = true; if (r.ILRegion.Kind == ILExceptionRegionKind.Filter) CreateBasicBlock(r.ILRegion.FilterOffset).FilterStart = true; CreateBasicBlock(r.ILRegion.HandlerOffset).HandlerStart = true; } } // // Basic block importing // private void ImportBasicBlocks() { _pendingBasicBlocks = _basicBlocks[0]; while (_pendingBasicBlocks != null) { BasicBlock basicBlock = _pendingBasicBlocks; _pendingBasicBlocks = basicBlock.Next; StartImportingBasicBlock(basicBlock); ImportBasicBlock(basicBlock); EndImportingBasicBlock(basicBlock); } } private void MarkBasicBlock(BasicBlock basicBlock) { if (basicBlock.EndOffset == 0) { // Link basicBlock.Next = _pendingBasicBlocks; _pendingBasicBlocks = basicBlock; basicBlock.EndOffset = -1; } } private void ImportBasicBlock(BasicBlock basicBlock) { _currentBasicBlock = basicBlock; _currentOffset = basicBlock.StartOffset; for (;;) { StartImportingInstruction(); ILOpcode opCode = (ILOpcode)ReadILByte(); again: switch (opCode) { case ILOpcode.nop: ImportNop(); break; case ILOpcode.break_: ImportBreak(); break; case ILOpcode.ldarg_0: case ILOpcode.ldarg_1: case ILOpcode.ldarg_2: case ILOpcode.ldarg_3: ImportLoadVar(opCode - ILOpcode.ldarg_0, true); break; case ILOpcode.ldloc_0: case ILOpcode.ldloc_1: case ILOpcode.ldloc_2: case ILOpcode.ldloc_3: ImportLoadVar(opCode - ILOpcode.ldloc_0, false); break; case ILOpcode.stloc_0: case ILOpcode.stloc_1: case ILOpcode.stloc_2: case ILOpcode.stloc_3: ImportStoreVar(opCode - ILOpcode.stloc_0, false); break; case ILOpcode.ldarg_s: ImportLoadVar(ReadILByte(), true); break; case ILOpcode.ldarga_s: ImportAddressOfVar(ReadILByte(), true); break; case ILOpcode.starg_s: ImportStoreVar(ReadILByte(), true); break; case ILOpcode.ldloc_s: ImportLoadVar(ReadILByte(), false); break; case ILOpcode.ldloca_s: ImportAddressOfVar(ReadILByte(), false); break; case ILOpcode.stloc_s: ImportStoreVar(ReadILByte(), false); break; case ILOpcode.ldnull: ImportLoadNull(); break; case ILOpcode.ldc_i4_m1: ImportLoadInt(-1, StackValueKind.Int32); break; case ILOpcode.ldc_i4_0: case ILOpcode.ldc_i4_1: case ILOpcode.ldc_i4_2: case ILOpcode.ldc_i4_3: case ILOpcode.ldc_i4_4: case ILOpcode.ldc_i4_5: case ILOpcode.ldc_i4_6: case ILOpcode.ldc_i4_7: case ILOpcode.ldc_i4_8: ImportLoadInt(opCode - ILOpcode.ldc_i4_0, StackValueKind.Int32); break; case ILOpcode.ldc_i4_s: ImportLoadInt((sbyte)ReadILByte(), StackValueKind.Int32); break; case ILOpcode.ldc_i4: ImportLoadInt((int)ReadILUInt32(), StackValueKind.Int32); break; case ILOpcode.ldc_i8: ImportLoadInt((long)ReadILUInt64(), StackValueKind.Int64); break; case ILOpcode.ldc_r4: ImportLoadFloat(ReadILFloat()); break; case ILOpcode.ldc_r8: ImportLoadFloat(ReadILDouble()); break; case ILOpcode.dup: ImportDup(); break; case ILOpcode.pop: ImportPop(); break; case ILOpcode.jmp: ImportJmp(ReadILToken()); return; case ILOpcode.call: ImportCall(opCode, ReadILToken()); break; case ILOpcode.calli: ImportCalli(ReadILToken()); break; case ILOpcode.ret: ImportReturn(); return; case ILOpcode.br_s: case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: { int delta = (sbyte)ReadILByte(); ImportBranch(opCode + (ILOpcode.br - ILOpcode.br_s), _basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br_s) ? _basicBlocks[_currentOffset] : null); } return; case ILOpcode.br: case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: { int delta = (int)ReadILUInt32(); ImportBranch(opCode, _basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br) ? _basicBlocks[_currentOffset] : null); } return; case ILOpcode.switch_: { uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); int[] jmpDelta = new int[count]; for (uint i = 0; i < count; i++) jmpDelta[i] = (int)ReadILUInt32(); ImportSwitchJump(jmpBase, jmpDelta, _basicBlocks[_currentOffset]); } return; case ILOpcode.ldind_i1: ImportLoadIndirect(WellKnownType.SByte); break; case ILOpcode.ldind_u1: ImportLoadIndirect(WellKnownType.Byte); break; case ILOpcode.ldind_i2: ImportLoadIndirect(WellKnownType.Int16); break; case ILOpcode.ldind_u2: ImportLoadIndirect(WellKnownType.UInt16); break; case ILOpcode.ldind_i4: ImportLoadIndirect(WellKnownType.Int32); break; case ILOpcode.ldind_u4: ImportLoadIndirect(WellKnownType.UInt32); break; case ILOpcode.ldind_i8: ImportLoadIndirect(WellKnownType.Int64); break; case ILOpcode.ldind_i: ImportLoadIndirect(WellKnownType.IntPtr); break; case ILOpcode.ldind_r4: ImportLoadIndirect(WellKnownType.Single); break; case ILOpcode.ldind_r8: ImportLoadIndirect(WellKnownType.Double); break; case ILOpcode.ldind_ref: ImportLoadIndirect(null); break; case ILOpcode.stind_ref: ImportStoreIndirect(null); break; case ILOpcode.stind_i1: ImportStoreIndirect(WellKnownType.SByte); break; case ILOpcode.stind_i2: ImportStoreIndirect(WellKnownType.Int16); break; case ILOpcode.stind_i4: ImportStoreIndirect(WellKnownType.Int32); break; case ILOpcode.stind_i8: ImportStoreIndirect(WellKnownType.Int64); break; case ILOpcode.stind_r4: ImportStoreIndirect(WellKnownType.Single); break; case ILOpcode.stind_r8: ImportStoreIndirect(WellKnownType.Double); break; case ILOpcode.add: case ILOpcode.sub: case ILOpcode.mul: case ILOpcode.div: case ILOpcode.div_un: case ILOpcode.rem: case ILOpcode.rem_un: case ILOpcode.and: case ILOpcode.or: case ILOpcode.xor: ImportBinaryOperation(opCode); break; case ILOpcode.shl: case ILOpcode.shr: case ILOpcode.shr_un: ImportShiftOperation(opCode); break; case ILOpcode.neg: case ILOpcode.not: ImportUnaryOperation(opCode); break; case ILOpcode.conv_i1: ImportConvert(WellKnownType.Byte, false, false); break; case ILOpcode.conv_i2: ImportConvert(WellKnownType.Int16, false, false); break; case ILOpcode.conv_i4: ImportConvert(WellKnownType.Int32, false, false); break; case ILOpcode.conv_i8: ImportConvert(WellKnownType.Int64, false, false); break; case ILOpcode.conv_r4: ImportConvert(WellKnownType.Single, false, false); break; case ILOpcode.conv_r8: ImportConvert(WellKnownType.Double, false, false); break; case ILOpcode.conv_u4: ImportConvert(WellKnownType.UInt32, false, false); break; case ILOpcode.conv_u8: ImportConvert(WellKnownType.UInt64, false, false); break; case ILOpcode.callvirt: ImportCall(opCode, ReadILToken()); break; case ILOpcode.cpobj: ImportCpOpj(ReadILToken()); break; case ILOpcode.ldobj: ImportLoadIndirect(ReadILToken()); break; case ILOpcode.ldstr: ImportLoadString(ReadILToken()); break; case ILOpcode.newobj: ImportCall(opCode, ReadILToken()); break; case ILOpcode.castclass: case ILOpcode.isinst: ImportCasting(opCode, ReadILToken()); break; case ILOpcode.conv_r_un: ImportConvert(WellKnownType.Double, false, true); break; case ILOpcode.unbox: ImportUnbox(ReadILToken(), opCode); break; case ILOpcode.throw_: ImportThrow(); return; case ILOpcode.ldfld: ImportLoadField(ReadILToken(), false); break; case ILOpcode.ldflda: ImportAddressOfField(ReadILToken(), false); break; case ILOpcode.stfld: ImportStoreField(ReadILToken(), false); break; case ILOpcode.ldsfld: ImportLoadField(ReadILToken(), true); break; case ILOpcode.ldsflda: ImportAddressOfField(ReadILToken(), true); break; case ILOpcode.stsfld: ImportStoreField(ReadILToken(), true); break; case ILOpcode.stobj: ImportStoreIndirect(ReadILToken()); break; case ILOpcode.conv_ovf_i1_un: ImportConvert(WellKnownType.SByte, true, true); break; case ILOpcode.conv_ovf_i2_un: ImportConvert(WellKnownType.Int16, true, true); break; case ILOpcode.conv_ovf_i4_un: ImportConvert(WellKnownType.Int32, true, true); break; case ILOpcode.conv_ovf_i8_un: ImportConvert(WellKnownType.Int64, true, true); break; case ILOpcode.conv_ovf_u1_un: ImportConvert(WellKnownType.Byte, true, true); break; case ILOpcode.conv_ovf_u2_un: ImportConvert(WellKnownType.UInt16, true, true); break; case ILOpcode.conv_ovf_u4_un: ImportConvert(WellKnownType.UInt32, true, true); break; case ILOpcode.conv_ovf_u8_un: ImportConvert(WellKnownType.UInt64, true, true); break; case ILOpcode.conv_ovf_i_un: ImportConvert(WellKnownType.IntPtr, true, true); break; case ILOpcode.conv_ovf_u_un: ImportConvert(WellKnownType.UIntPtr, true, true); break; case ILOpcode.box: ImportBox(ReadILToken()); break; case ILOpcode.newarr: ImportNewArray(ReadILToken()); break; case ILOpcode.ldlen: ImportLoadLength(); break; case ILOpcode.ldelema: ImportAddressOfElement(ReadILToken()); break; case ILOpcode.ldelem_i1: ImportLoadElement(WellKnownType.SByte); break; case ILOpcode.ldelem_u1: ImportLoadElement(WellKnownType.Byte); break; case ILOpcode.ldelem_i2: ImportLoadElement(WellKnownType.Int16); break; case ILOpcode.ldelem_u2: ImportLoadElement(WellKnownType.UInt16); break; case ILOpcode.ldelem_i4: ImportLoadElement(WellKnownType.Int32); break; case ILOpcode.ldelem_u4: ImportLoadElement(WellKnownType.UInt32); break; case ILOpcode.ldelem_i8: ImportLoadElement(WellKnownType.Int64); break; case ILOpcode.ldelem_i: ImportLoadElement(WellKnownType.IntPtr); break; case ILOpcode.ldelem_r4: ImportLoadElement(WellKnownType.Single); break; case ILOpcode.ldelem_r8: ImportLoadElement(WellKnownType.Double); break; case ILOpcode.ldelem_ref: ImportLoadElement(null); break; case ILOpcode.stelem_i: ImportStoreElement(WellKnownType.IntPtr); break; case ILOpcode.stelem_i1: ImportStoreElement(WellKnownType.SByte); break; case ILOpcode.stelem_i2: ImportStoreElement(WellKnownType.Int16); break; case ILOpcode.stelem_i4: ImportStoreElement(WellKnownType.Int32); break; case ILOpcode.stelem_i8: ImportStoreElement(WellKnownType.Int32); break; case ILOpcode.stelem_r4: ImportStoreElement(WellKnownType.Single); break; case ILOpcode.stelem_r8: ImportStoreElement(WellKnownType.Double); break; case ILOpcode.stelem_ref: ImportStoreElement(null); break; case ILOpcode.ldelem: ImportLoadElement(ReadILToken()); break; case ILOpcode.stelem: ImportStoreElement(ReadILToken()); break; case ILOpcode.unbox_any: ImportUnbox(ReadILToken(), opCode); break; case ILOpcode.conv_ovf_i1: ImportConvert(WellKnownType.SByte, true, false); break; case ILOpcode.conv_ovf_u1: ImportConvert(WellKnownType.Byte, true, false); break; case ILOpcode.conv_ovf_i2: ImportConvert(WellKnownType.Int16, true, false); break; case ILOpcode.conv_ovf_u2: ImportConvert(WellKnownType.UInt16, true, false); break; case ILOpcode.conv_ovf_i4: ImportConvert(WellKnownType.Int32, true, false); break; case ILOpcode.conv_ovf_u4: ImportConvert(WellKnownType.UInt32, true, false); break; case ILOpcode.conv_ovf_i8: ImportConvert(WellKnownType.Int64, true, false); break; case ILOpcode.conv_ovf_u8: ImportConvert(WellKnownType.UInt64, true, false); break; case ILOpcode.refanyval: ImportRefAnyVal(ReadILToken()); break; case ILOpcode.ckfinite: ImportCkFinite(); break; case ILOpcode.mkrefany: ImportMkRefAny(ReadILToken()); break; case ILOpcode.ldtoken: ImportLdToken(ReadILToken()); break; case ILOpcode.conv_u2: ImportConvert(WellKnownType.UInt16, false, false); break; case ILOpcode.conv_u1: ImportConvert(WellKnownType.Byte, false, false); break; case ILOpcode.conv_i: ImportConvert(WellKnownType.IntPtr, false, false); break; case ILOpcode.conv_ovf_i: ImportConvert(WellKnownType.IntPtr, true, false); break; case ILOpcode.conv_ovf_u: ImportConvert(WellKnownType.UIntPtr, true, false); break; case ILOpcode.add_ovf: case ILOpcode.add_ovf_un: case ILOpcode.mul_ovf: case ILOpcode.mul_ovf_un: case ILOpcode.sub_ovf: case ILOpcode.sub_ovf_un: ImportBinaryOperation(opCode); break; case ILOpcode.endfinally: //both endfinally and endfault ImportEndFinally(); return; case ILOpcode.leave: { int delta = (int)ReadILUInt32(); ImportLeave(_basicBlocks[_currentOffset + delta]); } return; case ILOpcode.leave_s: { int delta = (sbyte)ReadILByte(); ImportLeave(_basicBlocks[_currentOffset + delta]); } return; case ILOpcode.stind_i: ImportStoreIndirect(WellKnownType.IntPtr); break; case ILOpcode.conv_u: ImportConvert(WellKnownType.UIntPtr, false, false); break; case ILOpcode.prefix1: opCode = (ILOpcode)(0x100 + ReadILByte()); goto again; case ILOpcode.arglist: ImportArgList(); break; case ILOpcode.ceq: case ILOpcode.cgt: case ILOpcode.cgt_un: case ILOpcode.clt: case ILOpcode.clt_un: ImportCompareOperation(opCode); break; case ILOpcode.ldftn: case ILOpcode.ldvirtftn: ImportLdFtn(ReadILToken(), opCode); break; case ILOpcode.ldarg: ImportLoadVar(ReadILUInt16(), true); break; case ILOpcode.ldarga: ImportAddressOfVar(ReadILUInt16(), true); break; case ILOpcode.starg: ImportStoreVar(ReadILUInt16(), true); break; case ILOpcode.ldloc: ImportLoadVar(ReadILUInt16(), false); break; case ILOpcode.ldloca: ImportAddressOfVar(ReadILUInt16(), false); break; case ILOpcode.stloc: ImportStoreVar(ReadILUInt16(), false); break; case ILOpcode.localloc: ImportLocalAlloc(); break; case ILOpcode.endfilter: ImportEndFilter(); return; case ILOpcode.unaligned: ImportUnalignedPrefix(ReadILByte()); continue; case ILOpcode.volatile_: ImportVolatilePrefix(); continue; case ILOpcode.tail: ImportTailPrefix(); continue; case ILOpcode.initobj: ImportInitObj(ReadILToken()); break; case ILOpcode.constrained: ImportConstrainedPrefix(ReadILToken()); continue; case ILOpcode.cpblk: ImportCpBlk(); break; case ILOpcode.initblk: ImportInitBlk(); break; case ILOpcode.no: ImportNoPrefix(ReadILByte()); continue; case ILOpcode.rethrow: ImportRethrow(); return; case ILOpcode.sizeof_: ImportSizeOf(ReadILToken()); break; case ILOpcode.refanytype: ImportRefAnyType(); break; case ILOpcode.readonly_: ImportReadOnlyPrefix(); continue; default: ReportInvalidInstruction(opCode); EndImportingInstruction(); return; } EndImportingInstruction(); // Check if control falls through the end of method. if (_currentOffset >= _basicBlocks.Length) { ReportFallthroughAtEndOfMethod(); return; } BasicBlock nextBasicBlock = _basicBlocks[_currentOffset]; if (nextBasicBlock != null) { ImportFallthrough(nextBasicBlock); return; } } } private void ImportLoadIndirect(WellKnownType wellKnownType) { ImportLoadIndirect(GetWellKnownType(wellKnownType)); } private void ImportStoreIndirect(WellKnownType wellKnownType) { ImportStoreIndirect(GetWellKnownType(wellKnownType)); } private void ImportLoadElement(WellKnownType wellKnownType) { ImportLoadElement(GetWellKnownType(wellKnownType)); } private void ImportStoreElement(WellKnownType wellKnownType) { ImportStoreElement(GetWellKnownType(wellKnownType)); } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.Collections; using System.IO; using NUnit.Framework; using NStorage.FileSystem; using NStorage.Utility; using NStorage.Storage; using NStorage.Properties; using NStorage.Test.POIFS.FileSystem; namespace NStorage.Test.POIFS.FileSystem { /** * Class to Test POIFSDocument functionality * * @author Marc Johnson */ [TestFixture] public class TestDocument { /** * Constructor TestDocument * * @param name */ public TestDocument() { } /** * Integration Test -- really about all we can do * * @exception IOException */ [Test] public void TestPOIFSDocument() { // Verify correct number of blocks Get Created for document // that is exact multituple of block size POIFSDocument document; byte[] array = new byte[4096]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new POIFSDocument("foo", new SlowInputStream(new MemoryStream(array))); checkDocument(document, array); // Verify correct number of blocks Get Created for document // that is not an exact multiple of block size array = new byte[4097]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new POIFSDocument("bar", new MemoryStream(array)); checkDocument(document, array); // Verify correct number of blocks Get Created for document // that is small array = new byte[4095]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new POIFSDocument("_bar", new MemoryStream(array)); checkDocument(document, array); // Verify correct number of blocks Get Created for document // that is rather small array = new byte[199]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new POIFSDocument("_bar2", new MemoryStream(array)); checkDocument(document, array); // Verify that output is correct array = new byte[4097]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new POIFSDocument("foobar", new MemoryStream(array)); checkDocument(document, array); document.StartBlock=0x12345678; // what a big file!! DocumentProperty property = document.DocumentProperty; MemoryStream stream = new MemoryStream(); property.WriteData(stream); byte[] output = stream.ToArray(); byte[] array2 = { ( byte ) 'f', ( byte ) 0, ( byte ) 'o', ( byte ) 0, ( byte ) 'o', ( byte ) 0, ( byte ) 'b', ( byte ) 0, ( byte ) 'a', ( byte ) 0, ( byte ) 'r', ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 14, ( byte ) 0, ( byte ) 2, ( byte ) 1, unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0x78, ( byte ) 0x56, ( byte ) 0x34, ( byte ) 0x12, ( byte ) 1, ( byte ) 16, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0 }; Assert.AreEqual(array2.Length, output.Length); for (int j = 0; j < output.Length; j++) { Assert.AreEqual(array2[j], output[j], "Checking property offset " + j); } } private POIFSDocument makeCopy(POIFSDocument document, byte[] input, byte[] data) { POIFSDocument copy = null; if (input.Length >= 4096) { RawDataBlock[] blocks = new RawDataBlock[(input.Length + 511) / 512]; MemoryStream stream = new MemoryStream(data); int index = 0; while (true) { RawDataBlock block = new RawDataBlock(stream); if (block.EOF) { break; } blocks[index++] = block; } copy = new POIFSDocument("test" + input.Length, blocks, input.Length); } else { copy = new POIFSDocument( "test" + input.Length, (SmallDocumentBlock[])document.SmallBlocks, input.Length); } return copy; } private void checkDocument(POIFSDocument document, byte[] input) { int big_blocks = 0; int small_blocks = 0; int total_output = 0; if (input.Length >= 4096) { big_blocks = (input.Length + 511) / 512; total_output = big_blocks * 512; } else { small_blocks = (input.Length + 63) / 64; total_output = 0; } checkValues( big_blocks, small_blocks, total_output, makeCopy( document, input, checkValues( big_blocks, small_blocks, total_output, document, input)), input); } private byte[] checkValues(int big_blocks, int small_blocks, int total_output, POIFSDocument document, byte[] input) { Assert.AreEqual(document, document.DocumentProperty.Document); int increment = (int)Math.Sqrt(input.Length); for (int j = 1; j <= input.Length; j += increment) { byte[] buffer = new byte[j]; int offset = 0; for (int k = 0; k < (input.Length / j); k++) { document.Read(buffer, offset); for (int n = 0; n < buffer.Length; n++) { Assert.AreEqual(input[(k * j) + n], buffer[n] , "checking byte " + (k * j) + n); } offset += j; } } Assert.AreEqual(big_blocks, document.CountBlocks); Assert.AreEqual(small_blocks, document.SmallBlocks.Length); MemoryStream stream = new MemoryStream(); document.WriteBlocks(stream); byte[] output = stream.ToArray(); Assert.AreEqual(total_output, output.Length); int limit = Math.Min(total_output, input.Length); for (int j = 0; j < limit; j++) { Assert.AreEqual(input[j], output[j], "Checking document offset " + j); } for (int j = limit; j < output.Length; j++) { Assert.AreEqual(unchecked((byte)-1), output[j], "Checking document offset " + j); } return output; } } }
// 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. // File System.Linq.Queryable.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Linq { static public partial class Queryable { #region Methods and constructors public static TSource Aggregate<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TSource, TSource>> func) { return default(TSource); } public static TAccumulate Aggregate<TSource, TAccumulate>(IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<Func<TAccumulate, TSource, TAccumulate>> func) { return default(TAccumulate); } public static TResult Aggregate<TSource, TAccumulate, TResult>(IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<Func<TAccumulate, TSource, TAccumulate>> func, System.Linq.Expressions.Expression<Func<TAccumulate, TResult>> selector) { return default(TResult); } public static bool All<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(bool); } public static bool Any<TSource>(IQueryable<TSource> source) { return default(bool); } public static bool Any<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(bool); } public static IQueryable<TElement> AsQueryable<TElement>(IEnumerable<TElement> source) { return default(IQueryable<TElement>); } public static IQueryable AsQueryable(System.Collections.IEnumerable source) { return default(IQueryable); } public static Nullable<double> Average(IQueryable<Nullable<double>> source) { return default(Nullable<double>); } public static double Average(IQueryable<double> source) { return default(double); } public static Decimal Average(IQueryable<Decimal> source) { return default(Decimal); } public static double Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int>> selector) { return default(double); } public static Nullable<Decimal> Average(IQueryable<Nullable<Decimal>> source) { return default(Nullable<Decimal>); } public static Nullable<double> Average(IQueryable<Nullable<int>> source) { return default(Nullable<double>); } public static double Average(IQueryable<int> source) { return default(double); } public static double Average(IQueryable<long> source) { return default(double); } public static float Average(IQueryable<float> source) { return default(float); } public static Nullable<double> Average(IQueryable<Nullable<long>> source) { return default(Nullable<double>); } public static Nullable<double> Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<double>>> selector) { return default(Nullable<double>); } public static double Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, double>> selector) { return default(double); } public static Decimal Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Decimal>> selector) { return default(Decimal); } public static Nullable<float> Average(IQueryable<Nullable<float>> source) { return default(Nullable<float>); } public static Nullable<Decimal> Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<Decimal>>> selector) { return default(Nullable<Decimal>); } public static Nullable<double> Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<int>>> selector) { return default(Nullable<double>); } public static float Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, float>> selector) { return default(float); } public static double Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, long>> selector) { return default(double); } public static Nullable<float> Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<float>>> selector) { return default(Nullable<float>); } public static Nullable<double> Average<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<long>>> selector) { return default(Nullable<double>); } public static IQueryable<TResult> Cast<TResult>(IQueryable source) { return default(IQueryable<TResult>); } public static IQueryable<TSource> Concat<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2) { return default(IQueryable<TSource>); } public static bool Contains<TSource>(IQueryable<TSource> source, TSource item, IEqualityComparer<TSource> comparer) { return default(bool); } public static bool Contains<TSource>(IQueryable<TSource> source, TSource item) { return default(bool); } public static int Count<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(int); } public static int Count<TSource>(IQueryable<TSource> source) { return default(int); } public static IQueryable<TSource> DefaultIfEmpty<TSource>(IQueryable<TSource> source) { return default(IQueryable<TSource>); } public static IQueryable<TSource> DefaultIfEmpty<TSource>(IQueryable<TSource> source, TSource defaultValue) { return default(IQueryable<TSource>); } public static IQueryable<TSource> Distinct<TSource>(IQueryable<TSource> source) { return default(IQueryable<TSource>); } public static IQueryable<TSource> Distinct<TSource>(IQueryable<TSource> source, IEqualityComparer<TSource> comparer) { return default(IQueryable<TSource>); } public static TSource ElementAt<TSource>(IQueryable<TSource> source, int index) { return default(TSource); } public static TSource ElementAtOrDefault<TSource>(IQueryable<TSource> source, int index) { return default(TSource); } public static IQueryable<TSource> Except<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { return default(IQueryable<TSource>); } public static IQueryable<TSource> Except<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2) { return default(IQueryable<TSource>); } public static TSource First<TSource>(IQueryable<TSource> source) { return default(TSource); } public static TSource First<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(TSource); } public static TSource FirstOrDefault<TSource>(IQueryable<TSource> source) { return default(TSource); } public static TSource FirstOrDefault<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(TSource); } public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, IEqualityComparer<TKey> comparer) { return default(IQueryable<IGrouping<TKey, TSource>>); } public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector) { return default(IQueryable<IGrouping<TKey, TSource>>); } public static IQueryable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<Func<TSource, TElement>> elementSelector) { return default(IQueryable<IGrouping<TKey, TElement>>); } public static IQueryable<TResult> GroupBy<TSource, TKey, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<Func<TKey, IEnumerable<TSource>, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { return default(IQueryable<TResult>); } public static IQueryable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<Func<TSource, TElement>> elementSelector, IEqualityComparer<TKey> comparer) { return default(IQueryable<IGrouping<TKey, TElement>>); } public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<Func<TSource, TElement>> elementSelector, System.Linq.Expressions.Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> GroupBy<TSource, TKey, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<Func<TKey, IEnumerable<TSource>, TResult>> resultSelector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<Func<TSource, TElement>> elementSelector, System.Linq.Expressions.Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { return default(IQueryable<TResult>); } public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(IQueryable<TOuter> outer, IEnumerable<TInner> inner, System.Linq.Expressions.Expression<Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(IQueryable<TOuter> outer, IEnumerable<TInner> inner, System.Linq.Expressions.Expression<Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { return default(IQueryable<TResult>); } public static IQueryable<TSource> Intersect<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2) { return default(IQueryable<TSource>); } public static IQueryable<TSource> Intersect<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { return default(IQueryable<TSource>); } public static IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(IQueryable<TOuter> outer, IEnumerable<TInner> inner, System.Linq.Expressions.Expression<Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<Func<TOuter, TInner, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { return default(IQueryable<TResult>); } public static IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(IQueryable<TOuter> outer, IEnumerable<TInner> inner, System.Linq.Expressions.Expression<Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<Func<TOuter, TInner, TResult>> resultSelector) { return default(IQueryable<TResult>); } public static TSource Last<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(TSource); } public static TSource Last<TSource>(IQueryable<TSource> source) { return default(TSource); } public static TSource LastOrDefault<TSource>(IQueryable<TSource> source) { return default(TSource); } public static TSource LastOrDefault<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(TSource); } public static long LongCount<TSource>(IQueryable<TSource> source) { return default(long); } public static long LongCount<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(long); } public static TSource Max<TSource>(IQueryable<TSource> source) { return default(TSource); } public static TResult Max<TSource, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TResult>> selector) { return default(TResult); } public static TResult Min<TSource, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TResult>> selector) { return default(TResult); } public static TSource Min<TSource>(IQueryable<TSource> source) { return default(TSource); } public static IQueryable<TResult> OfType<TResult>(IQueryable source) { return default(IQueryable<TResult>); } public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { return default(IOrderedQueryable<TSource>); } public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector) { return default(IOrderedQueryable<TSource>); } public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector) { return default(IOrderedQueryable<TSource>); } public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { return default(IOrderedQueryable<TSource>); } public static IQueryable<TSource> Reverse<TSource>(IQueryable<TSource> source) { return default(IQueryable<TSource>); } public static IQueryable<TResult> Select<TSource, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int, TResult>> selector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> Select<TSource, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TResult>> selector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> SelectMany<TSource, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int, IEnumerable<TResult>>> selector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> SelectMany<TSource, TCollection, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int, IEnumerable<TCollection>>> collectionSelector, System.Linq.Expressions.Expression<Func<TSource, TCollection, TResult>> resultSelector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> SelectMany<TSource, TCollection, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, IEnumerable<TCollection>>> collectionSelector, System.Linq.Expressions.Expression<Func<TSource, TCollection, TResult>> resultSelector) { return default(IQueryable<TResult>); } public static IQueryable<TResult> SelectMany<TSource, TResult>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, IEnumerable<TResult>>> selector) { return default(IQueryable<TResult>); } public static bool SequenceEqual<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { return default(bool); } public static bool SequenceEqual<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2) { return default(bool); } public static TSource Single<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(TSource); } public static TSource Single<TSource>(IQueryable<TSource> source) { return default(TSource); } public static TSource SingleOrDefault<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(TSource); } public static TSource SingleOrDefault<TSource>(IQueryable<TSource> source) { return default(TSource); } public static IQueryable<TSource> Skip<TSource>(IQueryable<TSource> source, int count) { return default(IQueryable<TSource>); } public static IQueryable<TSource> SkipWhile<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(IQueryable<TSource>); } public static IQueryable<TSource> SkipWhile<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int, bool>> predicate) { return default(IQueryable<TSource>); } public static Nullable<double> Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<double>>> selector) { return default(Nullable<double>); } public static double Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, double>> selector) { return default(double); } public static Decimal Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Decimal>> selector) { return default(Decimal); } public static Nullable<int> Sum(IQueryable<Nullable<int>> source) { return default(Nullable<int>); } public static Nullable<Decimal> Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<Decimal>>> selector) { return default(Nullable<Decimal>); } public static Nullable<double> Sum(IQueryable<Nullable<double>> source) { return default(Nullable<double>); } public static double Sum(IQueryable<double> source) { return default(double); } public static Nullable<Decimal> Sum(IQueryable<Nullable<Decimal>> source) { return default(Nullable<Decimal>); } public static Decimal Sum(IQueryable<Decimal> source) { return default(Decimal); } public static Nullable<float> Sum(IQueryable<Nullable<float>> source) { return default(Nullable<float>); } public static long Sum(IQueryable<long> source) { return default(long); } public static int Sum(IQueryable<int> source) { return default(int); } public static float Sum(IQueryable<float> source) { return default(float); } public static Nullable<long> Sum(IQueryable<Nullable<long>> source) { return default(Nullable<long>); } public static int Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int>> selector) { return default(int); } public static long Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, long>> selector) { return default(long); } public static Nullable<long> Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<long>>> selector) { return default(Nullable<long>); } public static float Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, float>> selector) { return default(float); } public static Nullable<float> Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<float>>> selector) { return default(Nullable<float>); } public static Nullable<int> Sum<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, Nullable<int>>> selector) { return default(Nullable<int>); } public static IQueryable<TSource> Take<TSource>(IQueryable<TSource> source, int count) { return default(IQueryable<TSource>); } public static IQueryable<TSource> TakeWhile<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(IQueryable<TSource>); } public static IQueryable<TSource> TakeWhile<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int, bool>> predicate) { return default(IQueryable<TSource>); } public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { return default(IOrderedQueryable<TSource>); } public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector) { return default(IOrderedQueryable<TSource>); } public static IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector) { return default(IOrderedQueryable<TSource>); } public static IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { return default(IOrderedQueryable<TSource>); } public static IQueryable<TSource> Union<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2) { return default(IQueryable<TSource>); } public static IQueryable<TSource> Union<TSource>(IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { return default(IQueryable<TSource>); } public static IQueryable<TSource> Where<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate) { return default(IQueryable<TSource>); } public static IQueryable<TSource> Where<TSource>(IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, int, bool>> predicate) { return default(IQueryable<TSource>); } public static IQueryable<TResult> Zip<TFirst, TSecond, TResult>(IQueryable<TFirst> source1, IEnumerable<TSecond> source2, System.Linq.Expressions.Expression<Func<TFirst, TSecond, TResult>> resultSelector) { return default(IQueryable<TResult>); } #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; internal class TestApp { private static unsafe long test_4() { AA loc_x = new AA(0, 100); return (&loc_x.m_b)->m_bval; } private static unsafe long test_11(B[][] ab, long i, long j) { fixed (B* pb = &ab[i][j]) { return pb->m_bval; } } private static unsafe long test_18(B* pb1, long i) { B* pb; return (pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval; } private static unsafe long test_25(B* pb, long[,,] i, long ii, byte jj) { return (&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval; } private static unsafe long test_32(ulong ub, byte lb) { return ((B*)(ub | lb))->m_bval; } private static unsafe long test_39(long p, long s) { return ((B*)((p >> 4) | s))->m_bval; } private static unsafe long test_46(B[] ab) { fixed (B* pb = &ab[0]) { return pb[0].m_bval; } } private static unsafe long test_53(B* pb) { return (++pb)[0].m_bval; } private static unsafe long test_60(B* pb, long[] i, long ii) { return (&pb[i[ii]])[0].m_bval; } private static unsafe long test_67(AA* px) { return (AA.get_pb_1(px) + 1)[0].m_bval; } private static unsafe long test_74(long pb) { return ((B*)checked(((long)pb) + 1))[0].m_bval; } private static unsafe long test_81(B* pb) { return AA.get_bv1((pb--)); } private static unsafe long test_88(AA[,] ab, long i) { long j = 0; fixed (B* pb = &ab[--i, ++j].m_b) { return AA.get_bv1(pb); } } private static unsafe long test_95(B* pb1, long i) { B* pb; return AA.get_bv1((pb = pb1 + i)); } private static unsafe long test_102(B* pb1, B* pb2) { return AA.get_bv1((pb1 > pb2 ? pb2 : null)); } private static unsafe long test_109(long pb) { return AA.get_bv1(((B*)pb)); } private static unsafe long test_116(double* pb, long i) { return AA.get_bv1(((B*)(pb + i))); } private static unsafe long test_123(ref B b) { fixed (B* pb = &b) { return AA.get_bv2(*pb); } } private static unsafe long test_130(B* pb) { return AA.get_bv2(*(--pb)); } private static unsafe long test_137(B* pb, long i) { return AA.get_bv2(*(&pb[-(i << (int)i)])); } private static unsafe long test_144(AA* px) { return AA.get_bv2(*AA.get_pb(px)); } private static unsafe long test_151(long pb) { return AA.get_bv2(*((B*)checked((long)pb))); } private static unsafe long test_158(B* pb) { return AA.get_bv3(ref *(pb++)); } private static unsafe long test_165(B[,] ab, long i, long j) { fixed (B* pb = &ab[i, j]) { return AA.get_bv3(ref *pb); } } private static unsafe long test_172(B* pb1) { B* pb; return AA.get_bv3(ref *(pb = pb1 - 8)); } private static unsafe long test_179(B* pb, B* pb1, B* pb2) { return AA.get_bv3(ref *(pb = pb + (pb2 - pb1))); } private static unsafe long test_186(B* pb1, bool trig) { fixed (B* pb = &AA.s_x.m_b) { return AA.get_bv3(ref *(trig ? pb : pb1)); } } private static unsafe long test_193(byte* pb) { return AA.get_bv3(ref *((B*)(pb + 7))); } private static unsafe long test_200(B b) { return (&b)->m_bval == 100 ? 100 : 101; } private static unsafe long test_207() { fixed (B* pb = &AA.s_x.m_b) { return pb->m_bval == 100 ? 100 : 101; } } private static unsafe long test_214(B* pb, long i) { return (&pb[i * 2])->m_bval == 100 ? 100 : 101; } private static unsafe long test_221(B* pb1, B* pb2) { return (pb1 >= pb2 ? pb1 : null)->m_bval == 100 ? 100 : 101; } private static unsafe long test_228(long pb) { return ((B*)pb)->m_bval == 100 ? 100 : 101; } private static unsafe long test_235(B* pb) { return AA.get_i1(&pb->m_bval); } private static unsafe long test_242(B[] ab, long i) { fixed (B* pb = &ab[i]) { return AA.get_i1(&pb->m_bval); } } private static unsafe long test_249(B* pb) { return AA.get_i1(&(pb += 6)->m_bval); } private static unsafe long test_256(B* pb, long[,,] i, long ii) { return AA.get_i1(&(&pb[++i[--ii, 0, 0]])->m_bval); } private static unsafe long test_263(AA* px) { return AA.get_i1(&((B*)AA.get_pb_i(px))->m_bval); } private static unsafe long test_270(byte diff, A* pa) { return AA.get_i1(&((B*)(((byte*)pa) + diff))->m_bval); } private static unsafe long test_277() { AA loc_x = new AA(0, 100); return AA.get_i2((&loc_x.m_b)->m_bval); } private static unsafe long test_284(B[][] ab, long i, long j) { fixed (B* pb = &ab[i][j]) { return AA.get_i2(pb->m_bval); } } private static unsafe long test_291(B* pb1, long i) { B* pb; return AA.get_i2((pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval); } private static unsafe long test_298(B* pb, long[,,] i, long ii, byte jj) { return AA.get_i2((&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval); } private static unsafe long test_305(ulong ub, byte lb) { return AA.get_i2(((B*)(ub | lb))->m_bval); } private static unsafe long test_312(long p, long s) { return AA.get_i2(((B*)((p >> 4) | s))->m_bval); } private static unsafe long test_319(B[] ab) { fixed (B* pb = &ab[0]) { return AA.get_i3(ref pb->m_bval); } } private static unsafe long test_326(B* pb) { return AA.get_i3(ref (++pb)->m_bval); } private static unsafe long test_333(B* pb, long[] i, long ii) { return AA.get_i3(ref (&pb[i[ii]])->m_bval); } private static unsafe long test_340(AA* px) { return AA.get_i3(ref (AA.get_pb_1(px) + 1)->m_bval); } private static unsafe long test_347(long pb) { return AA.get_i3(ref ((B*)checked(((long)pb) + 1))->m_bval); } private static unsafe long test_354(B* pb) { return AA.get_bv1((pb--)) != 100 ? 99 : 100; } private static unsafe long test_361(AA[,] ab, long i) { long j = 0; fixed (B* pb = &ab[--i, ++j].m_b) { return AA.get_bv1(pb) != 100 ? 99 : 100; } } private static unsafe long test_368(B* pb1, long i) { B* pb; return AA.get_bv1((pb = pb1 + i)) != 100 ? 99 : 100; } private static unsafe long test_375(B* pb1, B* pb2) { return AA.get_bv1((pb1 > pb2 ? pb2 : null)) != 100 ? 99 : 100; } private static unsafe long test_382(long pb) { return AA.get_bv1(((B*)pb)) != 100 ? 99 : 100; } private static unsafe long test_389(double* pb, long i) { return AA.get_bv1(((B*)(pb + i))) != 100 ? 99 : 100; } private static unsafe long test_396(B* pb1, B* pb2) { if (pb1 >= pb2) return 100; throw new Exception(); } private static unsafe int Main() { AA loc_x = new AA(0, 100); AA.init_all(0); loc_x = new AA(0, 100); if (test_4() != 100) { Console.WriteLine("test_4() failed."); return 104; } AA.init_all(0); loc_x = new AA(0, 100); if (test_11(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_11() failed."); return 111; } AA.init_all(0); loc_x = new AA(0, 100); if (test_18(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_18() failed."); return 118; } AA.init_all(0); loc_x = new AA(0, 100); if (test_25(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100) { Console.WriteLine("test_25() failed."); return 125; } AA.init_all(0); loc_x = new AA(0, 100); if (test_32(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100) { Console.WriteLine("test_32() failed."); return 132; } AA.init_all(0); loc_x = new AA(0, 100); if (test_39(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100) { Console.WriteLine("test_39() failed."); return 139; } AA.init_all(0); loc_x = new AA(0, 100); if (test_46(new B[] { loc_x.m_b }) != 100) { Console.WriteLine("test_46() failed."); return 146; } AA.init_all(0); loc_x = new AA(0, 100); if (test_53(&loc_x.m_b - 1) != 100) { Console.WriteLine("test_53() failed."); return 153; } AA.init_all(0); loc_x = new AA(0, 100); if (test_60(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100) { Console.WriteLine("test_60() failed."); return 160; } AA.init_all(0); loc_x = new AA(0, 100); if (test_67(&loc_x) != 100) { Console.WriteLine("test_67() failed."); return 167; } AA.init_all(0); loc_x = new AA(0, 100); if (test_74((long)(((long)&loc_x.m_b) - 1)) != 100) { Console.WriteLine("test_74() failed."); return 174; } AA.init_all(0); loc_x = new AA(0, 100); if (test_81(&loc_x.m_b) != 100) { Console.WriteLine("test_81() failed."); return 181; } AA.init_all(0); loc_x = new AA(0, 100); if (test_88(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100) { Console.WriteLine("test_88() failed."); return 188; } AA.init_all(0); loc_x = new AA(0, 100); if (test_95(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_95() failed."); return 195; } AA.init_all(0); loc_x = new AA(0, 100); if (test_102(&loc_x.m_b + 1, &loc_x.m_b) != 100) { Console.WriteLine("test_102() failed."); return 202; } AA.init_all(0); loc_x = new AA(0, 100); if (test_109((long)&loc_x.m_b) != 100) { Console.WriteLine("test_109() failed."); return 209; } AA.init_all(0); loc_x = new AA(0, 100); if (test_116(((double*)(&loc_x.m_b)) - 4, 4) != 100) { Console.WriteLine("test_116() failed."); return 216; } AA.init_all(0); loc_x = new AA(0, 100); if (test_123(ref loc_x.m_b) != 100) { Console.WriteLine("test_123() failed."); return 223; } AA.init_all(0); loc_x = new AA(0, 100); if (test_130(&loc_x.m_b + 1) != 100) { Console.WriteLine("test_130() failed."); return 230; } AA.init_all(0); loc_x = new AA(0, 100); if (test_137(&loc_x.m_b + 2, 1) != 100) { Console.WriteLine("test_137() failed."); return 237; } AA.init_all(0); loc_x = new AA(0, 100); if (test_144(&loc_x) != 100) { Console.WriteLine("test_144() failed."); return 244; } AA.init_all(0); loc_x = new AA(0, 100); if (test_151((long)(long)&loc_x.m_b) != 100) { Console.WriteLine("test_151() failed."); return 251; } AA.init_all(0); loc_x = new AA(0, 100); if (test_158(&loc_x.m_b) != 100) { Console.WriteLine("test_158() failed."); return 258; } AA.init_all(0); loc_x = new AA(0, 100); if (test_165(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_165() failed."); return 265; } AA.init_all(0); loc_x = new AA(0, 100); if (test_172(&loc_x.m_b + 8) != 100) { Console.WriteLine("test_172() failed."); return 272; } AA.init_all(0); loc_x = new AA(0, 100); if (test_179(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100) { Console.WriteLine("test_179() failed."); return 279; } AA.init_all(0); loc_x = new AA(0, 100); if (test_186(&loc_x.m_b, true) != 100) { Console.WriteLine("test_186() failed."); return 286; } AA.init_all(0); loc_x = new AA(0, 100); if (test_193(((byte*)(&loc_x.m_b)) - 7) != 100) { Console.WriteLine("test_193() failed."); return 293; } AA.init_all(0); loc_x = new AA(0, 100); if (test_200(loc_x.m_b) != 100) { Console.WriteLine("test_200() failed."); return 300; } AA.init_all(0); loc_x = new AA(0, 100); if (test_207() != 100) { Console.WriteLine("test_207() failed."); return 307; } AA.init_all(0); loc_x = new AA(0, 100); if (test_214(&loc_x.m_b - 2, 1) != 100) { Console.WriteLine("test_214() failed."); return 314; } AA.init_all(0); loc_x = new AA(0, 100); if (test_221(&loc_x.m_b, &loc_x.m_b) != 100) { Console.WriteLine("test_221() failed."); return 321; } AA.init_all(0); loc_x = new AA(0, 100); if (test_228((long)&loc_x.m_b) != 100) { Console.WriteLine("test_228() failed."); return 328; } AA.init_all(0); loc_x = new AA(0, 100); if (test_235(&loc_x.m_b) != 100) { Console.WriteLine("test_235() failed."); return 335; } AA.init_all(0); loc_x = new AA(0, 100); if (test_242(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100) { Console.WriteLine("test_242() failed."); return 342; } AA.init_all(0); loc_x = new AA(0, 100); if (test_249(&loc_x.m_b - 6) != 100) { Console.WriteLine("test_249() failed."); return 349; } AA.init_all(0); loc_x = new AA(0, 100); if (test_256(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100) { Console.WriteLine("test_256() failed."); return 356; } AA.init_all(0); loc_x = new AA(0, 100); if (test_263(&loc_x) != 100) { Console.WriteLine("test_263() failed."); return 363; } AA.init_all(0); loc_x = new AA(0, 100); if (test_270((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100) { Console.WriteLine("test_270() failed."); return 370; } AA.init_all(0); loc_x = new AA(0, 100); if (test_277() != 100) { Console.WriteLine("test_277() failed."); return 377; } AA.init_all(0); loc_x = new AA(0, 100); if (test_284(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_284() failed."); return 384; } AA.init_all(0); loc_x = new AA(0, 100); if (test_291(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_291() failed."); return 391; } AA.init_all(0); loc_x = new AA(0, 100); if (test_298(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100) { Console.WriteLine("test_298() failed."); return 398; } AA.init_all(0); loc_x = new AA(0, 100); if (test_305(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100) { Console.WriteLine("test_305() failed."); return 405; } AA.init_all(0); loc_x = new AA(0, 100); if (test_312(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100) { Console.WriteLine("test_312() failed."); return 412; } AA.init_all(0); loc_x = new AA(0, 100); if (test_319(new B[] { loc_x.m_b }) != 100) { Console.WriteLine("test_319() failed."); return 419; } AA.init_all(0); loc_x = new AA(0, 100); if (test_326(&loc_x.m_b - 1) != 100) { Console.WriteLine("test_326() failed."); return 426; } AA.init_all(0); loc_x = new AA(0, 100); if (test_333(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100) { Console.WriteLine("test_333() failed."); return 433; } AA.init_all(0); loc_x = new AA(0, 100); if (test_340(&loc_x) != 100) { Console.WriteLine("test_340() failed."); return 440; } AA.init_all(0); loc_x = new AA(0, 100); if (test_347((long)(((long)&loc_x.m_b) - 1)) != 100) { Console.WriteLine("test_347() failed."); return 447; } AA.init_all(0); loc_x = new AA(0, 100); if (test_354(&loc_x.m_b) != 100) { Console.WriteLine("test_354() failed."); return 454; } AA.init_all(0); loc_x = new AA(0, 100); if (test_361(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100) { Console.WriteLine("test_361() failed."); return 461; } AA.init_all(0); loc_x = new AA(0, 100); if (test_368(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_368() failed."); return 468; } AA.init_all(0); loc_x = new AA(0, 100); if (test_375(&loc_x.m_b + 1, &loc_x.m_b) != 100) { Console.WriteLine("test_375() failed."); return 475; } AA.init_all(0); loc_x = new AA(0, 100); if (test_382((long)&loc_x.m_b) != 100) { Console.WriteLine("test_382() failed."); return 482; } AA.init_all(0); loc_x = new AA(0, 100); if (test_389(((double*)(&loc_x.m_b)) - 4, 4) != 100) { Console.WriteLine("test_389() failed."); return 489; } AA.init_all(0); loc_x = new AA(0, 100); if (test_396(&loc_x.m_b, &loc_x.m_b) != 100) { Console.WriteLine("test_396() failed."); return 496; } Console.WriteLine("All tests passed."); return 100; } }
using System; using GuruComponents.Netrix; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.WebEditing.Elements; namespace GuruComponents.Netrix.VmlDesigner.Elements { /// <summary> /// Gives direct access to the underlying DOM of any element. /// </summary> /// <remarks> /// To access the document just query the ElementDom from body element. /// </remarks> public class ElementDom : IElementDom { Interop.IHTMLDOMNode node; private IHtmlEditor htmlEditor; private System.Xml.XmlNodeType nodeType; internal ElementDom(Interop.IHTMLDOMNode Element, IHtmlEditor htmlEditor) { this.node = Element; this.htmlEditor = htmlEditor; if (Element.nodeType == 0) { nodeType = System.Xml.XmlNodeType.Attribute; } else { switch (Element.nodeType) { case 1: nodeType = System.Xml.XmlNodeType.Element; break; case 3: nodeType = System.Xml.XmlNodeType.Text; break; default: nodeType = System.Xml.XmlNodeType.None; break; } } } /// <summary> /// Exchanges the location of two objects in the document hierarchy. /// </summary> /// <remarks>If elements are removed at run time, before the closing tag is parsed, areas of the document might not render.</remarks> /// <param name="node">Object that specifies the existing element.</param> /// <returns>Returns a reference to the object that invoked the method.</returns> public IElement SwapNode(IElement node) { Interop.IHTMLDOMNode newNode = (this.node).swapNode((Interop.IHTMLDOMNode) node); return this.htmlEditor.GenericElementFactory.CreateElement(newNode as Interop.IHTMLElement) as IElement; } /// <overloads/> /// <summary> /// Returns the direct descendent children elements, including text nodes. /// </summary> /// <remarks> /// This method returns text portions as <see cref="TextNodeElement"/> objects. /// </remarks> /// <param name="includeTextNodes">If <c>True</c> the collection will include text parts as <see cref="TextNodeElement"/> objects.</param> /// <returns></returns> public ElementCollection GetChildNodes(bool includeTextNodes) { Interop.IHTMLDOMChildrenCollection children = (Interop.IHTMLDOMChildrenCollection) node.childNodes; ElementCollection ec = new ElementCollection(); int length = children.length; for (int i = 0; i < length; i++) { Interop.IHTMLDOMNode element = children.item(i) as Interop.IHTMLDOMNode; if (element != null && element != node) { if (element.nodeName.Equals("#text")) { ec.Add(new TextNodeElement(element, this.htmlEditor)); } else { ec.Add(this.htmlEditor.GenericElementFactory.CreateElement(element as Interop.IHTMLElement)); } } } return ec; } /// <summary> /// Returns the direct descendent children elements. /// </summary> /// <remarks> /// Doe snot returns any text nodes between the elements. /// </remarks> /// <returns></returns> public ElementCollection GetChildNodes() { Interop.IHTMLDOMChildrenCollection children = (Interop.IHTMLDOMChildrenCollection) node.childNodes; ElementCollection ec = new ElementCollection(); int length = children.length; for (int i = 0; i < length; i++) { Interop.IHTMLDOMNode element = children.item(i) as Interop.IHTMLDOMNode; if (element != null && element != node) { if (element.nodeName.Equals("#text")) continue; ec.Add(this.htmlEditor.GenericElementFactory.CreateElement(element as Interop.IHTMLElement)); } } return ec; } /// <summary> /// Returns the parent if there is any, or <c>null</c> otherwise. /// </summary> /// <returns>Returns the element as <see cref="IElement"/>, by forcing the cast to avoid access to non-native objects.</returns> public IElement GetParent() { Interop.IHTMLElement parentNode = node.parentNode as Interop.IHTMLElement; if (parentNode != null) { return htmlEditor.GenericElementFactory.CreateElement(parentNode) as IElement; } else { return null; } } # region Explicit XmlNode implementation public string LocalName { get { return ((Interop.IHTMLElement) node).GetTagName(); } } public string Name { get { string ns = (((Interop.IHTMLElement2) node).GetScopeName() == null) ? String.Empty : ((Interop.IHTMLElement2) node).GetScopeName(); if (ns.Length > 0) ns += ":"; return String.Concat(ns, LocalName); } } public System.Xml.XmlNodeType NodeType { get { return nodeType; } } public void WriteContentTo(System.Xml.XmlWriter w) { w.WriteRaw(((Interop.IHTMLElement) node).GetInnerHTML()); } public void WriteTo(System.Xml.XmlWriter w) { w.WriteRaw(((Interop.IHTMLElement) node).GetInnerHTML()); } # endregion /// <summary> /// Returns the last child of the current element. /// </summary> public IElement LastChild { get { Interop.IHTMLElement el = node.lastChild as Interop.IHTMLElement; if (el != null) { return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement; } else { if (node.lastChild != null && node.lastChild.nodeName == "#text") { return new TextNodeElement(node.lastChild, this.htmlEditor); } return null; } } } /// <summary> /// Returns the first child of the current element. /// </summary> public IElement FirstChild { get { Interop.IHTMLElement el = node.firstChild as Interop.IHTMLElement; if (el != null) { return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement; } else { if (node.firstChild != null && node.firstChild.nodeName == "#text") { return new TextNodeElement(node.firstChild, this.htmlEditor); } return null; } } } /// <summary> /// Gets <c>true</c>, if the element has child elements. /// </summary> public bool HasChildNodes { get { return node.hasChildNodes(); } } /// <summary> /// Return the next sibling of this element. /// </summary> public IElement NextSibling { get { Interop.IHTMLElement el = node.nextSibling as Interop.IHTMLElement; if (el != null) { return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement; } else { if (node.nextSibling != null && node.nextSibling.nodeName == "#text") { return new TextNodeElement(node.nextSibling, this.htmlEditor); } return null; } } } /// <summary> /// Return the previous sibling of the element. /// </summary> public IElement PreviousSibling { get { Interop.IHTMLElement el = node.previousSibling as Interop.IHTMLElement; if (el != null) { return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement; } else { if (node.previousSibling != null && node.previousSibling.nodeName == "#text") { return new TextNodeElement(node.previousSibling, this.htmlEditor); } return null; } } } /// <summary> /// Return the previous sibling of the element. /// </summary> public IElement Parent { get { Interop.IHTMLElement el = node.parentNode as Interop.IHTMLElement; if (el != null) { return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement; } else { if (node.parentNode != null && node.parentNode.nodeName == "#text") { return new TextNodeElement(node.parentNode, this.htmlEditor); } return null; } } } /// <summary> /// Insert a new element before the current one. /// </summary> /// <param name="newChild">The new element, which has to be inserted.</param> /// <param name="refChild">The element, before which the new element is inserted.</param> /// <returns>The new element, if successful, <c>null</c> (<c>Nothing</c> in VB.NET) else.</returns> public IElement InsertBefore (IElement newChild, IElement refChild) { Interop.IHTMLDOMNode nc, rc; if (newChild is TextNodeElement) { nc = ((TextNodeElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode; } else { nc = newChild.GetBaseElement() as Interop.IHTMLDOMNode; } if (refChild is TextNodeElement) { rc = ((TextNodeElement) refChild).GetBaseElement() as Interop.IHTMLDOMNode; } else { rc = refChild.GetBaseElement() as Interop.IHTMLDOMNode; } try { if (nc != null && rc != null) { return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement)node.insertBefore(nc, rc)) as IElement; } else { return null; } } catch { return null; } } /// <summary> /// Removes a child element from the collection of children. /// </summary> /// <param name="oldChild">The element which has to be removed.</param> /// <returns>Returns the parent element.</returns> public IElement RemoveChild (IElement oldChild) { Interop.IHTMLDOMNode oc; if (oldChild is TextNodeElement) { oc = ((TextNodeElement) oldChild).GetBaseElement() as Interop.IHTMLDOMNode; } else { oc = oldChild.GetBaseElement() as Interop.IHTMLDOMNode; } try { Interop.IHTMLDOMNode parent = node.removeChild(oc); return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement)parent) as IElement; } catch { return null; } } /// <summary> /// Replaces an element in the children collection with a new one. /// </summary> /// <param name="oldChild">The child element which should be replaced.</param> /// <param name="newChild">The new element which replaces the old one.</param> /// <returns>The IElement object representing the new element.</returns> public IElement ReplaceChild (IElement oldChild, IElement newChild) { Interop.IHTMLDOMNode nc, rc; if (newChild is TextNodeElement) { nc = ((TextNodeElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode; } else { nc = newChild.GetBaseElement() as Interop.IHTMLDOMNode; } if (oldChild is TextNodeElement) { rc = ((TextNodeElement) oldChild).GetBaseElement() as Interop.IHTMLDOMNode; } else { rc = oldChild.GetBaseElement() as Interop.IHTMLDOMNode; } try { if (rc != null && nc != null) { return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement)node.replaceChild(nc, rc)) as IElement; } else { return null; } } catch { return null; } } /// <summary> /// Appends a new child to the children collection. /// </summary> /// <param name="newChild"></param> /// <returns></returns> public IElement AppendChild (IElement newChild) { Interop.IHTMLDOMNode nc; if (newChild is TextNodeElement) { nc = ((TextNodeElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode; } else { nc = newChild.GetBaseElement() as Interop.IHTMLDOMNode; } try { if (nc != null) { Interop.IHTMLDOMNode newNode = node.appendChild(nc); if (newNode != null) { return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement)newNode) as IElement; } } return null; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message, "ElementDom:AppendChild"); return null; } } /// <summary> /// Removes the current element from document /// </summary> /// <param name="deep">If <c>true</c>, all child element will be removed too. Otherwise the children will be preserved.</param> public void RemoveElement(bool deep) { try { node.removeNode(deep); } catch { } } } }
#region References using System; using System.Collections; using System.Linq; using System.Reflection; using Rosetta.Configuration; #endregion namespace Rosetta.Types { public abstract class Type { #region Constructors protected Type() { var type = GetType(); var methods = type.GetMethods().Where(x => x.Name == "ConvertTo"); TypeNames = methods .Select(x => x.GetParameters().First().ParameterType.FullName) .Where(x => x != "System.Object") .ToArray(); } #endregion #region Properties /// <summary> /// The type names this converter supports. /// </summary> public string[] TypeNames { get; private set; } #endregion #region Methods public T Combine<T>(object input, CombineMethod method, T value) { var type = GetType(); var inputType = input.GetType(); var methodInfos = type.GetMethods().Where(x => x.Name == "Combine"); var methodInfo = methodInfos.FirstOrDefault(x => { var parameter = x.GetParameters().First(); if (!parameter.ParameterType.IsGenericType) { return false; } var generic = parameter.ParameterType.GetGenericArguments()[0]; return generic != null && generic.FullName == inputType.FullName; }); if (methodInfo == null) { throw new ArgumentException("The type converter does not support this type."); } var genericMethod = methodInfo.MakeGenericMethod(typeof (T)); return (T) genericMethod.Invoke(this, new[] { input, method, value }); } public object Combine(IEnumerable input, string type, CombineMethod method, object value) { var toType = System.Type.GetType(type); if (toType == null) { throw new ArgumentException("Failed to find the target type.", nameof(type)); } var myType = GetType(); var methodInfos = myType.GetMethods().Where(x => x.Name == "Combine"); var methodInfo = methodInfos.FirstOrDefault(x => { var parameter = x.GetParameters().First(); if (!parameter.ParameterType.IsGenericType) { return false; } var generic = parameter.ParameterType.GetGenericArguments()[0]; return generic != null && generic.FullName == type; }); if (methodInfo == null) { throw new ArgumentException("The type converter does not support this type."); } return methodInfo.Invoke(this, new[] { input, method, value }); } public object ConvertTo(object input, string type, string format = "") { var toType = System.Type.GetType(type); if (toType == null) { throw new ArgumentException("Failed to find the target type.", nameof(type)); } var myType = GetType(); var inputType = input.GetType(); var methods = myType.GetMethods().Where(x => x.Name == "ConvertTo"); var method = methods.FirstOrDefault(x => x.GetParameters().First().ParameterType.FullName == inputType.FullName); if (method == null) { return Activator.CreateInstance(myType); } var genericMethod = method.MakeGenericMethod(toType); return genericMethod.Invoke(this, new[] { input, format }); } /// <summary> /// Convert the input to a specific type with optional formatting. /// </summary> /// <param name="input"> The object to convert. </param> /// <param name="format"> The optional format to assist in conversion. </param> /// <returns> The new object converted to. </returns> public T ConvertTo<T>(object input, string format = null) { var type = GetType(); var inputType = input.GetType(); var methods = type.GetMethods().Where(x => x.Name == "ConvertTo"); var method = methods.FirstOrDefault(x => x.GetParameters().First().ParameterType.FullName == inputType.FullName); if (method == null) { throw new ArgumentException("The type converter does not support this type."); } var genericMethod = method.MakeGenericMethod(typeof (T)); return (T) genericMethod.Invoke(this, new[] { input, format }); } /// <summary> /// Parses the object from a string. /// </summary> /// <param name="typeName"> </param> /// <param name="input"> </param> /// <returns> </returns> public object Parse(string typeName, string input) { var methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var method = methods.FirstOrDefault(x => x.ReturnType.FullName == typeName && (x.Name.Equals("Parse") || x.Name.EndsWith(".Parse"))); if (method == null) { throw new ArgumentException("The type converter does not support this type."); } return method.Invoke(this, new object[] { input }); } public string PostProcess(object value, string type, ProcessSettings settings) { var response = settings == null ? value : Process(value, type, settings); return ConvertTo(response, type).ToString(); } public object Process(object value, string type, ProcessSettings settings) { if (settings == null) { return value; } var toType = System.Type.GetType(type); if (toType == null) { throw new ArgumentException("Failed to find the target type.", nameof(type)); } var myType = GetType(); var inputType = value.GetType(); var methods = myType.GetMethods().Where(x => x.Name == "Process"); var method = methods.FirstOrDefault(x => x.GetParameters().First().ParameterType.FullName == inputType.FullName); if (method == null) { throw new ArgumentException("The type converter does not support this type."); } return method.Invoke(this, new[] { value, settings }); } /// <summary> /// Parses the object from a string. /// </summary> /// <param name="input"> </param> /// <param name="value"> </param> /// <returns> </returns> public bool TryParse<T>(string input, out T value) { var valueType = typeof (T); var methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var method = methods.Where(x => x.Name.Equals("TryParse")).FirstOrDefault(x => { var parameterInfos = x.GetParameters(); return parameterInfos.Count() == 2 && parameterInfos[1].ParameterType.FullName == valueType.FullName + "&"; }); if (method == null) { throw new ArgumentException("The type converter does not support this type."); } var parameters = new[] { input, Activator.CreateInstance(valueType) }; var result = method.Invoke(this, parameters); value = (T) parameters[1]; return (bool) result; } #endregion } }
using System; using System.IO; using ICSharpCode.SharpZipLib.Checksum; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.GZip { /// <summary> /// This filter stream is used to compress a stream into a "GZIP" stream. /// The "GZIP" format is described in RFC 1952. /// /// author of the original java version : John Leuner /// </summary> /// <example> This sample shows how to gzip a file /// <code> /// using System; /// using System.IO; /// /// using ICSharpCode.SharpZipLib.GZip; /// using ICSharpCode.SharpZipLib.Core; /// /// class MainClass /// { /// public static void Main(string[] args) /// { /// using (Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"))) /// using (FileStream fs = File.OpenRead(args[0])) { /// byte[] writeData = new byte[4096]; /// Streamutils.Copy(s, fs, writeData); /// } /// } /// } /// } /// </code> /// </example> public class GZipOutputStream : DeflaterOutputStream { enum OutputState { Header, Footer, Finished, Closed, }; #region Instance Fields /// <summary> /// CRC-32 value for uncompressed data /// </summary> protected Crc32 crc = new Crc32(); OutputState state_ = OutputState.Header; #endregion #region Constructors /// <summary> /// Creates a GzipOutputStream with the default buffer size /// </summary> /// <param name="baseOutputStream"> /// The stream to read data (to be compressed) from /// </param> public GZipOutputStream(Stream baseOutputStream) : this(baseOutputStream, 4096) { } /// <summary> /// Creates a GZipOutputStream with the specified buffer size /// </summary> /// <param name="baseOutputStream"> /// The stream to read data (to be compressed) from /// </param> /// <param name="size"> /// Size of the buffer to use /// </param> public GZipOutputStream(Stream baseOutputStream, int size) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size) { } #endregion #region Public API /// <summary> /// Sets the active compression level (1-9). The new level will be activated /// immediately. /// </summary> /// <param name="level">The compression level to set.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Level specified is not supported. /// </exception> /// <see cref="Deflater"/> public void SetLevel(int level) { if (level < Deflater.BEST_SPEED) { throw new ArgumentOutOfRangeException(nameof(level)); } deflater_.SetLevel(level); } /// <summary> /// Get the current compression level. /// </summary> /// <returns>The current compression level.</returns> public int GetLevel() { return deflater_.GetLevel(); } #endregion #region Stream overrides /// <summary> /// Write given buffer to output updating crc /// </summary> /// <param name="buffer">Buffer to write</param> /// <param name="offset">Offset of first byte in buf to write</param> /// <param name="count">Number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { if (state_ == OutputState.Header) { WriteHeader(); } if (state_ != OutputState.Footer) { throw new InvalidOperationException("Write not permitted in current state"); } crc.Update(buffer, offset, count); base.Write(buffer, offset, count); } /// <summary> /// Writes remaining compressed output data to the output stream /// and closes it. /// </summary> protected override void Dispose(bool disposing) { try { Finish(); } finally { if (state_ != OutputState.Closed) { state_ = OutputState.Closed; if (IsStreamOwner) { baseOutputStream_.Dispose(); } } } } #endregion #region DeflaterOutputStream overrides /// <summary> /// Finish compression and write any footer information required to stream /// </summary> public override void Finish() { // If no data has been written a header should be added. if (state_ == OutputState.Header) { WriteHeader(); } if (state_ == OutputState.Footer) { state_ = OutputState.Finished; base.Finish(); var totalin = (uint)(deflater_.TotalIn & 0xffffffff); var crcval = (uint)(crc.Value & 0xffffffff); byte[] gzipFooter; unchecked { gzipFooter = new byte[] { (byte) crcval, (byte) (crcval >> 8), (byte) (crcval >> 16), (byte) (crcval >> 24), (byte) totalin, (byte) (totalin >> 8), (byte) (totalin >> 16), (byte) (totalin >> 24) }; } baseOutputStream_.Write(gzipFooter, 0, gzipFooter.Length); } } #endregion #region Support Routines void WriteHeader() { if (state_ == OutputState.Header) { state_ = OutputState.Footer; var mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals byte[] gzipHeader = { // The two magic bytes (byte) (GZipConstants.GZIP_MAGIC >> 8), (byte) (GZipConstants.GZIP_MAGIC & 0xff), // The compression type (byte) Deflater.DEFLATED, // The flags (not set) 0, // The modification time (byte) mod_time, (byte) (mod_time >> 8), (byte) (mod_time >> 16), (byte) (mod_time >> 24), // The extra flags 0, // The OS type (unknown) (byte) 255 }; baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length); } } #endregion } }
/* Copyright (c) 2014, RMIT Training 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 CounterCompliance 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.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace CounterReports.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections; using System.Windows.Forms; using System.IO; namespace l2pvp { public partial class Client { public bool isAttacking = false; public class htmcommand { public string s; public DateTime t; public uint currenttarget; } #region Threads bool skill_use = false; protected void useShotFunc() { if (useshot == null) return; ByteBuffer requse = new ByteBuffer(9); requse.WriteByte(0x19); requse.WriteUInt32(useshot.objid); requse.WriteUInt32(0); NewMessage(requse); } public void skillfunction() { ByteBuffer actionmsg = new ByteBuffer(18); actionmsg.WriteByte(0x1f); int actionindex = actionmsg.GetIndex(); ByteBuffer cancelpacket = new ByteBuffer(3); cancelpacket.WriteByte(0x48); cancelpacket.WriteInt16(1); bool doskill;// = false; while (true) { try { //isAttacking = false; //Thread.Sleep(500); if (gs.leader != null && gs.leader.targetid == 0) Thread.Sleep(500); while (startdance) { Thread.Sleep(100); } #region SelectTarget if (gs.TargetterID != 0 && this == gs.leader && gs.allplayerinfo.ContainsKey(gs.TargetterID)) { targetid = gs.allplayerinfo[gs.TargetterID].TargetID; } if (gs.battack == true) { CharInfo mytarget = gs.target; if (mytarget != null && this == gs.leader) { if (targetid != mytarget.ID) { actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(mytarget.ID); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); NewMsgHP(actionmsg); } targetid = mytarget.ID; if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0) || mytarget.isAlikeDead == 1) { //I am leader! if (this == gs.leader) { if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin) { //NewMsgHP(cancelpacket); // gs.targetselection.Interrupt(); } continue; } else { isAttacking = false; continue; } } } } if (skillattack != true) { Thread.Sleep(1000); continue; } #endregion if ((gs.AssistLeader == true || gs.battack == true) && skillattack == true) { uint targ; if (gs.leader != null) targ = gs.leader.targetid; else continue; if (targ != 0 && gs.enemylist.ContainsKey(targ)) { //is an enemy //ATTACK! //if you are attacking you shouldn't be following CharInfo mytarget2 = gs.enemylist[targ]; if (mytarget2.isAlikeDead == 1) { isAttacking = false; NewMsgHP(cancelpacket); continue; } isAttacking = true; if (targetid != mytarget2.ID) { actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(mytarget2.ID); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); NewMsgHP(actionmsg); } lock (aslock) { foreach (AttackSkills a in askills) { if (mytarget2.peace == 1 || ((mytarget2.AbnormalEffects & gs.medusastate) != 0) || mytarget2.isAlikeDead == 1) { //I am leader! //if (this == gs.leader) //{ // if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin) // gs.targetselection.Interrupt(); // break; //} //else break; } doskill = false; switch (a.condition) { case 0: //always doskill = true; break; case 1: //HP switch (a.comparison) { case 0: //== if (mytarget2.Cur_HP == a.value) doskill = true; break; case 1: //> if (mytarget2.Cur_HP > a.value) doskill = true; break; case 2: //< if (mytarget2.Cur_HP < a.value) doskill = true; break; } break; case 2: //distance double distance = System.Math.Sqrt(Math.Pow((pinfo.X - mytarget2.X), 2) + Math.Pow((pinfo.Y - mytarget2.Y), 2) + Math.Pow(pinfo.Z - mytarget2.Z, 2)); switch (a.comparison) { case 0: //== if (distance == a.value) doskill = true; break; case 1: //> if (distance > a.value) doskill = true; break; case 2: //< if (distance < a.value) doskill = true; break; } break; case 3://once if (a.used == mytarget2.ID) doskill = false; else doskill = true; break; } if (doskill == true) { useShotFunc(); launchMagic(a.useskill, mytarget2.ID, Convert.ToInt32(shiftattack)); if (a.useskill.skillstate()) a.used = mytarget2.ID; } } } } else if (targ != 0 && gs.moblist.ContainsKey(targ)) { //attack the mob NPC mob = gs.moblist[targ]; if (mob.isAlikeDead) { isAttacking = false; NewMsgHP(cancelpacket); continue; } isAttacking = true; if (targetid != mob.objid) { actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(mob.objid); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); NewMsgHP(actionmsg); } lock (aslock) { foreach (AttackSkills a in askills) { if (mob.isAlikeDead == true) { //I am leader! //if (this == gs.leader) //{ // if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin) // gs.targetselection.Interrupt(); // break; //} //else isAttacking = false; NewMsgHP(cancelpacket); break; } doskill = false; switch (a.condition) { case 0: //always doskill = true; break; case 1: //HP switch (a.comparison) { case 0: //== if (mob.Cur_HP == a.value) doskill = true; break; case 1: //> if (mob.Cur_HP > a.value) doskill = true; break; case 2: //< if (mob.Cur_HP < a.value) doskill = true; break; } break; case 2: //distance double distance = System.Math.Sqrt(Math.Pow((pinfo.X - mob.posX), 2) + Math.Pow((pinfo.Y - mob.posY), 2) + Math.Pow(pinfo.Z - mob.posZ, 2)); switch (a.comparison) { case 0: //== if (distance == a.value) doskill = true; break; case 1: //> if (distance > a.value) doskill = true; break; case 2: //< if (distance < a.value) doskill = true; break; } break; case 3://once if (a.used == mob.objid) doskill = false; else doskill = true; break; } if (doskill == true) { skill_use = true; useShotFunc(); launchMagic(a.useskill, mob.objid, Convert.ToInt32(shiftattack)); if (a.useskill.skillstate()) { Console.WriteLine("Used skill {0}", a.useskill.name); a.used = mob.objid; } else { Console.WriteLine("Couldn't use skill {0}", a.useskill.name); } skill_use = false; } } } } else { isAttacking = false; } } } catch (ThreadAbortException e) { return; } catch { //Console.WriteLine("Thread interrupted"); } } } ManualResetEvent attack_mre = new ManualResetEvent(false); ManualResetEvent skill_mre = new ManualResetEvent(false); public void attackfunction() { ByteBuffer actionmsg = new ByteBuffer(18); actionmsg.WriteByte(0x1f); int actionindex = actionmsg.GetIndex(); ByteBuffer cancelpacket = new ByteBuffer(3); cancelpacket.WriteByte(0x48); cancelpacket.WriteInt16(1); ByteBuffer useskillmsg = new ByteBuffer(10); useskillmsg.WriteByte(0x39); int skillindex = useskillmsg.GetIndex(); useskillmsg.WriteUInt32(0); useskillmsg.WriteUInt32(1); int shiftindex = useskillmsg.GetIndex(); useskillmsg.WriteByte(0x00); ByteBuffer validateposition = new ByteBuffer(21); validateposition.WriteByte(0x59); int valposindex = validateposition.GetIndex(); ByteBuffer data = new ByteBuffer(0x12); data.WriteByte(0x01); //data.WriteUInt32(target.ID); int index = data.GetIndex(); useshot = null; while (true) { // isAttacking = false; try { while (skill_use) Thread.Sleep(500); Thread.Sleep(500); if (gs.leader != null && gs.leader.targetid == 0) Thread.Sleep(500); while (startdance) { Thread.Sleep(100); } if (gs.TargetterID != 0 && this == gs.leader && gs.allplayerinfo.ContainsKey(gs.TargetterID)) { targetid = gs.allplayerinfo[gs.TargetterID].TargetID; } if (gs.battack == true) { CharInfo mytarget = gs.target; if (mytarget != null && this == gs.leader) { if (targetid != mytarget.ID) { actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(mytarget.ID); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); NewMessage(actionmsg); } targetid = mytarget.ID; } if (mytarget != null) { if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0) || mytarget.isAlikeDead == 1) { //I am leader! if (this == gs.leader) { NewMessage(cancelpacket); //if (gs.targetselection.ThreadState == ThreadState.WaitSleepJoin) // gs.targetselection.Interrupt(); continue; } else { NewMessage(cancelpacket); isAttacking = false; continue; } } } } if (battack != true) { Thread.Sleep(1000); continue; } if (gs.leader != null && (gs.AssistLeader == true || gs.battack == true) && battack == true) { uint targ = gs.leader.targetid; if (targ != 0 && gs.enemylist.ContainsKey(targ)) { //is an enemy //ATTACK! //if you are attacking you shouldn't be following CharInfo mytarget2 = gs.enemylist[targ]; if (mytarget2.isAlikeDead == 1) { NewMessage(cancelpacket); isAttacking = false; attacking = 0; continue; } if (isAttacking && attacking == targ) { //auto attacking attacking = 0; Thread.Sleep(1000); } isAttacking = true; if (targetid != pinfo.ObjID) { actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(targ); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); NewMessage(actionmsg); } data.SetIndex(index); double distance = 0.0; distance = System.Math.Sqrt(Math.Pow((pinfo.X - mytarget2.X), 2) + Math.Pow((pinfo.Y - mytarget2.Y), 2) + Math.Pow(pinfo.Z - mytarget2.Z, 2)); if (distance <= (adist + 25)) { useShotFunc(); data.WriteUInt32(mytarget2.ID); data.WriteInt32(pinfo.X); data.WriteInt32(pinfo.Y); data.WriteInt32(pinfo.Z); if (shiftattack == true) data.WriteByte(1); else data.WriteByte(0); validateposition.SetIndex(valposindex); validateposition.WriteInt32(pinfo.X); validateposition.WriteInt32(pinfo.Y); validateposition.WriteInt32(pinfo.Z); validateposition.WriteInt32(pinfo.Airship); validateposition.WriteInt32(0); NewMessage(data); attacking = targ; } } else if (targ != 0 && gs.moblist.ContainsKey(targ)) { //attack the mob NPC mob = gs.moblist[targ]; if (mob.isAlikeDead) { NewMessage(cancelpacket); isAttacking = false; attacking = 0; continue; } if(isAttacking && attacking == targ) { //auto attacking attacking = 0; Thread.Sleep(1000); } isAttacking = true; if (targetid != mob.objid) { actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(targ); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); NewMessage(actionmsg); } data.SetIndex(index); double distance = 0.0; distance = System.Math.Sqrt(Math.Pow((pinfo.X - mob.posX), 2) + Math.Pow((pinfo.Y - mob.posY), 2) + Math.Pow(pinfo.Z - mob.posZ, 2)); if (distance <= (adist + 25)) { useShotFunc(); data.WriteUInt32(targ); data.WriteInt32(pinfo.X); data.WriteInt32(pinfo.Y); data.WriteInt32(pinfo.Z); if (shiftattack == true) data.WriteByte(1); else data.WriteByte(0); NewMessage(data); attacking = targ; } } else { isAttacking = false; } } else { isAttacking = false; } } catch (ThreadAbortException e) { return; } catch { //Console.WriteLine("Exception but ignoring"); } } } public void defendfunction() { ByteBuffer actionmsg = new ByteBuffer(18); actionmsg.WriteByte(0x1f); int actionindex = actionmsg.GetIndex(); ByteBuffer cancelpacket = new ByteBuffer(3); cancelpacket.WriteByte(0x48); cancelpacket.WriteInt16(1); ByteBuffer useskillmsg = new ByteBuffer(10); useskillmsg.WriteByte(0x39); int skillindex = useskillmsg.GetIndex(); useskillmsg.WriteUInt32(0); useskillmsg.WriteUInt32(1); int shiftindex = useskillmsg.GetIndex(); useskillmsg.WriteByte(0x00); ByteBuffer validateposition = new ByteBuffer(21); validateposition.WriteByte(0x59); int valposindex = validateposition.GetIndex(); bool doskill;// = false; while (true) { Thread.Sleep(1000); if (defense == false || gs.battack == false) continue; int count = gs.enemylist.Values.Count; CharInfo[] attackers = new CharInfo[count + 10]; gs.enemylist.Values.CopyTo(attackers, 0); foreach (CharInfo mytarget in attackers) { Thread.Sleep(100); if (mytarget != null) { if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0) || mytarget.isAlikeDead == 1) { mytarget.peace = 0; continue; } actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(mytarget.ID); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); NewMessage(actionmsg); if (mytarget.peace == 1 || ((mytarget.AbnormalEffects & gs.medusastate) != 0) || mytarget.isAlikeDead == 1) { mytarget.peace = 0; continue; } lock (dslock) { foreach (DefenseSkills a in dskills) { doskill = false; switch (a.condition) { case 0: //always doskill = true; break; case 1: //HP switch (a.comparison) { case 0: //== if (mytarget.Cur_HP == a.value) doskill = true; break; case 1: //> if (mytarget.Cur_HP > a.value) doskill = true; break; case 2: //< if (mytarget.Cur_HP < a.value) doskill = true; break; } break; case 2: //distance double distance = System.Math.Sqrt(Math.Pow((pinfo.X - mytarget.X), 2) + Math.Pow((pinfo.Y - mytarget.Y), 2) + Math.Pow(pinfo.Z - mytarget.Z, 2)); switch (a.comparison) { case 0: //== if (distance == a.value) doskill = true; break; case 1: //> if (distance > a.value) doskill = true; break; case 2: //< if (distance < a.value) doskill = true; break; } break; } if (doskill == true && (mytarget.AbnormalEffects & a.effect) == 0 && pinfo.Cur_MP >= a.MP) { useShotFunc(); actionmsg.SetIndex(actionindex); actionmsg.WriteUInt32(mytarget.ID); actionmsg.WriteInt32(pinfo.X); actionmsg.WriteInt32(pinfo.Y); actionmsg.WriteInt32(pinfo.Z); actionmsg.WriteByte(1); useskillmsg.SetIndex(shiftindex); if (shiftattack) useskillmsg.WriteByte(1); else useskillmsg.WriteByte(0); useskillmsg.SetIndex(skillindex); useskillmsg.WriteUInt32(a.useskill.id); NewMessage(actionmsg); NewMessage(useskillmsg); validateposition.SetIndex(valposindex); validateposition.WriteInt32(pinfo.X); validateposition.WriteInt32(pinfo.Y); validateposition.WriteInt32(pinfo.Z); validateposition.WriteInt32(pinfo.Airship); validateposition.WriteInt32(0); NewMessage(validateposition); } Thread.Sleep(250); } } } } } } public bool autofollow; public bool autotalk; public int followdistance; public int talktime; public Object commandlock; public void movepawnthread() { int newx, newy; int condition = x.Next(50); List<htmcommand> discard = new List<htmcommand>(); while (true) { try { Thread.Sleep(500); if (gs.leader == null || pinfo == null || gs.leader.pinfo == null) continue; while (gs.leader == this) Thread.Sleep(10000); if (autofollow && !isAttacking) { int fx = gs.leader.pinfo.X; int fy = gs.leader.pinfo.Y; int fz = gs.leader.pinfo.Z; int ox = pinfo.X; int oy = pinfo.Y; int oz = pinfo.Z; double distance = 0.0; distance = System.Math.Sqrt(Math.Pow((pinfo.X - fx), 2) + Math.Pow((pinfo.Y - fy), 2) + Math.Pow(pinfo.Z - fz, 2)); int dx = pinfo.X - fx; int dy = pinfo.Y - fy; if (distance > (followdistance * 2) && distance < 2000) { double degree = convertHeadingToDegree(gs.leader.pinfo.Airship); double perpendicular; if (condition % 2 == 0) { perpendicular = degree - 90; } else { perpendicular = degree + 90; } int dxy = x.Next(0, followdistance); newx = (int)(dxy * Math.Cos(perpendicular)); newy = (int)(dxy * Math.Sin(perpendicular)); newx += fx; newy += fy; ByteBuffer mpacket = new ByteBuffer(29); mpacket.WriteByte(0x0f); mpacket.WriteInt32(newx); mpacket.WriteInt32(newy); mpacket.WriteInt32(fz); mpacket.WriteInt32(ox); mpacket.WriteInt32(oy); mpacket.WriteInt32(oz); mpacket.WriteInt32(1); this.NewMessage(mpacket); //ByteBuffer movepacket = new ByteBuffer(29); //movepacket.WriteByte(0x01); //movepacket.WriteInt32(newx); //movepacket.WriteInt32(newy); //movepacket.WriteInt32(gs.leader.pinfo.Z); //movepacket.WriteInt32(pinfo.X); //movepacket.WriteInt32(pinfo.Y); //movepacket.WriteInt32(pinfo.Z); //movepacket.WriteInt32(1); //this.NewMessage(movepacket); //bwaiting = true; } //if (gs.current[1].pinfo != null && pinfo != null) //{ // //if its null nothing we can do // ByteBuffer autofollowpacket = new ByteBuffer(18); // autofollowpacket.WriteByte(0x04); // autofollowpacket.WriteUInt32(gs.current[1].pinfo.ObjID); // autofollowpacket.WriteInt32(pinfo.X); // autofollowpacket.WriteInt32(pinfo.Y); // autofollowpacket.WriteInt32(pinfo.Z); // autofollowpacket.WriteByte(0); // this.NewMessage(autofollowpacket); //} } if (autotalk && !isAttacking) { if (commandlist.Count > 0) { //command list has items try { lock (commandlock) { foreach (htmcommand h in commandlist) { try { DateTime n = DateTime.Now; double fudgefactor = x.NextDouble(); if (n >= h.t.AddSeconds(talktime + fudgefactor)) { ByteBuffer action = new ByteBuffer(); action.WriteByte(0x1f); action.WriteUInt32(h.currenttarget); action.WriteInt32(pinfo.X); action.WriteInt32(pinfo.Y); action.WriteInt32(pinfo.Z); action.WriteByte(0); this.NewMessage(action); this.NewMessage(action); ByteBuffer htmlCommand = new ByteBuffer(); htmlCommand.WriteByte(0x23); htmlCommand.WriteString(h.s); this.NewMessage(htmlCommand); discard.Add(h); } } catch { } } try { foreach (htmcommand d in discard) { commandlist.Remove(d); } discard.Clear(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } catch { } } } else { commandlist.Clear(); } } catch { Console.WriteLine("exiting move thread"); return; } } } private void useItem(uint itemID) { ByteBuffer requse = new ByteBuffer(9); requse.WriteByte(0x19); requse.WriteUInt32(itemID); requse.WriteUInt32(0); NewMessage(requse); } public void statusmonthread() { int sleeptime = 100; int cpspamtime = 200; DateTime cpelixirtime; DateTime hpelixirtime; DateTime qhptime; DateTime gcptime; DateTime cptime; DateTime ghptime; pinfo.qhptime = DateTime.Now.AddMinutes(-60); pinfo.ghppottime = DateTime.Now.AddMinutes(-60); pinfo.cppottime = DateTime.Now.AddMinutes(-60); pinfo.smallcppottime = DateTime.Now.AddMinutes(-60); pinfo.elixirCPtime = DateTime.Now.AddMinutes(-60); pinfo.elixirHPtime = DateTime.Now.AddMinutes(-60); while (true) { try { if (sleeptime < 0) sleeptime = 10; Thread.Sleep(sleeptime); //Thread.Sleep(10); sleeptime = 50; if (pinfo == null) continue; if (gs.usebsoe && bsoeid != 0 && ((Convert.ToDouble(pinfo.Cur_CP * 100)) / Convert.ToDouble(pinfo.Max_CP)) < 50) { useItem(bsoeid); bsoeid = 0; } if (pinfo.Cur_HP <= (pinfo.Max_HP - gs.qhphp)) { if (pinfo.qhp > 0 && gs.qhp) { oldtime = pinfo.qhptime; if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now) { useItem(QHP); pinfo.qhptime = DateTime.Now; } else { //not soon enough to use pot sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds; if (sleeptime > 100) sleeptime = 100; } } } if (gs.bPercentRecover) { //recover to the given percentage by spamming both small and big CP together if (pinfo.Cur_CP <= (gs.PercentRecover / 100.0) * pinfo.Max_CP) { if (pinfo.lesscppots > 0 && gs.cppots) { oldtime = pinfo.smallcppottime; if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now) { useItem(LCP); pinfo.smallcppottime = DateTime.Now; } else { //not soon enough to use pot sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds; if (sleeptime > 100) sleeptime = 100; } } if (pinfo.cppots > 0 && gs.cppots) { oldtime = pinfo.cppottime; if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now) { useItem(GCP); pinfo.cppottime = DateTime.Now; } else { //not soon enough to use pot sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds; if (sleeptime > 100) sleeptime = 100; } } } } if (!gs.bPercentRecover && pinfo.Cur_CP <= (pinfo.Max_CP - 50)) { if (pinfo.lesscppots > 0 && gs.cppots) { oldtime = pinfo.smallcppottime; if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now) { useItem(LCP); pinfo.smallcppottime = DateTime.Now; } else { //not soon enough to use pot sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds; if (sleeptime > 100) sleeptime = 100; } } } if (!gs.bPercentRecover && pinfo.Cur_CP <= (pinfo.Max_CP - 200)) { //use cp pot if (pinfo.cppots > 0 && gs.cppots) { oldtime = pinfo.cppottime; if (oldtime.AddMilliseconds(cpspamtime) <= DateTime.Now) { useItem(GCP); pinfo.cppottime = DateTime.Now; } else { //not soon enough to use pot sleeptime = (oldtime.AddMilliseconds(cpspamtime) - DateTime.Now).Milliseconds; if (sleeptime > 100) sleeptime = 100; } } } if (pinfo.Cur_HP <= (pinfo.Max_HP - gs.ghphp)) { if (pinfo.ghppots > 0 && gs.ghppots) { oldtime = pinfo.ghppottime; if (oldtime.AddSeconds(15) <= DateTime.Now) { useItem(GHP); pinfo.ghppottime = DateTime.Now; } } } if (pinfo.Cur_CP <= (pinfo.Max_CP - gs.cpelixir)) { if (pinfo.elixirCP_A > 0 && gs.elixir && pinfo.Level >= 61 && pinfo.Level < 76) { oldtime = pinfo.elixirCPtime; if (oldtime.AddSeconds(301) <= DateTime.Now) { useItem(ECP_A); pinfo.elixirCPtime = DateTime.Now; } } if (pinfo.elixirCP_S > 0 && gs.elixir && pinfo.Level >= 76) { oldtime = pinfo.elixirCPtime; if (oldtime.AddSeconds(301) <= DateTime.Now) { useItem(ECP_S); pinfo.elixirCPtime = DateTime.Now; } } } if (pinfo.Cur_HP <= (pinfo.Max_HP - gs.hpelixir)) { if (pinfo.elixirHP_A > 0 && gs.elixir && pinfo.Level >= 61 && pinfo.Level < 76) { oldtime = pinfo.elixirHPtime; if (oldtime.AddSeconds(301) <= DateTime.Now) { useItem(EHP_A); pinfo.elixirHPtime = DateTime.Now; } } if (pinfo.elixirHP_S > 0 && gs.elixir && pinfo.Level >= 76) { oldtime = pinfo.elixirHPtime; if (oldtime.AddSeconds(301) <= DateTime.Now) { useItem(EHP_S); pinfo.elixirHPtime = DateTime.Now; } } } } catch (ThreadAbortException e) { return; } catch (Exception e) { } } } public void PeriodicFunction() { //return; ByteBuffer requestaction = new ByteBuffer(10); requestaction.WriteByte(0x56); requestaction.WriteInt32(1007); requestaction.WriteInt32(0); requestaction.WriteByte(0); while (true) { Thread.Sleep(60000); if (pinfo != null && blessing == true) this.NewMessage(requestaction); } } public Queue<PlayerBuffs> rebuffqueue; public object rebufflock; public void singlebufffunction() { PlayerBuffs currentbuff = null; ByteBuffer useskillmsg = new ByteBuffer(10); useskillmsg.WriteByte(0x39); int skillindex = useskillmsg.GetIndex(); useskillmsg.WriteUInt32(0); useskillmsg.WriteUInt32(1); int shiftindex = useskillmsg.GetIndex(); useskillmsg.WriteByte(0x00); sbuff_mre.Reset(); while (true) { while (rebuffqueue.Count == 0) sbuff_mre.WaitOne(1000, true); sbuff_mre.Reset(); lock (rebufflock) { currentbuff = rebuffqueue.Dequeue(); if (currentbuff == null) continue; } doBuff(useskillmsg, skillindex, currentbuff); } } public void bufffunction() { ByteBuffer useskillmsg = new ByteBuffer(10); useskillmsg.WriteByte(0x39); int skillindex = useskillmsg.GetIndex(); useskillmsg.WriteUInt32(0); useskillmsg.WriteUInt32(1); int shiftindex = useskillmsg.GetIndex(); useskillmsg.WriteByte(0x00); while (true) { //wait until this is signaled try { buff_mre.WaitOne(); lock (bufflock) { foreach (PlayerBuffs p in bufflist) { doBuff(useskillmsg, skillindex, p); } } buff_mre.Reset(); } catch (ThreadAbortException e) { return; } catch (Exception ex) { //MessageBox.Show(ex.ToString()); } } } private void doBuff(ByteBuffer useskillmsg, int skillindex, PlayerBuffs p) { if (p.objid == 0 && p.self != true) { //we haven't found the player yet //search in allplayerinfo CharInfo[] cinfos = new CharInfo[gs.allplayerinfo.Count]; gs.allplayerinfo.Values.CopyTo(cinfos, 0); foreach (CharInfo cinfo in cinfos) { if (p.player == cinfo.Name) { p.objid = cinfo.ID; } } } if (p.objid != 0) { //target the guy //execute the list of skills on him ByteBuffer action = new ByteBuffer(); action.WriteByte(0x1f); action.WriteUInt32(p.objid); action.WriteInt32(pinfo.X); action.WriteInt32(pinfo.Y); action.WriteInt32(pinfo.Z); action.WriteByte(0); NewMessage(action); p.lastuse = DateTime.Now; foreach (skill s in p.bufflist.Values) { if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now) { ReSkill r = new ReSkill(s, p.objid); lock (redolistlock) { redolist.Enqueue(r); } continue; } useskillmsg.SetIndex(skillindex); useskillmsg.WriteUInt32(s.id); NewMessage(useskillmsg); s.mre.WaitOne(10000); s.mre.Reset(); if (s.skillstate()) { System.Threading.Thread.Sleep((int)s.hitTime); } else { ReSkill r = new ReSkill(s, p.objid); lock (redolistlock) { redolist.Enqueue(r); } } //wait for response //s.lastuse = DateTime.Now; } } else if (p.self) { p.lastuse = DateTime.Now; foreach (skill s in p.bufflist.Values) { if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now) { ReSkill r = new ReSkill(s, p.objid); lock (redolistlock) { redolist.Enqueue(r); } continue; } useskillmsg.SetIndex(skillindex); useskillmsg.WriteUInt32(s.id); NewMessage(useskillmsg); s.mre.WaitOne(10000); s.mre.Reset(); if (s.skillstate()) { System.Threading.Thread.Sleep((int)s.hitTime); } else { ReSkill r = new ReSkill(s, p.objid); lock (redolistlock) { redolist.Enqueue(r); } } //wait for response //s.lastuse = DateTime.Now; } } } private void launchBuff(skill s, uint objectid, int shift) { if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now) { ReSkill r = new ReSkill(s, objectid); lock (redolistlock) { redolist.Enqueue(r); } return; } s.setstate(false); s.mre.Reset(); useSkill(s.id, objectid, shift); s.mre.WaitOne(2000); s.mre.Reset(); if (s.skillstate()) { //wait for response s.lastuse = DateTime.Now; System.Threading.Thread.Sleep((int)s.hitTime); } else { //System.Console.WriteLine("skill failed"); ReSkill r = new ReSkill(s, objectid); lock (redolistlock) { redolist.Enqueue(r); } } } private void launchMagic(skill s, uint objectid, int shift) { if (s.lastuse.AddMilliseconds(s.reuseDelay) > DateTime.Now) { return; } s.setstate(false); s.mre.Reset(); useSkill(s.id, objectid, shift); s.mre.WaitOne(5000); s.mre.Reset(); if (s.skillstate()) { //wait for response System.Threading.Thread.Sleep((int)s.hitTime); } else { //System.Console.WriteLine("skill failed"); } } private void useSkill(uint skillid, uint objectid, int shift) { if (targetid != objectid && objectid != 0) { ByteBuffer action = new ByteBuffer(); action.WriteByte(0x1f); action.WriteUInt32(objectid); action.WriteInt32(pinfo.X); action.WriteInt32(pinfo.Y); action.WriteInt32(pinfo.Z); action.WriteByte(1); NewMessage(action); } ByteBuffer useskillmsg = new ByteBuffer(10); useskillmsg.WriteByte(0x39); useskillmsg.WriteUInt32(skillid); useskillmsg.WriteUInt32(1); int shiftindex = useskillmsg.GetIndex(); if (shift == 1) useskillmsg.WriteByte(1); else useskillmsg.WriteByte(0); NewMessage(useskillmsg); ByteBuffer validateposition = new ByteBuffer(21); validateposition.WriteByte(0x59); validateposition.WriteInt32(pinfo.X); validateposition.WriteInt32(pinfo.Y); validateposition.WriteInt32(pinfo.Z); validateposition.WriteInt32(pinfo.Airship); validateposition.WriteInt32(0); NewMessage(validateposition); } public void PartyMonitorFunction() { } public void fightbufffunction() { ByteBuffer useskillmsg = new ByteBuffer(10); useskillmsg.WriteByte(0x39); int skillindex = useskillmsg.GetIndex(); useskillmsg.WriteUInt32(0); useskillmsg.WriteUInt32(1); int shiftindex = useskillmsg.GetIndex(); useskillmsg.WriteByte(0x00); while (true) { //wait until this is signaled try { fightbuff_mre.WaitOne(); foreach (PlayerBuffs p in fightbufflist) { doBuff(useskillmsg, skillindex, p); } fightbuff_mre.Reset(); } catch (ThreadAbortException e) { return; } catch (Exception ex) { //MessageBox.Show(ex.ToString()); } } } public ManualResetEvent item_mre; public void itemfunction() { while (true) { item_mre.WaitOne(); item_mre.Reset(); foreach (ClientItems i in useItems) { useItem(i.inventory.ObjID); } } } System.Collections.Queue danceq; System.Threading.ManualResetEvent dancemre; bool startdance = false; public void dancefunction() { danceq = new Queue(); dancemre = new ManualResetEvent(false); evtSkill s; while (true) { dancemre.WaitOne(); if (gs.buffs == false) { lock (dancelock) { danceq.Clear(); } } while (danceq.Count > 0) { startdance = true; lock (dancelock) { if (danceq.Count == 0) continue; s = (evtSkill)danceq.Dequeue(); } //System.Console.WriteLine("launching skill {0} - event {1}", s.act.name, s.evt.name); s.succeed = false; launchMagic(s.act, 0, 0); //bool ret = s.mre.WaitOne(3000); //s.mre.Reset(); if (s.succeed || s.act.skillstate()) { ////skill succeeded //probably do nothing? //Console.WriteLine("skill {0} succeeded", s.act.name); s.act.setstate(false); } else { //skill failed .. requeue // Console.WriteLine("skill {0} failed", s.act.name); lock (dancelock) { ReSkill r = new ReSkill(s.act, 0); redolist.Enqueue(r); } } } startdance = false; dancemre.Reset(); } } Queue<ReSkill> redolist; object redolistlock; void timebufffunction() { ByteBuffer useskillmsg = new ByteBuffer(10); useskillmsg.WriteByte(0x39); int skillindex = useskillmsg.GetIndex(); useskillmsg.WriteUInt32(0); useskillmsg.WriteUInt32(1); int shiftindex = useskillmsg.GetIndex(); useskillmsg.WriteByte(0x00); ReSkill redoskill = null; while (true) { Thread.Sleep(1000); lock (bufflock) { if (gs.buffs == false) { lock (redolistlock) { redolist.Clear(); } continue; } foreach (PlayerBuffs p in bufflist) { if (p.lastuse.AddMinutes(p.bufftimer) <= DateTime.Now) { doBuff(useskillmsg, skillindex, p); } } int count = redolist.Count; for (int i = 0; i < count; i++) { lock (redolistlock) { redoskill = redolist.Dequeue(); } launchBuff(redoskill.s, redoskill.objid, 0); } } } } #endregion } class ReSkill { public uint objid; public skill s; public ReSkill(skill _s, uint _oid) { objid = _oid; s = _s; } } }
using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Networking.Shared; namespace Orleans.Runtime.Messaging { internal abstract class ConnectionListener { private readonly IConnectionListenerFactory listenerFactory; private readonly CancellationTokenSource cancellation = new CancellationTokenSource(); private readonly ConcurrentDictionary<Connection, Task> connections = new ConcurrentDictionary<Connection, Task>(ReferenceEqualsComparer.Instance); private readonly INetworkingTrace trace; private IConnectionListener listener; private ConnectionDelegate connectionDelegate; private Task runTask; protected ConnectionListener( IServiceProvider serviceProvider, IConnectionListenerFactory listenerFactory, IOptions<ConnectionOptions> connectionOptions, INetworkingTrace trace) { this.ServiceProvider = serviceProvider; this.listenerFactory = listenerFactory; this.ConnectionOptions = connectionOptions.Value; this.trace = trace; } public abstract EndPoint Endpoint { get; } protected IServiceProvider ServiceProvider { get; } public int ConnectionCount => this.connections.Count; protected ConnectionOptions ConnectionOptions { get; } protected abstract Connection CreateConnection(ConnectionContext context); protected ConnectionDelegate ConnectionDelegate { get { if (this.connectionDelegate != null) return this.connectionDelegate; lock (this) { if (this.connectionDelegate != null) return this.connectionDelegate; // Configure the connection builder using the user-defined options. var connectionBuilder = new ConnectionBuilder(this.ServiceProvider); this.ConnectionOptions.ConfigureConnectionBuilder(connectionBuilder); Connection.ConfigureBuilder(connectionBuilder); return this.connectionDelegate = connectionBuilder.Build(); } } } public async Task BindAsync(CancellationToken cancellationToken) { this.listener = await this.listenerFactory.BindAsync(this.Endpoint, cancellationToken); } public void Start() { if (this.runTask != null) throw new InvalidOperationException("Start has already been called"); if (this.listener is null) throw new InvalidOperationException("Listener is not bound"); this.runTask = Task.Run(() => this.RunAsync()); } private async Task RunAsync() { var runCancellation = this.cancellation.Token; var runCancellationTask = runCancellation.WhenCancelled(); while (!runCancellation.IsCancellationRequested) { try { var acceptTask = this.listener.AcceptAsync(runCancellation); if (!acceptTask.IsCompletedSuccessfully) { // Allow the call to be gracefully cancelled. var completed = await Task.WhenAny(acceptTask.AsTask(), runCancellationTask); if (ReferenceEquals(completed, runCancellationTask)) break; } var context = acceptTask.Result; if (context == null) break; var connection = this.CreateConnection(context); _ = RunConnection(connection); } catch (ObjectDisposedException) { break; } catch (OperationCanceledException) { break; } catch (Exception exception) { this.trace.LogWarning("Exception in AcceptAsync: {Exception}", exception); } } async Task RunConnection(Connection connection) { try { using (this.BeginConnectionScope(connection)) { var connectionTask = connection.Run(); this.connections.TryAdd(connection, connectionTask); await connectionTask; } } catch { // Swallow exceptions here. } finally { this.connections.TryRemove(connection, out _); } } } public async Task StopAsync(CancellationToken cancellationToken) { this.cancellation.Cancel(throwOnFirstException: false); if (this.runTask != null) { try { await this.runTask; } catch (Exception exception) { this.trace.LogWarning( exception, "Exception while waiting for accept loop to terminate: {Exception}", exception); } } try { ValueTask listenerStop = default; if (this.listener != null) { listenerStop = this.listener.UnbindAsync(CancellationToken.None); } var cycles = 0; var exception = new ConnectionAbortedException("Shutting down"); while (this.ConnectionCount > 0 && !cancellationToken.IsCancellationRequested) { foreach (var connection in this.connections.Keys.ToImmutableList()) { try { connection.Close(exception); } catch { } } await Task.Delay(10); if (++cycles > 100 && cycles % 500 == 0 && this.ConnectionCount > 0) { this.trace?.LogWarning("Waiting for {NumRemaining} connections to terminate", this.ConnectionCount); } } await listenerStop; if (this.listener != null) { await this.listener.DisposeAsync(); } } catch (Exception exception) { this.trace?.LogWarning("Exception during shutdown: {Exception}", exception); } } private IDisposable BeginConnectionScope(Connection connection) { if (this.trace.IsEnabled(LogLevel.Critical)) { return this.trace.BeginScope(new ConnectionLogScope(connection.Context.ConnectionId)); } return null; } } }
// // System.Drawing.Color.cs // // Author: // Dennis Hayes (dennish@raytek.com) // Ben Houston (ben@exocortex.org) // // (C) 2002 Dennis Hayes // Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace System.Drawing { #if ONLY_1_1 [Serializable] #endif public enum KnownColor { ActiveBorder = 1, ActiveCaption = 2, ActiveCaptionText = 3, AppWorkspace = 4, Control = 5, ControlDark = 6, ControlDarkDark = 7, ControlLight = 8, ControlLightLight = 9, ControlText = 10, Desktop = 11, GrayText = 12, Highlight = 13, HighlightText = 14, HotTrack = 15, InactiveBorder = 16, InactiveCaption = 17, InactiveCaptionText = 18, Info = 19, InfoText = 20, Menu = 21, MenuText = 22, ScrollBar = 23, Window = 24, WindowFrame = 25, WindowText = 26, Transparent = 27, AliceBlue = 28, AntiqueWhite = 29, Aqua = 30, Aquamarine = 31, Azure = 32, Beige = 33, Bisque = 34, Black = 35, BlanchedAlmond = 36, Blue = 37, BlueViolet = 38, Brown = 39, BurlyWood = 40, CadetBlue = 41, Chartreuse = 42, Chocolate = 43, Coral = 44, CornflowerBlue = 45, Cornsilk = 46, Crimson = 47, Cyan = 48, DarkBlue = 49, DarkCyan = 50, DarkGoldenrod = 51, DarkGray = 52, DarkGreen = 53, DarkKhaki = 54, DarkMagenta = 55, DarkOliveGreen = 56, DarkOrange = 57, DarkOrchid = 58, DarkRed = 59, DarkSalmon = 60, DarkSeaGreen = 61, DarkSlateBlue = 62, DarkSlateGray = 63, DarkTurquoise = 64, DarkViolet = 65, DeepPink = 66, DeepSkyBlue = 67, DimGray = 68, DodgerBlue = 69, Firebrick = 70, FloralWhite = 71, ForestGreen = 72, Fuchsia = 73, Gainsboro = 74, GhostWhite = 75, Gold = 76, Goldenrod = 77, Gray = 78, Green = 79, GreenYellow = 80, Honeydew = 81, HotPink = 82, IndianRed = 83, Indigo = 84, Ivory = 85, Khaki = 86, Lavender = 87, LavenderBlush = 88, LawnGreen = 89, LemonChiffon = 90, LightBlue = 91, LightCoral = 92, LightCyan = 93, LightGoldenrodYellow = 94, LightGray = 95, LightGreen = 96, LightPink = 97, LightSalmon = 98, LightSeaGreen = 99, LightSkyBlue = 100, LightSlateGray = 101, LightSteelBlue = 102, LightYellow = 103, Lime = 104, LimeGreen = 105, Linen = 106, Magenta = 107, Maroon = 108, MediumAquamarine = 109, MediumBlue = 110, MediumOrchid = 111, MediumPurple = 112, MediumSeaGreen = 113, MediumSlateBlue = 114, MediumSpringGreen = 115, MediumTurquoise = 116, MediumVioletRed = 117, MidnightBlue = 118, MintCream = 119, MistyRose = 120, Moccasin = 121, NavajoWhite = 122, Navy = 123, OldLace = 124, Olive = 125, OliveDrab = 126, Orange = 127, OrangeRed = 128, Orchid = 129, PaleGoldenrod = 130, PaleGreen = 131, PaleTurquoise = 132, PaleVioletRed = 133, PapayaWhip = 134, PeachPuff = 135, Peru = 136, Pink = 137, Plum = 138, PowderBlue = 139, Purple = 140, Red = 141, RosyBrown = 142, RoyalBlue = 143, SaddleBrown = 144, Salmon = 145, SandyBrown = 146, SeaGreen = 147, SeaShell = 148, Sienna = 149, Silver = 150, SkyBlue = 151, SlateBlue = 152, SlateGray = 153, Snow = 154, SpringGreen = 155, SteelBlue = 156, Tan = 157, Teal = 158, Thistle = 159, Tomato = 160, Turquoise = 161, Violet = 162, Wheat = 163, White = 164, WhiteSmoke = 165, Yellow = 166, YellowGreen = 167, #if NET_2_0 ButtonFace = 168, ButtonHighlight = 169, ButtonShadow = 170, GradientActiveCaption = 171, GradientInactiveCaption = 172, MenuBar = 173, MenuHighlight = 174 #endif } }
using System; using NBitcoin.BouncyCastle.Crypto.Parameters; using NBitcoin.BouncyCastle.Crypto.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Engines { /** * HC-256 is a software-efficient stream cipher created by Hongjun Wu. It * generates keystream from a 256-bit secret key and a 256-bit initialization * vector. * <p> * http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc256_p3.pdf * </p><p> * Its brother, HC-128, is a third phase candidate in the eStream contest. * The algorithm is patent-free. No attacks are known as of today (April 2007). * See * * http://www.ecrypt.eu.org/stream/hcp3.html * </p> */ public class HC256Engine : IStreamCipher { private uint[] p = new uint[1024]; private uint[] q = new uint[1024]; private uint cnt = 0; private uint Step() { uint j = cnt & 0x3FF; uint ret; if (cnt < 1024) { uint x = p[(j - 3 & 0x3FF)]; uint y = p[(j - 1023 & 0x3FF)]; p[j] += p[(j - 10 & 0x3FF)] + (RotateRight(x, 10) ^ RotateRight(y, 23)) + q[((x ^ y) & 0x3FF)]; x = p[(j - 12 & 0x3FF)]; ret = (q[x & 0xFF] + q[((x >> 8) & 0xFF) + 256] + q[((x >> 16) & 0xFF) + 512] + q[((x >> 24) & 0xFF) + 768]) ^ p[j]; } else { uint x = q[(j - 3 & 0x3FF)]; uint y = q[(j - 1023 & 0x3FF)]; q[j] += q[(j - 10 & 0x3FF)] + (RotateRight(x, 10) ^ RotateRight(y, 23)) + p[((x ^ y) & 0x3FF)]; x = q[(j - 12 & 0x3FF)]; ret = (p[x & 0xFF] + p[((x >> 8) & 0xFF) + 256] + p[((x >> 16) & 0xFF) + 512] + p[((x >> 24) & 0xFF) + 768]) ^ q[j]; } cnt = cnt + 1 & 0x7FF; return ret; } private byte[] key, iv; private bool initialised; private void Init() { if (key.Length != 32 && key.Length != 16) throw new ArgumentException("The key must be 128/256 bits long"); if (iv.Length < 16) throw new ArgumentException("The IV must be at least 128 bits long"); if (key.Length != 32) { byte[] k = new byte[32]; Array.Copy(key, 0, k, 0, key.Length); Array.Copy(key, 0, k, 16, key.Length); key = k; } if (iv.Length < 32) { byte[] newIV = new byte[32]; Array.Copy(iv, 0, newIV, 0, iv.Length); Array.Copy(iv, 0, newIV, iv.Length, newIV.Length - iv.Length); iv = newIV; } cnt = 0; uint[] w = new uint[2560]; for (int i = 0; i < 32; i++) { w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3))); } for (int i = 0; i < 32; i++) { w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3))); } for (uint i = 16; i < 2560; i++) { uint x = w[i - 2]; uint y = w[i - 15]; w[i] = (RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10)) + w[i - 7] + (RotateRight(y, 7) ^ RotateRight(y, 18) ^ (y >> 3)) + w[i - 16] + i; } Array.Copy(w, 512, p, 0, 1024); Array.Copy(w, 1536, q, 0, 1024); for (int i = 0; i < 4096; i++) { Step(); } cnt = 0; } public string AlgorithmName { get { return "HC-256"; } } /** * Initialise a HC-256 cipher. * * @param forEncryption whether or not we are for encryption. Irrelevant, as * encryption and decryption are the same. * @param params the parameters required to set up the cipher. * @throws ArgumentException if the params argument is * inappropriate (ie. the key is not 256 bit long). */ public void Init( bool forEncryption, ICipherParameters parameters) { ICipherParameters keyParam = parameters; if (parameters is ParametersWithIV) { iv = ((ParametersWithIV)parameters).GetIV(); keyParam = ((ParametersWithIV)parameters).Parameters; } else { iv = new byte[0]; } if (keyParam is KeyParameter) { key = ((KeyParameter)keyParam).GetKey(); Init(); } else { throw new ArgumentException( "Invalid parameter passed to HC256 init - " + parameters.GetType().Name, "parameters"); } initialised = true; } private byte[] buf = new byte[4]; private int idx = 0; private byte GetByte() { if (idx == 0) { Pack.UInt32_To_LE(Step(), buf); } byte ret = buf[idx]; idx = idx + 1 & 0x3; return ret; } public void ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); if ((inOff + len) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + len) > output.Length) throw new DataLengthException("output buffer too short"); for (int i = 0; i < len; i++) { output[outOff + i] = (byte)(input[inOff + i] ^ GetByte()); } } public void Reset() { idx = 0; Init(); } public byte ReturnByte(byte input) { return (byte)(input ^ GetByte()); } private static uint RotateRight(uint x, int bits) { return (x >> bits) | (x << -bits); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace CommunityEvents.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Bareplan (c) 2015-17 MIT License <baltasarq@gmail.com> namespace Bareplan.Core { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Pair = System.Collections.Generic.KeyValuePair<System.DateTime, Document.Task>; /// <summary> /// Represents documents with dates and tasks. /// The document is ordered by date, which has a corresponding task. /// </summary> public class Document { /// <summary>A task, associated with a date.</summary> public class Task { /// <summary>The default task one is first created.</summary> public const string KindTag = "exercises"; /// <summary>The default task one is first created.</summary> public const string ContentsTag = "thema"; /// <summary>Creates a new task with default kind and contents = contentags + i. /// Initializes a new instance of the <see cref="T:Bareplan.Core.Document.Task"/> class. /// </summary> /// <param name="i">The index.</param> public Task(int i) : this( KindTag, ContentsTag + i.ToString() ) { } public Task(string kind = KindTag, string contents = ContentsTag) { this.Kind = kind; this.Contents = contents; } /// <summary> /// Gets or sets the contents for this task. /// </summary> /// <value>The contents, as a string.</value> public string Contents { get; set; } /// <summary> /// Gets or sets the kind of task. /// </summary> /// <value>The kind, as a string.</value> public string Kind { get; set; } public override string ToString() { return this.Kind + ": " + this.Contents; } } /// <summary> /// Initializes a new <see cref="T:Bareplan.Core.Document"/>. /// </summary> public Document() { this.Steps = new Steps( this ); this.dates = new List<DateTime>(); this.tasks = new List<Task>(); this.InitialDate = DateTime.Now; this.hasNext = false; this.FileName = ""; this.NeedsSaving = true; } /// <summary> /// Adds a new date/pair as the last row. /// </summary> public void AddLast() { DateTime date = this.LastDate; if ( this.CountDates > 0 ) { date = date.AddDays( this.Steps.NextStep ); } this.dates.Add( date ); this.tasks.Add( new Task( this.CountDates + 1 ) ); this.NeedsSaving = true; } /// <summary> /// Modify the specified the date/task at the given row number. /// </summary> /// <param name="rowNumber">The row number to modify.</param> /// <param name="date">A <see cref="DateTime"/>.</param> /// <param name="task">A <see cref="Task"/>.</param> public void Modify(int rowNumber, DateTime date, Task task) { this.dates[ rowNumber ] = date; this.tasks[ rowNumber ] = task; this.NeedsSaving = true; } /// <summary> /// Inserts a new date/task pair before the given position. /// </summary> /// <param name="i">The index of the position to insert in.</param> public void InsertRow(int i) { this.tasks.Insert( i, new Task( i + 1 ) ); this.dates.Insert( i, this.dates[ i ] ); this.NeedsSaving = true; } /// <summary> /// Inserts a <see cref="Task"/> with the default values. /// </summary> /// <param name="i">The index of the position to insert in.</param> /// <seealso cref="M:InsertTask"/> public void InsertTask(int i) { this.InsertTask( i, new Task( i + 1 ) ); } /// <summary> /// Inserts the task with the given value. /// Adds a new date at the end of dates, /// so both lists are kept of equal length. /// </summary> /// <param name="i">The index.</param> /// <param name="task">The <see cref="Task"/>.</param> public void InsertTask(int i, Task task) { this.tasks.Insert( i, task ); this.dates.Add( this.LastDate.AddDays( this.Steps.NextStep ) ); this.NeedsSaving = true; } /// <summary> /// Inserts a date, honoring the steps. /// A new task (with default contents) is added at the end of tasks, /// so both lists are kept of equal length. /// </summary> /// <param name="rowNumber">The position to insert in.</param> /// <seealso cref="Task"/> public void InsertDate(int rowNumber) { int count = this.tasks.Count; // Insert this.dates.Insert( rowNumber, this.dates[ rowNumber ] ); this.tasks.Add( new Task( count + 1 ) ); this.NeedsSaving = true; } /// <summary> /// Removes the pair date/task at the specified position. /// </summary> /// <param name="i">The position to remove.</param> public void Remove(int i) { if ( this.CountDates > i ) { this.dates.RemoveAt( i ); this.tasks.RemoveAt( i ); } this.NeedsSaving = true; } /// <summary> /// Removes the task at a given position. /// A new task is added at the end of the tasks, /// so both lists are kept of equal length. /// </summary> /// <param name="i">The index.</param> public void RemoveTask(int i) { if ( this.CountDates > i ) { this.tasks.RemoveAt( i ); this.tasks.Add( new Task( this.CountDates ) ); } this.NeedsSaving = true; } /// <summary> /// Removes the date at a given position. /// A new date is added at the end of the dates, /// so both lists are kept of equal length. /// </summary> /// <param name="i">The index.</param> public void RemoveDate(int i) { if ( this.CountDates > i ) { this.dates.RemoveAt( i ); this.dates.Add( this.LastDate.AddDays( this.Steps.NextStep ) ); } this.NeedsSaving = true; } /// <summary> /// Goes to the first date/task entry. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.KeyValuePair"/> with date&amp;task. /// </returns> public Pair GotoFirst() { this.enumDates = this.dates.GetEnumerator(); this.enumTasks = this.tasks.GetEnumerator(); this.hasNext = true; return this.Next(); } /// <summary> /// Returns the current date/task entry. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.KeyValuePair"/> with date&amp;task. /// </returns> public Pair Next() { this.hasNext = ( this.enumDates.MoveNext() && this.enumTasks.MoveNext() ); return new KeyValuePair<DateTime, Task>( enumDates.Current, enumTasks.Current ); } /// <summary> /// Gets the last date in the list of dates /// </summary> public DateTime LastDate { get { DateTime toret = this.InitialDate; int numDates = this.CountDates; if ( numDates > 0 ) { toret = this.dates[ numDates - 1 ]; } return toret; } } /// <summary> /// Tells whether the end of the document has been reached. /// </summary> /// <returns><c>true</c>, if end was reached, <c>false</c> otherwise.</returns> /// <seealso cref="M:Document.Next"/> /// <seealso cref="M:Document.GotoFirst"/> public bool IsEnd() { return !this.hasNext; } /// <summary> /// Gets the number of stored dates. /// </summary> /// <value>The count of dates.</value> public int CountDates { get { return this.dates.Count; } } /// <summary> /// Gets the number of stored tasks. /// </summary> /// <value>The count of tasks.</value> public int CountTasks { get { return this.tasks.Count; } } /// <summary> /// Gets the date at the given position. /// </summary> /// <returns>A <see cref="System.DateTime"/>.</returns> /// <param name="i">The index.</param> public DateTime GetDate(int i) { return this.dates[ i ]; } /// <summary> /// Gets the task at the given position. /// </summary> /// <returns>The task.</returns> /// <param name="i">The index.</param> public Task GetTask(int i) { return this.tasks[ i ]; } /// <summary> /// Recalculates dates after changing initial date or steps. /// </summary> public void Recalculate() { DateTime currentDate = this.InitialDate; this.Steps.GotoFirstStep(); int currentStep = this.Steps.NextStep; for (int i = 0; i < this.dates.Count; ++i) { this.dates[ i ] = currentDate; currentDate = currentDate.AddDays( currentStep ); currentStep = this.Steps.NextStep; } this.NeedsSaving = true; } /// <summary> /// Gets all dates. /// </summary> /// <value>The dates, as a <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection"/>.</value> public ReadOnlyCollection<DateTime> Dates { get { return new ReadOnlyCollection<DateTime>( this.dates.ToArray() ); } } /// <summary> /// Gets all tasks. /// </summary> /// <value>The tasks, as a <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection"/>.</value> public ReadOnlyCollection<Task> Tasks { get { return new ReadOnlyCollection<Task>( this.tasks.ToArray() ); } } /// <summary> /// Gets or sets the name of the file for this planning document. /// </summary> /// <value>The name of the file.</value> public string FileName { get; set; } /// <summary> /// Gets a value indicating whether /// this <see cref="T:Bareplan.Core.Document"/> has a file name. /// </summary> /// <value><c>true</c> if has name; otherwise, <c>false</c>.</value> public bool HasName { get { return ( this.FileName.Length > 0 ); } } /// <summary> /// Gets or sets the initial date. /// </summary> /// <value>The initial date, as a <see cref="T:System.DateTime"/>.</value> public DateTime InitialDate { get { return this.initialDate; } set { if ( this.initialDate != value ) { this.initialDate = value; this.Recalculate(); this.NeedsSaving = true; } } } /// <summary> /// Gets the steps for creating new date/task pairs. /// A step is an amout in days. /// </summary> /// <value>The <see cref="Steps"/>.</value> public Steps Steps { get; private set; } /// <summary> /// Looks for tasks in the given date. /// </summary> /// <returns>A vector with the positions of the tasks.</returns> /// <param name="date">A DateTime object, containing the date to look for.</param> public int[] LookForTasksIn(DateTime date) { var toret = new List<int>(); int pos = 0; System.Console.WriteLine("-- Looking for: " + date); while( pos < this.dates.Count ) { System.Console.WriteLine("Considering " + this.dates[pos]); // There are no more possible matching dates (they are sorted). if ( this.dates[ pos ] > date ) { break; } if ( this.dates[ pos ] == date ) { toret.Add( pos ); } ++pos; } return toret.ToArray(); } /// <summary> /// Gets a value indicating whether this <see cref="T:Bareplan.Core.Document"/> needs saving. /// </summary> /// <value><c>true</c> if needs saving; otherwise, <c>false</c>.</value> public bool NeedsSaving { get; internal set; } List<DateTime> dates; List<Task> tasks; List<DateTime>.Enumerator enumDates; List<Task>.Enumerator enumTasks; bool hasNext; DateTime initialDate; } }
///////////////////////////////////////////////////////////////////////////////// // // vp_FPBodyAnimator.cs // ?VisionPunk. All Rights Reserved. // https://twitter.com/VisionPunk // http://www.visionpunk.com // // description: this script animates a human character model that needs to // move around and use guns a lot! it is designed for use with // the provided 'UFPSExampleAnimator' and can be used in 1st // and 3rd person, for local, remote or AI players. // // this is the FIRST PERSON version of the script, intended for // use on a local, first person player only (!). it has special // logic to replace materials of the head, arms and rest of // the body between an invisible-but-shadow-casting material, // and their default materials. the script also performs special // position adjustment logic to make the body work well with // spring-based vp_FPCamera motions without having the camera // clipping the local character's body model. // // PLEASE NOTE: // 1) this script is intended for desktop platforms and // is not designed for mobile or VR platforms (!) // 2) IMPORTANT: in order to use this system as intended, you // need to split up the local player's body model so that // it has three materials: one for the body, one for the // head and one material for the arms. for more info, see // this manual chapter: // http://bit.ly/1rtfJC6 // 3) for information on the animation features, see the // comments in the base class, 'vp_BodyAnimator' // ///////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Collections; using System.Collections.Generic; public class vp_FPBodyAnimator : vp_BodyAnimator { // required components protected vp_FPController m_FPController = null; protected vp_FPCamera m_FPCamera = null; // camera public Vector3 EyeOffset = new Vector3(0, -0.08f, -0.1f); // tweak this for the best camera position, esp. when looking down protected bool m_WasFirstPersonLastFrame = false; protected float m_DefaultCamHeight = 0.0f; // lookdown public float LookDownZoomFactor = 15.0f; // can be used to adjust the appearance of the body when looking down protected float LookDownForwardOffset = 0.05f; // materials public bool ShowUnarmedArms = true; // when active, this will display the body model's arms if no weapon is wielded public Material InvisibleMaterial = null; // this should be set to an invisible, shadow casting material. see the included 'InvisibleShadowCaster' shader & material protected Material[] m_FirstPersonMaterials; protected Material[] m_FirstPersonWithArmsMaterials; protected Material[] m_ThirdPersonMaterials; protected Material[] m_InvisiblePersonMaterials; // --- properties --- public vp_FPCamera FPCamera { get { if (m_FPCamera == null) m_FPCamera = transform.root.GetComponentInChildren<vp_FPCamera>(); return m_FPCamera; } } public vp_FPController FPController { get { if (m_FPController == null) m_FPController = transform.root.GetComponent<vp_FPController>(); return m_FPController; } } vp_FPWeaponShooter m_CurrentShooter = null; public vp_FPWeaponShooter CurrentShooter { get { if ((m_CurrentShooter == null) || ((m_CurrentShooter != null) && ((!m_CurrentShooter.enabled) || (!vp_Utility.IsActive(m_CurrentShooter.gameObject))))) { if ((WeaponHandler != null) && (WeaponHandler.CurrentWeapon != null)) m_CurrentShooter = WeaponHandler.CurrentWeapon.GetComponentInChildren<vp_FPWeaponShooter>(); } return m_CurrentShooter; } } protected float DefaultCamHeight { get { if (m_DefaultCamHeight == 0.0f) { // attempt to fetch Y position from the camera's default state if (FPCamera != null && FPCamera.DefaultState != null && FPCamera.DefaultState.Preset != null) m_DefaultCamHeight = ((Vector3)FPCamera.DefaultState.Preset.GetFieldValue("PositionOffset")).y; else m_DefaultCamHeight = 1.75f; // default on fail } return m_DefaultCamHeight; } } /// <summary> /// /// </summary> protected override void Awake() { #if UNITY_IPHONE || UNITY_ANDROID Debug.LogError("Error (" + this + ") This script from base UFPS is intended for desktop and not supported on mobile. Are you attempting to use a PC/Mac player prefab on IOS/Android?"); Component.DestroyImmediate(this); return; #endif base.Awake(); InitMaterials(); m_WasFirstPersonLastFrame = Player.IsFirstPerson.Get(); // prevent camera from doing its own collision. (we'll do it // from this script's 'UpdateCamera' method instead) FPCamera.HasCollision = false; Player.IsFirstPerson.Set(true); } /// <summary> /// /// </summary> protected override void OnEnable() { base.OnEnable(); RefreshMaterials(); } /// <summary> /// /// </summary> protected override void OnDisable() { base.OnDisable(); } /// <summary> /// /// </summary> protected override void LateUpdate() { base.LateUpdate(); if (Time.timeScale == 0.0f) return; if (Player.IsFirstPerson.Get()) { UpdatePosition(); UpdateCameraPosition(); UpdateCameraRotation(); UpdateCameraCollision(); } else { FPCamera.DoCameraCollision(); } UpdateFirePosition(); } /// <summary> /// swaps out the body model's material array depending on current /// gameplay situation, at the end of the frame to give other /// logics time to finish (e.g. 'Player.IsFirstPerson.Set') /// </summary> public void RefreshMaterials() { StartCoroutine(RefreshMaterialsOnEndOfFrame()); } /// <summary> /// swaps out the body model's material array at the end of the /// frame. must be called using 'RefreshMaterials' /// </summary> protected IEnumerator RefreshMaterialsOnEndOfFrame() { yield return new WaitForEndOfFrame(); if (InvisibleMaterial == null) { Debug.LogWarning("Warning (" + this + ") No invisible material has been set. Head and arms will look buggy in first person."); goto fail; } if (!Player.IsFirstPerson.Get()) { if (m_ThirdPersonMaterials != null) Renderer.materials = m_ThirdPersonMaterials; // all body parts visible } else { if (!Player.Dead.Active && !Player.Climb.Active) // player is alive and not climbing { // if we can show unarmed arms, and player is unarmed and not climbing if (ShowUnarmedArms && ((Player.CurrentWeaponIndex.Get() < 1) && !Player.Climb.Active)) { if (m_FirstPersonWithArmsMaterials != null) Renderer.materials = m_FirstPersonWithArmsMaterials; // only head is invisible } // player is armed, climbing, or prohibited to show naked arms :) else { if (m_FirstPersonMaterials != null) Renderer.materials = m_FirstPersonMaterials; // head & arms are invisible } } else // player is dead ... { if (m_InvisiblePersonMaterials != null) Renderer.materials = m_InvisiblePersonMaterials; // all bodyparts invisible in order not to clip camera on ragdoll } } fail: {} } /// <summary> /// forces model position to bottom center of character controller /// and applies user defined camera offset /// </summary> protected override void UpdatePosition() { // fix body model position to the charactercontroller Transform.position = FPController.SmoothPosition + (FPController.SkinWidth * Vector3.down); if (Player.IsFirstPerson.Get() && !Player.Climb.Active) { // in 1st person, make camera spring physics wear off the more we look // at our feet, and have the springs take over the more we look forward // NOTE: when looking forward, the headless dude's feet will be dangling // mid-air, and will clip the ground when jumping. however, these issues // are only noticeable in editor scene view and not in 1st person! if ((m_HeadLookBones != null) && (m_HeadLookBones.Count > 0)) { Transform.position = Vector3.Lerp(Transform.position, // blend between model position ... Transform.position + (FPCamera.Transform.position - m_HeadLookBones[0].transform.position), // ... and camera spring position ... Mathf.Lerp(1, 0, Mathf.Max(0.0f, ((Player.Rotation.Get().x) / 60.0f)))); // ... by lookdown factor } else Debug.LogWarning("Warning (" + this + ") No headlookbones have been assigned!"); } else { // in 3rd person, keep the XY position as-is, but zero out Z position // or we'll get some heavy stuttering when moving forward / backward Transform.localPosition = Vector3.Scale(Transform.localPosition, (Vector3.right + Vector3.up)); } if (Player.Climb.Active) Transform.localPosition += ClimbOffset; } /// <summary> /// performs special position adjustment logic to make the /// body work well with spring-based vp_FPCamera motions /// without having the camera clipping the local character's /// body model. /// </summary> protected virtual void UpdateCameraPosition() { // nail camera to neck FPCamera.transform.position = m_HeadLookBones[0].transform.position; float lookDown = Mathf.Max(0.0f, ((Player.Rotation.Get().x - 45) / 45.0f)); lookDown = Mathf.SmoothStep(0, 1, lookDown); FPCamera.transform.localPosition = new Vector3( FPCamera.transform.localPosition.x, FPCamera.transform.localPosition.y, FPCamera.transform.localPosition.z + lookDown * (Player.Crouch.Active ? 0.0f : LookDownForwardOffset) ); // apply user-adjusted 'eye position' to camera FPCamera.Transform.localPosition -= EyeOffset; // update camera zoom FPCamera.ZoomOffset = (-LookDownZoomFactor * lookDown); FPCamera.RefreshZoom(); } /// <summary> /// adjusts the camera if attacking with a melee weapon during lookdown, in /// order to prevent stabbing ourselves in the gut :) /// </summary> protected virtual void UpdateCameraRotation() { if ((Player.CurrentWeaponType.Get() == (int)vp_Weapon.Type.Melee) && Player.Attack.Active) { if (Player.Rotation.Get().x > 65) Player.Rotation.Set(new Vector2(65, Player.Rotation.Get().y)); return; } } /// <summary> /// runs the collision check for the camera and reacts to collisions /// by moving the body (but not the controller) away from collision /// surfaces by the same distance as the camera /// </summary> protected virtual void UpdateCameraCollision() { FPCamera.DoCameraCollision(); if (FPCamera.CollisionVector != Vector3.zero) Transform.position += FPCamera.CollisionVector; } /// <summary> /// /// </summary> protected override void UpdateGrounding() { m_Grounded = FPController.Grounded; } /// <summary> /// (for 3rd person) shows a yellow line indicating the look direction, /// and a red ball indicating the current look point /// </summary> protected override void UpdateDebugInfo() { if (ShowDebugObjects) { DebugLookTarget.transform.position = FPCamera.LookPoint; DebugLookArrow.transform.LookAt(DebugLookTarget.transform.position); if (!vp_Utility.IsActive(m_DebugLookTarget)) vp_Utility.Activate(m_DebugLookTarget); if (!vp_Utility.IsActive(m_DebugLookArrow)) vp_Utility.Activate(m_DebugLookArrow); } else { if (m_DebugLookTarget != null) vp_Utility.Activate(m_DebugLookTarget, false); if (m_DebugLookArrow != null) vp_Utility.Activate(m_DebugLookArrow, false); } } /// <summary> /// refreshes shooter fire position last in update, to make sure /// it's always in the last known center of 'ProjectileSpawnPoint' /// over the duration of the upcoming update /// </summary> protected void UpdateFirePosition() { if (CurrentShooter == null) return; if (CurrentShooter.ProjectileSpawnPoint == null) return; CurrentShooter.FirePosition = CurrentShooter.ProjectileSpawnPoint.transform.position; } /// <summary> /// caches the materials on the model on Awake. the materials /// are sorted into four arrays to be swapped off and onto the /// model at runtime depending on the current gameplay situation. /// NOTE: the initialization looks for material names containing /// the words "head" and "arm" /// </summary> protected virtual void InitMaterials() { if (InvisibleMaterial == null) { Debug.LogWarning("Warning (" + ") No invisible material has been set."); return; } m_FirstPersonMaterials = new Material[Renderer.materials.Length]; m_FirstPersonWithArmsMaterials = new Material[Renderer.materials.Length]; m_ThirdPersonMaterials = new Material[Renderer.materials.Length]; m_InvisiblePersonMaterials = new Material[Renderer.materials.Length]; for (int v = 0; v < Renderer.materials.Length; v++) { // create 4 material arrays from the provided one ... // ... one with visible materials on all body parts (for 3rd person) m_ThirdPersonMaterials[v] = Renderer.materials[v]; // ... one with invisible head and arm materials (for classic 1st person) if (Renderer.materials[v].name.ToLower().Contains("head") || Renderer.materials[v].name.ToLower().Contains("arm")) m_FirstPersonMaterials[v] = InvisibleMaterial; else m_FirstPersonMaterials[v] = Renderer.materials[v]; // ... one with an invisible head but visible arms (for unarmed 1st person and VR mods) if (Renderer.materials[v].name.ToLower().Contains("head")) m_FirstPersonWithArmsMaterials[v] = InvisibleMaterial; else m_FirstPersonWithArmsMaterials[v] = Renderer.materials[v]; // ... and one array with all-invisible materials (for ragdolled 1st person) m_InvisiblePersonMaterials[v] = InvisibleMaterial; } RefreshMaterials(); } /// <summary> /// this is a method rather than a property to allow overriding /// </summary> protected override bool GetIsMoving() { return (Vector3.Scale(Player.MotorThrottle.Get(), (Vector3.right + Vector3.forward))).magnitude > 0.01f; } /// <summary> /// /// </summary> protected override Vector3 GetLookPoint() { return FPCamera.LookPoint; } /// <summary> /// /// </summary> protected override Vector3 OnValue_LookPoint { get { return GetLookPoint(); } } /// <summary> /// /// </summary> protected override void OnMessage_CameraToggle3rdPerson() { base.OnMessage_CameraToggle3rdPerson(); RefreshMaterials(); } /// <summary> /// /// </summary> protected virtual void OnStop_SetWeapon() { RefreshMaterials(); } /// <summary> /// /// </summary> protected override void OnStart_Climb() { base.OnStart_Climb(); RefreshMaterials(); } /// <summary> /// /// </summary> protected virtual void OnStop_Climb() { RefreshMaterials(); } /// <summary> /// /// </summary> protected override void OnStart_Dead() { base.OnStart_Dead(); RefreshMaterials(); } }
// 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.Collections.Generic; using System.Web.UI; using System.Web.UI.WebControls; using WebsitePanel.Providers.HostedSolution; using System.Linq; using WebsitePanel.Providers.Web; using WebsitePanel.EnterpriseServer.Base.HostedSolution; using WebsitePanel.Providers.RemoteDesktopServices; namespace WebsitePanel.Portal.RDS.UserControls { public partial class RDSCollectionApps : WebsitePanelControlBase { public const string DirectionString = "DirectionString"; protected enum SelectedState { All, Selected, Unselected } public void SetApps(RemoteApplication[] apps) { BindApps(apps, false); } public void SetApps(RemoteApplication[] apps, WebPortal.PageModule module) { Module = module; BindApps(apps, false); } public RemoteApplication[] GetApps() { return GetGridViewApps(SelectedState.All).ToArray(); } protected void Page_Load(object sender, EventArgs e) { // register javascript if (!Page.ClientScript.IsClientScriptBlockRegistered("SelectAllCheckboxes")) { string script = @" function SelectAllCheckboxes(box) { var state = box.checked; var elm = box.parentElement.parentElement.parentElement.parentElement.getElementsByTagName(""INPUT""); for(i = 0; i < elm.length; i++) if(elm[i].type == ""checkbox"" && elm[i].id != box.id && elm[i].checked != state && !elm[i].disabled) elm[i].checked = state; }"; Page.ClientScript.RegisterClientScriptBlock(typeof(RDSCollectionUsers), "SelectAllCheckboxes", script, true); } } protected void btnAdd_Click(object sender, EventArgs e) { // bind all servers BindPopupApps(); // show modal AddAppsModal.Show(); } protected void btnDelete_Click(object sender, EventArgs e) { List<RemoteApplication> selectedApps = GetGridViewApps(SelectedState.Unselected); BindApps(selectedApps.ToArray(), false); } protected void btnAddSelected_Click(object sender, EventArgs e) { List<RemoteApplication> selectedApps = GetPopUpGridViewApps(); BindApps(selectedApps.ToArray(), true); } protected void BindPopupApps() { RdsCollection collection = ES.Services.RDS.GetRdsCollection(PanelRequest.CollectionID); List<StartMenuApp> apps = ES.Services.RDS.GetAvailableRemoteApplications(PanelRequest.ItemID, collection.Name).ToList(); var sessionHosts = ES.Services.RDS.GetRdsCollectionSessionHosts(PanelRequest.CollectionID); var addedApplications = GetApps(); var aliases = addedApplications.Select(p => p.Alias); apps = apps.Where(x => !aliases.Contains(x.Alias)).ToList(); if (Direction == SortDirection.Ascending) { apps = apps.OrderBy(a => a.DisplayName).ToList(); Direction = SortDirection.Descending; } else { apps = apps.OrderByDescending(a => a.DisplayName).ToList(); Direction = SortDirection.Ascending; } var requiredParams = addedApplications.Select(a => a.RequiredCommandLine.ToLower()); foreach (var host in sessionHosts) { if (!requiredParams.Contains(string.Format("/v:{0}", host.ToLower()))) { var fullRemote = new StartMenuApp { DisplayName = string.Format("Full Desktop - {0}", host.ToLower()), FilePath = "c:\\windows\\system32\\mstsc.exe", RequiredCommandLine = string.Format("/v:{0}", host.ToLower()) }; var sessionHost = collection.Servers.Where(s => s.FqdName.Equals(host, StringComparison.CurrentCultureIgnoreCase)).First(); if (sessionHost != null) { fullRemote.DisplayName = string.Format("Full Desktop - {0}", sessionHost.Name.ToLower()); } fullRemote.Alias = fullRemote.DisplayName.Replace(" ", ""); if (apps.Count > 0) { apps.Insert(0, fullRemote); } else { apps.Add(fullRemote); } } } gvPopupApps.DataSource = apps; gvPopupApps.DataBind(); } protected void BindApps(RemoteApplication[] newApps, bool preserveExisting) { // get binded addresses List<RemoteApplication> apps = new List<RemoteApplication>(); if(preserveExisting) apps.AddRange(GetGridViewApps(SelectedState.All)); // add new servers if (newApps != null) { foreach (RemoteApplication newApp in newApps) { // check if exists bool exists = false; foreach (RemoteApplication app in apps) { if (app.DisplayName == newApp.DisplayName) { exists = true; break; } } if (exists) continue; apps.Add(newApp); } } gvApps.DataSource = apps; gvApps.DataBind(); } protected List<RemoteApplication> GetGridViewApps(SelectedState state) { List<RemoteApplication> apps = new List<RemoteApplication>(); for (int i = 0; i < gvApps.Rows.Count; i++) { GridViewRow row = gvApps.Rows[i]; CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect"); if (chkSelect == null) continue; RemoteApplication app = new RemoteApplication(); app.Alias = (string)gvApps.DataKeys[i][0]; app.DisplayName = ((LinkButton)row.FindControl("lnkDisplayName")).Text; app.FilePath = ((HiddenField)row.FindControl("hfFilePath")).Value; app.RequiredCommandLine = ((HiddenField)row.FindControl("hfRequiredCommandLine")).Value; var users = ((HiddenField)row.FindControl("hfUsers")).Value; if (!string.IsNullOrEmpty(users)) { app.Users = new string[]{"New"}; } if (state == SelectedState.All || (state == SelectedState.Selected && chkSelect.Checked) || (state == SelectedState.Unselected && !chkSelect.Checked)) apps.Add(app); } return apps; } protected List<RemoteApplication> GetPopUpGridViewApps() { List<RemoteApplication> apps = new List<RemoteApplication>(); for (int i = 0; i < gvPopupApps.Rows.Count; i++) { GridViewRow row = gvPopupApps.Rows[i]; CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect"); if (chkSelect == null) continue; if (chkSelect.Checked) { apps.Add(new RemoteApplication { Alias = (string)gvPopupApps.DataKeys[i][0], DisplayName = ((Literal)row.FindControl("litName")).Text, FilePath = ((HiddenField)row.FindControl("hfFilePathPopup")).Value, RequiredCommandLine = ((HiddenField)row.FindControl("hfRequiredCommandLinePopup")).Value }); } } return apps; } protected void cmdSearch_Click(object sender, ImageClickEventArgs e) { BindPopupApps(); } protected void gvApps_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "EditApplication") { Response.Redirect(GetCollectionUsersEditUrl(e.CommandArgument.ToString())); } } protected SortDirection Direction { get { return ViewState[DirectionString] == null ? SortDirection.Descending : (SortDirection)ViewState[DirectionString]; } set { ViewState[DirectionString] = value; } } protected static int CompareAccount(StartMenuApp app1, StartMenuApp app2) { return string.Compare(app1.DisplayName, app2.DisplayName); } public string GetCollectionUsersEditUrl(string appId) { return EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "rds_application_edit_users", "CollectionId=" + PanelRequest.CollectionID, "ItemID=" + PanelRequest.ItemID, "ApplicationID=" + appId); } } }
using SparklrLib.Objects; using SparklrWP.Utils; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading; using System.Windows; namespace SparklrWP { public sealed class MainViewModel : INotifyPropertyChanged, IDisposable { /// <summary> /// The streamUpdater starts stream updates every 10 seconds. /// </summary> Timer streamUpdater; Comparison<ItemViewModel> itemComparison = new Comparison<ItemViewModel>( (p, q) => { if (p.OrderTime > q.OrderTime) return 1; else if (p.OrderTime < q.OrderTime) return -1; else return 0; } ); public MainViewModel() { this.Items = new ObservableCollectionWithItemNotification<ItemViewModel>(); _friends = new ObservableCollection<FriendViewModel>(); GroupedItems = _friends.GroupFriends(); streamUpdater = new Timer(streamUpdater_Tick, null, Timeout.Infinite, Timeout.Infinite); //We do not start the updater here. It will be started by the callback of the reponse //Warning: Possible issue where a internet conenction is not stable loadData(); loadFriends(); } /// <summary> /// Occures when the streamUpdater elapses /// </summary> /// <param name="state"></param> void streamUpdater_Tick(object state) { //The streamUpdater is stopped in loadData to prevent multiple requests loadData(); } private ObservableCollectionWithItemNotification<ItemViewModel> _items; /// <summary> /// A collection for ItemViewModel objects. /// </summary> public ObservableCollectionWithItemNotification<ItemViewModel> Items { get { return _items; } private set { if (_items != value) { _items = value; Deployment.Current.Dispatcher.BeginInvoke(() => { NotifyPropertyChanged("Items"); }); } } } public void Update() { this.loadData(true); } public bool IsDataLoaded { get; private set; } public int LastTime = 0; /// <summary> /// Creates and adds a few ItemViewModel objects into the Items collection. /// </summary> /// <param name="stopTimer">Indicates if the internal timer should be stopped</param> private async void loadData(bool stopTimer = true) { //Stop the updater, to prevent multiple requests if (stopTimer) streamUpdater.Change(Timeout.Infinite, Timeout.Infinite); GlobalLoading.Instance.IsLoading = true; JSONRequestEventArgs<SparklrLib.Objects.Responses.Beacon.Stream> args = await App.Client.GetBeaconStreamAsync(LastTime); await import(args); GlobalLoading.Instance.IsLoading = false; streamUpdater.Change(10000, Timeout.Infinite); } private async System.Threading.Tasks.Task import(JSONRequestEventArgs<SparklrLib.Objects.Responses.Beacon.Stream> args) { if (args.IsSuccessful) { SparklrLib.Objects.Responses.Beacon.Stream stream = args.Object; if (stream != null && stream.data != null) { if (stream.notifications != null) { NewCount = stream.notifications.Count; Notifications.Clear(); foreach (SparklrLib.Objects.Responses.Beacon.Notification n in stream.notifications) { Notifications.Add(new NotificationViewModel(n.id) { Message = n.body, From = n.from }); } } int count = stream.data.length; List<ItemViewModel> newItems = new List<ItemViewModel>(Items); foreach (var t in stream.data.timeline) { if (LastTime < t.time) { LastTime = t.time; } if (LastTime < t.modified) { LastTime = t.modified; } ItemViewModel existingitem = null; existingitem = (from i in newItems where i.Id == t.id select i).FirstOrDefault(); if (existingitem == null) { ItemViewModel newItem = new ItemViewModel(t.id) { Message = t.message, CommentCount = (t.commentcount == null ? 0 : (int)t.commentcount), From = t.from.ToString(), OrderTime = t.modified > t.time ? t.modified : t.time }; if (!String.IsNullOrEmpty(t.meta)) { newItem.ImageUrl = "http://d.sparklr.me/i/t" + t.meta; } JSONRequestEventArgs<SparklrLib.Objects.Responses.Work.Username[]> response = await App.Client.GetUsernamesAsync(new int[] { t.from }); if (response.IsSuccessful && response.Object[0] != null && !string.IsNullOrEmpty(response.Object[0].username)) newItem.From = response.Object[0].username; newItems.Add(newItem); } else { existingitem.Message = t.message; existingitem.CommentCount = (t.commentcount == null ? 0 : (int)t.commentcount); existingitem.From = t.from.ToString(); existingitem.OrderTime = t.modified > t.time ? t.modified : t.time; JSONRequestEventArgs<SparklrLib.Objects.Responses.Work.Username[]> response = await App.Client.GetUsernamesAsync(new int[] { t.from }); if (response.IsSuccessful && response.Object[0] != null && !string.IsNullOrEmpty(response.Object[0].username)) existingitem.From = response.Object[0].username; } } newItems.Sort(itemComparison); newItems.Reverse(); Items = new ObservableCollectionWithItemNotification<ItemViewModel>(newItems); this.IsDataLoaded = true; #if DEBUG foreach (ItemViewModel i in Items) { if (i.ImageUrl != null) App.logger.log(i.ImageUrl); } #endif } } } public async void LoadMore() { streamUpdater.Change(Timeout.Infinite, Timeout.Infinite); GlobalLoading.Instance.IsLoading = true; //TODO: Implement properly JSONRequestEventArgs<SparklrLib.Objects.Responses.Beacon.Stream> moreItems = await App.Client.GetMoreItems(LastTime); await import(moreItems); GlobalLoading.Instance.IsLoading = false; streamUpdater.Change(10000, Timeout.Infinite); } private async void loadFriends() { JSONRequestEventArgs<SparklrLib.Objects.Responses.Work.Friends> fargs = await App.Client.GetFriendsAsync(); if (fargs.IsSuccessful) { List<int> friends = new List<int>(); foreach (int id in fargs.Object.followers) { friends.Add(id); } foreach (int id in fargs.Object.following) { if (!friends.Contains(id)) friends.Add(id); } JSONRequestEventArgs<SparklrLib.Objects.Responses.Work.Username[]> uargs = await App.Client.GetUsernamesAsync(friends.ToArray()); foreach (int id in friends) { AddFriend(new FriendViewModel(id) { Name = App.Client.Usernames.ContainsKey(id) ? App.Client.Usernames[id] : "User " + id, Image = "http://d.sparklr.me/i/t" + id + ".jpg" }); } } } private ObservableCollection<FriendViewModel> _friends; public ObservableCollection<FriendViewModel> Friends { get { return new ObservableCollection<FriendViewModel>(_friends); } } ObservableCollection<GroupedObservableCollection<FriendViewModel>> _groupedItems; public ObservableCollection<GroupedObservableCollection<FriendViewModel>> GroupedItems { get { return _groupedItems; } set { if (_groupedItems != value) { _groupedItems = value; NotifyPropertyChanged("GroupedItems"); } } } private int _newCount = 0; public int NewCount { get { return _newCount; } set { if (value != _newCount) { _newCount = value; NotifyPropertyChanged("NewCount"); } } } private ObservableCollection<NotificationViewModel> _notifications = new ObservableCollection<NotificationViewModel>(); public ObservableCollection<NotificationViewModel> Notifications { get { return _notifications; } private set { if (_notifications != value) { _notifications = value; NotifyPropertyChanged("Notifications"); } } } public void AddFriend(FriendViewModel f) { _friends.Add(f); GroupedItems.AddFriend(f); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { //Dispose our disposable stuff if (streamUpdater != null) streamUpdater.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using Xunit; namespace DispatchProxyTests { public static class DispatchProxyTests { [Fact] public static void Create_Proxy_Derives_From_DispatchProxy_BaseType() { TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy); Assert.IsAssignableFrom<TestDispatchProxy>(proxy); } [Fact] public static void Create_Proxy_Implements_All_Interfaces() { TestType_IHelloAndGoodbyeService proxy = DispatchProxy.Create<TestType_IHelloAndGoodbyeService, TestDispatchProxy>(); Assert.NotNull(proxy); Type[] implementedInterfaces = typeof(TestType_IHelloAndGoodbyeService).GetTypeInfo().ImplementedInterfaces.ToArray(); foreach (Type t in implementedInterfaces) { Assert.IsAssignableFrom(t, proxy); } } [Fact] public static void Create_Proxy_Internal_Interface() { TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_InternalInterfaceService, TestDispatchProxy>(); Assert.NotNull(proxy); } [Fact] public static void Create_Proxy_Implements_Internal_Interfaces() { TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_PublicInterfaceService_Implements_Internal, TestDispatchProxy>(); Assert.NotNull(proxy); } [Fact] public static void Create_Same_Proxy_Type_And_Base_Type_Reuses_Same_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.IsType(proxy1.GetType(), proxy2); } [Fact] public static void Create_Proxy_Instances_Of_Same_Proxy_And_Base_Type_Are_Unique() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(object.ReferenceEquals(proxy1, proxy2), String.Format("First and second instance of proxy type {0} were the same instance", proxy1.GetType().Name)); } [Fact] public static void Create_Same_Proxy_Type_With_Different_BaseType_Uses_Different_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy2>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(proxy1.GetType() == proxy2.GetType(), String.Format("Proxy generated for base type {0} used same for base type {1}", typeof(TestDispatchProxy).Name, typeof(TestDispatchProxy).Name)); } [Fact] public static void Created_Proxy_With_Different_Proxy_Type_Use_Different_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IGoodbyeService proxy2 = DispatchProxy.Create<TestType_IGoodbyeService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(proxy1.GetType() == proxy2.GetType(), String.Format("Proxy generated for type {0} used same for type {1}", typeof(TestType_IHelloService).Name, typeof(TestType_IGoodbyeService).Name)); } [Fact] public static void Create_Using_Concrete_Proxy_Type_Throws_ArgumentException() { Assert.Throws<ArgumentException>("T", () => DispatchProxy.Create<TestType_ConcreteClass, TestDispatchProxy>()); } [Fact] public static void Create_Using_Sealed_BaseType_Throws_ArgumentException() { Assert.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Sealed_TestDispatchProxy>()); } [Fact] public static void Create_Using_Abstract_BaseType_Throws_ArgumentException() { Assert.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Abstract_TestDispatchProxy>()); } [Fact] public static void Create_Using_BaseType_Without_Default_Ctor_Throws_ArgumentException() { Assert.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, NoDefaultCtor_TestDispatchProxy>()); } [Fact] public static void Invoke_Receives_Correct_MethodInfo_And_Arguments() { bool wasInvoked = false; StringBuilder errorBuilder = new StringBuilder(); // This Func is called whenever we call a method on the proxy. // This is where we validate it received the correct arguments and methods Func<MethodInfo, object[], object> invokeCallback = (method, args) => { wasInvoked = true; if (method == null) { string error = String.Format("Proxy for {0} was called with null method", typeof(TestType_IHelloService).Name); errorBuilder.AppendLine(error); return null; } else { MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); if (expectedMethod != method) { string error = String.Format("Proxy for {0} was called with incorrect method. Expected = {1}, Actual = {2}", typeof(TestType_IHelloService).Name, expectedMethod, method); errorBuilder.AppendLine(error); return null; } } return "success"; }; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy); TestDispatchProxy dispatchProxy = proxy as TestDispatchProxy; Assert.NotNull(dispatchProxy); // Redirect Invoke to our own Func above dispatchProxy.CallOnInvoke = invokeCallback; // Calling this method now will invoke the Func above which validates correct method proxy.Hello("testInput"); Assert.True(wasInvoked, "The invoke method was not called"); Assert.True(errorBuilder.Length == 0, errorBuilder.ToString()); } [Fact] public static void Invoke_Receives_Correct_MethodInfo() { MethodInfo invokedMethod = null; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethod = method; return String.Empty; }; proxy.Hello("testInput"); MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethod != null && expectedMethod == invokedMethod, String.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod)); } [Fact] public static void Invoke_Receives_Correct_Arguments() { object[] actualArgs = null; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { actualArgs = args; return String.Empty; }; proxy.Hello("testInput"); object[] expectedArgs = new object[] { "testInput" }; Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length, String.Format("Invoked expected object[] of length {0} but actual was {1}", expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString()))); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(actualArgs[i]), String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], actualArgs[i])); } } [Fact] public static void Invoke_Returns_Correct_Value() { TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { return "testReturn"; }; string expectedResult = "testReturn"; string actualResult = proxy.Hello(expectedResult); Assert.Equal(expectedResult, actualResult); } [Fact] public static void Invoke_Multiple_Parameters_Receives_Correct_Arguments() { object[] invokedArgs = null; object[] expectedArgs = new object[] { (int)42, "testString", (double)5.0 }; TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedArgs = args; return 0.0; }; proxy.TestMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]); Assert.True(invokedArgs != null && invokedArgs.Length == expectedArgs.Length, String.Format("Expected {0} arguments but actual was {1}", expectedArgs.Length, invokedArgs == null ? "null" : invokedArgs.Length.ToString())); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(invokedArgs[i]), String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], invokedArgs[i])); } } [Fact] public static void Invoke_Multiple_Parameters_Via_Params_Receives_Correct_Arguments() { object[] actualArgs = null; object[] invokedArgs = null; object[] expectedArgs = new object[] { 42, "testString", 5.0 }; TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedArgs = args; return String.Empty; }; proxy.ParamsMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]); // All separate params should have become a single object[1] array Assert.True(invokedArgs != null && invokedArgs.Length == 1, String.Format("Expected single element object[] but actual was {0}", invokedArgs == null ? "null" : invokedArgs.Length.ToString())); // That object[1] should contain an object[3] containing the args actualArgs = invokedArgs[0] as object[]; Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length, String.Format("Invoked expected object[] of length {0} but actual was {1}", expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString()))); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(actualArgs[i]), String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], actualArgs[i])); } } [Fact] public static void Invoke_Void_Returning_Method_Accepts_Null_Return() { MethodInfo invokedMethod = null; TestType_IOneWay proxy = DispatchProxy.Create<TestType_IOneWay, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethod = method; return null; }; proxy.OneWay(); MethodInfo expectedMethod = typeof(TestType_IOneWay).GetTypeInfo().GetDeclaredMethod("OneWay"); Assert.True(invokedMethod != null && expectedMethod == invokedMethod, String.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod)); } [Fact] public static void Invoke_Same_Method_Multiple_Interfaces_Calls_Correct_Method() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IHelloService1And2 proxy = DispatchProxy.Create<TestType_IHelloService1And2, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; ((TestType_IHelloService)proxy).Hello("calling 1"); ((TestType_IHelloService2)proxy).Hello("calling 2"); Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been TestType_IHelloService.Hello but actual was {0}", invokedMethods[0])); expectedMethod = typeof(TestType_IHelloService2).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been TestType_IHelloService2.Hello but actual was {0}", invokedMethods[1])); } [Fact] public static void Invoke_Thrown_Exception_Rethrown_To_Caller() { Exception actualException = null; InvalidOperationException expectedException = new InvalidOperationException("testException"); TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { throw expectedException; }; try { proxy.Hello("testCall"); } catch (Exception e) { actualException = e; } Assert.Equal(expectedException, actualException); } [Fact] public static void Invoke_Property_Setter_And_Getter_Invokes_Correct_Methods() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; proxy.ReadWrite = "testValue"; string actualValue = proxy.ReadWrite; Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); PropertyInfo propertyInfo = typeof(TestType_IPropertyService).GetTypeInfo().GetDeclaredProperty("ReadWrite"); Assert.NotNull(propertyInfo); MethodInfo expectedMethod = propertyInfo.SetMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = propertyInfo.GetMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); Assert.Null(actualValue); } [Fact] public static void Proxy_Declares_Interface_Properties() { TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>(); PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("ReadWrite"); Assert.NotNull(propertyInfo); } [Fact] public static void Invoke_Event_Add_And_Remove_And_Raise_Invokes_Correct_Methods() { // C# cannot emit raise_Xxx method for the event, so we must use System.Reflection.Emit to generate such event. AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("EventBuilder"), AssemblyBuilderAccess.Run); ModuleBuilder modb = ab.DefineDynamicModule("mod"); TypeBuilder tb = modb.DefineType("TestType_IEventService", TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract); EventBuilder eb = tb.DefineEvent("AddRemoveRaise", EventAttributes.None, typeof(EventHandler)); eb.SetAddOnMethod(tb.DefineMethod("add_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) })); eb.SetRemoveOnMethod( tb.DefineMethod("remove_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) })); eb.SetRaiseMethod(tb.DefineMethod("raise_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventArgs) })); TypeInfo ieventServiceTypeInfo = tb.CreateTypeInfo(); List<MethodInfo> invokedMethods = new List<MethodInfo>(); object proxy = typeof(DispatchProxy) .GetRuntimeMethod("Create", Array.Empty<Type>()).MakeGenericMethod(ieventServiceTypeInfo.AsType(), typeof(TestDispatchProxy)) .Invoke(null, null); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; EventHandler handler = new EventHandler((sender, e) => {}); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "add_AddRemoveRaise").Invoke(proxy, new object[] { handler }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "raise_AddRemoveRaise").Invoke(proxy, new object[] { EventArgs.Empty }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "remove_AddRemoveRaise").Invoke(proxy, new object[] { handler }); Assert.True(invokedMethods.Count == 3, String.Format("Expected 3 method invocations but received {0}", invokedMethods.Count)); EventInfo eventInfo = ieventServiceTypeInfo.GetDeclaredEvent("AddRemoveRaise"); Assert.NotNull(eventInfo); MethodInfo expectedMethod = eventInfo.AddMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = eventInfo.RaiseMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); expectedMethod = eventInfo.RemoveMethod; Assert.True(invokedMethods[2] != null && expectedMethod == invokedMethods[2], String.Format("Third invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); } [Fact] public static void Proxy_Declares_Interface_Events() { TestType_IEventService proxy = DispatchProxy.Create<TestType_IEventService, TestDispatchProxy>(); EventInfo eventInfo = proxy.GetType().GetTypeInfo().GetDeclaredEvent("AddRemove"); Assert.NotNull(eventInfo); } [Fact] public static void Invoke_Indexer_Setter_And_Getter_Invokes_Correct_Methods() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; proxy["key"] = "testValue"; string actualValue = proxy["key"]; Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); PropertyInfo propertyInfo = typeof(TestType_IIndexerService).GetTypeInfo().GetDeclaredProperty("Item"); Assert.NotNull(propertyInfo); MethodInfo expectedMethod = propertyInfo.SetMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = propertyInfo.GetMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); Assert.Null(actualValue); } [Fact] public static void Proxy_Declares_Interface_Indexers() { TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>(); PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("Item"); Assert.NotNull(propertyInfo); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapAttributeSchema.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System.Collections; using System.IO; using System.Text; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { /// <summary> /// A specific a name form in the directory schema. /// The LdapNameFormSchema class represents the definition of a Name Form. It /// is used to discover or modify the allowed naming attributes for a particular /// object class. /// </summary> /// <seealso cref="LdapSchemaElement"> /// </seealso> /// <seealso cref="LdapSchema"> /// </seealso> public class LdapNameFormSchema : LdapSchemaElement { /// <summary> /// Returns the name of the object class which this name form applies to. /// </summary> /// <returns> /// The name of the object class. /// </returns> public virtual string ObjectClass { get { return objectClass; } } /// <summary> /// Returns the list of required naming attributes for an entry /// controlled by this name form. /// </summary> /// <returns> /// The list of required naming attributes. /// </returns> public virtual string[] RequiredNamingAttributes { get { return required; } } /// <summary> /// Returns the list of optional naming attributes for an entry /// controlled by this content rule. /// </summary> /// <returns> /// The list of the optional naming attributes. /// </returns> public virtual string[] OptionalNamingAttributes { get { return optional; } } private readonly string objectClass; private readonly string[] required; private readonly string[] optional; /// <summary> /// Constructs a name form for adding to or deleting from the schema. /// </summary> /// <param name="names"> /// The name(s) of the name form. /// </param> /// <param name="oid"> /// The unique object identifier of the name form - in /// dotted numerical format. /// </param> /// <param name="description"> /// An optional description of the name form. /// </param> /// <param name="obsolete"> /// True if the name form is obsolete. /// </param> /// <param name="objectClass"> /// The object to which this name form applies. /// This may be specified by either name or /// numeric oid. /// </param> /// <param name="required"> /// A list of the attributes that must be present /// in the RDN of an entry that this name form /// controls. These attributes may be specified by /// either name or numeric oid. /// </param> /// <param name="optional"> /// A list of the attributes that may be present /// in the RDN of an entry that this name form /// controls. These attributes may be specified by /// either name or numeric oid. /// </param> public LdapNameFormSchema(string[] names, string oid, string description, bool obsolete, string objectClass, string[] required, string[] optional) : base(LdapSchema.schemaTypeNames[LdapSchema.NAME_FORM]) { this.names = new string[names.Length]; names.CopyTo(this.names, 0); this.oid = oid; this.description = description; this.obsolete = obsolete; this.objectClass = objectClass; this.required = new string[required.Length]; required.CopyTo(this.required, 0); this.optional = new string[optional.Length]; optional.CopyTo(this.optional, 0); Value = formatString(); } /* } /** * Constructs a Name Form from the raw string value returned on a * schema query for nameForms. * * @param raw The raw string value returned on a schema * query for nameForms. */ public LdapNameFormSchema(string raw) : base(LdapSchema.schemaTypeNames[LdapSchema.NAME_FORM]) { obsolete = false; try { var parser = new SchemaParser(raw); if (parser.Names != null) { names = new string[parser.Names.Length]; parser.Names.CopyTo(names, 0); } if ((object) parser.ID != null) oid = new StringBuilder(parser.ID).ToString(); if ((object) parser.Description != null) description = new StringBuilder(parser.Description).ToString(); if (parser.Required != null) { required = new string[parser.Required.Length]; parser.Required.CopyTo(required, 0); } if (parser.Optional != null) { optional = new string[parser.Optional.Length]; parser.Optional.CopyTo(optional, 0); } if ((object) parser.ObjectClass != null) objectClass = parser.ObjectClass; obsolete = parser.Obsolete; var qualifiers = parser.Qualifiers; AttributeQualifier attrQualifier; while (qualifiers.MoveNext()) { attrQualifier = (AttributeQualifier) qualifiers.Current; setQualifier(attrQualifier.Name, attrQualifier.Values); } Value = formatString(); } catch (IOException ex) { Logger.Log.LogWarning("Exception swallowed", ex); } } /// <summary> /// Returns a string in a format suitable for directly adding to a /// directory, as a value of the particular schema element class. /// </summary> /// <returns> /// A string representation of the class' definition. /// </returns> protected internal override string formatString() { var valueBuffer = new StringBuilder("( "); string token; string[] strArray; if ((object) (token = ID) != null) { valueBuffer.Append(token); } strArray = Names; if (strArray != null) { valueBuffer.Append(" NAME "); if (strArray.Length == 1) { valueBuffer.Append("'" + strArray[0] + "'"); } else { valueBuffer.Append("( "); for (var i = 0; i < strArray.Length; i++) { valueBuffer.Append(" '" + strArray[i] + "'"); } valueBuffer.Append(" )"); } } if ((object) (token = Description) != null) { valueBuffer.Append(" DESC "); valueBuffer.Append("'" + token + "'"); } if (Obsolete) { valueBuffer.Append(" OBSOLETE"); } if ((object) (token = ObjectClass) != null) { valueBuffer.Append(" OC "); valueBuffer.Append("'" + token + "'"); } if ((strArray = RequiredNamingAttributes) != null) { valueBuffer.Append(" MUST "); if (strArray.Length > 1) valueBuffer.Append("( "); for (var i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" $ "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } if ((strArray = OptionalNamingAttributes) != null) { valueBuffer.Append(" MAY "); if (strArray.Length > 1) valueBuffer.Append("( "); for (var i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" $ "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } IEnumerator en; if ((en = QualifierNames) != null) { string qualName; string[] qualValue; while (en.MoveNext()) { qualName = (string) en.Current; valueBuffer.Append(" " + qualName + " "); if ((qualValue = getQualifier(qualName)) != null) { if (qualValue.Length > 1) valueBuffer.Append("( "); for (var i = 0; i < qualValue.Length; i++) { if (i > 0) valueBuffer.Append(" "); valueBuffer.Append("'" + qualValue[i] + "'"); } if (qualValue.Length > 1) valueBuffer.Append(" )"); } } } valueBuffer.Append(" )"); return valueBuffer.ToString(); } } }
using System; using System.Text; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Asn1 { public class DerBitString : DerStringBase { private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private readonly byte[] data; private readonly int padBits; /** * return the correct number of pad bits for a bit string defined in * a 32 bit constant */ static internal int GetPadBits( int bitString) { int val = 0; for (int i = 3; i >= 0; i--) { // // this may look a little odd, but if it isn't done like this pre jdk1.2 // JVM's break! // if (i != 0) { if ((bitString >> (i * 8)) != 0) { val = (bitString >> (i * 8)) & 0xFF; break; } } else { if (bitString != 0) { val = bitString & 0xFF; break; } } } if (val == 0) { return 7; } int bits = 1; while (((val <<= 1) & 0xFF) != 0) { bits++; } return 8 - bits; } /** * return the correct number of bytes for a bit string defined in * a 32 bit constant */ static internal byte[] GetBytes( int bitString) { int bytes = 4; for (int i = 3; i >= 1; i--) { if ((bitString & (0xFF << (i * 8))) != 0) { break; } bytes--; } byte[] result = new byte[bytes]; for (int i = 0; i < bytes; i++) { result[i] = (byte) ((bitString >> (i * 8)) & 0xFF); } return result; } /** * return a Bit string from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerBitString GetInstance( object obj) { if (obj == null || obj is DerBitString) { return (DerBitString) obj; } throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); } /** * return a Bit string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerBitString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerBitString) { return GetInstance(o); } return FromAsn1Octets(((Asn1OctetString)o).GetOctets()); } internal DerBitString( byte data, int padBits) { this.data = new byte[]{ data }; this.padBits = padBits; } /** * @param data the octets making up the bit string. * @param padBits the number of extra bits at the end of the string. */ public DerBitString( byte[] data, int padBits) { // TODO Deep copy? this.data = data; this.padBits = padBits; } public DerBitString( byte[] data) { // TODO Deep copy? this.data = data; } public DerBitString( Asn1Encodable obj) { this.data = obj.GetDerEncoded(); //this.padBits = 0; } public byte[] GetBytes() { return data; } public int PadBits { get { return padBits; } } /** * @return the value of the bit string as an int (truncating if necessary) */ public int IntValue { get { int value = 0; for (int i = 0; i != data.Length && i != 4; i++) { value |= (data[i] & 0xff) << (8 * i); } return value; } } internal override void Encode( DerOutputStream derOut) { byte[] bytes = new byte[GetBytes().Length + 1]; bytes[0] = (byte) PadBits; Array.Copy(GetBytes(), 0, bytes, 1, bytes.Length - 1); derOut.WriteEncoded(Asn1Tags.BitString, bytes); } protected override int Asn1GetHashCode() { return padBits.GetHashCode() ^ Arrays.GetHashCode(data); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerBitString other = asn1Object as DerBitString; if (other == null) return false; return this.padBits == other.padBits && Arrays.AreEqual(this.data, other.data); } public override string GetString() { StringBuilder buffer = new StringBuilder("#"); byte[] str = GetDerEncoded(); for (int i = 0; i != str.Length; i++) { uint ubyte = str[i]; buffer.Append(table[(ubyte >> 4) & 0xf]); buffer.Append(table[str[i] & 0xf]); } return buffer.ToString(); } internal static DerBitString FromAsn1Octets(byte[] octets) { if (octets.Length < 1) throw new ArgumentException("truncated BIT STRING detected"); int padBits = octets[0]; byte[] data = new byte[octets.Length - 1]; Array.Copy(octets, 1, data, 0, data.Length); return new DerBitString(data, padBits); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.Cx.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedFlowsClientTest { [xunit::FactAttribute] public void CreateFlowRequestObject() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateFlowRequest request = new CreateFlowRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Flow = new Flow(), LanguageCode = "language_code2f6c7160", }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.CreateFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.CreateFlow(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateFlowRequestObjectAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateFlowRequest request = new CreateFlowRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Flow = new Flow(), LanguageCode = "language_code2f6c7160", }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.CreateFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.CreateFlowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.CreateFlowAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateFlow() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateFlowRequest request = new CreateFlowRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Flow = new Flow(), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.CreateFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.CreateFlow(request.Parent, request.Flow); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateFlowAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateFlowRequest request = new CreateFlowRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Flow = new Flow(), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.CreateFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.CreateFlowAsync(request.Parent, request.Flow, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.CreateFlowAsync(request.Parent, request.Flow, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateFlowResourceNames() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateFlowRequest request = new CreateFlowRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Flow = new Flow(), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.CreateFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.CreateFlow(request.ParentAsAgentName, request.Flow); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateFlowResourceNamesAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateFlowRequest request = new CreateFlowRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Flow = new Flow(), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.CreateFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.CreateFlowAsync(request.ParentAsAgentName, request.Flow, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.CreateFlowAsync(request.ParentAsAgentName, request.Flow, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteFlowRequestObject() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteFlowRequest request = new DeleteFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); client.DeleteFlow(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteFlowRequestObjectAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteFlowRequest request = new DeleteFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); await client.DeleteFlowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteFlowAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteFlow() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteFlowRequest request = new DeleteFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); client.DeleteFlow(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteFlowAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteFlowRequest request = new DeleteFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); await client.DeleteFlowAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteFlowAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteFlowResourceNames() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteFlowRequest request = new DeleteFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); client.DeleteFlow(request.FlowName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteFlowResourceNamesAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteFlowRequest request = new DeleteFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); await client.DeleteFlowAsync(request.FlowName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteFlowAsync(request.FlowName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFlowRequestObject() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowRequest request = new GetFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "language_code2f6c7160", }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.GetFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.GetFlow(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFlowRequestObjectAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowRequest request = new GetFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "language_code2f6c7160", }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.GetFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.GetFlowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.GetFlowAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFlow() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowRequest request = new GetFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.GetFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.GetFlow(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFlowAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowRequest request = new GetFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.GetFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.GetFlowAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.GetFlowAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFlowResourceNames() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowRequest request = new GetFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.GetFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.GetFlow(request.FlowName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFlowResourceNamesAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowRequest request = new GetFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.GetFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.GetFlowAsync(request.FlowName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.GetFlowAsync(request.FlowName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateFlowRequestObject() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateFlowRequest request = new UpdateFlowRequest { Flow = new Flow(), UpdateMask = new wkt::FieldMask(), LanguageCode = "language_code2f6c7160", }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.UpdateFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.UpdateFlow(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateFlowRequestObjectAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateFlowRequest request = new UpdateFlowRequest { Flow = new Flow(), UpdateMask = new wkt::FieldMask(), LanguageCode = "language_code2f6c7160", }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.UpdateFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.UpdateFlowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.UpdateFlowAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateFlow() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateFlowRequest request = new UpdateFlowRequest { Flow = new Flow(), UpdateMask = new wkt::FieldMask(), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.UpdateFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow response = client.UpdateFlow(request.Flow, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateFlowAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateFlowRequest request = new UpdateFlowRequest { Flow = new Flow(), UpdateMask = new wkt::FieldMask(), }; Flow expectedResponse = new Flow { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", TransitionRoutes = { new TransitionRoute(), }, EventHandlers = { new EventHandler(), }, NluSettings = new NluSettings(), TransitionRouteGroupsAsTransitionRouteGroupNames = { TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }, }; mockGrpcClient.Setup(x => x.UpdateFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Flow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); Flow responseCallSettings = await client.UpdateFlowAsync(request.Flow, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Flow responseCancellationToken = await client.UpdateFlowAsync(request.Flow, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ValidateFlowRequestObject() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateFlowRequest request = new ValidateFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "language_code2f6c7160", }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.ValidateFlow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult response = client.ValidateFlow(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ValidateFlowRequestObjectAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateFlowRequest request = new ValidateFlowRequest { FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "language_code2f6c7160", }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.ValidateFlowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FlowValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult responseCallSettings = await client.ValidateFlowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FlowValidationResult responseCancellationToken = await client.ValidateFlowAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFlowValidationResultRequestObject() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowValidationResultRequest request = new GetFlowValidationResultRequest { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "language_code2f6c7160", }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFlowValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult response = client.GetFlowValidationResult(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFlowValidationResultRequestObjectAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowValidationResultRequest request = new GetFlowValidationResultRequest { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "language_code2f6c7160", }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFlowValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FlowValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult responseCallSettings = await client.GetFlowValidationResultAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FlowValidationResult responseCancellationToken = await client.GetFlowValidationResultAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFlowValidationResult() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowValidationResultRequest request = new GetFlowValidationResultRequest { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFlowValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult response = client.GetFlowValidationResult(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFlowValidationResultAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowValidationResultRequest request = new GetFlowValidationResultRequest { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFlowValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FlowValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult responseCallSettings = await client.GetFlowValidationResultAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FlowValidationResult responseCancellationToken = await client.GetFlowValidationResultAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFlowValidationResultResourceNames() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowValidationResultRequest request = new GetFlowValidationResultRequest { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFlowValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult response = client.GetFlowValidationResult(request.FlowValidationResultName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFlowValidationResultResourceNamesAsync() { moq::Mock<Flows.FlowsClient> mockGrpcClient = new moq::Mock<Flows.FlowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFlowValidationResultRequest request = new GetFlowValidationResultRequest { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), }; FlowValidationResult expectedResponse = new FlowValidationResult { FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), ValidationMessages = { new ValidationMessage(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetFlowValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FlowValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FlowsClient client = new FlowsClientImpl(mockGrpcClient.Object, null); FlowValidationResult responseCallSettings = await client.GetFlowValidationResultAsync(request.FlowValidationResultName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FlowValidationResult responseCancellationToken = await client.GetFlowValidationResultAsync(request.FlowValidationResultName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // Copyright (c) Microsoft. 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. // using System.Collections.Generic; using System.Net; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Hyak.Common.TransientFaultHandling; using Microsoft.Azure.Test; using Xunit; namespace ResourceGroups.Tests { public class LiveResourceTests : TestBase { const string WebResourceProviderVersion = "2014-04-01"; const string StoreResourceProviderVersion = "2014-04-01-preview"; string ResourceGroupLocation { get { return "South Central US"; } } public static ResourceIdentity CreateResourceIdentity(GenericResourceExtended resource) { string[] parts = resource.Type.Split('/'); return new ResourceIdentity { ResourceType = parts[1], ResourceProviderNamespace = parts[0], ResourceName = resource.Name, ResourceProviderApiVersion = WebResourceProviderVersion }; } public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler) { handler.IsPassThrough = true; return this.GetResourceManagementClient().WithHandler(handler); } public string GetWebsiteLocation(ResourceManagementClient client) { return ResourcesManagementTestUtilities.GetResourceLocation(client, "Microsoft.Web/sites"); } public string GetMySqlLocation(ResourceManagementClient client) { return ResourcesManagementTestUtilities.GetResourceLocation(client, "SuccessBricks.ClearDB/databases"); } [Fact] public void CleanupAllResources() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1)); var groups = client.ResourceGroups.List(null); foreach (var group in groups.ResourceGroups) { TracingAdapter.Information("Deleting resources for RG {0}", group.Name); var resources = client.Resources.List(new ResourceListParameters { ResourceGroupName = group.Name, ResourceType = "Microsoft.Web/sites" }); foreach (var resource in resources.Resources) { var response = client.Resources.Delete(group.Name, CreateResourceIdentity(resource)); } var groupResponse = client.ResourceGroups.BeginDeleting(group.Name); } } } [Fact] public void CreateResourceWithPlan() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(handler); string mySqlLocation = GetMySqlLocation(client); var groupIdentity = new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "SuccessBricks.ClearDB", ResourceType = "databases", ResourceProviderApiVersion = StoreResourceProviderVersion }; client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation }); var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, groupIdentity, new GenericResource { Location = mySqlLocation, Plan = new Plan {Name = "Free"}, Tags = new Dictionary<string, string> { { "provision_source", "RMS" } } } ); Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode); Assert.Equal(resourceName, createOrUpdateResult.Resource.Name); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, createOrUpdateResult.Resource.Location), string.Format("Resource location for resource '{0}' does not match expected location '{1}'", createOrUpdateResult.Resource.Location, mySqlLocation)); Assert.NotNull(createOrUpdateResult.Resource.Plan); Assert.Equal("Free", createOrUpdateResult.Resource.Plan.Name); var getResult = client.Resources.Get(groupName, groupIdentity); Assert.Equal(HttpStatusCode.OK, getResult.StatusCode); Assert.Equal(resourceName, getResult.Resource.Name); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, getResult.Resource.Location), string.Format("Resource location for resource '{0}' does not match expected location '{1}'", getResult.Resource.Location, mySqlLocation)); Assert.NotNull(getResult.Resource.Plan); Assert.Equal("Free", getResult.Resource.Plan.Name); } } [Fact] public void CreatedResourceIsAvailableInList() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(handler); string websiteLocation = "westus"; client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation }); var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }, new GenericResource { Location = websiteLocation, Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}", } ); Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode); Assert.NotNull(createOrUpdateResult.Resource.Id); Assert.Equal(resourceName, createOrUpdateResult.Resource.Name); Assert.Equal("Microsoft.Web/sites", createOrUpdateResult.Resource.Type); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, createOrUpdateResult.Resource.Location), string.Format("Resource location for website '{0}' does not match expected location '{1}'", createOrUpdateResult.Resource.Location, websiteLocation)); var listResult = client.Resources.List(new ResourceListParameters { ResourceGroupName = groupName }); Assert.Equal(1, listResult.Resources.Count); Assert.Equal(resourceName, listResult.Resources[0].Name); Assert.Equal("Microsoft.Web/sites", listResult.Resources[0].Type); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.Resources[0].Location), string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.Resources[0].Location, websiteLocation)); listResult = client.Resources.List(new ResourceListParameters { ResourceGroupName = groupName, Top = 10 }); Assert.Equal(1, listResult.Resources.Count); Assert.Equal(resourceName, listResult.Resources[0].Name); Assert.Equal("Microsoft.Web/sites", listResult.Resources[0].Type); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.Resources[0].Location), string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.Resources[0].Location, websiteLocation)); } } [Fact] public void CreatedResourceIsAvailableInListFilteredByTagName() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); string resourceNameNoTags = TestUtilities.GenerateName("csmr"); string tagName = TestUtilities.GenerateName("csmtn"); var client = GetResourceManagementClient(handler); string websiteLocation = "westus"; client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation }); client.Resources.CreateOrUpdate(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }, new GenericResource { Tags = new Dictionary<string, string> { { tagName, "" } }, Location = websiteLocation, Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}" } ); client.Resources.CreateOrUpdate(groupName, new ResourceIdentity { ResourceName = resourceNameNoTags, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }, new GenericResource { Location = websiteLocation, Properties = "{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}" } ); var listResult = client.Resources.List(new ResourceListParameters { ResourceGroupName = groupName, TagName = tagName }); Assert.Equal(1, listResult.Resources.Count); Assert.Equal(resourceName, listResult.Resources[0].Name); var getResult = client.Resources.Get(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }); Assert.Equal(resourceName, getResult.Resource.Name); Assert.True(getResult.Resource.Tags.Keys.Contains(tagName)); } } [Fact] public void CreatedResourceIsAvailableInListFilteredByTagNameAndValue() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); string resourceNameNoTags = TestUtilities.GenerateName("csmr"); string tagName = TestUtilities.GenerateName("csmtn"); string tagValue = TestUtilities.GenerateName("csmtv"); var client = GetResourceManagementClient(handler); string websiteLocation = "westus"; client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation }); client.Resources.CreateOrUpdate(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }, new GenericResource { Tags = new Dictionary<string, string> { { tagName, tagValue } }, Location = websiteLocation, Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}" } ); client.Resources.CreateOrUpdate(groupName, new ResourceIdentity { ResourceName = resourceNameNoTags, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }, new GenericResource { Location = websiteLocation, Properties = "{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}" } ); var listResult = client.Resources.List(new ResourceListParameters { ResourceGroupName = groupName, TagName = tagName, TagValue = tagValue }); Assert.Equal(1, listResult.Resources.Count); Assert.Equal(resourceName, listResult.Resources[0].Name); var getResult = client.Resources.Get(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }); Assert.Equal(resourceName, getResult.Resource.Name); Assert.True(getResult.Resource.Tags.Keys.Contains(tagName)); } } [Fact] public void CreatedAndDeleteResource() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(handler); client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1)); string location = "westus"; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location }); var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }, new GenericResource { Location = location, Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}" } ); Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode); var listResult = client.Resources.List(new ResourceListParameters { ResourceGroupName = groupName }); Assert.Equal(resourceName, listResult.Resources[0].Name); var deleteResult = client.Resources.Delete(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }); Assert.Equal(HttpStatusCode.OK, deleteResult.StatusCode); } } [Fact] public void CreatedAndListResource() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(handler); string location = "westus"; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location }); var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Microsoft.Web", ResourceType = "sites", ResourceProviderApiVersion = WebResourceProviderVersion }, new GenericResource { Location = location, Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } }, Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}" } ); Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode); var listResult = client.Resources.List(new ResourceListParameters { ResourceType = "Microsoft.Web/sites" }); Assert.NotEmpty(listResult.Resources); Assert.Equal(2, listResult.Resources[0].Tags.Count); } } } }
/* Copyright 2015-2018 Daniel Adrian Redondo Suarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using TWCore.Net.RPC; using TWCore.Net.RPC.Attributes; using TWCore.Net.RPC.Client; using TWCore.Net.RPC.Client.Transports.Default; using TWCore.Net.RPC.Server; using TWCore.Net.RPC.Server.Transports.Default; using TWCore.Serialization.NSerializer; using TWCore.Serialization.PWSerializer; using TWCore.Services; using TWCore.Threading; // ReSharper disable ArrangeTypeMemberModifiers // ReSharper disable InconsistentNaming // ReSharper disable FieldCanBeMadeReadOnly.Local // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnusedMember.Global // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable EventNeverSubscribedTo.Global // ReSharper disable UnusedMemberInSuper.Global // ReSharper disable UnusedMethodReturnValue.Global // ReSharper disable UnusedVariable namespace TWCore.Tests { /// <inheritdoc /> public class RpcTest : ContainerParameterServiceAsync { public RpcTest() : base("rpctest", "RPC Test") { } protected override async Task OnHandlerAsync(ParameterHandlerInfo info) { Core.Log.Warning("Starting RPC TEST"); var serializer = new NBinarySerializer(); var service = new MyService(); Core.Log.InfoBasic("Setting RPC Server"); var rpcServer = new RPCServer(new DefaultTransportServer(20050, serializer)); rpcServer.AddService(service); await rpcServer.StartAsync().ConfigureAwait(false); Core.Log.InfoBasic("Setting RPC Client"); var rpcClient = new RPCClient(new DefaultTransportClient("127.0.0.1", 20050, 1, serializer)); var sw = Stopwatch.StartNew(); //IHello test Core.Log.InfoBasic("IHello test"); dynamic hClient = await rpcClient.CreateDynamicProxyAsync<IHello>().ConfigureAwait(false); var rtest = (string)hClient.SayHi("MyName"); using (var watch = Watch.Create("IHello Time - SayHi | TestAsync")) { for (var i = 0; i < 5000; i++) { var rHClient = (string) hClient.SayHi("MyName"); } for (var i = 0; i < 5000; i++) { var rHClient = await ((Task<object>) hClient.TestAsync()).ConfigureAwait(false); } Core.Log.InfoBasic("Per Item: {0}", watch.GlobalElapsedMilliseconds / 10000); } //IMyService test Core.Log.InfoBasic("IMyService test"); dynamic dClient = await rpcClient.CreateDynamicProxyAsync<IMyService>().ConfigureAwait(false); using (var watch = Watch.Create("IMyService Time - GetAllAsync")) { for (var i = 0; i < 5000; i++) { var aLst = await ((Task<object>) dClient.GetAllAsync()).ConfigureAwait(false); } Core.Log.InfoBasic("Per Item: {0}", watch.GlobalElapsedMilliseconds / 5000); } //Proxy class test Core.Log.InfoBasic("Proxy class test"); var client = await rpcClient.CreateProxyAsync<MyServiceProxy>().ConfigureAwait(false); await client.NDate(Core.Now).ConfigureAwait(false); var enumResult = await client.TestEnum("Valor", Option.Option1).ConfigureAwait(false); using (var watch = Watch.Create("Proxy class Time - GetAllAsync")) { for (var i = 0; i < 10000; i++) { var resp = await client.GetAllAsync().ConfigureAwait(false); } Core.Log.InfoBasic("Per Item: {0}", watch.GlobalElapsedMilliseconds / 10000); } using (var watch = Watch.Create("Parallel GetAllAsync Time")) { var rAwait = await Enumerable.Range(0, 100) .Select(i => client.GetAllAsync()) .ConfigureAwait(false); Core.Log.InfoBasic("Per Item: {0}", watch.GlobalElapsedMilliseconds / 100); } //Event test Core.Log.InfoBasic("Event test"); using (var watch = Watch.Create("Event Test - AddSimplePersona")) { client.OnAddSimplePersona += (s, e) => { //Core.Log.Warning("On Add SimplePersona was fired!!!"); }; for (var i = 0; i < 10000; i++) { client.AddSimplePersona(new SimplePerson {Lastname = "Test", Firstname = "Test"}); } Core.Log.InfoBasic("Per Item: {0}", watch.GlobalElapsedMilliseconds / 10000); } var sTime = sw.Elapsed; Console.ReadLine(); Core.Log.Warning("All Rpc Requests on: {0}", sTime); rpcClient.Dispose(); await rpcServer.StopAsync().ConfigureAwait(false); Core.Log.InfoBasic("Test End."); } } #region RPC Server Test [Serializable] public class SimplePerson { public Guid PersonId { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public bool Enabled { get; set; } } public enum Option { Option1, Option2 } public interface IMyService { event EventHandler OnAddSimplePersona; SimplePerson GetSimplePersona(string name, string apellido); SimplePerson GetSimplePersona(Guid simplePersonaId); List<SimplePerson> GetAll(); bool AddSimplePersona(SimplePerson simplePersona); Task<bool> IsEnabled(); Task<Option> TestEnum(string name, Option option); Task<bool> NDate(DateTime? value); } public interface IHello { string SayHi(string name); string Test(); } public class MyService : IMyService, IHello { List<SimplePerson> _tmpSPerson; [RPCEvent(RPCMessageScope.Global)] public event EventHandler OnAddSimplePersona; #region SimplePersons List<SimplePerson> SimplePersonas = new List<SimplePerson> { new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() }, new SimplePerson { Firstname = "Daniel", Lastname = "Redondo", Enabled = true, PersonId = Guid.NewGuid() } }; #endregion public List<SimplePerson> GetAll() => _tmpSPerson ?? (_tmpSPerson = SimplePersonas.Concat(SimplePersonas).Concat(SimplePersonas).Concat(SimplePersonas).ToList()); public SimplePerson GetSimplePersona(Guid simplePersonaId) => SimplePersonas.FirstOrDefault((p, pId) => p.PersonId == pId, simplePersonaId); public SimplePerson GetSimplePersona(string name, string apellido) => SimplePersonas.FirstOrDefault((p, mName, mApellido) => p.Firstname == mName && p.Lastname == mApellido, name, apellido); public string SayHi(string name) => $"Hi {name}!"; public string Test() => string.Empty; public bool AddSimplePersona(SimplePerson simplePersona) { SimplePersonas.Add(simplePersona); OnAddSimplePersona?.Invoke(this, new EventArgs<SimplePerson>(simplePersona)); return true; } public Task<bool> IsEnabled() { return TaskHelper.CompleteTrue; } public Task<Option> TestEnum(string name, Option option) { if (option == Option.Option1) return Task.FromResult(Option.Option2); return Task.FromResult(Option.Option1); } public Task<bool> NDate(DateTime? value) { return Task.FromResult(true); } } #pragma warning disable 67 public class MyServiceProxy : RPCProxy, IMyService { public event EventHandler OnAddSimplePersona; public bool AddSimplePersona(SimplePerson simplePersona) => Invoke<SimplePerson, bool>(simplePersona); public List<SimplePerson> GetAll() => Invoke<List<SimplePerson>>(); public SimplePerson GetSimplePersona(Guid simplePersonaId) => Invoke<Guid, SimplePerson>(simplePersonaId); public SimplePerson GetSimplePersona(string name, string apellido) => Invoke<string, string, SimplePerson>(name, apellido); public Task<List<SimplePerson>> GetAllAsync() => InvokeAsAsync<List<SimplePerson>>(); public Task<bool> IsEnabled() => InvokeAsync<bool>(); public Task<Option> TestEnum(string name, Option option) => InvokeAsync<string, Option, Option>(name, option); public Task<bool> NDate(DateTime? value) => InvokeAsync<DateTime?, bool>(value); } #endregion }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Contoso.Branding.ThemesWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xnlab.SharpDups.Infrastructure; using Xnlab.SharpDups.Model; namespace Xnlab.SharpDups.Logic { public class ProgressiveDupDetector : IDupDetector { private const int DefaultBufferSize = 64 * 1024; private const int DefaulfQuickHashSize = 3 * 20; private int _workers; public DupResult Find(IEnumerable<string> files, int workers, int quickHashSize, int bufferSize) { var result = new DupResult { Duplicates = new List<Duplicate>(), FailedToProcessFiles = new List<string>(), TotalFiles = files.LongCount() }; var totalComparedFiles = 0L; var totalFileBytes = 0L; var totalReadBytes = 0L; _workers = workers; if (_workers <= 0) _workers = 5; if (bufferSize <= 3) bufferSize = DefaultBufferSize; if (quickHashSize <= 0) quickHashSize = DefaulfQuickHashSize; //groups with same file size var sameSizeGroups = files.Select(f => { try { return GetDupFileItem(f); } catch (Exception) { result.FailedToProcessFiles.Add(f); return null; } }).Where(f => f != null).GroupBy(f => f.Size).Where(g => g.Count() > 1); var mappedSameSizeGroupList = new ConcurrentBag<IGrouping<string, DupItem>>(); Parallel.ForEach(MapFileSizeGroups(sameSizeGroups), mappedSameSizeGroups => { foreach (var group in mappedSameSizeGroups) { foreach (var file in group) { Interlocked.Increment(ref totalComparedFiles); try { //fast random bytes checking QuickHashFile(file, quickHashSize, ref totalFileBytes, ref totalReadBytes); } catch (Exception) { file.Status = CompareStatus.Failed; result.FailedToProcessFiles.Add(file.FileName); } } //groups with same quick hash value var sameQuickHashGroups = group.Where(f => f.Status != CompareStatus.Failed).GroupBy(f => f.QuickHash).Where(g => g.Count() > 1); foreach (var sameQuickHashGroup in sameQuickHashGroups) { mappedSameSizeGroupList.Add(sameQuickHashGroup); } } }); Parallel.ForEach(MapFileHashGroups(mappedSameSizeGroupList), mappedSameSizehGroups => { foreach (var quickHashGroup in mappedSameSizehGroups) { ProgressiveHash(quickHashGroup, bufferSize, ref totalReadBytes); result.FailedToProcessFiles.AddRange(quickHashGroup.Where(f => f.Status == CompareStatus.Failed).Select(f => f.FileName)); //phew, finally..... //group by same file hash var sameFullHashGroups = quickHashGroup.Where(g => g.Status != CompareStatus.Failed).GroupBy(g => g.FullHash).Where(g => g.Count() > 1); result.Duplicates.AddRange(sameFullHashGroups.Select(fullHashGroup => new Duplicate { Items = fullHashGroup.Select(f => new FileItem { FileName = f.FileName, ModifiedTime = f.ModifiedTime, Size = f.Size }) })); } }); result.TotalComparedFiles = totalComparedFiles; result.TotalBytesInComparedFiles = totalFileBytes; result.TotalReadBytes = totalReadBytes; return result; } private static DupItem GetDupFileItem(string f) { var info = new FileInfo(f); return new DupItem { FileName = f, ModifiedTime = info.LastWriteTime, Size = info.Length }; } public static DupItem ProgressiveHashFile(string file, int quickHashSize, int bufferSize) { var dupFileItem = GetDupFileItem(file); var totalFileBytes = 0L; var totalReadBytes = 0L; QuickHashFile(dupFileItem, quickHashSize, ref totalFileBytes, ref totalReadBytes); var length = dupFileItem.Size / bufferSize; if (length == 0) length = 1; var position = 0L; for (var i = 0; i < length; i++) { ProgressiveHashSection(position, dupFileItem, bufferSize, ref totalReadBytes); position += bufferSize; } return dupFileItem; } public static bool ProgressiveCompareFile(DupItem sourceDupItem, string targetFile, int quickHashSize, int bufferSize) { var totalFileBytes = 0L; var totalReadBytes = 0L; var targetDupFileItem = GetDupFileItem(targetFile); if (targetDupFileItem.Size != sourceDupItem.Size) return false; QuickHashFile(targetDupFileItem, quickHashSize, ref totalFileBytes, ref totalReadBytes); if (targetDupFileItem.QuickHash != sourceDupItem.QuickHash) return false; var length = targetDupFileItem.Size / bufferSize; if (length == 0) length = 1; var position = 0L; for (var i = 0; i < length; i++) { ProgressiveHashSection(position, targetDupFileItem, bufferSize, ref totalReadBytes); if (sourceDupItem.HashSections.Count < i + 1 || targetDupFileItem.HashSections[i] != sourceDupItem.HashSections[i]) return false; position += bufferSize; } return true; } private static void QuickHashFile(DupItem file, int quickHashSize, ref long totalFileBytes, ref long totalReadBytes) { Interlocked.Add(ref totalFileBytes, file.Size); var hashSize = (int)Math.Min(file.Size, quickHashSize); using (var stream = File.Open(file.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { file.Tags = new byte[hashSize]; for (var i = 0; i < 3; i++) { var sectionSize = hashSize / 3; long position; if (i == 0) position = 0; else if (i == 1) position = file.Size / 2 - sectionSize / 2; else position = file.Size - sectionSize; stream.Seek(position, SeekOrigin.Begin); stream.Read(file.Tags, i * sectionSize, sectionSize); } file.QuickHash = HashTool.HashBytesText(file.Tags); if (file.Size <= hashSize) file.Status = CompareStatus.Matched; Interlocked.Add(ref totalReadBytes, hashSize); } } private static void ProgressiveHash(IGrouping<string, DupItem> quickHashGroup, int bufferSize, ref long totalReadBytes) { var groups = quickHashGroup.ToArray(); var first = groups.First(); var length = first.Size / bufferSize; if (length == 0) length = 1; var position = 0L; for (var i = 0; i < length; i++) { foreach (var group in groups.Where(g => g.Status == CompareStatus.None).GroupBy(g => i == 0 ? string.Empty : g.HashSections[i - 1])) { var hashCount = 0; foreach (var groupFile in group) { try { ProgressiveHashSection(position, groupFile, bufferSize, ref totalReadBytes); } catch (Exception) { groupFile.Status = CompareStatus.Failed; } hashCount = groupFile.HashSections.Count; } foreach (var incrementalGroupWithSameHashSection in group.Where(g => g.Status != CompareStatus.Failed).GroupBy(g => g.HashSections[hashCount - 1])) { if (incrementalGroupWithSameHashSection.Count() == 1) { foreach (var item in incrementalGroupWithSameHashSection) { item.Status = CompareStatus.Different; } } } } position += bufferSize; } foreach (var groupFile in groups.Where(g => g.Status != CompareStatus.Different)) { if (groupFile.Status != CompareStatus.Matched) groupFile.FullHash = string.Join(string.Empty, groupFile.HashSections); } } private static void ProgressiveHashSection(long position, DupItem dupItem, int bufferSize, ref long totalReadBytes) { if (dupItem.HashSections == null) dupItem.HashSections = new List<string>(); dupItem.HashSections.Add(HashTool.HashFile(dupItem.FileName, position, bufferSize, bufferSize, out var readSize)); Interlocked.Add(ref totalReadBytes, readSize); } private IEnumerable<IEnumerable<IGrouping<long, DupItem>>> MapFileSizeGroups(IEnumerable<IGrouping<long, DupItem>> source) => Slice(source); private IEnumerable<IEnumerable<IGrouping<T, DupItem>>> Slice<T>(IEnumerable<IGrouping<T, DupItem>> source) { var it = source.ToArray(); var size = it.Length / _workers; if (size == 0) size = 1; return it.Section(size); } private IEnumerable<IEnumerable<IGrouping<string, DupItem>>> MapFileHashGroups(IEnumerable<IGrouping<string, DupItem>> source) => Slice(source); } }
// 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.Data.Common; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Runtime.Versioning; namespace System.Data.OleDb { internal struct SchemaSupport { internal Guid _schemaRowset; internal int _restrictions; } internal sealed class OleDbConnectionString : DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution internal static class KEY { internal const string Asynchronous_Processing = "asynchronous processing"; internal const string Connect_Timeout = "connect timeout"; internal const string Data_Provider = "data provider"; internal const string Data_Source = "data source"; internal const string Extended_Properties = "extended properties"; internal const string File_Name = "file name"; internal const string Initial_Catalog = "initial catalog"; internal const string Ole_DB_Services = "ole db services"; internal const string Persist_Security_Info = "persist security info"; internal const string Prompt = "prompt"; internal const string Provider = "provider"; internal const string RemoteProvider = "remote provider"; internal const string WindowHandle = "window handle"; } // registry key and dword value entry for udl pooling private static class UDL { internal const string Header = "\xfeff[oledb]\r\n; Everything after this line is an OLE DB initstring\r\n"; internal const string Location = "SOFTWARE\\Microsoft\\DataAccess\\Udl Pooling"; internal const string Pooling = "Cache Size"; internal static volatile bool _PoolSizeInit; internal static int _PoolSize; internal static volatile Dictionary<string, string> _Pool; internal static object _PoolLock = new object(); } private static class VALUES { internal const string NoPrompt = "noprompt"; } // set during ctor internal readonly bool PossiblePrompt; internal readonly string ActualConnectionString; // cached value passed to GetDataSource private readonly string _expandedConnectionString; internal SchemaSupport[] _schemaSupport; internal int _sqlSupport; internal bool _supportMultipleResults; internal bool _supportIRow; internal bool _hasSqlSupport; internal bool _hasSupportMultipleResults, _hasSupportIRow; private int _oledbServices; // these are cached delegates (per unique connectionstring) internal UnsafeNativeMethods.IUnknownQueryInterface DangerousDataSourceIUnknownQueryInterface; internal UnsafeNativeMethods.IDBInitializeInitialize DangerousIDBInitializeInitialize; internal UnsafeNativeMethods.IDBCreateSessionCreateSession DangerousIDBCreateSessionCreateSession; internal UnsafeNativeMethods.IDBCreateCommandCreateCommand DangerousIDBCreateCommandCreateCommand; // since IDBCreateCommand interface may not be supported for a particular provider (only IOpenRowset) // we cache that fact rather than call QueryInterface on every call to Open internal bool HaveQueriedForCreateCommand; // SxS: if user specifies a value for "File Name=" (UDL) in connection string, OleDbConnectionString will load the connection string // from the UDL file. The UDL file is opened as FileMode.Open, FileAccess.Read, FileShare.Read, allowing concurrent access to it. internal OleDbConnectionString(string connectionString, bool validate) : base(connectionString) { string prompt = this[KEY.Prompt]; PossiblePrompt = ((!ADP.IsEmpty(prompt) && (0 != string.Compare(prompt, VALUES.NoPrompt, StringComparison.OrdinalIgnoreCase))) || !ADP.IsEmpty(this[KEY.WindowHandle])); if (!IsEmpty) { string udlConnectionString = null; if (!validate) { int position = 0; string udlFileName = null; _expandedConnectionString = ExpandDataDirectories(ref udlFileName, ref position); if (!ADP.IsEmpty(udlFileName)) { // fail via new FileStream vs. GetFullPath udlFileName = ADP.GetFullPath(udlFileName); } if (null != udlFileName) { udlConnectionString = LoadStringFromStorage(udlFileName); if (!ADP.IsEmpty(udlConnectionString)) { _expandedConnectionString = _expandedConnectionString.Substring(0, position) + udlConnectionString + ';' + _expandedConnectionString.Substring(position); } } } if (validate || ADP.IsEmpty(udlConnectionString)) { ActualConnectionString = ValidateConnectionString(connectionString); } } } internal int ConnectTimeout { get { return base.ConvertValueToInt32(KEY.Connect_Timeout, ADP.DefaultConnectionTimeout); } } internal string DataSource { get { return base.ConvertValueToString(KEY.Data_Source, string.Empty); } } internal string InitialCatalog { get { return base.ConvertValueToString(KEY.Initial_Catalog, string.Empty); } } internal string Provider { get { Debug.Assert(!ADP.IsEmpty(this[KEY.Provider]), "no Provider"); return this[KEY.Provider]; } } internal int OleDbServices { get { return _oledbServices; } } internal SchemaSupport[] SchemaSupport { // OleDbConnection.GetSchemaRowsetInformation get { return _schemaSupport; } set { _schemaSupport = value; } } protected internal override string Expand() { if (null != _expandedConnectionString) { return _expandedConnectionString; } else { return base.Expand(); } } internal int GetSqlSupport(OleDbConnection connection) { int sqlSupport = _sqlSupport; if (!_hasSqlSupport) { object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_SQLSUPPORT); if (value is int) { // not OleDbPropertyStatus sqlSupport = (int)value; } _sqlSupport = sqlSupport; _hasSqlSupport = true; } return sqlSupport; } internal bool GetSupportIRow(OleDbConnection connection, OleDbCommand command) { bool supportIRow = _supportIRow; if (!_hasSupportIRow) { object value = command.GetPropertyValue(OleDbPropertySetGuid.Rowset, ODB.DBPROP_IRow); // SQLOLEDB always returns VARIANT_FALSE for DBPROP_IROW, so base the answer on existance supportIRow = !(value is OleDbPropertyStatus); _supportIRow = supportIRow; _hasSupportIRow = true; } return supportIRow; } internal bool GetSupportMultipleResults(OleDbConnection connection) { bool supportMultipleResults = _supportMultipleResults; if (!_hasSupportMultipleResults) { object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_MULTIPLERESULTS); if (value is int) {// not OleDbPropertyStatus supportMultipleResults = (ODB.DBPROPVAL_MR_NOTSUPPORTED != (int)value); } _supportMultipleResults = supportMultipleResults; _hasSupportMultipleResults = true; } return supportMultipleResults; } private static int UdlPoolSize { // SxS: UdpPoolSize reads registry value to get the pool size get { int poolsize = UDL._PoolSize; if (!UDL._PoolSizeInit) { object value = ADP.LocalMachineRegistryValue(UDL.Location, UDL.Pooling); if (value is int) { poolsize = (int)value; poolsize = ((0 < poolsize) ? poolsize : 0); UDL._PoolSize = poolsize; } UDL._PoolSizeInit = true; } return poolsize; } } private static string LoadStringFromStorage(string udlfilename) { string udlConnectionString = null; Dictionary<string, string> udlcache = UDL._Pool; if ((null == udlcache) || !udlcache.TryGetValue(udlfilename, out udlConnectionString)) { udlConnectionString = LoadStringFromFileStorage(udlfilename); if (null != udlConnectionString) { Debug.Assert(!ADP.IsEmpty(udlfilename), "empty filename didn't fail"); if (0 < UdlPoolSize) { Debug.Assert(udlfilename == ADP.GetFullPath(udlfilename), "only cache full path filenames"); if (null == udlcache) { udlcache = new Dictionary<string, string>(); udlcache[udlfilename] = udlConnectionString; lock (UDL._PoolLock) { if (null != UDL._Pool) { udlcache = UDL._Pool; } else { UDL._Pool = udlcache; udlcache = null; } } } if (null != udlcache) { lock (udlcache) { udlcache[udlfilename] = udlConnectionString; } } } } } return udlConnectionString; } private static string LoadStringFromFileStorage(string udlfilename) { // Microsoft Data Link File Format // The first two lines of a .udl file must have exactly the following contents in order to work properly: // [oledb] // ; Everything after this line is an OLE DB initstring // string connectionString = null; Exception failure = null; try { int hdrlength = ADP.CharSize * UDL.Header.Length; using (FileStream fstream = new FileStream(udlfilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { long length = fstream.Length; if (length < hdrlength || (0 != length % ADP.CharSize)) { failure = ADP.InvalidUDL(); } else { byte[] bytes = new byte[hdrlength]; int count = fstream.Read(bytes, 0, bytes.Length); if (count < hdrlength) { failure = ADP.InvalidUDL(); } else if (System.Text.Encoding.Unicode.GetString(bytes, 0, hdrlength) != UDL.Header) { failure = ADP.InvalidUDL(); } else { // please verify header before allocating memory block for connection string bytes = new byte[length - hdrlength]; count = fstream.Read(bytes, 0, bytes.Length); connectionString = System.Text.Encoding.Unicode.GetString(bytes, 0, count); } } } } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableExceptionType(e)) { throw; } throw ADP.UdlFileError(e); } if (null != failure) { throw failure; } return connectionString.Trim(); } private string ValidateConnectionString(string connectionString) { if (ConvertValueToBoolean(KEY.Asynchronous_Processing, false)) { throw ODB.AsynchronousNotSupported(); } int connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, 0); if (connectTimeout < 0) { throw ADP.InvalidConnectTimeoutValue(); } string progid = ConvertValueToString(KEY.Data_Provider, null); if (null != progid) { progid = progid.Trim(); if (0 < progid.Length) { // don't fail on empty 'Data Provider' value ValidateProvider(progid); } } progid = ConvertValueToString(KEY.RemoteProvider, null); if (null != progid) { progid = progid.Trim(); if (0 < progid.Length) { // don't fail on empty 'Data Provider' value ValidateProvider(progid); } } progid = ConvertValueToString(KEY.Provider, string.Empty).Trim(); ValidateProvider(progid); // will fail on empty 'Provider' value // initialize to default // If the value is not provided in connection string and OleDbServices registry key has not been set by the provider, // the default for the provider is -1 (all services are ON). // our default is -13, we turn off ODB.DBPROPVAL_OS_AGR_AFTERSESSION and ODB.DBPROPVAL_OS_CLIENTCURSOR flags _oledbServices = DbConnectionStringDefaults.OleDbServices; bool hasOleDBServices = (base.ContainsKey(KEY.Ole_DB_Services) && !ADP.IsEmpty((string)base[KEY.Ole_DB_Services])); if (!hasOleDBServices) { // don't touch registry if they have OLE DB Services string classid = (string)ADP.ClassesRootRegistryValue(progid + "\\CLSID", string.Empty); if ((null != classid) && (0 < classid.Length)) { // CLSID detection of 'Microsoft OLE DB Provider for ODBC Drivers' Guid classidProvider = new Guid(classid); if (ODB.CLSID_MSDASQL == classidProvider) { throw ODB.MSDASQLNotSupported(); } object tmp = ADP.ClassesRootRegistryValue("CLSID\\{" + classidProvider.ToString("D", CultureInfo.InvariantCulture) + "}", ODB.OLEDB_SERVICES); if (null != tmp) { // @devnote: some providers like MSDataShape don't have the OLEDB_SERVICES value // the MSDataShape provider doesn't support the 'Ole Db Services' keyword // hence, if the value doesn't exist - don't prepend to string try { _oledbServices = (int)tmp; } catch (InvalidCastException e) { ADP.TraceExceptionWithoutRethrow(e); } _oledbServices &= ~(ODB.DBPROPVAL_OS_AGR_AFTERSESSION | ODB.DBPROPVAL_OS_CLIENTCURSOR); StringBuilder builder = new StringBuilder(); builder.Append(KEY.Ole_DB_Services); builder.Append("="); builder.Append(_oledbServices.ToString(CultureInfo.InvariantCulture)); builder.Append(";"); builder.Append(connectionString); connectionString = builder.ToString(); } } } else { // parse the Ole Db Services value from connection string _oledbServices = ConvertValueToInt32(KEY.Ole_DB_Services, DbConnectionStringDefaults.OleDbServices); } return connectionString; } internal static bool IsMSDASQL(string progid) { return (("msdasql" == progid) || progid.StartsWith("msdasql.", StringComparison.Ordinal) || ("microsoft ole db provider for odbc drivers" == progid)); } private static void ValidateProvider(string progid) { if (ADP.IsEmpty(progid)) { throw ODB.NoProviderSpecified(); } if (ODB.MaxProgIdLength <= progid.Length) { throw ODB.InvalidProviderSpecified(); } progid = progid.ToLower(CultureInfo.InvariantCulture); if (IsMSDASQL(progid)) { // fail msdasql even if not on the machine. throw ODB.MSDASQLNotSupported(); } } internal static void ReleaseObjectPool() { UDL._PoolSizeInit = false; UDL._Pool = null; } } }
using System; /// <summary> /// Int16.IConverible.ToSbyte(IFormatProvider) /// </summary> public class Int16IConvertibleToSByte { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random int16 to sbyte "); try { Int16 i1 = 200; while (i1 > 127) { i1 = (Int16)TestLibrary.Generator.GetByte(-55); } IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != i1) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,tht int16 is:" + i1); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Convert zero to sbyte "); try { Int16 i1 = 0; IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != i1) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Convert a negative int16 to sbyte "); try { Int16 i1 = 200; while (i1 > 127) { i1 = (Int16)TestLibrary.Generator.GetByte(-55); } IConvertible Icon1 = (IConvertible)(-i1); if (Icon1.ToSByte(null) != (-i1)) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,the int16 is:" + i1); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Check the boundary value of sbyte.MinValue"); try { Int16 i1 = (Int16)sbyte.MinValue; IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != (i1)) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Check the boundary value of sbyte.MaxValue"); try { Int16 i1 = (Int16)sbyte.MaxValue; IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != (i1)) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Test the overflowException"); try { Int16 i1 = 0; while (i1 <= 127) { i1 = TestLibrary.Generator.GetInt16(-55); } IConvertible Icon1 = (IConvertible)(i1); if (Icon1.ToSByte(null) != i1) { } TestLibrary.TestFramework.LogError("101", "An overflowException was not thrown as expected "); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { Int16IConvertibleToSByte test = new Int16IConvertibleToSByte(); TestLibrary.TestFramework.BeginTestCase("Int16IConvertibleToSByte"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); //Cursor.lockState = CursorLockMode.None; } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
using System; using System.Collections.Generic; using System.IO; using System.Printing; using System.Text; using System.Windows; using System.Windows.Documents.Serialization; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Controls; namespace DocumentSerialization { class TxtSerializerWriter:SerializerWriter { public TxtSerializerWriter(Stream stream) { _stream = stream; _writer = new StreamWriter(_stream); } /// <summary> /// Write a single DependencyObject and close package /// </summary> public override void Write(Visual visual) { Write(visual, null); } /// <summary> /// Write a single DependencyObject and close package /// </summary> public override void Write(Visual visual, PrintTicket printTicket) { SerializeVisualTree(visual); _writer.Close(); } /// <summary> /// Asynchronous Write a single DependencyObject and close package /// </summary> public override void WriteAsync(Visual visual) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DependencyObject and close package /// </summary> public override void WriteAsync(Visual visual, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DependencyObject and close package /// </summary> public override void WriteAsync(Visual visual, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DependencyObject and close package /// </summary> public override void WriteAsync(Visual visual, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single DocumentPaginator and close package /// </summary> public override void Write(DocumentPaginator documentPaginator) { Write(documentPaginator, null); } /// <summary> /// Write a single DocumentPaginator and close package /// </summary> public override void Write(DocumentPaginator documentPaginator, PrintTicket printTicket) { //SerializeVisualTree(documentPaginator.Source as DependencyObject); for( int i = 0; i < documentPaginator.PageCount; i++ ) { DocumentPage page = documentPaginator.GetPage(i); SerializeVisualTree(page.Visual); } _writer.Close(); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single FixedPage and close package /// </summary> public override void Write(FixedPage fixedPage) { Write(fixedPage, null); } /// <summary> /// Write a single FixedPage and close package /// </summary> public override void Write(FixedPage fixedPage, PrintTicket printTicket) { SerializeVisualTree(fixedPage); _writer.Close(); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single FixedDocument and close package /// </summary> public override void Write(FixedDocument fixedDocument) { Write(fixedDocument, null); } /// <summary> /// Write a single FixedDocument and close package /// </summary> public override void Write(FixedDocument fixedDocument, PrintTicket printTicket) { Write(fixedDocument.DocumentPaginator, printTicket); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single FixedDocumentSequence and close package /// </summary> public override void Write(FixedDocumentSequence fixedDocumentSequence) { Write(fixedDocumentSequence, null); } /// <summary> /// Write a single FixedDocumentSequence and close package /// </summary> public override void Write(FixedDocumentSequence fixedDocumentSequence, PrintTicket printTicket) { Write(fixedDocumentSequence.DocumentPaginator, printTicket); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Cancel Asynchronous Write /// </summary> public override void CancelAsync() { throw new NotSupportedException(); } /// <summary> /// Create a SerializerWriterCollator to gobble up multiple Visuals /// </summary> public override SerializerWriterCollator CreateVisualsCollator() { throw new NotSupportedException(); } /// <summary> /// Create a SerializerWriterCollator to gobble up multiple Visuals /// </summary> public override SerializerWriterCollator CreateVisualsCollator(PrintTicket documentSequencePT, PrintTicket documentPT) { throw new NotSupportedException(); } #pragma warning disable 0067 /// <summary> /// This event will be invoked if the writer wants a PrintTicker /// </summary> public override event WritingPrintTicketRequiredEventHandler WritingPrintTicketRequired; /// <summary> /// This event will be invoked if the writer progress changes /// </summary> public override event WritingProgressChangedEventHandler WritingProgressChanged; /// <summary> /// This event will be invoked if the writer is done /// </summary> public override event WritingCompletedEventHandler WritingCompleted; /// <summary> /// This event will be invoked if the writer has been cancelled /// </summary> public override event WritingCancelledEventHandler WritingCancelled; #pragma warning restore 0067 private void SerializeVisualTree(DependencyObject objectTree) { List<GlyphRun> glyphrunList = new List<GlyphRun>(); WalkVisualTree(glyphrunList, objectTree); try { // NOTE: this is not gaurenteed to get the text in any reasonable order // To correct this the transforms associated with the parent drawing groups // can be collected and the glyph runs sorted into text blocks // This is a complex algorythem out side the scope of this sampel foreach (GlyphRun glyphRun in glyphrunList) { StringBuilder builder = new StringBuilder(glyphRun.Characters.Count); foreach (char ch in glyphRun.Characters) { builder.Append(ch); } _writer.Write(builder.ToString()); _writer.Write(" "); } } finally { } } private void WalkVisualTree(List<GlyphRun> textObjects, DependencyObject treeObject) { System.Windows.Media.Drawing content = VisualTreeHelper.GetDrawing(treeObject as Visual); BuildGlypeTree(textObjects, content); int childCount = VisualTreeHelper.GetChildrenCount( treeObject ); for (int i = 0; i < childCount; i++) { DependencyObject child = VisualTreeHelper.GetChild(treeObject, i); WalkVisualTree(textObjects, child); } } private void BuildGlypeTree(List<GlyphRun> textObjects, System.Windows.Media.Drawing drawing) { if (drawing is GlyphRunDrawing) { textObjects.Add((drawing as GlyphRunDrawing).GlyphRun); } else if (drawing is DrawingGroup) { DrawingCollection children = (drawing as DrawingGroup).Children; for (int i = 0; i < children.Count; i++) { BuildGlypeTree(textObjects, children[i]); } } } private string GetTextFromVisual(DependencyObject visual) { string result = ""; if (visual is TextBlock) { result = (visual as TextBlock).Text; } else if (visual is TextBox) { result = (visual as TextBox).Text; } else if (visual is FlowDocument) { FlowDocument flowDocument = (visual as FlowDocument); result = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd).Text;; } else if (visual is Glyphs) { result = (visual as Glyphs).UnicodeString; } return result; } private Stream _stream; private TextWriter _writer; } class CompareByLocation : IComparer<GlyphRun> { public int Compare(GlyphRun a, GlyphRun b) { Point aPoint = a.BaselineOrigin; Point bPoint = b.BaselineOrigin; int result = 0; //Vertical takes priorty over horizontal if (aPoint.Y > bPoint.Y) { return -1; } else if (aPoint.Y > bPoint.Y) { result = 1; } else if (aPoint.X < bPoint.X) { result = -1; } else if (aPoint.X > bPoint.X) { result = 1; } return result; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Provides functionality to use animating sprites in your scenes. /// </summary> public class OTAnimatingSprite : OTSprite { //----------------------------------------------------------------------------- // Editor settings //----------------------------------------------------------------------------- public OTAnimation _animation; public string _animationFrameset = ""; public float _speed = 1; public bool _looping = true; public int _numberOfPlays = -1; public bool _playOnStart = true; public bool _startAtRandomFrame = false; public bool _destroyWhenFinished = false; /// <summary> /// Animation editor preview progress manipulator. /// </summary> /// <remarks> /// This manipulator set the sprite's display frame according to the animation procentual progress value. /// By increasing or decreasing (0-100) this editor property, you can preview your current /// animation. /// </remarks> public int animationPreview = 0; [HideInInspector] public string _animationName = ""; //----------------------------------------------------------------------------- // Delegates //----------------------------------------------------------------------------- /// <summary> /// Animation start delegate. /// </summary> /// <remarks> /// The onAnimationStart delegate will be called when an animation is started. /// </remarks> public OTObject.ObjectDelegate onAnimationStart = null; /// <summary> /// Animation finish delegate. /// </summary> /// <remarks> /// The onAnimationFinish delegate will be called when the animation finishes or is stopped. /// </remarks> public OTObject.ObjectDelegate onAnimationFinish = null; /// <summary> /// Animation frame progress delegate. /// </summary> /// <remarks> /// The onAnimationFrame delegate will be called when the animation progresses a frame. /// </remarks> public OTObject.ObjectDelegate onAnimationFrame = null; /// <summary> /// Animation pauze delegate. /// </summary> /// <remarks> /// The onAnimationPauze delegate will be called when the animation is pauzed. /// </remarks> public OTObject.ObjectDelegate onAnimationPauze = null; /// <summary> /// Animation resume delegate. /// </summary> /// <remarks> /// The onAnimationResume delegate will be called when the animation is resumed. /// </remarks> public OTObject.ObjectDelegate onAnimationResume = null; //----------------------------------------------------------------------------- // public attributes (get/set) //----------------------------------------------------------------------------- /// <summary> /// This sprite's animation /// </summary> new public OTAnimation animation { get { return _animation; } set { _animation = value; if (isPlaying) waiting = true; else System.Array.Resize<OTAnimation.Frame>(ref frames,frCount); } } /// <summary> /// Specific animation frameset /// </summary> /// <remarks> /// If not specified (empty) the all animation framesets are played /// </remarks> public string animationFrameset { get { return _animationFrameset; } set { _animationFrameset = value; animationFramesetLower = value.ToLower(); if (isPlaying) waiting = true; } } /// <summary> /// Looping animation indicator /// </summary> public bool looping { get { return _looping; } set { _looping = value; if (value) _numberOfPlays = -1; else _numberOfPlays = 1; } } /// <summary> /// The number of times an animation is played /// </summary> public int numberOfPlays { get { return _numberOfPlays; } set { _numberOfPlays = value; } } /// <summary> /// Animation speed /// </summary> public float speed { get { return _speed; } set { _speed = value; } } /// <summary> /// Animation will start playing when the sprite is 'started' /// </summary> public bool playOnStart { get { return _playOnStart; } set { _playOnStart = value; } } /// <summary> /// The animation will start to play at a random frame /// </summary> public bool startAtRandomFrame { get { return _startAtRandomFrame; } set { _startAtRandomFrame = value; } } /// <summary> /// Sprite will be destroyed automaticly after the animation finishes. /// </summary> public bool destroyWhenFinished { get { return _destroyWhenFinished; } set { _destroyWhenFinished = value; } } /// <summary> /// Animation is playhing indicator /// </summary> public bool isPlaying { get { return _playing; } } /// <summary> /// Indicates that the animation is only playing a specific part /// </summary> public bool isPlayingPartly { get { return (_playing && endFrame != -1); } } /// <summary> /// Indicates that the animation is playing forward /// </summary> public bool isPlayingForward { get { return (_playing && direction == 1); } } /// <summary> /// Indicates that the animation is playing backward /// </summary> public bool isPlayingBackward { get { return (_playing && direction == -1); } } /// <summary> /// Reverse the animation. /// </summary> public void Reverse() { if (animation!=null) { direction *= -1 ; time = animation.GetDuration(frameset)-time; } } //----------------------------------------------------------------------------- // private and protected fields //----------------------------------------------------------------------------- bool waiting = true; float time = 0; float _time = -1; bool _playing = false; int direction = 1; int startFrame = -1; int endFrame = -1; float delay = 0; float waitTime = 0; float endTime = 0; int timesPlayed = 0; OTAnimationFrameset frameset = null; float frDuration; int frCount; //----------------------------------------------------------------------------- // public methods //----------------------------------------------------------------------------- public override void StartUp() { if (Application.isPlaying && playOnStart) Play(); base.StartUp(); } /// <summary> /// Plays this sprite's animation. /// </summary> public void Play() { this.startFrame = -1; this.endFrame = -1; this.delay = 0; _Play(); } /// <summary> /// Plays a frameset of this sprite's animation. /// </summary> /// <param name="frameSet">Animation frameset to play.</param> public void Play(string frameSet) { this.animationFrameset = frameSet; this.startFrame = -1; this.endFrame = -1; this.delay = 0; _Play(); } /// <summary> /// Plays a frameset of this sprite's animation once. /// </summary> /// <param name="frameSet">Animation frameset to play.</param> public void PlayOnce(string frameSet) { this.animationFrameset = frameSet; this.looping = false; this.startFrame = -1; this.endFrame = -1; this.delay = 0; _Play(); } /// <summary> /// Plays a frameset of this sprite's animation looping. /// </summary> /// <param name="frameSet">Animation frameset to play.</param> public void PlayLoop(string frameSet) { if (this.animationFrameset != frameSet || !_playing) { this.animationFrameset = frameSet; this.looping = true; this.startFrame = -1; this.endFrame = -1; this.delay = 0; _Play(); } } /// <summary> /// Plays a specific animation. /// </summary> /// <param name="animation">Animation to play.</param> public void Play(OTAnimation animation) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; Play(); } } /// <summary> /// Plays a specific animation's frameSet. /// </summary> /// <param name="animation">Animation to play a frameset from.</param> /// <param name="frameSet">Animation framset to play.</param> public void Play(OTAnimation animation, string frameSet) { if (animation != null) { this.animation = animation; this.animationFrameset = frameSet; Play(); } } /// <summary> /// Plays this sprite's animation from a start frame. /// </summary> /// <param name="startFrame">Animation frame number where to start.</param> public void Play(int startFrame) { this.animationFrameset = ""; this.startFrame = startFrame; this.endFrame = -1; this.delay = 0; _Play(); } /// <summary> /// Plays a specific animation from a start frame. /// </summary> /// <param name="animation">Animation to play.</param> /// <param name="startFrame">Animation frame number where to start.</param> public void Play(OTAnimation animation, int startFrame) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; Play(startFrame); } } /// <summary> /// Plays this sprite's animation from a start frame, starting after a delay. /// </summary> /// <param name="startFrame">Animation frame number where to start.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void Play(int startFrame, float delay) { this.startFrame = startFrame; this.animationFrameset = ""; this.endFrame = -1; this.delay = delay; _Play(); } /// <summary> /// Plays a specific animation from a start frame, starting after a delay. /// </summary> /// <param name="animation">Animation to play.</param> /// <param name="startFrame">Animation frame number where to start.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void Play(OTAnimation animation, int startFrame, float delay) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; Play(startFrame, delay); } } /// <summary> /// Plays this sprite's animation partly from a start frame to an end frame, starting after a delay. /// </summary> /// <param name="startFrame">Animation frame number where to start.</param> /// <param name="endFrame">Animation frame number where to end.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void Play(int startFrame, int endFrame, float delay) { if (startFrame <= endFrame) { this.startFrame = startFrame; this.animationFrameset = ""; this.endFrame = endFrame; this.delay = delay; _Play(); } else { this.endFrame = startFrame; this.animationFrameset = ""; this.startFrame = endFrame; this.delay = delay; _PlayBackward(); } } /// <summary> /// Plays a specific animation partly from a start frame to an end frame, starting after a delay. /// </summary> /// <param name="animation">Animation to play.</param> /// <param name="startFrame">Animation frame number where to start.</param> /// <param name="endFrame">Animation frame number where to end.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void Play(OTAnimation animation, int startFrame, int endFrame, float delay) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; Play(startFrame, endFrame, delay); } } /// <summary> /// Plays this sprite's animation backward. /// </summary> public void PlayBackward() { this.startFrame = -1; this.endFrame = -1; this.animationFrameset = ""; _PlayBackward(); } /// <summary> /// Plays this a frameset of this sprite's animation backward. /// </summary> /// <param name="frameSet">Animation frameset to play.</param> public void PlayBackward(string frameSet) { this.startFrame = -1; this.endFrame = -1; this.animationFrameset = frameSet; _PlayBackward(); } /// <summary> /// Plays this a frameset of this sprite's animation backward once. /// </summary> /// <param name="frameSet">Animation frameset to play.</param> public void PlayOnceBackward(string frameSet) { this.startFrame = -1; this.endFrame = -1; this.looping = false; this.animationFrameset = frameSet; _PlayBackward(); } /// <summary> /// Plays this a frameset of this sprite's animation backward looping. /// </summary> /// <param name="frameSet">Animation frameset to play.</param> public void PlayLoopBackward(string frameSet) { this.startFrame = -1; this.endFrame = -1; this.looping = true; this.animationFrameset = frameSet; _PlayBackward(); } /// <summary> /// Plays a specific animation backward. /// </summary> /// <param name="animation">Animation to play.</param> public void PlayBackward(OTAnimation animation) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; PlayBackward(); } } /// <summary> /// Plays a specific animation's frameset backward. /// </summary> /// <param name="animation">Animation to play a frameset from.</param> /// <param name="frameSet">Animation framset to play backward.</param> public void PlayBackward(OTAnimation animation, string frameSet) { if (animation != null) { this.animation = animation; this.animationFrameset = frameSet; PlayBackward(); } } /// <summary> /// Plays this sprite's animation backward starting at the start frame. /// </summary> /// <param name="startFrame">Animation frame number (from the back) where to start.</param> public void PlayBackward(int startFrame) { this.startFrame = startFrame; this.animationFrameset = ""; this.endFrame = -1; this.delay = 0; _PlayBackward(); } /// <summary> /// Plays a specific animation backward starting at the start frame. /// </summary> /// <param name="animation">Animation to play.</param> /// <param name="startFrame">Animation frame number (from the back) where to start.</param> public void PlayBackward(OTAnimation animation, int startFrame) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; PlayBackward(startFrame); } } /// <summary> /// Plays this sprite's animation backward from a start frame, starting after a delay. /// </summary> /// <param name="startFrame">Animation frame number (from the back) where to start.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void PlayBackward(int startFrame, float delay) { this.animationFrameset = ""; this.startFrame = startFrame; this.endFrame = -1; this.delay = delay; _PlayBackward(); } /// <summary> /// Plays a specific animation backward from a start frame, starting after a delay. /// </summary> /// <param name="animation">Animation to play.</param> /// <param name="startFrame">Animation frame number (from the back) where to start.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void PlayBackward(OTAnimation animation, int startFrame, float delay) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; PlayBackward(startFrame, delay); } } /// <summary> /// Plays this sprite's animation partly backward from a start frame to an end frame, starting after a delay. /// </summary> /// <param name="startFrame">Animation frame number (from the back) where to start.</param> /// <param name="endFrame">Animation frame number (from the back) where to end.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void PlayBackward(int startFrame, int endFrame, float delay) { if (startFrame <= endFrame) { this.animationFrameset = ""; this.startFrame = startFrame; this.endFrame = endFrame; this.delay = delay; _PlayBackward(); } else { this.animationFrameset = ""; this.endFrame = startFrame; this.startFrame = endFrame; this.delay = delay; _Play(); } } /// <summary> /// Plays a specific animation partly backward from a start frame to an end frame, starting after a delay. /// </summary> /// <param name="animation">Animation to play</param> /// <param name="startFrame">Animation frame number (from the back) where to start.</param> /// <param name="endFrame">Animation frame number (from the back) where to end.</param> /// <param name="delay">After this delay in seconds the animation will be started.</param> public void PlayBackward(OTAnimation animation, int startFrame, int endFrame, float delay) { if (animation != null) { this.animation = animation; this.animationFrameset = ""; PlayBackward(startFrame, endFrame, delay); } } /// <summary> /// Pauze the current playhing animation. /// </summary> public void Pauze() { _playing = false; if (onAnimationPauze != null) onAnimationPauze(this); if (!CallBack("onAnimationPauze", callBackParams)) CallBack("OnAnimationPauze", callBackParams); } /// <summary> /// Resume the current pauzed animation. /// </summary> public void Resume() { _playing = true; if (onAnimationResume != null) onAnimationResume(this); if (!CallBack("onAnimationResume", callBackParams)) CallBack("OnAnimationResume", callBackParams); } /// <summary> /// Stop the current plagying animation. /// </summary> public void Stop() { _playing = false; time = 0; timesPlayed = 0; endFrame = -1; if (onAnimationFinish != null) onAnimationFinish(this); if (!CallBack("onAnimationFinish", callBackParams)) CallBack("OnAnimationFinish", callBackParams); if (destroyWhenFinished) OT.DestroyObject(this); } protected override Material InitMaterial() { if (spriteContainer == null && animation != null) return null; Material mat = base.InitMaterial(); return mat; } /// <summary> /// Show a specific animation frame. /// </summary> /// <param name="frameIndex">Container index of the frame to show.</param> public void ShowFrame(int frameIndex) { if (animation != null && animation.isReady) { if (frameIndex >= 0 && frameIndex < animation.frameCount) { if (isPlaying) Pauze(); this.frameIndex = frameIndex; } else throw (new System.IndexOutOfRangeException("Frame index out of range!")); } } //----------------------------------------------------------------------------- // class methods //----------------------------------------------------------------------------- protected override string GetTypeName() { return "Animating Sprite"; } override protected void CheckSettings() { base.CheckSettings(); if (Application.isEditor || OT.dirtyChecks || dirtyChecks) { if (animation!=null) _animationName = animation.name; } } string animationFramesetLower = ""; protected override void Start() { base.Start(); animationFramesetLower = animationFrameset.ToLower(); if (playOnStart) Play(); } void _Play() { direction = 1; __Play(); } void _PlayBackward() { direction = -1; __Play(); } void __Play() { _playing = true; waiting = true; timesPlayed = 0; } float frTime = 0; float frDurationDelta = 0; OTAnimation.Frame[] frames = new OTAnimation.Frame[]{}; void UpdateFrame(float deltaTime) { if (frames == null || frames.Length == 0) return; if (frTime == 0 || frTime >= frDurationDelta) { if (frTime>=frDurationDelta) frTime -= frDurationDelta; int idx = Mathf.FloorToInt(time/frDurationDelta); if (idx>=frames.Length) idx = 0; OTAnimation.Frame animationFrame = frames[idx]; if (spriteContainer != animationFrame.container || animationFrame.frameIndex != frameIndex) { if (passive) { spriteContainer = animationFrame.container; frameIndex = animationFrame.frameIndex; } else { _spriteContainer = animationFrame.container; _frameIndex = animationFrame.frameIndex; } if (onAnimationFrame != null) onAnimationFrame(this); if (!CallBack("onAnimationFrame", callBackParams)) CallBack("OnAnimationFrame", callBackParams); isDirty = true; } time += (deltaTime * speed); if (endFrame != -1 && time >= endTime) { Stop(); return; } } else time += (deltaTime * speed); if (time >= frDuration) { if (looping) time -= frDuration; else { time = 0; timesPlayed++; if (timesPlayed >= numberOfPlays) Stop(); } } frTime += (deltaTime * speed); // Debug.Log("frTime ="+frTime+", time = "+time); } void HandleWaiting() { if (waitTime >= delay) { waitTime = 0; delay = 0; if (animationFrameset != "") { frameset = animation.GetFrameset(animationFrameset); if (frameset!=null) { framesetName = frameset.name.ToLower(); animationFramesetLower = animationFrameset.ToLower(); } frDuration = animation.GetDuration(frameset); frCount = animation.GetFrameCount(frameset); } else { frameset = null; frDuration = animation.duration; frCount = animation.frameCount; } frDurationDelta = frDuration/frCount; frTime = 0; if (frCount==0) return; if (startAtRandomFrame) time = frDurationDelta * (Mathf.Floor(frCount * Random.value)); else { if (startFrame != -1) { time = frDurationDelta * startFrame; if (endFrame != -1) endTime = frDurationDelta * (endFrame + 1) - 0.001f; } else time = 0; } System.Array.Resize<OTAnimation.Frame>(ref frames,frCount); // cache the animation frames for quicker lookup for (int i=0; i<frCount; i++) frames[i] = animation.GetFrame(i * frDurationDelta, direction, frameset); waiting = false; if (onAnimationStart != null) onAnimationStart(this); if (!CallBack("onAnimationStart", new object[] { this })) CallBack("OnAnimationStart", new object[] { this }); } else waitTime += Time.deltaTime; } // Update is called once per frame string framesetName = ""; protected override void Update() { if (animation == null && _animationName!=null) animation = OT.AnimationByName(_animationName); if (spriteContainer != null && !spriteContainer.isReady) return; if (speed < 0) speed = 0; if (Application.isPlaying && animation != null && animation.isReady && _playing) { if (waiting) HandleWaiting(); if (!waiting) UpdateFrame(Time.deltaTime); } else EditorPreview(); if (!passive) base.Update(); } void EditorPreview() { if (animationPreview < 0) animationPreview = 0; else if (animationPreview > 100) animationPreview = 100; if (!Application.isPlaying && animation != null && animation.isReady) { if (animationFrameset != "" && (frameset == null || (frameset != null && framesetName != animationFramesetLower))) { frameset = animation.GetFrameset(animationFrameset); frCount = animation.GetFrameCount(frameset); frDuration = animation.GetDuration(frameset); System.Array.Resize<OTAnimation.Frame>(ref frames,0); } else { frCount = animation.frameCount; frDuration = animation.duration; } frDurationDelta = frDuration/frCount; if (frames.Length == 0) { System.Array.Resize<OTAnimation.Frame>(ref frames,frCount); // cache the animation frames for quicker lookup for (int i=0; i<frCount; i++) frames[i] = animation.GetFrame(i * frDurationDelta, direction, frameset); } frDuration = animation.GetDuration(frameset); if (frameset != null && frameset.name == "") frameset = null; time = ((frDuration / 100) * animationPreview); if (time == frDuration) time -= 0.001f; if (time != _time) { frTime = frDurationDelta; UpdateFrame(0); _time = time; } } else if (animation != null && animation.isReady) { if (spriteContainer == null) spriteContainer = animation.GetFrame(0, 1, null).container; } } }
// // TorrentFile.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2006 Alan McGovern using System; using System.Collections.Generic; using System.Text; namespace ResumeEditor.Torrents { /// <summary> /// This is the base class for the files available to download from within a .torrent. /// This should be inherited by both Client and Tracker "TorrentFile" classes /// </summary> public class TorrentFile : IEquatable<TorrentFile> { #region Private Fields private BitField bitfield; private BitField selector; private byte[] ed2k; private int endPiece; private string fullPath; private long length; private byte[] md5; private string path; private Priority priority; private byte[] sha1; private int startPiece; #endregion Private Fields #region Member Variables /// <summary> /// The number of pieces which have been successfully downloaded which are from this file /// </summary> public BitField BitField { get { return this.bitfield; } } public long BytesDownloaded { get { return (long)(BitField.PercentComplete * Length / 100.0); } } /// <summary> /// The ED2K hash of the file /// </summary> public byte[] ED2K { get { return ed2k; } } /// <summary> /// The index of the last piece of this file /// </summary> public int EndPieceIndex { get { return this.endPiece; } } public string FullPath { get { return fullPath; } internal set { fullPath = value; } } /// <summary> /// The length of the file in bytes /// </summary> public long Length { get { return length; } } /// <summary> /// The MD5 hash of the file /// </summary> public byte[] MD5 { get { return this.md5; } internal set { md5 = value; } } /// <summary> /// In the case of a single torrent file, this is the name of the file. /// In the case of a multi-file torrent this is the relative path of the file /// (including the filename) from the base directory /// </summary> public string Path { get { return path; } } /// <summary> /// The priority of this torrent file /// </summary> public Priority Priority { get { return this.priority; } set { this.priority = value; } } /// <summary> /// The SHA1 hash of the file /// </summary> public byte[] SHA1 { get { return this.sha1; } } /// <summary> /// The index of the first piece of this file /// </summary> public int StartPieceIndex { get { return this.startPiece; } } #endregion #region Constructors public TorrentFile(string path, long length) : this(path, length, path) { } public TorrentFile (string path, long length, string fullPath) : this (path, length, fullPath, 0, 0) { } public TorrentFile (string path, long length, int startIndex, int endIndex) : this (path, length, path, startIndex, endIndex) { } public TorrentFile(string path, long length, string fullPath, int startIndex, int endIndex) : this(path, length, fullPath, startIndex, endIndex, null, null, null) { } public TorrentFile(string path, long length, string fullPath, int startIndex, int endIndex, byte[] md5, byte[] ed2k, byte[] sha1) { this.bitfield = new BitField(endIndex - startIndex + 1); this.ed2k = ed2k; this.endPiece = endIndex; this.fullPath = fullPath; this.length = length; this.md5 = md5; this.path = path; this.priority = Priority.Normal; this.sha1 = sha1; this.startPiece = startIndex; } #endregion #region Methods public override bool Equals(object obj) { return Equals(obj as TorrentFile); } public bool Equals(TorrentFile other) { return other == null ? false : path == other.path && length == other.length; ; } public override int GetHashCode() { return path.GetHashCode(); } internal BitField GetSelector(int totalPieces) { if (selector != null) return selector; selector = new BitField(totalPieces); for (int i = StartPieceIndex; i <= EndPieceIndex; i++) selector[i] = true; return selector; } public override string ToString() { StringBuilder sb = new StringBuilder(32); sb.Append("File: "); sb.Append(path); sb.Append(" StartIndex: "); sb.Append(StartPieceIndex); sb.Append(" EndIndex: "); sb.Append(EndPieceIndex); return sb.ToString(); } #endregion Methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclassgenmeth.regclassgenmeth; using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclassgenmeth.regclassgenmeth { using System.Collections.Generic; public class C { } public interface I { } public class MemberClass { #region Instance methods public T Method_ReturnsT<T>() { return default(T); } public T Method_ReturnsT<T>(T t) { return t; } public T Method_ReturnsT<T, U>(out T t) { t = default(T); return t; } public T Method_ReturnsT<T>(ref T t) { t = default(T); return t; } public T Method_ReturnsT<T>(params T[] t) { return default(T); } public int M<T>(T t) where T : IEnumerable<T> { return 3; } public T Method_ReturnsT<T, U>(params U[] d) { return default(T); } public T Method_ReturnsT<T, U>(float x, T t, U u) { return default(T); } public T Method_ReturnsT<T, U>(U u) { return default(T); } public T Method_ReturnsT<T, U, V>(out U u, ref V v) { u = default(U); return default(T); } public int Method_ReturnsInt<T>(T t) { return 1; } public string Method_ReturnsString<T, U>(T t, U u) { return "foo"; } public float Method_ReturnsFloat<T, U, V>(T t, dynamic d, U u) { return 3.4f; } public float Method_ReturnsFloat<T, U, V>(T t, dynamic d, U u, ref decimal dec) { dec = 3m; return 3.4f; } public dynamic Method_ReturnsDynamic<T>(T t) { return t; } public dynamic Method_ReturnsDynamic<T, U>(T t, U u, dynamic d) { return u; } public dynamic Method_ReturnsDynamic<T, U, V>(T t, U u, V v, dynamic d) { return v; } #region Constraints on methods that have a new type parameter public U Method_ReturnsUConstraint<U>(U u) where U : class { return null; } public U Method_ReturnsUConstraint<T, U>(T t) where U : new() { return new U(); } public U Method_ReturnsUConstraint<T, U, V>(T t, V v) where U : new() where V : U, new() { return new V(); } public dynamic Method_ReturnsDynamicConstraint<T, U>(T t, U u, dynamic d) where U : new() { return new U(); } public dynamic Method_ReturnsDynamicConstraint<T, U, V>(T t, U u, V v, dynamic d) where V : class { return u; } public float Method_ReturnsFloatConstraint<T, U, V>(T t, dynamic d, U u, ref decimal dec) where V : U { dec = 3m; return 3.4f; } public string Method_ReturnsStringConstraint<T, U, V>(T t, dynamic d, U u) where U : class where V : U { return ""; } //These are negative methods... you should not be able to call them with the dynamic type because the dynamic type would not satisfy the constraints //you cannot call this like: Method_ReturnsUConstraint<dynamic>(d); because object does not derive from C public U Method_ReturnsUNegConstraint<U>(U u) where U : C { return null; } public T Method_ReturnsTNegConstraint<T, U>(U u) where U : struct { return default(T); } public float Method_ReturnsFloatNegConstraint<T, U, V>(T t, dynamic d, U u, ref decimal dec) where V : U where U : I { dec = 3m; return 3.4f; } #endregion #region Nested class public class NestedMemberClass<U> { public U Method_ReturnsU(U t) { return default(U); } public U Method_ReturnsT(params U[] d) { return default(U); } public U Method_ReturnsT<V>(out U u, ref V v) { u = default(U); return default(U); } public dynamic Method_ReturnsDynamic(U t, U u, dynamic d) { return u; } public dynamic Method_ReturnsDynamic<V>(U t, U u, V v, dynamic d) { return v; } public decimal Method_ReturnsDecimal<V>(U t, dynamic d, U u) { return 3.4m; } public byte Method_ReturnsByte<V>(U t, dynamic d, U u, ref double dec) { dec = 3; return 4; } } #endregion #endregion } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass001.regclass001 { // <Title> Tests regular class generic method used in regular method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t.TestMethod()) return 1; return 0; } public bool TestMethod() { dynamic mc = new MemberClass(); return (bool)mc.Method_ReturnsT<bool>(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass002.regclass002 { // <Title> Tests regular class generic method used in variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static dynamic s_mc = new MemberClass(); private int _loc = (int)s_mc.Method_ReturnsT<int, string>(string.Empty, null, "abc"); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._loc != 0) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass003.regclass003 { // <Title> Tests regular class generic method used in indexer body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class Test { private Dictionary<int, string> _dic = new Dictionary<int, string>(); private MemberClass _mc = new MemberClass(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (TestSet() == 0 && TestGet() == 0) return 0; else return 1; } private static int TestSet() { Test t = new Test(); t[0] = "Test0"; t[1] = null; t[2] = "Test2"; if (t._dic[0] == "Test0" && t._dic[1] == null && t._dic[2] == "Test2") return 0; else return 1; } private static int TestGet() { Test t = new Test(); t._dic[2] = "Test0"; t._dic[1] = null; t._dic[0] = "Test2"; if (t[2] == "Test0" && t[1] == null && t[0] == "Test2") return 0; else return 1; } public string this[int i] { set { dynamic dy = _mc; _dic.Add((int)dy.Method_ReturnsT(i), value); } get { dynamic dy = _mc; return _dic[(int)dy.Method_ReturnsT(i)]; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass004.regclass004 { // <Title> Tests regular class generic method used in static constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static int s_field = 10; private static int s_result = -1; public Test() { dynamic dy = new MemberClass(); string s = "Foo"; Test.s_result = dy.Method_ReturnsT<int, int, string>(out s_field, ref s); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (Test.s_field == 0 && Test.s_result == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass005.regclass005 { // <Title> Tests regular class generic method used in variable named dynamic.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 1; dynamic dynamic = new MemberClass(); int result = dynamic.Method_ReturnsT<int>(ref i); if (i == 0 && result == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass006.regclass006 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t1 = new Test(); return t1.TestMethod<long>(1L) == 0 ? 0 : 1; } public T TestMethod<T>(T t) { dynamic dy = new MemberClass(); return (T)dy.Method_ReturnsT<T>(t, t, t); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass008.regclass008 { // <Title> Tests regular class generic method used in method body of method with conditional attribute.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static int s_result = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t1 = new Test(); t1.TestMethod(); return s_result; } [System.Diagnostics.Conditional("c1")] public void TestMethod() { dynamic dy = new MemberClass(); s_result = (int)dy.Method_ReturnsT<int, string>(null) + 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass009.regclass009 { // <Title> Tests regular class generic method used in arguments to method invocation.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections; using System.Collections.Generic; public class Test { public class InnerTest : IEnumerable<InnerTest> { public int Field; #region IEnumerable<InnerTest> Members public IEnumerator<InnerTest> GetEnumerator() { return new InnerTestEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new InnerTestEnumerator(); } #endregion } public class InnerTestEnumerator : IEnumerator<InnerTest>, IEnumerator { private InnerTest[] _list = new InnerTest[] { new InnerTest() { Field = 0 } , new InnerTest() { Field = 1 } , null } ; private int _index = -1; #region IEnumerator<InnerTest> Members public InnerTest Current { get { return _list[_index]; } } #endregion #region IDisposable Members public void Dispose() { // Empty. } #endregion #region IEnumerator Members object IEnumerator.Current { get { return _list[_index]; } } public bool MoveNext() { _index++; return _index >= _list.Length ? false : true; } public void Reset() { _index = -1; } #endregion } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); dynamic mc = new MemberClass(); int result = t.Method((int)mc.M<InnerTest>(new InnerTest())); return result == 3 ? 0 : 1; } public int Method(int value) { return value; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass010.regclass010 { // <Title> Tests regular class generic method used in implicitly-typed variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); string u = string.Empty; string v = string.Empty; var result = (int)mc.Method_ReturnsT<int, string, string>(out u, ref v); if (result == 0 && u == null && v == string.Empty) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass011.regclass011 { // <Title> Tests regular class generic method used in implicitly-typed variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); var tc = new { A1 = (int)mc.Method_ReturnsInt<int>(0), A2 = (string)mc.Method_ReturnsString<int, int>(1, 2) } ; if (tc != null && tc.A1 == 1 && tc.A2 == "foo") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass012.regclass012 { // <Title> Tests regular class generic method used in property-set body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private float _field; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); t.TestProperty = 1.1f; if (t.TestProperty == 3.4f) return 0; return 1; } public float TestProperty { set { dynamic mc = new MemberClass(); dynamic mv = value; _field = (float)mc.Method_ReturnsFloat<float, string, string>(value, mv, null); } get { return _field; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass013.regclass013 { // <Title> Tests regular class generic method used in constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private float _filed; private decimal _dec; public Test() { dynamic mc = new MemberClass(); _filed = mc.Method_ReturnsFloat<string, long, int>(null, mc, 1L, ref _dec); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._filed == 3.4f && t._dec == 3M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass014.regclass014 { // <Title> Tests regular class generic method used in operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); int result = (int)mc.Method_ReturnsDynamic<int>(7) % (int)mc.Method_ReturnsDynamic<int>(5); if ((int)mc.Method_ReturnsDynamic<int>(99) != 99) return 1; if (result == 2) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass015.regclass015 { // <Title> Tests regular class generic method used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); string result = (string)mc.Method_ReturnsDynamic<int, string>(10, null, mc) ?? string.Empty; if (result == string.Empty) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass016.regclass016 { // <Title> Tests regular class generic method used in query expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var list = new List<string>() { null, "b", null, "a" } ; dynamic mc = new MemberClass(); string a = "a"; dynamic da = a; var result = list.Where(p => p == (string)mc.Method_ReturnsDynamic<string, int, string>(null, 10, a, da)).ToList(); if (result.Count == 1 && result[0] == "a") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass017.regclass017 { // <Title> Tests regular class generic method used in short-circuit boolean expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass.NestedMemberClass<string>(); int loopCount = 0; while ((int)dy.Method_ReturnsDynamic<int>(null, null, loopCount, dy) < 10) { loopCount++; } return loopCount - 10; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass018.regclass018 { // <Title> Tests regular class generic method used in destructor.</Title> // <Description> // On IA64 the GC.WaitForPendingFinalizers() does not actually work... // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Runtime.CompilerServices; public class Test { private static string s_field; public static object locker = new object(); ~Test() { lock (locker) { dynamic mc = new MemberClass.NestedMemberClass<Test>(); s_field = mc.Method_ReturnsDynamic<string>(null, null, "Test", mc); } } private static int Verify() { lock (Test.locker) { if (Test.s_field != "Test") { return 1; } } return 0; } [MethodImpl(MethodImplOptions.NoInlining)] private static void RequireLifetimesEnded() { Test t = new Test(); Test.s_field = "Field"; GC.KeepAlive(t); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { RequireLifetimesEnded(); GC.Collect(); GC.WaitForPendingFinalizers(); // If move the code in Verify() to here, the finalizer will only be executed after exited Main return Verify(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass019.regclass019 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (object)dy.Method_ReturnsUConstraint<Test>(new Test()); return result == null ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass020.regclass020 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (Test)dy.Method_ReturnsUConstraint<int, Test>(4); if (result != null && result._field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass021.regclass021 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } public class InnerTest : Test { public InnerTest() { _field = 11; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (Test)dy.Method_ReturnsUConstraint<string, Test, InnerTest>(null, new InnerTest() { _field = 0 } ); if (result.GetType() == typeof(InnerTest) && result._field == 11) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass022.regclass022 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic result = dy.Method_ReturnsDynamicConstraint<int, Test>(1, new Test() { _field = 0 } , dy); if (((Test)result)._field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass023.regclass023 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(12,9\).*CS0414</Expects> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic s = "Test"; dynamic result = dy.Method_ReturnsDynamicConstraint<string, string, string>((string)s, (string)s, (string)s, s); if (((string)result) == "Test") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass024.regclass024 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(12,9\).*CS0414</Expects> public class Test { private int _field; public Test() { _field = 10; } public class InnerTest : Test { public InnerTest() { _field = 11; } } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); Test t = new Test(); dynamic it = new InnerTest(); decimal dec = 0M; float result = (float)dy.Method_ReturnsFloatConstraint<Test, Test, InnerTest>(t, it, t, ref dec); if (result == 3.4f && dec == 3M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass025.regclass025 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic t = new Test(); try { dynamic result = dy.Method_ReturnsUNegConstraint<Test>(t); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.GenericConstraintNotSatisfiedRefType, e.Message, "MemberClass.Method_ReturnsUNegConstraint<U>(U)", "C", "U", "Test")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass027.regclass027 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); MyTest mt = new MyTest(); dynamic d = mt; decimal dec = 0M; try { float result = (float)dy.Method_ReturnsFloatNegConstraint<Test, dynamic, DerivedMyTest>(null, d, d, ref dec); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (!ErrorVerifier.Verify(ErrorMessageId.GenericConstraintNotSatisfiedRefType, e.Message, "MemberClass.Method_ReturnsFloatNegConstraint<T,U,V>(T, object, U, ref decimal)", "I", "U", "object")) return 1; } return 0; } } public class MyTest : I { } public class DerivedMyTest : MyTest { } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass028.regclass028 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass.NestedMemberClass<string>(); string result = (string)dy.Method_ReturnsU("0"); if (result == null) return 0; return 1; } } //</Code> }
// // Color.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // 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 System.ComponentModel; using System.Windows.Markup; namespace Xwt.Drawing { [TypeConverter (typeof(ColorValueConverter))] [ValueSerializer (typeof(ColorValueSerializer))] [Serializable] public struct Color { double r, g, b, a; [NonSerialized] HslColor hsl; public double Red { get { return r; } set { r = Normalize (value); hsl = null; } } public double Green { get { return g; } set { g = Normalize (value); hsl = null; } } public double Blue { get { return b; } set { b = Normalize (value); hsl = null; } } public double Alpha { get { return a; } set { a = Normalize (value); } } public double Hue { get { return Hsl.H; } set { Hsl = new HslColor (Normalize (value), Hsl.S, Hsl.L); } } public double Saturation { get { return Hsl.S; } set { Hsl = new HslColor (Hsl.H, Normalize (value), Hsl.L); } } public double Light { get { return Hsl.L; } set { Hsl = new HslColor (Hsl.H, Hsl.S, Normalize (value)); } } double Normalize (double v) { if (v < 0) return 0; if (v > 1) return 1; return v; } public double Brightness { get { return System.Math.Sqrt (Red * .241 + Green * .691 + Blue * .068); } } HslColor Hsl { get { if (hsl == null) hsl = (HslColor)this; return hsl; } set { hsl = value; Color c = (Color)value; r = c.r; b = c.b; g = c.g; } } public Color (double red, double green, double blue): this () { Red = red; Green = green; Blue = blue; Alpha = 1f; } public Color (double red, double green, double blue, double alpha): this () { Red = red; Green = green; Blue = blue; Alpha = alpha; } public Color WithAlpha (double alpha) { Color c = this; c.Alpha = alpha; return c; } public Color WithIncreasedLight (double lightIncrement) { Color c = this; c.Light += lightIncrement; return c; } /// <summary> /// Returns a color which looks more contrasted (or less, if amount is negative) /// </summary> /// <returns>The new color</returns> /// <param name="amount">Amount to change (can be positive or negative).</param> /// <remarks> /// This method adds or removes light to/from the color to make it more contrasted when /// compared to a neutral grey. /// The resulting effect is that light colors are made lighter, and dark colors /// are made darker. If the amount is negative, the effect is inversed (colors are /// made less contrasted) /// </remarks> public Color WithIncreasedContrast (double amount) { return WithIncreasedContrast (new Color (0.5, 0.5, 0.5), amount); } /// <summary> /// Returns a color which looks more contrasted (or less, if amount is negative) with /// respect to a provided reference color. /// </summary> /// <returns>The new color</returns> /// <param name="referenceColor">Reference color.</param> /// <param name="amount">Amount to change (can be positive or negative).</param> public Color WithIncreasedContrast (Color referenceColor, double amount) { Color c = this; if (referenceColor.Light > Light) c.Light -= amount; else c.Light += amount; return c; } public Color BlendWith (Color target, double amount) { if (amount < 0 || amount > 1) throw new ArgumentException ("Blend amount must be between 0 and 1"); return new Color (BlendValue (r, target.r, amount), BlendValue (g, target.g, amount), BlendValue (b, target.b, amount), target.Alpha); } double BlendValue (double s, double t, double amount) { return s + (t - s) * amount; } public static Color FromBytes (byte red, byte green, byte blue) { return FromBytes (red, green, blue, 255); } public static Color FromBytes (byte red, byte green, byte blue, byte alpha) { return new Color { Red = ((double)red) / 255.0, Green = ((double)green) / 255.0, Blue = ((double)blue) / 255.0, Alpha = ((double)alpha) / 255.0 }; } public static Color FromHsl (double h, double s, double l) { return FromHsl (h, s, l, 1); } public static Color FromHsl (double h, double s, double l, double alpha) { HslColor hsl = new HslColor (h, s, l); Color c = (Color)hsl; c.Alpha = alpha; c.hsl = hsl; return c; } public static Color FromName (string name) { Color color; TryParse (name, out color); return color; } public static bool TryParse (string name, out Color color) { if (name == null) throw new ArgumentNullException ("name"); uint val; if (name.Length == 0 || !TryParseColourFromHex (name, out val)) { color = default (Color); return false; } color = Color.FromBytes ((byte)(val >> 24), (byte)((val >> 16) & 0xff), (byte)((val >> 8) & 0xff), (byte)(val & 0xff)); return true; } static bool TryParseColourFromHex (string str, out uint val) { val = 0; if (str[0] != '#' || str.Length > 9) return false; if (!uint.TryParse (str.Substring (1), System.Globalization.NumberStyles.HexNumber, null, out val)) return false; val = val << ((9 - str.Length) * 4); if (str.Length <= 7) val |= 0xff; return true; } public static bool operator == (Color c1, Color c2) { return c1.r == c2.r && c1.g == c2.g && c1.b == c2.b && c1.a == c2.a; } public static bool operator != (Color c1, Color c2) { return c1.r != c2.r || c1.g != c2.g || c1.b != c2.b || c1.a != c2.a; } public override bool Equals (object o) { if (!(o is Color)) return false; return (this == (Color) o); } public override int GetHashCode () { unchecked { var hash = r.GetHashCode (); hash = (hash * 397) ^ g.GetHashCode (); hash = (hash * 397) ^ b.GetHashCode (); hash = (hash * 397) ^ a.GetHashCode (); return hash; } } public override string ToString () { return string.Format ("[Color: Red={0}, Green={1}, Blue={2}, Alpha={3}]", Red, Green, Blue, Alpha); } public string ToHexString () { return "#" + ((int)(Red * 255)).ToString ("x2") + ((int)(Green * 255)).ToString ("x2") + ((int)(Blue * 255)).ToString ("x2") + ((int)(Alpha * 255)).ToString ("x2"); } } class ColorValueConverter: TypeConverter { static readonly ColorValueSerializer serializer = new ColorValueSerializer (); public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertTo (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { return serializer.ConvertToString (value, null); } public override object ConvertFrom (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return serializer.ConvertFromString ((string)value, null); } } class ColorValueSerializer: ValueSerializer { public override bool CanConvertFromString (string value, IValueSerializerContext context) { return true; } public override bool CanConvertToString (object value, IValueSerializerContext context) { return true; } public override string ConvertToString (object value, IValueSerializerContext context) { Color s = (Color) value; return s.ToHexString (); } public override object ConvertFromString (string value, IValueSerializerContext context) { Color c; if (Color.TryParse (value, out c)) return c; else throw new InvalidOperationException ("Could not parse color value: " + value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography; using Internal.Cryptography.Pal; using System; using System.IO; using System.Runtime.Serialization; using System.Security; using System.Text; namespace System.Security.Cryptography.X509Certificates { [Serializable] public class X509Certificate2 : X509Certificate { private volatile byte[] _lazyRawData; private volatile Oid _lazySignatureAlgorithm; private volatile int _lazyVersion; private volatile X500DistinguishedName _lazySubjectName; private volatile X500DistinguishedName _lazyIssuerName; private volatile PublicKey _lazyPublicKey; private volatile AsymmetricAlgorithm _lazyPrivateKey; private volatile X509ExtensionCollection _lazyExtensions; public override void Reset() { _lazyRawData = null; _lazySignatureAlgorithm = null; _lazyVersion = 0; _lazySubjectName = null; _lazyIssuerName = null; _lazyPublicKey = null; _lazyPrivateKey = null; _lazyExtensions = null; base.Reset(); } public X509Certificate2() : base() { } public X509Certificate2(byte[] rawData) : base(rawData) { } public X509Certificate2(byte[] rawData, string password) : base(rawData, password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, SecureString password) : base(rawData, password) { } public X509Certificate2(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) : base(rawData, password, keyStorageFlags) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) : base(rawData, password, keyStorageFlags) { } public X509Certificate2(IntPtr handle) : base(handle) { } internal X509Certificate2(ICertificatePal pal) : base(pal) { } public X509Certificate2(string fileName) : base(fileName) { } public X509Certificate2(string fileName, string password) : base(fileName, password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, SecureString password) : base(fileName, password) { } public X509Certificate2(string fileName, string password, X509KeyStorageFlags keyStorageFlags) : base(fileName, password, keyStorageFlags) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) : base(fileName, password, keyStorageFlags) { } public X509Certificate2(X509Certificate certificate) : base(certificate) { } protected X509Certificate2(SerializationInfo info, StreamingContext context) : base(info, context) { } public bool Archived { get { ThrowIfInvalid(); return Pal.Archived; } set { ThrowIfInvalid(); Pal.Archived = value; } } public X509ExtensionCollection Extensions { get { ThrowIfInvalid(); X509ExtensionCollection extensions = _lazyExtensions; if (extensions == null) { extensions = new X509ExtensionCollection(); foreach (X509Extension extension in Pal.Extensions) { X509Extension customExtension = CreateCustomExtensionIfAny(extension.Oid); if (customExtension == null) { extensions.Add(extension); } else { customExtension.CopyFrom(extension); extensions.Add(customExtension); } } _lazyExtensions = extensions; } return extensions; } } public string FriendlyName { get { ThrowIfInvalid(); return Pal.FriendlyName; } set { ThrowIfInvalid(); Pal.FriendlyName = value; } } public bool HasPrivateKey { get { ThrowIfInvalid(); return Pal.HasPrivateKey; } } public AsymmetricAlgorithm PrivateKey { get { ThrowIfInvalid(); if (!HasPrivateKey) return null; if (_lazyPrivateKey == null) { switch (GetKeyAlgorithm()) { case Oids.RsaRsa: _lazyPrivateKey = Pal.GetRSAPrivateKey(); break; case Oids.DsaDsa: _lazyPrivateKey = Pal.GetDSAPrivateKey(); break; default: // This includes ECDSA, because an Oids.Ecc key can be // many different algorithm kinds, not necessarily with mutual exclusion. // // Plus, .NET Framework only supports RSA and DSA in this property. throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } } return _lazyPrivateKey; } set { throw new PlatformNotSupportedException(); } } public X500DistinguishedName IssuerName { get { ThrowIfInvalid(); X500DistinguishedName issuerName = _lazyIssuerName; if (issuerName == null) issuerName = _lazyIssuerName = Pal.IssuerName; return issuerName; } } public DateTime NotAfter { get { return GetNotAfter(); } } public DateTime NotBefore { get { return GetNotBefore(); } } public PublicKey PublicKey { get { ThrowIfInvalid(); PublicKey publicKey = _lazyPublicKey; if (publicKey == null) { string keyAlgorithmOid = GetKeyAlgorithm(); byte[] parameters = GetKeyAlgorithmParameters(); byte[] keyValue = GetPublicKey(); Oid oid = new Oid(keyAlgorithmOid); publicKey = _lazyPublicKey = new PublicKey(oid, new AsnEncodedData(oid, parameters), new AsnEncodedData(oid, keyValue)); } return publicKey; } } public byte[] RawData { get { ThrowIfInvalid(); byte[] rawData = _lazyRawData; if (rawData == null) { rawData = _lazyRawData = Pal.RawData; } return rawData.CloneByteArray(); } } public string SerialNumber { get { byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); return serialNumber.ToHexStringUpper(); } } public Oid SignatureAlgorithm { get { ThrowIfInvalid(); Oid signatureAlgorithm = _lazySignatureAlgorithm; if (signatureAlgorithm == null) { string oidValue = Pal.SignatureAlgorithm; signatureAlgorithm = _lazySignatureAlgorithm = Oid.FromOidValue(oidValue, OidGroup.SignatureAlgorithm); } return signatureAlgorithm; } } public X500DistinguishedName SubjectName { get { ThrowIfInvalid(); X500DistinguishedName subjectName = _lazySubjectName; if (subjectName == null) subjectName = _lazySubjectName = Pal.SubjectName; return subjectName; } } public string Thumbprint { get { byte[] thumbPrint = GetCertHash(); return thumbPrint.ToHexStringUpper(); } } public int Version { get { ThrowIfInvalid(); int version = _lazyVersion; if (version == 0) version = _lazyVersion = Pal.Version; return version; } } public static X509ContentType GetCertContentType(byte[] rawData) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); return X509Pal.Instance.GetCertContentType(rawData); } public static X509ContentType GetCertContentType(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // Desktop compat: The desktop CLR expands the filename to a full path for the purpose of performing a CAS permission check. While CAS is not present here, // we still need to call GetFullPath() so we get the same exception behavior if the fileName is bad. string fullPath = Path.GetFullPath(fileName); return X509Pal.Instance.GetCertContentType(fileName); } public string GetNameInfo(X509NameType nameType, bool forIssuer) { return Pal.GetNameInfo(nameType, forIssuer); } public override string ToString() { return base.ToString(fVerbose: true); } public override string ToString(bool verbose) { if (verbose == false || Pal == null) return ToString(); StringBuilder sb = new StringBuilder(); // Version sb.AppendLine("[Version]"); sb.Append(" V"); sb.Append(Version); // Subject sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Subject]"); sb.Append(" "); sb.Append(SubjectName.Name); string simpleName = GetNameInfo(X509NameType.SimpleName, false); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } string emailName = GetNameInfo(X509NameType.EmailName, false); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } string upnName = GetNameInfo(X509NameType.UpnName, false); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } string dnsName = GetNameInfo(X509NameType.DnsName, false); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Issuer sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.Append(IssuerName.Name); simpleName = GetNameInfo(X509NameType.SimpleName, true); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } emailName = GetNameInfo(X509NameType.EmailName, true); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } upnName = GetNameInfo(X509NameType.UpnName, true); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } dnsName = GetNameInfo(X509NameType.DnsName, true); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Serial Number sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); sb.AppendLine(SerialNumber); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(NotBefore)); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(NotAfter)); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.AppendLine(Thumbprint); // Signature Algorithm sb.AppendLine(); sb.AppendLine("[Signature Algorithm]"); sb.Append(" "); sb.Append(SignatureAlgorithm.FriendlyName); sb.Append('('); sb.Append(SignatureAlgorithm.Value); sb.AppendLine(")"); // Public Key sb.AppendLine(); sb.Append("[Public Key]"); // It could throw if it's some user-defined CryptoServiceProvider try { PublicKey pubKey = PublicKey; sb.AppendLine(); sb.Append(" "); sb.Append("Algorithm: "); sb.Append(pubKey.Oid.FriendlyName); // So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys try { sb.AppendLine(); sb.Append(" "); sb.Append("Length: "); using (RSA pubRsa = this.GetRSAPublicKey()) { if (pubRsa != null) { sb.Append(pubRsa.KeySize); } } } catch (NotSupportedException) { } sb.AppendLine(); sb.Append(" "); sb.Append("Key Blob: "); sb.AppendLine(pubKey.EncodedKeyValue.Format(true)); sb.Append(" "); sb.Append("Parameters: "); sb.Append(pubKey.EncodedParameters.Format(true)); } catch (CryptographicException) { } // Private key Pal.AppendPrivateKeyInfo(sb); // Extensions X509ExtensionCollection extensions = Extensions; if (extensions.Count > 0) { sb.AppendLine(); sb.AppendLine(); sb.Append("[Extensions]"); foreach (X509Extension extension in extensions) { try { sb.AppendLine(); sb.Append("* "); sb.Append(extension.Oid.FriendlyName); sb.Append('('); sb.Append(extension.Oid.Value); sb.Append("):"); sb.AppendLine(); sb.Append(" "); sb.Append(extension.Format(true)); } catch (CryptographicException) { } } } sb.AppendLine(); return sb.ToString(); } public override void Import(byte[] rawData) { base.Import(rawData); } public override void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { base.Import(rawData, password, keyStorageFlags); } [System.CLSCompliantAttribute(false)] public override void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { base.Import(rawData, password, keyStorageFlags); } public override void Import(string fileName) { base.Import(fileName); } public override void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { base.Import(fileName, password, keyStorageFlags); } [System.CLSCompliantAttribute(false)] public override void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { base.Import(fileName, password, keyStorageFlags); } public bool Verify() { ThrowIfInvalid(); using (var chain = new X509Chain()) { // Use the default vales of chain.ChainPolicy including: // RevocationMode = X509RevocationMode.Online // RevocationFlag = X509RevocationFlag.ExcludeRoot // VerificationFlags = X509VerificationFlags.NoFlag // VerificationTime = DateTime.Now // UrlRetrievalTimeout = new TimeSpan(0, 0, 0) bool verified = chain.Build(this, throwOnException: false); return verified; } } private static X509Extension CreateCustomExtensionIfAny(Oid oid) { string oidValue = oid.Value; switch (oidValue) { case Oids.BasicConstraints: return X509Pal.Instance.SupportsLegacyBasicConstraintsExtension ? new X509BasicConstraintsExtension() : null; case Oids.BasicConstraints2: return new X509BasicConstraintsExtension(); case Oids.KeyUsage: return new X509KeyUsageExtension(); case Oids.EnhancedKeyUsage: return new X509EnhancedKeyUsageExtension(); case Oids.SubjectKeyIdentifier: return new X509SubjectKeyIdentifierExtension(); default: return null; } } } }
using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Windows.Input; using BFF.DataVirtualizingCollection.DataVirtualizingCollection; using BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters; using BFF.DataVirtualizingCollection.Sample.ViewModel.Interfaces; using BFF.DataVirtualizingCollection.Sample.ViewModel.Utility; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Functions; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Options; using BFF.DataVirtualizingCollection.SlidingWindow; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels { public interface IDataVirtualizingCollectionViewModelBase { string Name { get; } IGeneralOptionsViewModel GeneralOptionsViewModel { get; } ISpecificOptionsViewModel SpecificOptionsViewModel { get; } IPageLoadingBehaviorViewModel PageLoadingBehaviorViewModel { get; } IPageRemovalBehaviorViewModel PageRemovalBehaviorViewModel { get; } IFetcherKindViewModel FetcherKindViewModel { get; } IIndexAccessBehaviorViewModel IndexAccessBehaviorViewModel { get; } ICommand CreateNew { get; } IGeneralFunctionsViewModel GeneralFunctionsViewModel { get; } ISpecificFunctionsViewModel SpecificFunctionsViewModel { get; } BackendAccessKind BackendAccessKind { get; } IVirtualizationBase? Items { get; } } public abstract class DataVirtualizingCollectionViewModelBaseBase<TViewModel, TVirtualizationKind> : ObservableObject, IDisposable, IDataVirtualizingCollectionViewModelBase where TVirtualizationKind : class, IVirtualizationBase<TViewModel> { private readonly IBackendAccessAdapter<TViewModel> _backendAccessAdapter; private readonly IGetSchedulers _getSchedulers; private IVirtualizationBase? _items; private readonly SerialDisposable _serialItems; private readonly CompositeDisposable _compositeDisposable = new(); protected DataVirtualizingCollectionViewModelBaseBase( // parameters IBackendAccessAdapter<TViewModel> backendAccessAdapter, // dependencies IGeneralOptionsViewModel generalOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, IGetSchedulers getSchedulers) { _backendAccessAdapter = backendAccessAdapter; _getSchedulers = getSchedulers; GeneralOptionsViewModel = generalOptionsViewModel; PageLoadingBehaviorViewModel = pageLoadingBehaviorViewModel; PageRemovalBehaviorViewModel = pageRemovalBehaviorViewModel; FetcherKindViewModel = fetcherKindViewModel; GeneralFunctionsViewModel = generalFunctionsViewModel; IndexAccessBehaviorViewModel = fetcherKindViewModel.IndexAccessBehaviorViewModel; _serialItems = new SerialDisposable(); _compositeDisposable.Add(_serialItems); var createNew = new RxRelayCommand(SetItems); CreateNew = createNew; _compositeDisposable.Add(createNew); } public string Name => _backendAccessAdapter.Name; public BackendAccessKind BackendAccessKind => _backendAccessAdapter.BackendAccessKind; public IVirtualizationBase? Items { get { if (_items is null) SetItems(); return _items; } private set { if (_items == value) return; _items = value; _serialItems.Disposable = _items as IDisposable; OnPropertyChanged(); } } public IGeneralOptionsViewModel GeneralOptionsViewModel { get; } public abstract ISpecificOptionsViewModel SpecificOptionsViewModel { get; } public IPageLoadingBehaviorViewModel PageLoadingBehaviorViewModel { get; } public IPageRemovalBehaviorViewModel PageRemovalBehaviorViewModel { get; } public IFetcherKindViewModel FetcherKindViewModel { get; } public IIndexAccessBehaviorViewModel IndexAccessBehaviorViewModel { get; } public ICommand CreateNew { get; } public IGeneralFunctionsViewModel GeneralFunctionsViewModel { get; } public abstract ISpecificFunctionsViewModel SpecificFunctionsViewModel { get; } protected abstract IPageLoadingBehaviorCollectionBuilder<TViewModel, TVirtualizationKind> CreateInitialBuilder(int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler); private void SetItems() { var builder = CreateInitialBuilder( GeneralOptionsViewModel.PageSize, _getSchedulers.NotificationScheduler, _getSchedulers.BackgroundScheduler); var afterPageLoadingDecision = PageLoadingBehaviorViewModel.Configure(builder, _backendAccessAdapter.BackendAccess); var afterPageRemovalDecision = PageRemovalBehaviorViewModel.Configure(afterPageLoadingDecision); var afterFetcherKindDecision = FetcherKindViewModel.Configure(afterPageRemovalDecision, _backendAccessAdapter.BackendAccess); var collection = IndexAccessBehaviorViewModel.Configure( afterFetcherKindDecision, _backendAccessAdapter.BackendAccess, FetcherKindViewModel.FetcherKind); Items = collection; } public void Dispose() { _compositeDisposable.Dispose(); } } public class DataVirtualizingCollectionViewModel<TViewModel> : DataVirtualizingCollectionViewModelBaseBase<TViewModel, IDataVirtualizingCollection<TViewModel>> { public DataVirtualizingCollectionViewModel( // parameters IBackendAccessAdapter<TViewModel> backendAccessAdapter, // dependencies IGeneralOptionsViewModel generalOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, IGetSchedulers getSchedulers) : base( backendAccessAdapter, generalOptionsViewModel, pageLoadingBehaviorViewModel, pageRemovalBehaviorViewModel, fetcherKindViewModel, generalFunctionsViewModel, getSchedulers) { } public override ISpecificOptionsViewModel SpecificOptionsViewModel => ViewModels.Options.SpecificOptionsViewModel.Empty; public override ISpecificFunctionsViewModel SpecificFunctionsViewModel => ViewModels.Functions.SpecificFunctionsViewModel.Empty; protected override IPageLoadingBehaviorCollectionBuilder<TViewModel, IDataVirtualizingCollection<TViewModel>> CreateInitialBuilder( int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) { return DataVirtualizingCollectionBuilder.Build<TViewModel>( pageSize, notificationScheduler, backgroundScheduler); } } public class SlidingWindowViewModel<TViewModel> : DataVirtualizingCollectionViewModelBaseBase<TViewModel, ISlidingWindow<TViewModel>> { private readonly ISlidingWindowOptionsViewModel _slidingWindowOptionsViewModel; public SlidingWindowViewModel( // parameters IBackendAccessAdapter<TViewModel> backendAccessAdapter, // dependencies IGeneralOptionsViewModel generalOptionsViewModel, ISlidingWindowOptionsViewModel slidingWindowOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, ISlidingWindowFunctionsViewModel slidingWindowFunctionsViewModel, IGetSchedulers getSchedulers) : base( backendAccessAdapter, generalOptionsViewModel, pageLoadingBehaviorViewModel, pageRemovalBehaviorViewModel, fetcherKindViewModel, generalFunctionsViewModel, getSchedulers) { _slidingWindowOptionsViewModel = slidingWindowOptionsViewModel; SpecificFunctionsViewModel = slidingWindowFunctionsViewModel; } public override ISpecificOptionsViewModel SpecificOptionsViewModel => _slidingWindowOptionsViewModel; public override ISpecificFunctionsViewModel SpecificFunctionsViewModel { get; } protected override IPageLoadingBehaviorCollectionBuilder<TViewModel, ISlidingWindow<TViewModel>> CreateInitialBuilder( int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) { return SlidingWindowBuilder.Build<TViewModel>( _slidingWindowOptionsViewModel.WindowSize, _slidingWindowOptionsViewModel.WindowOffset, pageSize, notificationScheduler, backgroundScheduler); } } internal interface IDataVirtualizingCollectionViewModelFactory { IDataVirtualizingCollectionViewModelBase CreateDataVirtualizingCollection<T>( IBackendAccessAdapter<T> backendAccessAdapter); IDataVirtualizingCollectionViewModelBase CreateSlidingWindow<T>( IBackendAccessAdapter<T> backendAccessAdapter); } internal class DataVirtualizingCollectionViewModelFactory : IDataVirtualizingCollectionViewModelFactory { private readonly IGeneralOptionsViewModel _generalOptionsViewModel; private readonly ISlidingWindowOptionsViewModel _slidingWindowOptionsViewModel; private readonly IPageLoadingBehaviorViewModel _pageLoadingBehaviorViewModel; private readonly IPageRemovalBehaviorViewModel _pageRemovalBehaviorViewModel; private readonly IFetcherKindViewModelInternal _fetcherKindViewModel; private readonly IGeneralFunctionsViewModel _generalFunctionsViewModel; private readonly ISlidingWindowFunctionsViewModel _slidingWindowFunctionsViewModel; private readonly IGetSchedulers _getSchedulers; private readonly CompositeDisposable _compositeDisposableOfLifetimeScope; public DataVirtualizingCollectionViewModelFactory( IGeneralOptionsViewModel generalOptionsViewModel, ISlidingWindowOptionsViewModel slidingWindowOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, ISlidingWindowFunctionsViewModel slidingWindowFunctionsViewModel, IGetSchedulers getSchedulers, CompositeDisposable compositeDisposableOfLifetimeScope) { _generalOptionsViewModel = generalOptionsViewModel; _slidingWindowOptionsViewModel = slidingWindowOptionsViewModel; _pageLoadingBehaviorViewModel = pageLoadingBehaviorViewModel; _pageRemovalBehaviorViewModel = pageRemovalBehaviorViewModel; _fetcherKindViewModel = fetcherKindViewModel; _generalFunctionsViewModel = generalFunctionsViewModel; _slidingWindowFunctionsViewModel = slidingWindowFunctionsViewModel; _getSchedulers = getSchedulers; _compositeDisposableOfLifetimeScope = compositeDisposableOfLifetimeScope; } public IDataVirtualizingCollectionViewModelBase CreateDataVirtualizingCollection<T>(IBackendAccessAdapter<T> backendAccessAdapter) { var ret = new DataVirtualizingCollectionViewModel<T>( backendAccessAdapter, _generalOptionsViewModel, _pageLoadingBehaviorViewModel, _pageRemovalBehaviorViewModel, _fetcherKindViewModel, _generalFunctionsViewModel, _getSchedulers); _compositeDisposableOfLifetimeScope.Add(ret); return ret; } public IDataVirtualizingCollectionViewModelBase CreateSlidingWindow<T>(IBackendAccessAdapter<T> backendAccessAdapter) { var ret = new SlidingWindowViewModel<T>( backendAccessAdapter, _generalOptionsViewModel, _slidingWindowOptionsViewModel, _pageLoadingBehaviorViewModel, _pageRemovalBehaviorViewModel, _fetcherKindViewModel, _generalFunctionsViewModel, _slidingWindowFunctionsViewModel, _getSchedulers); _compositeDisposableOfLifetimeScope.Add(ret); return ret; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using TestLibrary; public class StringConcat8 { private int c_MAX_STRING_LENGTH = 256; private int c_MINI_STRING_LENGTH = 8; public static int Main() { StringConcat8 sc8 = new StringConcat8(); TestLibrary.TestFramework.BeginTestCase("StringConcat8"); if (sc8.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region PositiveTesting public bool PosTest1() { bool retVal = true; Random rand = new Random(-55); string ActualResult; string[] strA = new string[rand.Next(c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH)]; TestLibrary.TestFramework.BeginScenario("PostTest1:Concat string Array with all null member"); try { for (int i = 0; i < strA.Length; i++) { strA[i] = null; } ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("001", "Concat string Array with all null member ExpectResult is" + MergeStrings(strA) + "ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; Random rand = new Random(-55); string ActualResult; string[] strA = new string[rand.Next(c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH)]; TestLibrary.TestFramework.BeginScenario("PostTest2:Concat string Array with all empty member"); try { for (int i = 0; i < strA.Length; i++) { strA[i] = ""; } ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("003", "Concat string Array with all empty member ExpectResult is" + MergeStrings(strA) + " ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string ActualResult; string[] strA; TestLibrary.TestFramework.BeginScenario("PosTest3:Concat string Array with null and empty member"); try { strA = new string[] { null, "", null, "", null, "" }; ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("005", "Concat string Array with null and empty member ExpectResult is equel" + MergeStrings(strA) + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string ActualResult; string[] strA; TestLibrary.TestFramework.BeginScenario("PosTest4: Concat string Array with single letter member"); try { strA = new string[] {"a","b","c","d","e","f"}; ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("007", "Concat string Array with single letter member ExpectResult is" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string ActualResult; string[] strA; TestLibrary.TestFramework.BeginScenario("PosTest5:Concat string Array with null,empty and not nullstrings member"); try { strA = new string[] {null,"a","null","",null,"123"}; ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("009", "Concat string Array with null,empty and not nullstrings member ExpectResult is equel" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string ActualResult; string[] strA; TestLibrary.TestFramework.BeginScenario("PosTest6: Concat string Array with not nullstring and some symbols member one"); try { string str1 = "HelloWorld"; string str2 = "\n"; string str3 = "\t"; string str4 = "\0"; string str5 = "\u0041"; strA = new string[] { str1,str2,str3,str4,str5 }; ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("011", "Concat string Array with not nullstring and some symbols member ExpectResult is equel" + MergeStrings(strA) + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; string ActualResult; string[] strA; TestLibrary.TestFramework.BeginScenario("PosTest7: Concat string Array with not nullstrings and some symbols member two"); try { string str1 = "hello"; string str2 = "\u0020"; string str3 = "World"; string str4 = "\u0020"; string str5 = "!"; strA = new string[] { str1, str2, str3, str4, str5 }; ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("013", "Concat string Array with some strings and some symbols member two ExpectResult is equel" + MergeStrings(strA) + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; string ActualResult; string[] strA; TestLibrary.TestFramework.BeginScenario("PosTest8:Concat string Array with some not nullstrings member one"); try { string str1 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); string str2 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); string str3 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); string str4 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); string str5 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); strA = new string[] { str1, str2, str3, str4, str5 }; ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("015", "Concat string Array with some not nullstrings member one ExpectResult is equel" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; string ActualResult; string[] strA; TestLibrary.TestFramework.BeginScenario("PosTest9:Concat object Array with some not nullstrings member two"); try { string str1 = "helloworld".ToUpper() +"\n"; string str2 = "hello\0world".ToUpper() + "\n"; string str3 = "HELLOWORLD".ToLower() + "\n"; string str4 = "HelloWorld".ToUpper() + "\n"; string str5 = "hello world".Trim(); strA = new string[] { str1, str2, str3, str4, str5 }; ActualResult = string.Concat(strA); if (ActualResult != MergeStrings(strA)) { TestLibrary.TestFramework.LogError("015", "Concat object Array with some not nullstrings member two ExpectResult is equel" + MergeStrings(strA) + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e); retVal = false; } return retVal; } #endregion #region NegativeTesting public bool NegTest1() { bool retVal = true; Random rand = new Random(-55); TestLibrary.TestFramework.BeginScenario("NegTest1: Concat string Array is null"); string[] strA = new string[rand.Next(c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH)]; string ActualResult; try { strA = null; ActualResult = string.Concat(strA); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; Random rand = new Random(-55); string[] strA = new string[50 * 1024 * 1024]; string ActualResult; TestLibrary.TestFramework.BeginScenario("NegTest2: Concat string Array with many strings"); int TotalLength = 0; try { for (int i = 0; i < strA.Length; i++) { strA[i] = "HelloworldHelloworldHelloworldHelloworld!"; TotalLength += strA[i].ToString().Length; } ActualResult = string.Concat(strA); retVal = false; } catch (OutOfMemoryException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } #region Help method private string MergeStrings(string[] strS) { string ResultString = ""; foreach (string str in strS) { if (str == null|| str ==string.Empty ) ResultString += string.Empty; else ResultString += str.ToString(); } return ResultString; } #endregion #endregion }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.CreateViewSection.CS { /// <summary> /// The helper class which give some operation about point and vector. /// The point and vector are both presented by Autodesk.Revit.DB.XYZ structure. /// </summary> public class XYZMath { // Private Members const Double PRECISION = 0.0000000001; // Define a precision of double data // Methods /// <summary> /// Find the middle point of the line. /// </summary> /// <param name="first">the start point of the line</param> /// <param name="second">the end point of the line</param> /// <returns>the middle point of the line</returns> public static Autodesk.Revit.DB.XYZ FindMidPoint(Autodesk.Revit.DB.XYZ first, Autodesk.Revit.DB.XYZ second) { double x = (first.X + second.X) / 2; double y = (first.Y + second.Y) / 2; double z = (first.Z + second.Z) / 2; Autodesk.Revit.DB.XYZ midPoint = new Autodesk.Revit.DB.XYZ (x, y, z); return midPoint; } /// <summary> /// Find the distance between two points /// </summary> /// <param name="first">the first point</param> /// <param name="second">the first point</param> /// <returns>the distance of two points</returns> public static double FindDistance(Autodesk.Revit.DB.XYZ first, Autodesk.Revit.DB.XYZ second) { double x = first.X - second.X; double y = first.Y - second.Y; double z = first.Z - second.Z; return Math.Sqrt(x * x + y * y + z * z); } /// <summary> /// Find the direction vector from first point to second point /// </summary> /// <param name="first">the first point</param> /// <param name="second">the second point</param> /// <returns>the direction vector</returns> public static Autodesk.Revit.DB.XYZ FindDirection(Autodesk.Revit.DB.XYZ first, Autodesk.Revit.DB.XYZ second) { double x = second.X - first.X; double y = second.Y - first.Y; double z = second.Z - first.Z; double distance = FindDistance(first, second); Autodesk.Revit.DB.XYZ direction = new Autodesk.Revit.DB.XYZ (x / distance, y / distance, z / distance); return direction; } /// <summary> /// Find the right direction vector, /// which is the same meaning of RightDirection property in View class /// </summary> /// <param name="viewDirection">the view direction vector</param> /// <returns>the right direction vector</returns> public static Autodesk.Revit.DB.XYZ FindRightDirection(Autodesk.Revit.DB.XYZ viewDirection) { // Because this example only allow the beam to be horizontal, // the created viewSection should be vertical, // the same thing can also be found when the user select wall or floor. // So only need to turn 90 degree around Z axes will get Right Direction. double x = -viewDirection.Y; double y = viewDirection.X; double z = viewDirection.Z; Autodesk.Revit.DB.XYZ direction = new Autodesk.Revit.DB.XYZ (x, y, z); return direction; } /// <summary> /// Find the up direction vector, /// which is the same meaning of UpDirection property in View class /// </summary> /// <param name="viewDirection">the view direction vector</param> /// <returns>the up direction vector</returns> public static Autodesk.Revit.DB.XYZ FindUpDirection(Autodesk.Revit.DB.XYZ viewDirection) { // Because this example only allow the beam to be horizontal, // the created viewSection should be vertical, // the same thing can also be found when the user select wall or floor. // So UpDirection should be z axes. Autodesk.Revit.DB.XYZ direction = new Autodesk.Revit.DB.XYZ (0, 0, 1); return direction; } /// <summary> /// Find the middle point of a profile. /// This method is used to find out middle point of the selected wall or floor. /// </summary> /// <param name="curveArray">the array of curve which form the profile</param> /// <returns>the middle point of the profile</returns> public static Autodesk.Revit.DB.XYZ FindMiddlePoint(CurveArray curveArray) { // First form a point array which include all the end points of the curves List<Autodesk.Revit.DB.XYZ> array = new List<Autodesk.Revit.DB.XYZ>(); foreach (Curve curve in curveArray) { Autodesk.Revit.DB.XYZ first = curve.get_EndPoint(0); Autodesk.Revit.DB.XYZ second = curve.get_EndPoint(1); array.Add(first); array.Add(second); } // Second find the max and min value of three coordinate double maxX = array[0].X; // the max x coordinate in the array double minX = array[0].X; // the min x coordinate in the array double maxY = array[0].Y; // the max y coordinate in the array double minY = array[0].Y; // the min y coordinate in the array double maxZ = array[0].Z; // the max z coordinate in the array double minZ = array[0].Z; // the min z coordinate in the array foreach (Autodesk.Revit.DB.XYZ curve in array) { if (maxX < curve.X) { maxX = curve.X; } if (minX > curve.X) { minX = curve.X; } if (maxY < curve.Y) { maxY = curve.Y; } if (minY > curve.Y) { minY = curve.Y; } if (maxZ < curve.Z) { maxZ = curve.Z; } if (minZ > curve.Z) { minZ = curve.Z; } } // Third form the middle point using the average of max and min values double x = (maxX + minX) / 2; double y = (maxY + minY) / 2; double z = (maxZ + minZ) / 2; Autodesk.Revit.DB.XYZ midPoint = new Autodesk.Revit.DB.XYZ (x, y, z); return midPoint; } /// <summary> /// Find the view direction vector, /// which is the same meaning of ViewDirection property in View class /// </summary> /// <param name="curveArray">the curve array which form wall's AnalyticalModel</param> /// <returns>the view direction vector</returns> public static Autodesk.Revit.DB.XYZ FindWallViewDirection(CurveArray curveArray) { Autodesk.Revit.DB.XYZ direction = new Autodesk.Revit.DB.XYZ (); foreach (Curve curve in curveArray) { Autodesk.Revit.DB.XYZ startPoint = curve.get_EndPoint(0); Autodesk.Revit.DB.XYZ endPoint = curve.get_EndPoint(1); double distanceX = startPoint.X - endPoint.X; double distanceY = startPoint.Y - endPoint.Y; if(-PRECISION > distanceX || PRECISION < distanceX || -PRECISION > distanceY || PRECISION < distanceY) { Autodesk.Revit.DB.XYZ first = new Autodesk.Revit.DB.XYZ (startPoint.X, startPoint.Y, 0); Autodesk.Revit.DB.XYZ second = new Autodesk.Revit.DB.XYZ (endPoint.X, endPoint.Y, 0); direction = FindDirection(first, second); break; } } return direction; } /// <summary> /// Find the view direction vector, /// which is the same meaning of ViewDirection property in View class /// </summary> /// <param name="curveArray">the curve array which form floor's AnalyticalModel</param> /// <returns>the view direction vector</returns> public static Autodesk.Revit.DB.XYZ FindFloorViewDirection(CurveArray curveArray) { // Because the floor is always on the level, // so each curve can give the direction information. Curve curve = curveArray.get_Item(0); Autodesk.Revit.DB.XYZ first = curve.get_EndPoint(0); Autodesk.Revit.DB.XYZ second = curve.get_EndPoint(1); return FindDirection(first, second); } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Reflection; using NUnit.Framework; using Piccolo.Configuration; using Piccolo.Request; using Shouldly; namespace Piccolo.UnitTests.Request { public class RequestHandlerInvokerTests { #region Verbs [TestFixture] public class when_executing_get_request : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { _result = Invoker.Execute(new GetResource(), "GET", new Dictionary<string, string>(), new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("TEST"); } } [TestFixture] public class when_executing_post_request : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "post"}}; _result = Invoker.Execute(new PostResource(), "POST", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("post"); } } [TestFixture] public class when_executing_put_request : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "put"}}; _result = Invoker.Execute(new PutResource(), "PUT", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("put"); } } [TestFixture] public class when_executing_delete_request : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "delete"}}; _result = Invoker.Execute(new DeleteResource(), "DELETE", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("delete"); } } [Route("/RequestHandlerInvokerTests")] public class GetResource : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent("TEST")}); } } [Route("/PostRequestHandlerInvokerTests/{Param}")] public class PostResource : IPost<string, string> { public HttpResponseMessage<string> Post(string parameters) { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(Param)}); } public string Param { get; set; } } [Route("/PutRequestHandlerInvokerTests/{Param}")] public class PutResource : IPut<string, string> { public HttpResponseMessage<string> Put(string task) { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(Param)}); } public string Param { get; set; } } [Route("/DeleteRequestHandlerInvokerTests/{Param}")] public class DeleteResource : IDelete { public HttpResponseMessage<dynamic> Delete() { return new HttpResponseMessage<dynamic>(new HttpResponseMessage {Content = new StringContent(Param)}); } public string Param { get; set; } } #endregion #region Route Parameters [TestFixture] public class when_executing_get_request_with_string_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "TEST"}}; _result = Invoker.Execute(new GetResourceString(), "GET", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET TEST"); } } [TestFixture] public class when_executing_get_request_with_boolean_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "true"}}; _result = Invoker.Execute(new GetResourceBoolean(), "GET", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET True"); } } [TestFixture] public class when_executing_get_request_with_byte_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceByte(), "GET", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_int16_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceInt16(), "GET", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_int32_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceInt32(), "GET", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_datetime_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var routeParameters = new Dictionary<string, string> {{"param", "2013-07-22"}}; _result = Invoker.Execute(new GetResourceDateTime(), "GET", routeParameters, new Dictionary<string, string>(), string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 2013-07-22T00:00:00"); } } [TestFixture] public class when_executing_get_request_with_invalid_parameter_value : given_request_handler_invoker { [Test] public void it_should_thrown_exception() { var routeParameters = new Dictionary<string, string> {{"param", "undefined"}}; Assert.Throws<InvalidOperationException>(() => Invoker.Execute(new GetResourceInt32(), "GET", routeParameters, new Dictionary<string, string>(), string.Empty)); } } [Route("/RequestHandlerInvokerTests/String/{Param}")] public class GetResourceString : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } public String Param { get; set; } } [Route("/RequestHandlerInvokerTests/Boolean/{Param}")] public class GetResourceBoolean : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } public Boolean Param { get; set; } } [Route("/RequestHandlerInvokerTests/Byte/{Param}")] public class GetResourceByte : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } public Byte Param { get; set; } } [Route("/RequestHandlerInvokerTests/Int16/{Param}")] public class GetResourceInt16 : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } public Int16 Param { get; set; } } [Route("/RequestHandlerInvokerTests/Int32/{Param}")] public class GetResourceInt32 : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } public Int32 Param { get; set; } } [Route("/RequestHandlerInvokerTests/DateTime/{Param}")] public class GetResourceDateTime : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0:s}", Param))}); } public DateTime Param { get; set; } } #endregion #region Query Parameters [TestFixture] public class when_executing_get_request_with_optional_string_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "TEST"}}; _result = Invoker.Execute(new GetResourceOptionalString(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET TEST"); } } [TestFixture] public class when_executing_get_request_with_optional_boolean_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "true"}}; _result = Invoker.Execute(new GetResourceOptionalBoolean(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET True"); } } [TestFixture] public class when_executing_get_request_with_optional_nullable_boolean_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "true"}}; _result = Invoker.Execute(new GetResourceOptionalNullableBoolean(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET True"); } } [TestFixture] public class when_executing_get_request_with_optional_byte_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceOptionalByte(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_optional_nullable_byte_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceOptionalNullableByte(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_optional_int16_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceOptionalInt16(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_optional_nullable_int16_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceOptionalNullableInt16(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_optional_int32_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceOptionalInt32(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_optional_nullable_int32_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "1"}}; _result = Invoker.Execute(new GetResourceOptionalNullableInt32(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 1"); } } [TestFixture] public class when_executing_get_request_with_optional_datetime_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "2013-07-22"}}; _result = Invoker.Execute(new GetResourceOptionalDateTime(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 2013-07-22T00:00:00"); } } [TestFixture] public class when_executing_get_request_with_optional_nullable_datetime_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"param", "2013-07-22"}}; _result = Invoker.Execute(new GetResourceOptionalNullableDateTime(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET 2013-07-22T00:00:00"); } } [TestFixture] public class when_executing_get_request_with_redundant_query_parameter : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var queryParameters = new Dictionary<string, string> {{"redundant", ""}}; _result = Invoker.Execute(new GetResourceOptionalString(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("GET "); } } [TestFixture] public class when_executing_get_request_with_invalid_optional_parameter_value : given_request_handler_invoker { [Test] public void it_should_thrown_exception() { var queryParameters = new Dictionary<string, string> {{"param", "undefined"}}; Assert.Throws<InvalidOperationException>(() => Invoker.Execute(new GetResourceOptionalInt32(), "GET", new Dictionary<string, string>(), queryParameters, string.Empty)); } } [Route("/RequestHandlerInvokerTests/String/Optional")] public class GetResourceOptionalString : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public String Param { get; set; } } [Route("/RequestHandlerInvokerTests/Boolean/Optional")] public class GetResourceOptionalBoolean : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Boolean Param { get; set; } } [Route("/RequestHandlerInvokerTests/Boolean/OptionalNullable")] public class GetResourceOptionalNullableBoolean : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Boolean? Param { get; set; } } [Route("/RequestHandlerInvokerTests/Byte/Optional")] public class GetResourceOptionalByte : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Byte Param { get; set; } } [Route("/RequestHandlerInvokerTests/Byte/OptionalNullable")] public class GetResourceOptionalNullableByte : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Byte? Param { get; set; } } [Route("/RequestHandlerInvokerTests/Int16/Optional")] public class GetResourceOptionalInt16 : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Int16 Param { get; set; } } [Route("/RequestHandlerInvokerTests/Int16/OptionalNullable")] public class GetResourceOptionalNullableInt16 : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Int16? Param { get; set; } } [Route("/RequestHandlerInvokerTests/Int32/Optional")] public class GetResourceOptionalInt32 : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Int32 Param { get; set; } } [Route("/RequestHandlerInvokerTests/Int32/OptionalNullable")] public class GetResourceOptionalNullableInt32 : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0}", Param))}); } [Optional] public Int32? Param { get; set; } } [Route("/RequestHandlerInvokerTests/DateTime/Optional")] public class GetResourceOptionalDateTime : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0:s}", Param))}); } [Optional] public DateTime Param { get; set; } } [Route("/RequestHandlerInvokerTests/DateTime/OptionalNullable")] public class GetResourceOptionalNullableDateTime : IGet<string> { public HttpResponseMessage<string> Get() { return new HttpResponseMessage<string>(new HttpResponseMessage {Content = new StringContent(string.Format("GET {0:s}", Param))}); } [Optional] public DateTime? Param { get; set; } } #endregion #region PUT/POST Parameters [TestFixture] public class when_executing_post_request_with_payload : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var payload = "{" + "\"A\":1," + "\"B\":\"2\"" + "}"; _result = Invoker.Execute(new PostResourceWithPayload(), "POST", new Dictionary<string, string>(), new Dictionary<string, string>(), payload).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("A: 1; B: 2"); } } [Route("/PutRequestHandlerInvokerTests/Payload")] public class PostResourceWithPayload : IPost<PostResourceWithPayload.Parameters, PostResourceWithPayload.Parameters> { public HttpResponseMessage<Parameters> Post(Parameters parameters) { var content = string.Format("A: {0}; B: {1}", parameters.A, parameters.B); return new HttpResponseMessage<Parameters>(new HttpResponseMessage {Content = new StringContent(content)}); } public class Parameters { public int A { get; set; } public string B { get; set; } } } [TestFixture] public class when_executing_putt_request_with_payload : given_request_handler_invoker { private string _result; [SetUp] public void SetUp() { var payload = "{" + "\"A\":1," + "\"B\":\"2\"" + "}"; _result = Invoker.Execute(new PutResourceWithPayload(), "PUT", new Dictionary<string, string>(), new Dictionary<string, string>(), payload).Content.ReadAsStringAsync().Result; } [Test] public void it_should_bind_parameters() { _result.ShouldBe("A: 1; B: 2"); } } [Route("/PutRequestHandlerInvokerTests/Payload")] public class PutResourceWithPayload : IPut<PutResourceWithPayload.Parameters, PutResourceWithPayload.Parameters> { public HttpResponseMessage<Parameters> Put(Parameters task) { var content = string.Format("A: {0}; B: {1}", task.A, task.B); return new HttpResponseMessage<Parameters>(new HttpResponseMessage {Content = new StringContent(content)}); } public class Parameters { public int A { get; set; } public string B { get; set; } } } #endregion public abstract class given_request_handler_invoker { protected RequestHandlerInvoker Invoker; protected given_request_handler_invoker() { var configuration = Bootstrapper.ApplyConfiguration(Assembly.GetExecutingAssembly(), false); Invoker = new RequestHandlerInvoker(configuration.JsonDeserialiser, configuration.ParameterBinders); } } } }
using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; namespace MahApps.Metro.Controls { public class DataGridNumericUpDownColumn : DataGridBoundColumn { private static Style _defaultEditingElementStyle; private static Style _defaultElementStyle; static DataGridNumericUpDownColumn() { ElementStyleProperty.OverrideMetadata(typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(DefaultElementStyle)); EditingElementStyleProperty.OverrideMetadata(typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(DefaultEditingElementStyle)); } public static Style DefaultEditingElementStyle { get { if (_defaultEditingElementStyle == null) { Style style = new Style(typeof(NumericUpDown)); style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0))); style.Setters.Add(new Setter(Control.PaddingProperty, new Thickness(0.0))); style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Top)); style.Setters.Add(new Setter(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center)); style.Setters.Add(new Setter(FrameworkElement.MinHeightProperty, 0d)); style.Seal(); _defaultEditingElementStyle = style; } return _defaultEditingElementStyle; } } public static Style DefaultElementStyle { get { if (_defaultElementStyle == null) { Style style = new Style(typeof(NumericUpDown)); style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0d))); style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Top)); style.Setters.Add(new Setter(UIElement.IsHitTestVisibleProperty, false)); style.Setters.Add(new Setter(UIElement.FocusableProperty, false)); style.Setters.Add(new Setter(NumericUpDown.HideUpDownButtonsProperty, true)); style.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.Transparent)); style.Setters.Add(new Setter(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center)); style.Setters.Add(new Setter(FrameworkElement.MinHeightProperty, 0d)); style.Setters.Add(new Setter(ControlsHelper.DisabledVisualElementVisibilityProperty, Visibility.Collapsed)); style.Seal(); _defaultElementStyle = style; } return _defaultElementStyle; } } private static void ApplyBinding(BindingBase binding, DependencyObject target, DependencyProperty property) { if (binding != null) { BindingOperations.SetBinding(target, property, binding); } else { BindingOperations.ClearBinding(target, property); } } private void ApplyStyle(bool isEditing, bool defaultToElementStyle, FrameworkElement element) { Style style = PickStyle(isEditing, defaultToElementStyle); if (style != null) { element.Style = style; } } protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return GenerateNumericUpDown(true, cell); } protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { NumericUpDown generateNumericUpDown = GenerateNumericUpDown(false, cell); generateNumericUpDown.HideUpDownButtons = true; return generateNumericUpDown; } private NumericUpDown GenerateNumericUpDown(bool isEditing, DataGridCell cell) { NumericUpDown numericUpDown = (cell != null) ? (cell.Content as NumericUpDown) : null; if (numericUpDown == null) { numericUpDown = new NumericUpDown(); } SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontFamilyProperty, TextElement.FontFamilyProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontSizeProperty, TextElement.FontSizeProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontStyleProperty, TextElement.FontStyleProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontWeightProperty, TextElement.FontWeightProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.StringFormatProperty, NumericUpDown.StringFormatProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.MinimumProperty, NumericUpDown.MinimumProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.MaximumProperty, NumericUpDown.MaximumProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.IntervalProperty, NumericUpDown.IntervalProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.HideUpDownButtonsProperty, NumericUpDown.HideUpDownButtonsProperty); SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.UpDownButtonsWidthProperty, NumericUpDown.UpDownButtonsWidthProperty); if (isEditing) { SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.ForegroundProperty, TextElement.ForegroundProperty); } else { if (!SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.ForegroundProperty, TextElement.ForegroundProperty)) { ApplyBinding(new Binding(Control.ForegroundProperty.Name) { Source = cell, Mode = BindingMode.OneWay }, numericUpDown, TextElement.ForegroundProperty); } } ApplyStyle(isEditing, true, numericUpDown); ApplyBinding(Binding, numericUpDown, NumericUpDown.ValueProperty); numericUpDown.InterceptArrowKeys = true; numericUpDown.InterceptMouseWheel = true; numericUpDown.Speedup = true; return numericUpDown; } /// <summary> /// Called when a cell has just switched to edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="editingEventArgs">The event args of the input event that caused the cell to go into edit mode. May be null.</param> /// <returns>The unedited value of the cell.</returns> protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { NumericUpDown numericUpDown = editingElement as NumericUpDown; if (numericUpDown != null) { numericUpDown.Focus(); numericUpDown.SelectAll(); return numericUpDown.Value; } return null; } /// <summary> /// Synchronizes the column property. Taken from Helper code for DataGrid. /// </summary> internal static bool SyncColumnProperty(DependencyObject column, DependencyObject content, DependencyProperty columnProperty, DependencyProperty contentProperty) { if (IsDefaultValue(column, columnProperty)) { content.ClearValue(contentProperty); return false; } else { content.SetValue(contentProperty, column.GetValue(columnProperty)); return true; } } /// <summary> /// Taken from Helper code for DataGrid. /// </summary> private static bool IsDefaultValue(DependencyObject d, DependencyProperty dp) { return DependencyPropertyHelper.GetValueSource(d, dp).BaseValueSource == BaseValueSource.Default; } private Style PickStyle(bool isEditing, bool defaultToElementStyle) { Style style = isEditing ? EditingElementStyle : ElementStyle; if (isEditing && defaultToElementStyle && (style == null)) { style = ElementStyle; } return style; } /// <summary> /// The DependencyProperty for the StringFormat property. /// </summary> public static readonly DependencyProperty StringFormatProperty = NumericUpDown.StringFormatProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((string)NumericUpDown.StringFormatProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// Gets or sets the formatting for the displaying value. /// </summary> /// <remarks> /// <see href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx"></see> /// </remarks> public string StringFormat { get { return (string)GetValue(StringFormatProperty); } set { SetValue(StringFormatProperty, value); } } /// <summary> /// The DependencyProperty for the Minimum property. /// </summary> public static readonly DependencyProperty MinimumProperty = NumericUpDown.MinimumProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.MinimumProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double Minimum { get { return (double)GetValue(MinimumProperty); } set { SetValue(MinimumProperty, value); } } /// <summary> /// The DependencyProperty for the Maximum property. /// </summary> public static readonly DependencyProperty MaximumProperty = NumericUpDown.MaximumProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.MaximumProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double Maximum { get { return (double)GetValue(MaximumProperty); } set { SetValue(MaximumProperty, value); } } /// <summary> /// The DependencyProperty for the Interval property. /// </summary> public static readonly DependencyProperty IntervalProperty = NumericUpDown.IntervalProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.IntervalProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double Interval { get { return (double)GetValue(IntervalProperty); } set { SetValue(IntervalProperty, value); } } /// <summary> /// The DependencyProperty for the HideUpDownButtons property. /// </summary> public static readonly DependencyProperty HideUpDownButtonsProperty = NumericUpDown.HideUpDownButtonsProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.HideUpDownButtonsProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool HideUpDownButtons { get { return (bool)GetValue(HideUpDownButtonsProperty); } set { SetValue(HideUpDownButtonsProperty, value); } } /// <summary> /// The DependencyProperty for the UpDownButtonsWidth property. /// </summary> public static readonly DependencyProperty UpDownButtonsWidthProperty = NumericUpDown.UpDownButtonsWidthProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.UpDownButtonsWidthProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double UpDownButtonsWidth { get { return (double)GetValue(UpDownButtonsWidthProperty); } set { SetValue(UpDownButtonsWidthProperty, value); } } /// <summary> /// The DependencyProperty for the FontFamily property. /// Default Value: SystemFonts.MessageFontFamily /// </summary> public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontFamily, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The font family of the desired font. /// </summary> public FontFamily FontFamily { get { return (FontFamily)GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } } /// <summary> /// The DependencyProperty for the FontSize property. /// Default Value: SystemFonts.MessageFontSize /// </summary> public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontSize, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The size of the desired font. /// </summary> [TypeConverter(typeof(FontSizeConverter))] [Localizability(LocalizationCategory.None)] public double FontSize { get { return (double)GetValue(FontSizeProperty); } set { SetValue(FontSizeProperty, value); } } /// <summary> /// The DependencyProperty for the FontStyle property. /// Default Value: SystemFonts.MessageFontStyle /// </summary> public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontStyle, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The style of the desired font. /// </summary> public FontStyle FontStyle { get { return (FontStyle)GetValue(FontStyleProperty); } set { SetValue(FontStyleProperty, value); } } /// <summary> /// The DependencyProperty for the FontWeight property. /// Default Value: SystemFonts.MessageFontWeight /// </summary> public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontWeight, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The weight or thickness of the desired font. /// </summary> public FontWeight FontWeight { get { return (FontWeight)GetValue(FontWeightProperty); } set { SetValue(FontWeightProperty, value); } } /// <summary> /// The DependencyProperty for the Foreground property. /// Default Value: SystemColors.ControlTextBrush /// </summary> public static readonly DependencyProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemColors.ControlTextBrush, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// An brush that describes the foreground color. This overrides the cell foreground inherited color. /// </summary> public Brush Foreground { get { return (Brush)GetValue(ForegroundProperty); } set { SetValue(ForegroundProperty, value); } } /// <summary> /// Method used as property changed callback for properties which need RefreshCellContent to be called /// </summary> private static void NotifyPropertyChangeForRefreshContent(DependencyObject d, DependencyPropertyChangedEventArgs e) { Debug.Assert(d is DataGridNumericUpDownColumn, "d should be a DataGridNumericUpDownColumn"); ((DataGridNumericUpDownColumn)d).NotifyPropertyChanged(e.Property.Name); } /// <summary> /// Rebuilds the contents of a cell in the column in response to a binding change. /// </summary> /// <param name="element">The cell to update.</param> /// <param name="propertyName">The name of the column property that has changed.</param> protected override void RefreshCellContent(FrameworkElement element, string propertyName) { var cell = element as DataGridCell; var numericUpDown = cell?.Content as NumericUpDown; if (numericUpDown != null) { switch (propertyName) { case nameof(FontFamily): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontFamilyProperty, TextElement.FontFamilyProperty); break; case nameof(FontSize): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontSizeProperty, TextElement.FontSizeProperty); break; case nameof(FontStyle): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontStyleProperty, TextElement.FontStyleProperty); break; case nameof(FontWeight): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.FontWeightProperty, TextElement.FontWeightProperty); break; case nameof(StringFormat): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.StringFormatProperty, NumericUpDown.StringFormatProperty); break; case nameof(Minimum): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.MinimumProperty, NumericUpDown.MinimumProperty); break; case nameof(Maximum): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.MaximumProperty, NumericUpDown.MaximumProperty); break; case nameof(Interval): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.IntervalProperty, NumericUpDown.IntervalProperty); break; case nameof(HideUpDownButtons): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.HideUpDownButtonsProperty, NumericUpDown.HideUpDownButtonsProperty); break; case nameof(UpDownButtonsWidth): SyncColumnProperty(this, numericUpDown, DataGridNumericUpDownColumn.UpDownButtonsWidthProperty, NumericUpDown.UpDownButtonsWidthProperty); break; } } base.RefreshCellContent(element, propertyName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestCUInt64() { var test = new BooleanBinaryOpTest__TestCUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestCUInt64 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(UInt64); private const int Op2ElementCount = VectorSize / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector256<UInt64> _clsVar1; private static Vector256<UInt64> _clsVar2; private Vector256<UInt64> _fld1; private Vector256<UInt64> _fld2; private BooleanBinaryOpTest__DataTable<UInt64, UInt64> _dataTable; static BooleanBinaryOpTest__TestCUInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestCUInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<UInt64, UInt64>(_data1, _data2, VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.TestC( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Avx.TestC( Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Avx.TestC( Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Avx.TestC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr); var result = Avx.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestCUInt64(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Avx.TestC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt64> left, Vector256<UInt64> right, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((~left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestC)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.Runtime; using System.Runtime.Serialization; using System.Runtime.InteropServices; using MethodBase = System.Reflection.MethodBase; using Internal.Diagnostics; namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Exception : ISerializable { private void Init() { _message = null; HResult = __HResults.COR_E_EXCEPTION; } public Exception() { Init(); } public Exception(String message) { Init(); _message = message; } // Creates a new Exception. All derived classes should // provide this constructor. // Note: the stack trace is not started until the exception // is thrown // public Exception(String message, Exception innerException) { Init(); _message = message; _innerException = innerException; } protected Exception(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } public virtual String Message { get { if (_message == null) { String className = GetClassName(); return SR.Format(SR.Exception_WasThrown, className); } else { return _message; } } } public new Type GetType() => base.GetType(); public virtual IDictionary Data { get { if (_data == null) _data = new LowLevelListDictionary(); return _data; } } // TargetSite is not supported on CoreRT. Because it's likely use is diagnostic logging, returning null (a permitted return value) // seems more useful than throwing a PlatformNotSupportedException here. public MethodBase TargetSite => null; protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState { add { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); } remove { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); } } #region Interop Helpers internal class __RestrictedErrorObject { private object _realErrorObject; internal __RestrictedErrorObject(object errorObject) { _realErrorObject = errorObject; } public object RealErrorObject { get { return _realErrorObject; } } } internal void AddExceptionDataForRestrictedErrorInfo( string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object restrictedErrorObject) { IDictionary dict = Data; if (dict != null) { dict.Add("RestrictedDescription", restrictedError); dict.Add("RestrictedErrorReference", restrictedErrorReference); dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid); // Keep the error object alive so that user could retrieve error information // using Data["RestrictedErrorReference"] dict.Add("__RestrictedErrorObject", (restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject))); } } internal bool TryGetRestrictedErrorObject(out object restrictedErrorObject) { restrictedErrorObject = null; if (Data != null && Data.Contains("__RestrictedErrorObject")) { __RestrictedErrorObject restrictedObject = Data["__RestrictedErrorObject"] as __RestrictedErrorObject; if (restrictedObject != null) { restrictedErrorObject = restrictedObject.RealErrorObject; return true; } } return false; } internal bool TryGetRestrictedErrorDetails(out string restrictedError, out string restrictedErrorReference, out string restrictedCapabilitySid) { if (Data != null && Data.Contains("__RestrictedErrorObject")) { // We might not need to store this value any more. restrictedError = (string)Data["RestrictedDescription"]; restrictedErrorReference = (string)Data[nameof(restrictedErrorReference)]; restrictedCapabilitySid = (string)Data["RestrictedCapabilitySid"]; return true; } else { restrictedError = null; restrictedErrorReference = null; restrictedCapabilitySid = null; return false; } } /// <summary> /// Allow System.Private.Interop to set HRESULT of an exception /// </summary> internal void SetErrorCode(int hr) { HResult = hr; } /// <summary> /// Allow System.Private.Interop to set message of an exception /// </summary> internal void SetMessage(string msg) { _message = msg; } #endregion private string GetClassName() { return GetType().ToString(); } // Retrieves the lowest exception (inner most) for the given Exception. // This will traverse exceptions using the innerException property. // public virtual Exception GetBaseException() { Exception inner = InnerException; Exception back = this; while (inner != null) { back = inner; inner = inner.InnerException; } return back; } // Returns the inner exception contained in this exception // public Exception InnerException { get { return _innerException; } } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } private string GetStackTrace(bool needFileInfo) { return this.StackTrace; } public virtual String HelpLink { get { return _helpURL; } set { _helpURL = value; } } public virtual String Source { get { if (_source == null && HasBeenThrown) { _source = "<unknown>"; } return _source; } set { _source = value; } } public override String ToString() { return ToString(true, true); } private String ToString(bool needFileLineInfo, bool needMessage) { String message = (needMessage ? Message : null); String s; if (message == null || message.Length <= 0) { s = GetClassName(); } else { s = GetClassName() + ": " + message; } if (_innerException != null) { s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine + " " + SR.Exception_EndOfInnerExceptionStack; } string stackTrace = GetStackTrace(needFileLineInfo); if (stackTrace != null) { s += Environment.NewLine + stackTrace; } return s; } // WARNING: We allow diagnostic tools to directly inspect these three members (_message, _innerException and _HResult) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. internal String _message; private IDictionary _data; private Exception _innerException; private String _helpURL; private String _source; // Mainly used by VB. private int _HResult; // HResult public int HResult { get { return _HResult; } protected set { _HResult = value; } } // Returns the stack trace as a string. If no stack trace is // available, null is returned. public virtual String StackTrace { get { if (!HasBeenThrown) return null; return StackTraceHelper.FormatStackTrace(GetStackIPs(), true); } } internal IntPtr[] GetStackIPs() { IntPtr[] ips = new IntPtr[_idxFirstFreeStackTraceEntry]; if (_corDbgStackTrace != null) { Array.Copy(_corDbgStackTrace, ips, ips.Length); } return ips; } // WARNING: We allow diagnostic tools to directly inspect these two members (_corDbgStackTrace and _idxFirstFreeStackTraceEntry) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. // _corDbgStackTrace: Do not rename: This is for the use of the CorDbg interface. Contains the stack trace as an array of EIP's (ordered from // most nested call to least.) May also include a few "special" IP's from the SpecialIP class: private IntPtr[] _corDbgStackTrace; private int _idxFirstFreeStackTraceEntry; private void AppendStackIP(IntPtr IP, bool isFirstRethrowFrame) { Debug.Assert(!(this is OutOfMemoryException), "Avoid allocations if out of memory"); if (_idxFirstFreeStackTraceEntry == 0) { _corDbgStackTrace = new IntPtr[16]; } else if (isFirstRethrowFrame) { // For the first frame after rethrow, we replace the last entry in the stack trace with the IP // of the rethrow. This is overwriting the IP of where control left the corresponding try // region for the catch that is rethrowing. _corDbgStackTrace[_idxFirstFreeStackTraceEntry - 1] = IP; return; } if (_idxFirstFreeStackTraceEntry >= _corDbgStackTrace.Length) GrowStackTrace(); _corDbgStackTrace[_idxFirstFreeStackTraceEntry++] = IP; } private void GrowStackTrace() { IntPtr[] newArray = new IntPtr[_corDbgStackTrace.Length * 2]; for (int i = 0; i < _corDbgStackTrace.Length; i++) { newArray[i] = _corDbgStackTrace[i]; } _corDbgStackTrace = newArray; } private bool HasBeenThrown { get { return _idxFirstFreeStackTraceEntry != 0; } } private enum RhEHFrameType { RH_EH_FIRST_FRAME = 1, RH_EH_FIRST_RETHROW_FRAME = 2, } [RuntimeExport("AppendExceptionStackFrame")] private static void AppendExceptionStackFrame(object exceptionObj, IntPtr IP, int flags) { // This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions // back into the dispatcher. try { Exception ex = exceptionObj as Exception; if (ex == null) Environment.FailFast("Exceptions must derive from the System.Exception class"); if (!RuntimeExceptionHelpers.SafeToPerformRichExceptionSupport) return; bool isFirstFrame = (flags & (int)RhEHFrameType.RH_EH_FIRST_FRAME) != 0; bool isFirstRethrowFrame = (flags & (int)RhEHFrameType.RH_EH_FIRST_RETHROW_FRAME) != 0; // If out of memory, avoid any calls that may allocate. Otherwise, they may fail // with another OutOfMemoryException, which may lead to infinite recursion. bool outOfMemory = ex is OutOfMemoryException; if (!outOfMemory) ex.AppendStackIP(IP, isFirstRethrowFrame); // CORERT-TODO: RhpEtwExceptionThrown // https://github.com/dotnet/corert/issues/2457 #if !CORERT if (isFirstFrame) { string typeName = !outOfMemory ? ex.GetType().ToString() : "System.OutOfMemoryException"; string message = !outOfMemory ? ex.Message : "Insufficient memory to continue the execution of the program."; unsafe { fixed (char* exceptionTypeName = typeName, exceptionMessage = message) RuntimeImports.RhpEtwExceptionThrown(exceptionTypeName, exceptionMessage, IP, ex.HResult); } } #endif } catch { // We may end up with a confusing stack trace or a confusing ETW trace log, but at least we // can continue to dispatch this exception. } } //================================================================================================================== // Support for ExceptionDispatchInfo class - imports and exports the stack trace. //================================================================================================================== internal EdiCaptureState CaptureEdiState() { IntPtr[] stackTrace = _corDbgStackTrace; if (stackTrace != null) { IntPtr[] newStackTrace = new IntPtr[stackTrace.Length]; Array.Copy(stackTrace, 0, newStackTrace, 0, stackTrace.Length); stackTrace = newStackTrace; } return new EdiCaptureState() { StackTrace = stackTrace }; } internal void RestoreEdiState(EdiCaptureState ediCaptureState) { IntPtr[] stackTrace = ediCaptureState.StackTrace; int idxFirstFreeStackTraceEntry = 0; if (stackTrace != null) { IntPtr[] newStackTrace = new IntPtr[stackTrace.Length + 1]; Array.Copy(stackTrace, 0, newStackTrace, 0, stackTrace.Length); stackTrace = newStackTrace; while (stackTrace[idxFirstFreeStackTraceEntry] != (IntPtr)0) idxFirstFreeStackTraceEntry++; stackTrace[idxFirstFreeStackTraceEntry++] = StackTraceHelper.SpecialIP.EdiSeparator; } // Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance, // they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock. lock (s_EDILock) { _corDbgStackTrace = stackTrace; _idxFirstFreeStackTraceEntry = idxFirstFreeStackTraceEntry; } } internal struct EdiCaptureState { public IntPtr[] StackTrace; } // This is the object against which a lock will be taken // when attempt to restore the EDI. Since its static, its possible // that unrelated exception object restorations could get blocked // for a small duration but that sounds reasonable considering // such scenarios are going to be extremely rare, where timing // matches precisely. private static Object s_EDILock = new Object(); /// <summary> /// This is the binary format for serialized exceptions that get saved into a special buffer that is /// known to WER (by way of a runtime API) and will be saved into triage dumps. This format is known /// to SOS, so any changes must update CurrentSerializationVersion and have corresponding updates to /// SOS. /// </summary> [StructLayout(LayoutKind.Sequential)] private struct SERIALIZED_EXCEPTION_HEADER { internal IntPtr ExceptionEEType; internal Int32 HResult; internal Int32 StackTraceElementCount; // IntPtr * N : StackTrace elements } internal const int CurrentSerializationSignature = 0x31305845; // 'EX01' /// <summary> /// This method performs the serialization of one Exception object into the returned byte[]. /// </summary> internal unsafe byte[] SerializeForDump() { checked { int nStackTraceElements = _idxFirstFreeStackTraceEntry; int cbBuffer = sizeof(SERIALIZED_EXCEPTION_HEADER) + (nStackTraceElements * IntPtr.Size); byte[] buffer = new byte[cbBuffer]; fixed (byte* pBuffer = &buffer[0]) { SERIALIZED_EXCEPTION_HEADER* pHeader = (SERIALIZED_EXCEPTION_HEADER*)pBuffer; pHeader->HResult = _HResult; pHeader->ExceptionEEType = m_pEEType; pHeader->StackTraceElementCount = nStackTraceElements; IntPtr* pStackTraceElements = (IntPtr*)(pBuffer + sizeof(SERIALIZED_EXCEPTION_HEADER)); for (int i = 0; i < nStackTraceElements; i++) { pStackTraceElements[i] = _corDbgStackTrace[i]; } } return buffer; } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// A new piece of functionality /// First published in . /// </summary> public partial class Feature : XenObject<Feature> { public Feature() { } public Feature(string uuid, string name_label, string name_description, bool enabled, bool experimental, string version, XenRef<Host> host) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.enabled = enabled; this.experimental = experimental; this.version = version; this.host = host; } /// <summary> /// Creates a new Feature from a Proxy_Feature. /// </summary> /// <param name="proxy"></param> public Feature(Proxy_Feature proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Feature update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; enabled = update.enabled; experimental = update.experimental; version = update.version; host = update.host; } internal void UpdateFromProxy(Proxy_Feature proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; enabled = (bool)proxy.enabled; experimental = (bool)proxy.experimental; version = proxy.version == null ? null : (string)proxy.version; host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); } public Proxy_Feature ToProxy() { Proxy_Feature result_ = new Proxy_Feature(); result_.uuid = (uuid != null) ? uuid : ""; result_.name_label = (name_label != null) ? name_label : ""; result_.name_description = (name_description != null) ? name_description : ""; result_.enabled = enabled; result_.experimental = experimental; result_.version = (version != null) ? version : ""; result_.host = (host != null) ? host : ""; return result_; } /// <summary> /// Creates a new Feature from a Hashtable. /// </summary> /// <param name="table"></param> public Feature(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); enabled = Marshalling.ParseBool(table, "enabled"); experimental = Marshalling.ParseBool(table, "experimental"); version = Marshalling.ParseString(table, "version"); host = Marshalling.ParseRef<Host>(table, "host"); } public bool DeepEquals(Feature other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._enabled, other._enabled) && Helper.AreEqual2(this._experimental, other._experimental) && Helper.AreEqual2(this._version, other._version) && Helper.AreEqual2(this._host, other._host); } public override string SaveChanges(Session session, string opaqueRef, Feature server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static Feature get_record(Session session, string _feature) { return new Feature((Proxy_Feature)session.proxy.feature_get_record(session.uuid, (_feature != null) ? _feature : "").parse()); } /// <summary> /// Get a reference to the Feature instance with the specified UUID. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Feature> get_by_uuid(Session session, string _uuid) { return XenRef<Feature>.Create(session.proxy.feature_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get all the Feature instances with the given label. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<Feature>> get_by_name_label(Session session, string _label) { return XenRef<Feature>.Create(session.proxy.feature_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse()); } /// <summary> /// Get the uuid field of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_uuid(Session session, string _feature) { return (string)session.proxy.feature_get_uuid(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the name/label field of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_name_label(Session session, string _feature) { return (string)session.proxy.feature_get_name_label(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the name/description field of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_name_description(Session session, string _feature) { return (string)session.proxy.feature_get_name_description(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the enabled field of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static bool get_enabled(Session session, string _feature) { return (bool)session.proxy.feature_get_enabled(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the experimental field of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static bool get_experimental(Session session, string _feature) { return (bool)session.proxy.feature_get_experimental(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the version field of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static string get_version(Session session, string _feature) { return (string)session.proxy.feature_get_version(session.uuid, (_feature != null) ? _feature : "").parse(); } /// <summary> /// Get the host field of the given Feature. /// First published in . /// </summary> /// <param name="session">The session</param> /// <param name="_feature">The opaque_ref of the given feature</param> public static XenRef<Host> get_host(Session session, string _feature) { return XenRef<Host>.Create(session.proxy.feature_get_host(session.uuid, (_feature != null) ? _feature : "").parse()); } /// <summary> /// Return a list of all the Features known to the system. /// First published in . /// </summary> /// <param name="session">The session</param> public static List<XenRef<Feature>> get_all(Session session) { return XenRef<Feature>.Create(session.proxy.feature_get_all(session.uuid).parse()); } /// <summary> /// Get all the Feature Records at once, in a single XML RPC call /// First published in . /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Feature>, Feature> get_all_records(Session session) { return XenRef<Feature>.Create<Proxy_Feature>(session.proxy.feature_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// Indicates whether the feature is enabled /// </summary> public virtual bool enabled { get { return _enabled; } set { if (!Helper.AreEqual(value, _enabled)) { _enabled = value; Changed = true; NotifyPropertyChanged("enabled"); } } } private bool _enabled; /// <summary> /// Indicates whether the feature is experimental (as opposed to stable and fully supported) /// </summary> public virtual bool experimental { get { return _experimental; } set { if (!Helper.AreEqual(value, _experimental)) { _experimental = value; Changed = true; NotifyPropertyChanged("experimental"); } } } private bool _experimental; /// <summary> /// The version of this feature /// </summary> public virtual string version { get { return _version; } set { if (!Helper.AreEqual(value, _version)) { _version = value; Changed = true; NotifyPropertyChanged("version"); } } } private string _version; /// <summary> /// The host where this feature is available /// </summary> public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; Changed = true; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host; } }
// 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 Microsoft.Xunit.Performance; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] namespace Inlining { public static class ConstantArgsULong { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 100000; #endif // Ints feeding math operations. // // Inlining in Bench0xp should enable constant folding // Inlining in Bench0xn will not enable constant folding static ulong Five = 5; static ulong Ten = 10; static ulong Id(ulong x) { return x; } static ulong F00(ulong x) { return x * x; } static bool Bench00p() { ulong t = 10; ulong f = F00(t); return (f == 100); } static bool Bench00n() { ulong t = Ten; ulong f = F00(t); return (f == 100); } static bool Bench00p1() { ulong t = Id(10); ulong f = F00(t); return (f == 100); } static bool Bench00n1() { ulong t = Id(Ten); ulong f = F00(t); return (f == 100); } static bool Bench00p2() { ulong t = Id(10); ulong f = F00(Id(t)); return (f == 100); } static bool Bench00n2() { ulong t = Id(Ten); ulong f = F00(Id(t)); return (f == 100); } static bool Bench00p3() { ulong t = 10; ulong f = F00(Id(Id(t))); return (f == 100); } static bool Bench00n3() { ulong t = Ten; ulong f = F00(Id(Id(t))); return (f == 100); } static bool Bench00p4() { ulong t = 5; ulong f = F00(2 * t); return (f == 100); } static bool Bench00n4() { ulong t = Five; ulong f = F00(2 * t); return (f == 100); } static ulong F01(ulong x) { return 1000 / x; } static bool Bench01p() { ulong t = 10; ulong f = F01(t); return (f == 100); } static bool Bench01n() { ulong t = Ten; ulong f = F01(t); return (f == 100); } static ulong F02(ulong x) { return 20 * (x / 2); } static bool Bench02p() { ulong t = 10; ulong f = F02(t); return (f == 100); } static bool Bench02n() { ulong t = Ten; ulong f = F02(t); return (f == 100); } static ulong F03(ulong x) { return 91 + 1009 % x; } static bool Bench03p() { ulong t = 10; ulong f = F03(t); return (f == 100); } static bool Bench03n() { ulong t = Ten; ulong f = F03(t); return (f == 100); } static ulong F04(ulong x) { return 50 * (x % 4); } static bool Bench04p() { ulong t = 10; ulong f = F04(t); return (f == 100); } static bool Bench04n() { ulong t = Ten; ulong f = F04(t); return (f == 100); } static ulong F06(ulong x) { return 110 - x; } static bool Bench06p() { ulong t = 10; ulong f = F06(t); return (f == 100); } static bool Bench06n() { ulong t = Ten; ulong f = F06(t); return (f == 100); } static ulong F07(ulong x) { return ~x + 111; } static bool Bench07p() { ulong t = 10; ulong f = F07(t); return (f == 100); } static bool Bench07n() { ulong t = Ten; ulong f = F07(t); return (f == 100); } static ulong F071(ulong x) { return (x ^ 0xFFFFFFFFFFFFFFFF) + 111; } static bool Bench07p1() { ulong t = 10; ulong f = F071(t); return (f == 100); } static bool Bench07n1() { ulong t = Ten; ulong f = F071(t); return (f == 100); } static ulong F08(ulong x) { return (x & 0x7) + 98; } static bool Bench08p() { ulong t = 10; ulong f = F08(t); return (f == 100); } static bool Bench08n() { ulong t = Ten; ulong f = F08(t); return (f == 100); } static ulong F09(ulong x) { return (x | 0x7) + 85; } static bool Bench09p() { ulong t = 10; ulong f = F09(t); return (f == 100); } static bool Bench09n() { ulong t = Ten; ulong f = F09(t); return (f == 100); } // Ulongs feeding comparisons. // // Inlining in Bench1xp should enable branch optimization // Inlining in Bench1xn will not enable branch optimization static ulong F10(ulong x) { return x == 10 ? 100u : 0u; } static bool Bench10p() { ulong t = 10; ulong f = F10(t); return (f == 100); } static bool Bench10n() { ulong t = Ten; ulong f = F10(t); return (f == 100); } static ulong F101(ulong x) { return x != 10 ? 0u : 100u; } static bool Bench10p1() { ulong t = 10; ulong f = F101(t); return (f == 100); } static bool Bench10n1() { ulong t = Ten; ulong f = F101(t); return (f == 100); } static ulong F102(ulong x) { return x >= 10 ? 100u : 0u; } static bool Bench10p2() { ulong t = 10; ulong f = F102(t); return (f == 100); } static bool Bench10n2() { ulong t = Ten; ulong f = F102(t); return (f == 100); } static ulong F103(ulong x) { return x <= 10 ? 100u : 0u; } static bool Bench10p3() { ulong t = 10; ulong f = F103(t); return (f == 100); } static bool Bench10n3() { ulong t = Ten; ulong f = F102(t); return (f == 100); } static ulong F11(ulong x) { if (x == 10) { return 100; } else { return 0; } } static bool Bench11p() { ulong t = 10; ulong f = F11(t); return (f == 100); } static bool Bench11n() { ulong t = Ten; ulong f = F11(t); return (f == 100); } static ulong F111(ulong x) { if (x != 10) { return 0; } else { return 100; } } static bool Bench11p1() { ulong t = 10; ulong f = F111(t); return (f == 100); } static bool Bench11n1() { ulong t = Ten; ulong f = F111(t); return (f == 100); } static ulong F112(ulong x) { if (x > 10) { return 0; } else { return 100; } } static bool Bench11p2() { ulong t = 10; ulong f = F112(t); return (f == 100); } static bool Bench11n2() { ulong t = Ten; ulong f = F112(t); return (f == 100); } static ulong F113(ulong x) { if (x < 10) { return 0; } else { return 100; } } static bool Bench11p3() { ulong t = 10; ulong f = F113(t); return (f == 100); } static bool Bench11n3() { ulong t = Ten; ulong f = F113(t); return (f == 100); } // Ununsed (or effectively unused) parameters // // Simple callee analysis may overstate inline benefit static ulong F20(ulong x) { return 100; } static bool Bench20p() { ulong t = 10; ulong f = F20(t); return (f == 100); } static bool Bench20p1() { ulong t = Ten; ulong f = F20(t); return (f == 100); } static ulong F21(ulong x) { return x + 100 - x; } static bool Bench21p() { ulong t = 10; ulong f = F21(t); return (f == 100); } static bool Bench21n() { ulong t = Ten; ulong f = F21(t); return (f == 100); } static ulong F211(ulong x) { return x - x + 100; } static bool Bench21p1() { ulong t = 10; ulong f = F211(t); return (f == 100); } static bool Bench21n1() { ulong t = Ten; ulong f = F211(t); return (f == 100); } static ulong F22(ulong x) { if (x > 0) { return 100; } return 100; } static bool Bench22p() { ulong t = 10; ulong f = F22(t); return (f == 100); } static bool Bench22p1() { ulong t = Ten; ulong f = F22(t); return (f == 100); } static ulong F23(ulong x) { if (x > 0) { return 90 + x; } return 100; } static bool Bench23p() { ulong t = 10; ulong f = F23(t); return (f == 100); } static bool Bench23n() { ulong t = Ten; ulong f = F23(t); return (f == 100); } // Multiple parameters static ulong F30(ulong x, ulong y) { return y * y; } static bool Bench30p() { ulong t = 10; ulong f = F30(t, t); return (f == 100); } static bool Bench30n() { ulong t = Ten; ulong f = F30(t, t); return (f == 100); } static bool Bench30p1() { ulong s = Ten; ulong t = 10; ulong f = F30(s, t); return (f == 100); } static bool Bench30n1() { ulong s = 10; ulong t = Ten; ulong f = F30(s, t); return (f == 100); } static bool Bench30p2() { ulong s = 10; ulong t = 10; ulong f = F30(s, t); return (f == 100); } static bool Bench30n2() { ulong s = Ten; ulong t = Ten; ulong f = F30(s, t); return (f == 100); } static bool Bench30p3() { ulong s = 10; ulong t = s; ulong f = F30(s, t); return (f == 100); } static bool Bench30n3() { ulong s = Ten; ulong t = s; ulong f = F30(s, t); return (f == 100); } static ulong F31(ulong x, ulong y, ulong z) { return z * z; } static bool Bench31p() { ulong t = 10; ulong f = F31(t, t, t); return (f == 100); } static bool Bench31n() { ulong t = Ten; ulong f = F31(t, t, t); return (f == 100); } static bool Bench31p1() { ulong r = Ten; ulong s = Ten; ulong t = 10; ulong f = F31(r, s, t); return (f == 100); } static bool Bench31n1() { ulong r = 10; ulong s = 10; ulong t = Ten; ulong f = F31(r, s, t); return (f == 100); } static bool Bench31p2() { ulong r = 10; ulong s = 10; ulong t = 10; ulong f = F31(r, s, t); return (f == 100); } static bool Bench31n2() { ulong r = Ten; ulong s = Ten; ulong t = Ten; ulong f = F31(r, s, t); return (f == 100); } static bool Bench31p3() { ulong r = 10; ulong s = r; ulong t = s; ulong f = F31(r, s, t); return (f == 100); } static bool Bench31n3() { ulong r = Ten; ulong s = r; ulong t = s; ulong f = F31(r, s, t); return (f == 100); } // Two args, both used static ulong F40(ulong x, ulong y) { return x * x + y * y - 100; } static bool Bench40p() { ulong t = 10; ulong f = F40(t, t); return (f == 100); } static bool Bench40n() { ulong t = Ten; ulong f = F40(t, t); return (f == 100); } static bool Bench40p1() { ulong s = Ten; ulong t = 10; ulong f = F40(s, t); return (f == 100); } static bool Bench40p2() { ulong s = 10; ulong t = Ten; ulong f = F40(s, t); return (f == 100); } static ulong F41(ulong x, ulong y) { return x * y; } static bool Bench41p() { ulong t = 10; ulong f = F41(t, t); return (f == 100); } static bool Bench41n() { ulong t = Ten; ulong f = F41(t, t); return (f == 100); } static bool Bench41p1() { ulong s = 10; ulong t = Ten; ulong f = F41(s, t); return (f == 100); } static bool Bench41p2() { ulong s = Ten; ulong t = 10; ulong f = F41(s, t); return (f == 100); } private static IEnumerable<object[]> MakeArgs(params string[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> TestFuncs = MakeArgs( "Bench00p", "Bench00n", "Bench00p1", "Bench00n1", "Bench00p2", "Bench00n2", "Bench00p3", "Bench00n3", "Bench00p4", "Bench00n4", "Bench01p", "Bench01n", "Bench02p", "Bench02n", "Bench03p", "Bench03n", "Bench04p", "Bench04n", "Bench06p", "Bench06n", "Bench07p", "Bench07n", "Bench07p1", "Bench07n1", "Bench08p", "Bench08n", "Bench09p", "Bench09n", "Bench10p", "Bench10n", "Bench10p1", "Bench10n1", "Bench10p2", "Bench10n2", "Bench10p3", "Bench10n3", "Bench11p", "Bench11n", "Bench11p1", "Bench11n1", "Bench11p2", "Bench11n2", "Bench11p3", "Bench11n3", "Bench20p", "Bench20p1", "Bench21p", "Bench21n", "Bench21p1", "Bench21n1", "Bench22p", "Bench22p1", "Bench23p", "Bench23n", "Bench30p", "Bench30n", "Bench30p1", "Bench30n1", "Bench30p2", "Bench30n2", "Bench30p3", "Bench30n3", "Bench31p", "Bench31n", "Bench31p1", "Bench31n1", "Bench31p2", "Bench31n2", "Bench31p3", "Bench31n3", "Bench40p", "Bench40n", "Bench40p1", "Bench40p2", "Bench41p", "Bench41n", "Bench41p1", "Bench41p2" ); static Func<bool> LookupFunc(object o) { TypeInfo t = typeof(ConstantArgsULong).GetTypeInfo(); MethodInfo m = t.GetDeclaredMethod((string) o); return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>; } [Benchmark] [MemberData(nameof(TestFuncs))] public static void Test(object funcName) { Func<bool> f = LookupFunc(funcName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { f(); } } } } static bool TestBase(Func<bool> f) { bool result = true; for (int i = 0; i < Iterations; i++) { result &= f(); } return result; } public static int Main() { bool result = true; foreach(object[] o in TestFuncs) { string funcName = (string) o[0]; Func<bool> func = LookupFunc(funcName); bool thisResult = TestBase(func); if (!thisResult) { Console.WriteLine("{0} failed", funcName); } result &= thisResult; } return (result ? 100 : -1); } } }
//----------------------------------------------------------------------- // <copyright company="CoApp Project"> // Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors. // Contributors can be discovered using the 'git log' command. // All rights reserved. // </copyright> // <license> // The software is licensed under the Apache 2.0 License (the "License") // You may not use the software except in compliance with the License. // </license> //----------------------------------------------------------------------- namespace ClrPlus.Powershell.Azure.Provider { using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using ClrPlus.Core.Collections; using ClrPlus.Core.Exceptions; using ClrPlus.Core.Extensions; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Powershell.Provider.Utility; using Scripting.Languages.PropertySheet; public class AzureDriveInfo : PSDriveInfo { public const string SAS_GUID = "C28BE884-16CF-4401-8B30-18217CF8FF0D"; internal const string ProviderScheme = "azure"; internal const string ProviderDescription = "azure blob storage"; internal Path Path; internal string Secret; private CloudStorageAccount _account; private CloudBlobClient _blobStore; private readonly IDictionary<string, CloudBlobContainer> _containerCache = new XDictionary<string, CloudBlobContainer>(); private Uri _baseUri; private string _accountName; internal string HostAndPort { get { return Path.HostAndPort; } } internal string ContainerName { get { return Path.Container; } } private bool _isSas; internal string RootPath { get { return Path.SubPath; } } internal CloudBlobClient CloudFileSystem { get { if (_blobStore == null) { // is the secret really a SAS token? // Eric : this is the spot to use the token! if (_isSas) { _account = new CloudStorageAccount(new StorageCredentials(Secret), _baseUri, null, null); _blobStore = _account.CreateCloudBlobClient(); //get it to the right container and stuff /*if (_blobStore == null) throw new ClrPlusException("Couldn't get a CloudBlobClient for SasAccount {0} and SasContainer {1}".format(SasAccountUri, SasContainer));*/ } else { _account = new CloudStorageAccount(new StorageCredentials(_accountName, Secret), _baseUri, null, null); _blobStore = _account.CreateCloudBlobClient(); /* if (_blobStore == null) throw new ClrPlusException("Couldn't get a CloudBlobClient for SasAccount {0} and SasContainer {1}".format(SasAccountUri, SasContainer));*/ } } return _blobStore; } } internal CloudBlobContainer GetContainer(string containerName) { if (_containerCache.ContainsKey(containerName)) { return _containerCache[containerName]; } var container = CloudFileSystem.GetContainerReference(containerName); if (_isSas) { try { container.ListBlobs("$$$JUSTCHECKINGIFTHISCONTAINEREVENEXISTS$$$"); _containerCache.Add(containerName, container); } catch { return null; } return container; } else { if (container.Exists()) { _containerCache.Add(containerName, container); return container; } } return null; } public AzureDriveInfo(Rule aliasRule, ProviderInfo providerInfo, PSCredential psCredential = null) : this(GetDriveInfo(aliasRule, providerInfo, psCredential)) { // continues where the GetDriveInfo left off. /* Path = new Path { HostAndPort = aliasRule.HasProperty("key") ? aliasRule["key"].Value : aliasRule.Parameter, Container = aliasRule.HasProperty("container") ? aliasRule["container"].Value : "", SubPath = aliasRule.HasProperty("root") ? aliasRule["root"].Value.Replace('/', '\\').Replace("\\\\", "\\").Trim('\\') : "", }; Path.Validate(); Secret = aliasRule.HasProperty("secret") ? aliasRule["secret"].Value : psCredential != null ? psCredential.Password.ToUnsecureString() : null; * */ // Path.Validate(); // Secret = aliasRule.HasProperty("secret") ? aliasRule["secret"].Value : psCredential != null ? psCredential.Password.ToUnsecureString() : null; } private static PSDriveInfo GetDriveInfo(Rule aliasRule, ProviderInfo providerInfo, PSCredential psCredential) { var name = aliasRule.Parameter; var account = aliasRule.HasProperty("key") ? aliasRule["key"].Value : name; var container = aliasRule.HasProperty("container") ? aliasRule["container"].Value : ""; if(psCredential == null || (psCredential.UserName == null && psCredential.Password == null)) { psCredential = new PSCredential(account, aliasRule.HasProperty("secret") ? aliasRule["secret"].Value.ToSecureString() : null); } if (string.IsNullOrEmpty(container)) { return new PSDriveInfo(name, providerInfo, @"{0}:\{1}\".format(ProviderScheme, account), ProviderDescription, psCredential); } var root = aliasRule.HasProperty("root") ? aliasRule["root"].Value.Replace('/', '\\').Replace("\\\\", "\\").Trim('\\') : ""; if (string.IsNullOrEmpty(root)) { return new PSDriveInfo(name, providerInfo, @"{0}:\{1}\{2}\".format(ProviderScheme, account, container), ProviderDescription, psCredential); } return new PSDriveInfo(name, providerInfo, @"{0}:\{1}\{2}\{3}\".format(ProviderScheme, account, container, root), ProviderDescription, psCredential); } public AzureDriveInfo(PSDriveInfo driveInfo) : base(driveInfo) { Init(driveInfo.Provider, driveInfo.Root, driveInfo.Credential); } public AzureDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential) : base(name, provider, root, description, credential) { Init(provider, root, credential); } /* public static string SetRoot(string root, PSCredential credential) { if (credential != null && credential.UserName.Contains(" ")) { var sasUsernamePieces = credential.UserName.Split(' '); if (sasUsernamePieces.Length != 2) { throw new ClrPlusException("Wrong number of SASUsername pieces, should be 2"); } if (!sasUsernamePieces[1].IsWebUri()) throw new ClrPlusException("Second part of SASUsername must be a valid Azure Uri"); var containerUri = new Uri(sasUsernamePieces[1]); //TODO Do I actually need to flip the slashes here? I'll do it to be safe for now root = @"azure:\\{0}\{1}".format(sasUsernamePieces[0], containerUri.AbsolutePath.Replace('/', '\\')); SasAccountUri = "https://" + containerUri.Host; SasContainer = containerUri.AbsolutePath; //it's a SASToken! } return root; }*/ private void Init(ProviderInfo provider, string root, PSCredential credential) { // first, try to get the account from the credential // if that fails, attempt to get it from the root. // http://account.blob.core.windows.net ... guess the account, have the base uri // https://account.blob.core.windows.net ... guess the account, have the base uri // azure://coapp ... -> guess the account, generate the baseuri // http://downloads.coapp.org user must supply account, have the base uri // https://downloads.coapp.org user must supply account, have the base uri // http://127.0.0.1:10000/ user must supply account, have the base uri var parsedPath = Path.ParseWithContainer(root); //check if Credential is Sas if (credential != null && credential.UserName != null && credential.Password != null) { if (credential.UserName.Contains(SAS_GUID)) { _accountName = credential.UserName.Split(new[] { SAS_GUID }, StringSplitOptions.RemoveEmptyEntries)[0]; _isSas = true; } else _accountName = credential.UserName; if(parsedPath.Scheme == ProviderScheme) { // generate the baseuri like they do _baseUri = new Uri("https://{0}.blob.core.windows.net/".format(_accountName)); } else { _baseUri = new Uri("{0}://{1}/".format(parsedPath.Scheme, parsedPath.HostAndPort)); } Secret = credential.Password.ToUnsecureString(); } else { if(parsedPath.Scheme == ProviderScheme) { _accountName = parsedPath.HostName; _baseUri = new Uri("https://{0}.blob.core.windows.net/".format(_accountName)); } else if (parsedPath.HostName.ToLower().EndsWith(".blob.core.windows.net")) { _accountName = parsedPath.HostName.Substring(0, parsedPath.HostName.IndexOf('.')); _baseUri = new Uri("{0}://{1}/".format(parsedPath.Scheme, parsedPath.HostAndPort)); } else { // throw xxx } } Path = parsedPath; if (string.IsNullOrEmpty(parsedPath.HostAndPort) || string.IsNullOrEmpty(parsedPath.Scheme)) { Path = parsedPath; return; // this is the root azure namespace. } var pi = provider as AzureProviderInfo; if (pi == null) { throw new ClrPlusException("Invalid ProviderInfo"); } var alldrives = (pi.AddingDrives.Union(pi.Drives)).Select(each => each as AzureDriveInfo).ToArray(); if (parsedPath.Scheme == ProviderScheme) { // it's being passed a full url to a blob storage Path = parsedPath; if (credential == null || credential.Password == null) { // look for another mount off the same account and container for the credential foreach (var d in alldrives.Where(d => d.HostAndPort == HostAndPort && d.ContainerName == ContainerName)) { Secret = d.Secret; return; } // now look for another mount off just the same account for the credential foreach(var d in alldrives.Where(d => d.HostAndPort == HostAndPort)) { Secret = d.Secret; return; } throw new ClrPlusException("Missing credential information for {0} mount '{1}'".format(ProviderScheme, root)); } Secret = credential.Password.ToUnsecureString(); return; } // otherwise, it's an sub-folder off of another mount. foreach (var d in alldrives.Where(d => d.Name == parsedPath.Scheme)) { Path = new Path { HostAndPort = d.HostAndPort, Container = string.IsNullOrEmpty(d.ContainerName) ? parsedPath.HostAndPort : d.ContainerName, SubPath = string.IsNullOrEmpty(d.RootPath) ? parsedPath.SubPath : d.RootPath + '\\' + parsedPath.SubPath }; Path.Validate(); Secret = d.Secret; return; } } internal string ActualHostAndPort { get { return _baseUri == null ? "" : (((_baseUri.Scheme == "https" && _baseUri.Port == 443) || (_baseUri.Scheme == "http" && _baseUri.Port == 80) || _baseUri.Port == 0) ? _baseUri.Host : _baseUri.Host + ":" + _baseUri.Port); } } } /* internal class RelativeBlobDirectoryUri { internal string Container { get; private set; } internal IEnumerable<string> VirtualDirectories { get; private set; } internal RelativeBlobDirectoryUri(string relativeBlobDirectoryUri) { var splitString = relativeBlobDirectoryUri.Split('/'); //if (splitString.Length ==0) bad!!! if (splitString.Length >= 1) { Container = splitString[0]; } if (splitString.Length >= 2) { VirtualDirectories = splitString.Skip(1).ToList(); } } }*/ }
// 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.Immutable; namespace System.Reflection.Metadata.Ecma335 { // TODO: debug metadata blobs // TODO: revisit ctors (public vs internal vs static factories)? public struct BlobEncoder { public BlobBuilder Builder { get; } public BlobEncoder(BlobBuilder builder) { if (builder == null) { Throw.BuilderArgumentNull(); } Builder = builder; } public SignatureTypeEncoder FieldSignature() { Builder.WriteByte((byte)SignatureKind.Field); return new SignatureTypeEncoder(Builder); } /// <exception cref="ArgumentOutOfRangeException"><paramref name="genericArgumentCount"/> is not in range [0, 0xffff].</exception> public GenericTypeArgumentsEncoder MethodSpecificationSignature(int genericArgumentCount) { if (unchecked((uint)genericArgumentCount) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(genericArgumentCount)); } Builder.WriteByte((byte)SignatureKind.MethodSpecification); Builder.WriteCompressedInteger(genericArgumentCount); return new GenericTypeArgumentsEncoder(Builder); } /// <exception cref="ArgumentOutOfRangeException"><paramref name="genericParameterCount"/> is not in range [0, 0xffff].</exception> public MethodSignatureEncoder MethodSignature( SignatureCallingConvention convention = SignatureCallingConvention.Default, int genericParameterCount = 0, bool isInstanceMethod = false) { if (unchecked((uint)genericParameterCount) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(genericParameterCount)); } var attributes = (genericParameterCount != 0 ? SignatureAttributes.Generic : 0) | (isInstanceMethod ? SignatureAttributes.Instance : 0); Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, attributes).RawValue); if (genericParameterCount != 0) { Builder.WriteCompressedInteger(genericParameterCount); } return new MethodSignatureEncoder(Builder, hasVarArgs: convention == SignatureCallingConvention.VarArgs); } public MethodSignatureEncoder PropertySignature(bool isInstanceProperty = false) { Builder.WriteByte(new SignatureHeader(SignatureKind.Property, SignatureCallingConvention.Default, (isInstanceProperty ? SignatureAttributes.Instance : 0)).RawValue); return new MethodSignatureEncoder(Builder, hasVarArgs: false); } public void CustomAttributeSignature(out FixedArgumentsEncoder fixedArguments, out CustomAttributeNamedArgumentsEncoder namedArguments) { Builder.WriteUInt16(0x0001); fixedArguments = new FixedArgumentsEncoder(Builder); namedArguments = new CustomAttributeNamedArgumentsEncoder(Builder); } public void CustomAttributeSignature(Action<FixedArgumentsEncoder> fixedArguments, Action<CustomAttributeNamedArgumentsEncoder> namedArguments) { if (fixedArguments == null) Throw.ArgumentNull(nameof(fixedArguments)); if (namedArguments == null) Throw.ArgumentNull(nameof(namedArguments)); FixedArgumentsEncoder fixedArgumentsEncoder; CustomAttributeNamedArgumentsEncoder namedArgumentsEncoder; CustomAttributeSignature(out fixedArgumentsEncoder, out namedArgumentsEncoder); fixedArguments(fixedArgumentsEncoder); namedArguments(namedArgumentsEncoder); } /// <exception cref="ArgumentOutOfRangeException"><paramref name="variableCount"/> is not in range [0, 0x1fffffff].</exception> public LocalVariablesEncoder LocalVariableSignature(int variableCount) { if (unchecked((uint)variableCount) > BlobWriterImpl.MaxCompressedIntegerValue) { Throw.ArgumentOutOfRange(nameof(variableCount)); } Builder.WriteByte((byte)SignatureKind.LocalVariables); Builder.WriteCompressedInteger(variableCount); return new LocalVariablesEncoder(Builder); } // TODO: TypeSpec is limited to structured types (doesn't have primitive types) public SignatureTypeEncoder TypeSpecificationSignature() { return new SignatureTypeEncoder(Builder); } /// <exception cref="ArgumentOutOfRangeException"><paramref name="attributeCount"/> is not in range [0, 0x1fffffff].</exception> public PermissionSetEncoder PermissionSetBlob(int attributeCount) { if (unchecked((uint)attributeCount) > BlobWriterImpl.MaxCompressedIntegerValue) { Throw.ArgumentOutOfRange(nameof(attributeCount)); } Builder.WriteByte((byte)'.'); Builder.WriteCompressedInteger(attributeCount); return new PermissionSetEncoder(Builder); } public NamedArgumentsEncoder PermissionSetArguments(int argumentCount) { if (unchecked((uint)argumentCount) > BlobWriterImpl.MaxCompressedIntegerValue) { Throw.ArgumentOutOfRange(nameof(argumentCount)); } Builder.WriteCompressedInteger(argumentCount); return new NamedArgumentsEncoder(Builder); } } public struct MethodSignatureEncoder { public BlobBuilder Builder { get; } public bool HasVarArgs { get; } public MethodSignatureEncoder(BlobBuilder builder, bool hasVarArgs) { Builder = builder; HasVarArgs = hasVarArgs; } public void Parameters(int parameterCount, out ReturnTypeEncoder returnType, out ParametersEncoder parameters) { if (unchecked((uint)parameterCount) > BlobWriterImpl.MaxCompressedIntegerValue) { Throw.ArgumentOutOfRange(nameof(parameterCount)); } Builder.WriteCompressedInteger(parameterCount); returnType = new ReturnTypeEncoder(Builder); parameters = new ParametersEncoder(Builder, hasVarArgs: HasVarArgs); } public void Parameters(int parameterCount, Action<ReturnTypeEncoder> returnType, Action<ParametersEncoder> parameters) { if (returnType == null) Throw.ArgumentNull(nameof(returnType)); if (parameters == null) Throw.ArgumentNull(nameof(parameters)); ReturnTypeEncoder returnTypeEncoder; ParametersEncoder parametersEncoder; Parameters(parameterCount, out returnTypeEncoder, out parametersEncoder); returnType(returnTypeEncoder); parameters(parametersEncoder); } } public struct LocalVariablesEncoder { public BlobBuilder Builder { get; } public LocalVariablesEncoder(BlobBuilder builder) { Builder = builder; } public LocalVariableTypeEncoder AddVariable() { return new LocalVariableTypeEncoder(Builder); } } public struct LocalVariableTypeEncoder { public BlobBuilder Builder { get; } public LocalVariableTypeEncoder(BlobBuilder builder) { Builder = builder; } public CustomModifiersEncoder CustomModifiers() { return new CustomModifiersEncoder(Builder); } public SignatureTypeEncoder Type(bool isByRef = false, bool isPinned = false) { if (isPinned) { Builder.WriteByte((byte)SignatureTypeCode.Pinned); } if (isByRef) { Builder.WriteByte((byte)SignatureTypeCode.ByReference); } return new SignatureTypeEncoder(Builder); } public void TypedReference() { Builder.WriteByte((byte)SignatureTypeCode.TypedReference); } } public struct ParameterTypeEncoder { public BlobBuilder Builder { get; } public ParameterTypeEncoder(BlobBuilder builder) { Builder = builder; } public CustomModifiersEncoder CustomModifiers() { return new CustomModifiersEncoder(Builder); } public SignatureTypeEncoder Type(bool isByRef = false) { if (isByRef) { Builder.WriteByte((byte)SignatureTypeCode.ByReference); } return new SignatureTypeEncoder(Builder); } public void TypedReference() { Builder.WriteByte((byte)SignatureTypeCode.TypedReference); } } public struct PermissionSetEncoder { public BlobBuilder Builder { get; } public PermissionSetEncoder(BlobBuilder builder) { Builder = builder; } public PermissionSetEncoder AddPermission(string typeName, ImmutableArray<byte> encodedArguments) { if (typeName == null) { Throw.ArgumentNull(nameof(typeName)); } if (encodedArguments.IsDefault) { Throw.ArgumentNull(nameof(encodedArguments)); } if (encodedArguments.Length > BlobWriterImpl.MaxCompressedIntegerValue) { Throw.BlobTooLarge(nameof(encodedArguments)); } Builder.WriteSerializedString(typeName); Builder.WriteCompressedInteger(encodedArguments.Length); Builder.WriteBytes(encodedArguments); return new PermissionSetEncoder(Builder); } public PermissionSetEncoder AddPermission(string typeName, BlobBuilder encodedArguments) { if (typeName == null) { Throw.ArgumentNull(nameof(typeName)); } if (encodedArguments == null) { Throw.ArgumentNull(nameof(encodedArguments)); } if (encodedArguments.Count > BlobWriterImpl.MaxCompressedIntegerValue) { Throw.BlobTooLarge(nameof(encodedArguments)); } Builder.WriteSerializedString(typeName); Builder.WriteCompressedInteger(encodedArguments.Count); encodedArguments.WriteContentTo(Builder); return new PermissionSetEncoder(Builder); } } public struct GenericTypeArgumentsEncoder { public BlobBuilder Builder { get; } public GenericTypeArgumentsEncoder(BlobBuilder builder) { Builder = builder; } public SignatureTypeEncoder AddArgument() { return new SignatureTypeEncoder(Builder); } } public struct FixedArgumentsEncoder { public BlobBuilder Builder { get; } public FixedArgumentsEncoder(BlobBuilder builder) { Builder = builder; } public LiteralEncoder AddArgument() { return new LiteralEncoder(Builder); } } public struct LiteralEncoder { public BlobBuilder Builder { get; } public LiteralEncoder(BlobBuilder builder) { Builder = builder; } public VectorEncoder Vector() { return new VectorEncoder(Builder); } public void TaggedVector(out CustomAttributeArrayTypeEncoder arrayType, out VectorEncoder vector) { arrayType = new CustomAttributeArrayTypeEncoder(Builder); vector = new VectorEncoder(Builder); } public void TaggedVector(Action<CustomAttributeArrayTypeEncoder> arrayType, Action<VectorEncoder> vector) { if (arrayType == null) Throw.ArgumentNull(nameof(arrayType)); if (vector == null) Throw.ArgumentNull(nameof(vector)); CustomAttributeArrayTypeEncoder arrayTypeEncoder; VectorEncoder vectorEncoder; TaggedVector(out arrayTypeEncoder, out vectorEncoder); arrayType(arrayTypeEncoder); vector(vectorEncoder); } public ScalarEncoder Scalar() { return new ScalarEncoder(Builder); } public void TaggedScalar(out CustomAttributeElementTypeEncoder type, out ScalarEncoder scalar) { type = new CustomAttributeElementTypeEncoder(Builder); scalar = new ScalarEncoder(Builder); } public void TaggedScalar(Action<CustomAttributeElementTypeEncoder> type, Action<ScalarEncoder> scalar) { if (type == null) Throw.ArgumentNull(nameof(type)); if (scalar == null) Throw.ArgumentNull(nameof(scalar)); CustomAttributeElementTypeEncoder typeEncoder; ScalarEncoder scalarEncoder; TaggedScalar(out typeEncoder, out scalarEncoder); type(typeEncoder); scalar(scalarEncoder); } } public struct ScalarEncoder { public BlobBuilder Builder { get; } public ScalarEncoder(BlobBuilder builder) { Builder = builder; } public void NullArray() { Builder.WriteInt32(-1); } public void Constant(object value) { string str = value as string; if (str != null || value == null) { String(str); } else { Builder.WriteConstant(value); } } public void SystemType(string serializedTypeName) { String(serializedTypeName); } private void String(string value) { Builder.WriteSerializedString(value); } } public struct LiteralsEncoder { public BlobBuilder Builder { get; } public LiteralsEncoder(BlobBuilder builder) { Builder = builder; } public LiteralEncoder AddLiteral() { return new LiteralEncoder(Builder); } } public struct VectorEncoder { public BlobBuilder Builder { get; } public VectorEncoder(BlobBuilder builder) { Builder = builder; } public LiteralsEncoder Count(int count) { Builder.WriteUInt32((uint)count); return new LiteralsEncoder(Builder); } } public struct NameEncoder { public BlobBuilder Builder { get; } public NameEncoder(BlobBuilder builder) { Builder = builder; } public void Name(string name) { Builder.WriteSerializedString(name); } } public struct CustomAttributeNamedArgumentsEncoder { public BlobBuilder Builder { get; } public CustomAttributeNamedArgumentsEncoder(BlobBuilder builder) { Builder = builder; } public NamedArgumentsEncoder Count(int count) { if (unchecked((ushort)count) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(count)); } Builder.WriteUInt16((ushort)count); return new NamedArgumentsEncoder(Builder); } } public struct NamedArgumentsEncoder { public BlobBuilder Builder { get; } public NamedArgumentsEncoder(BlobBuilder builder) { Builder = builder; } public void AddArgument(bool isField, out NamedArgumentTypeEncoder type, out NameEncoder name, out LiteralEncoder literal) { Builder.WriteByte(isField ? (byte)CustomAttributeNamedArgumentKind.Field : (byte)CustomAttributeNamedArgumentKind.Property); type = new NamedArgumentTypeEncoder(Builder); name = new NameEncoder(Builder); literal = new LiteralEncoder(Builder); } public void AddArgument(bool isField, Action<NamedArgumentTypeEncoder> type, Action<NameEncoder> name, Action<LiteralEncoder> literal) { if (type == null) Throw.ArgumentNull(nameof(type)); if (name == null) Throw.ArgumentNull(nameof(name)); if (literal == null) Throw.ArgumentNull(nameof(literal)); NamedArgumentTypeEncoder typeEncoder; NameEncoder nameEncoder; LiteralEncoder literalEncoder; AddArgument(isField, out typeEncoder, out nameEncoder, out literalEncoder); type(typeEncoder); name(nameEncoder); literal(literalEncoder); } } public struct NamedArgumentTypeEncoder { public BlobBuilder Builder { get; } public NamedArgumentTypeEncoder(BlobBuilder builder) { Builder = builder; } public CustomAttributeElementTypeEncoder ScalarType() { return new CustomAttributeElementTypeEncoder(Builder); } public void Object() { Builder.WriteByte((byte)SerializationTypeCode.TaggedObject); } public CustomAttributeArrayTypeEncoder SZArray() { return new CustomAttributeArrayTypeEncoder(Builder); } } public struct CustomAttributeArrayTypeEncoder { public BlobBuilder Builder { get; } public CustomAttributeArrayTypeEncoder(BlobBuilder builder) { Builder = builder; } public void ObjectArray() { Builder.WriteByte((byte)SerializationTypeCode.SZArray); Builder.WriteByte((byte)SerializationTypeCode.TaggedObject); } public CustomAttributeElementTypeEncoder ElementType() { Builder.WriteByte((byte)SerializationTypeCode.SZArray); return new CustomAttributeElementTypeEncoder(Builder); } } public struct CustomAttributeElementTypeEncoder { public BlobBuilder Builder { get; } public CustomAttributeElementTypeEncoder(BlobBuilder builder) { Builder = builder; } private void WriteTypeCode(SerializationTypeCode value) { Builder.WriteByte((byte)value); } public void Boolean() => WriteTypeCode(SerializationTypeCode.Boolean); public void Char() => WriteTypeCode(SerializationTypeCode.Char); public void SByte() => WriteTypeCode(SerializationTypeCode.SByte); public void Byte() => WriteTypeCode(SerializationTypeCode.Byte); public void Int16() => WriteTypeCode(SerializationTypeCode.Int16); public void UInt16() => WriteTypeCode(SerializationTypeCode.UInt16); public void Int32() => WriteTypeCode(SerializationTypeCode.Int32); public void UInt32() => WriteTypeCode(SerializationTypeCode.UInt32); public void Int64() => WriteTypeCode(SerializationTypeCode.Int64); public void UInt64() => WriteTypeCode(SerializationTypeCode.UInt64); public void Single() => WriteTypeCode(SerializationTypeCode.Single); public void Double() => WriteTypeCode(SerializationTypeCode.Double); public void String() => WriteTypeCode(SerializationTypeCode.String); public void PrimitiveType(PrimitiveSerializationTypeCode type) { switch (type) { case PrimitiveSerializationTypeCode.Boolean: case PrimitiveSerializationTypeCode.Byte: case PrimitiveSerializationTypeCode.SByte: case PrimitiveSerializationTypeCode.Char: case PrimitiveSerializationTypeCode.Int16: case PrimitiveSerializationTypeCode.UInt16: case PrimitiveSerializationTypeCode.Int32: case PrimitiveSerializationTypeCode.UInt32: case PrimitiveSerializationTypeCode.Int64: case PrimitiveSerializationTypeCode.UInt64: case PrimitiveSerializationTypeCode.Single: case PrimitiveSerializationTypeCode.Double: case PrimitiveSerializationTypeCode.String: WriteTypeCode((SerializationTypeCode)type); return; default: Throw.ArgumentOutOfRange(nameof(type)); return; } } public void SystemType() { WriteTypeCode(SerializationTypeCode.Type); } public void Enum(string enumTypeName) { WriteTypeCode(SerializationTypeCode.Enum); Builder.WriteSerializedString(enumTypeName); } } public enum FunctionPointerAttributes { None = SignatureAttributes.None, HasThis = SignatureAttributes.Instance, HasExplicitThis = SignatureAttributes.Instance | SignatureAttributes.ExplicitThis } public struct SignatureTypeEncoder { public BlobBuilder Builder { get; } public SignatureTypeEncoder(BlobBuilder builder) { Builder = builder; } private void WriteTypeCode(SignatureTypeCode value) { Builder.WriteByte((byte)value); } private void ClassOrValue(bool isValueType) { Builder.WriteByte(isValueType ? (byte)SignatureTypeKind.ValueType : (byte)SignatureTypeKind.Class); } public void Boolean() => WriteTypeCode(SignatureTypeCode.Boolean); public void Char() => WriteTypeCode(SignatureTypeCode.Char); public void SByte() => WriteTypeCode(SignatureTypeCode.SByte); public void Byte() => WriteTypeCode(SignatureTypeCode.Byte); public void Int16() => WriteTypeCode(SignatureTypeCode.Int16); public void UInt16() => WriteTypeCode(SignatureTypeCode.UInt16); public void Int32() => WriteTypeCode(SignatureTypeCode.Int32); public void UInt32() => WriteTypeCode(SignatureTypeCode.UInt32); public void Int64() => WriteTypeCode(SignatureTypeCode.Int64); public void UInt64() => WriteTypeCode(SignatureTypeCode.UInt64); public void Single() => WriteTypeCode(SignatureTypeCode.Single); public void Double() => WriteTypeCode(SignatureTypeCode.Double); public void String() => WriteTypeCode(SignatureTypeCode.String); public void IntPtr() => WriteTypeCode(SignatureTypeCode.IntPtr); public void UIntPtr() => WriteTypeCode(SignatureTypeCode.UIntPtr); public void Object() => WriteTypeCode(SignatureTypeCode.Object); /// <summary> /// Writes primitive type code. /// </summary> /// <param name="type">Any primitive type code except for <see cref="PrimitiveTypeCode.TypedReference"/> and <see cref="PrimitiveTypeCode.Void"/>.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="type"/> is not valid in this context.</exception> public void PrimitiveType(PrimitiveTypeCode type) { switch (type) { case PrimitiveTypeCode.Boolean: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Char: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: case PrimitiveTypeCode.Single: case PrimitiveTypeCode.Double: case PrimitiveTypeCode.IntPtr: case PrimitiveTypeCode.UIntPtr: case PrimitiveTypeCode.String: case PrimitiveTypeCode.Object: Builder.WriteByte((byte)type); return; case PrimitiveTypeCode.TypedReference: case PrimitiveTypeCode.Void: default: Throw.ArgumentOutOfRange(nameof(type)); return; } } public void Array(out SignatureTypeEncoder elementType, out ArrayShapeEncoder arrayShape) { Builder.WriteByte((byte)SignatureTypeCode.Array); elementType = this; arrayShape = new ArrayShapeEncoder(Builder); } public void Array(Action<SignatureTypeEncoder> elementType, Action<ArrayShapeEncoder> arrayShape) { if (elementType == null) Throw.ArgumentNull(nameof(elementType)); if (arrayShape == null) Throw.ArgumentNull(nameof(arrayShape)); SignatureTypeEncoder elementTypeEncoder; ArrayShapeEncoder arrayShapeEncoder; Array(out elementTypeEncoder, out arrayShapeEncoder); elementType(elementTypeEncoder); arrayShape(arrayShapeEncoder); } /// <summary> /// Encodes a reference to a type. /// </summary> /// <param name="type"><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/>.</param> /// <param name="isValueType">True to mark the type as value type, false to mark it as a reference type in the signature.</param> /// <exception cref="ArgumentException"><paramref name="type"/> doesn't have the expected handle kind.</exception> public void Type(EntityHandle type, bool isValueType) { // Get the coded index before we start writing anything (might throw argument exception): // Note: We don't allow TypeSpec as per https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/Ecma-335-Issues.md#proposed-specification-change int codedIndex = CodedIndex.TypeDefOrRef(type); ClassOrValue(isValueType); Builder.WriteCompressedInteger(codedIndex); } /// <summary> /// Starts a function pointer signature. /// </summary> /// <param name="convention">Calling convention.</param> /// <param name="attributes">Function pointer attributes.</param> /// <param name="genericParameterCount">Generic parameter count.</param> /// <exception cref="ArgumentException"><paramref name="attributes"/> is invalid.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="genericParameterCount"/> is not in range [0, 0xffff].</exception> public MethodSignatureEncoder FunctionPointer( SignatureCallingConvention convention = SignatureCallingConvention.Default, FunctionPointerAttributes attributes = FunctionPointerAttributes.None, int genericParameterCount = 0) { // Spec: // The EXPLICITTHIS (0x40) bit can be set only in signatures for function pointers. // If EXPLICITTHIS (0x40) in the signature is set, then HASTHIS (0x20) shall also be set. if (attributes != FunctionPointerAttributes.None && attributes != FunctionPointerAttributes.HasThis && attributes != FunctionPointerAttributes.HasExplicitThis) { throw new ArgumentException(SR.InvalidSignature, nameof(attributes)); } if (unchecked((uint)genericParameterCount) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(genericParameterCount)); } Builder.WriteByte((byte)SignatureTypeCode.FunctionPointer); Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, (SignatureAttributes)attributes).RawValue); if (genericParameterCount != 0) { Builder.WriteCompressedInteger(genericParameterCount); } return new MethodSignatureEncoder(Builder, hasVarArgs: convention == SignatureCallingConvention.VarArgs); } /// <summary> /// Starts a generic instantiation signature. /// </summary> /// <param name="genericType"><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/>.</param> /// <param name="genericArgumentCount">Generic argument count.</param> /// <param name="isValueType">True to mark the type as value type, false to mark it as a reference type in the signature.</param> /// <exception cref="ArgumentException"><paramref name="genericType"/> doesn't have the expected handle kind.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="genericArgumentCount"/> is not in range [1, 0xffff].</exception> public GenericTypeArgumentsEncoder GenericInstantiation(EntityHandle genericType, int genericArgumentCount, bool isValueType) { if (unchecked((uint)(genericArgumentCount - 1)) > ushort.MaxValue - 1) { Throw.ArgumentOutOfRange(nameof(genericArgumentCount)); } // Get the coded index before we start writing anything (might throw argument exception): // Note: We don't allow TypeSpec as per https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/Ecma-335-Issues.md#proposed-specification-change int codedIndex = CodedIndex.TypeDefOrRef(genericType); Builder.WriteByte((byte)SignatureTypeCode.GenericTypeInstance); ClassOrValue(isValueType); Builder.WriteCompressedInteger(codedIndex); Builder.WriteCompressedInteger(genericArgumentCount); return new GenericTypeArgumentsEncoder(Builder); } /// <summary> /// Encodes a reference to type parameter of a containing generic method. /// </summary> /// <param name="parameterIndex">Parameter index.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="parameterIndex"/> is not in range [0, 0xffff].</exception> public void GenericMethodTypeParameter(int parameterIndex) { if (unchecked((uint)parameterIndex) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(parameterIndex)); } Builder.WriteByte((byte)SignatureTypeCode.GenericMethodParameter); Builder.WriteCompressedInteger(parameterIndex); } /// <summary> /// Encodes a reference to type parameter of a containing generic type. /// </summary> /// <param name="parameterIndex">Parameter index.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="parameterIndex"/> is not in range [0, 0xffff].</exception> public void GenericTypeParameter(int parameterIndex) { if (unchecked((uint)parameterIndex) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(parameterIndex)); } Builder.WriteByte((byte)SignatureTypeCode.GenericTypeParameter); Builder.WriteCompressedInteger(parameterIndex); } /// <summary> /// Starts pointer signature. /// </summary> public SignatureTypeEncoder Pointer() { Builder.WriteByte((byte)SignatureTypeCode.Pointer); return this; } /// <summary> /// Encodes <code>void*</code>. /// </summary> public void VoidPointer() { Builder.WriteByte((byte)SignatureTypeCode.Pointer); Builder.WriteByte((byte)SignatureTypeCode.Void); } /// <summary> /// Starts SZ array (vector) signature. /// </summary> public SignatureTypeEncoder SZArray() { Builder.WriteByte((byte)SignatureTypeCode.SZArray); return this; } /// <summary> /// Starts a signature of a type with custom modifiers. /// </summary> public CustomModifiersEncoder CustomModifiers() { return new CustomModifiersEncoder(Builder); } } public struct CustomModifiersEncoder { public BlobBuilder Builder { get; } public CustomModifiersEncoder(BlobBuilder builder) { Builder = builder; } public CustomModifiersEncoder AddModifier(bool isOptional, EntityHandle typeDefRefSpec) { if (isOptional) { Builder.WriteByte((byte)SignatureTypeCode.OptionalModifier); } else { Builder.WriteByte((byte)SignatureTypeCode.RequiredModifier); } Builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(typeDefRefSpec)); return this; } } public struct ArrayShapeEncoder { public BlobBuilder Builder { get; } public ArrayShapeEncoder(BlobBuilder builder) { Builder = builder; } public void Shape(int rank, ImmutableArray<int> sizes, ImmutableArray<int> lowerBounds) { Builder.WriteCompressedInteger(rank); Builder.WriteCompressedInteger(sizes.Length); foreach (int size in sizes) { Builder.WriteCompressedInteger(size); } if (lowerBounds.IsDefault) { Builder.WriteCompressedInteger(rank); for (int i = 0; i < rank; i++) { Builder.WriteCompressedSignedInteger(0); } } else { Builder.WriteCompressedInteger(lowerBounds.Length); foreach (int lowerBound in lowerBounds) { Builder.WriteCompressedSignedInteger(lowerBound); } } } } public struct ReturnTypeEncoder { public BlobBuilder Builder { get; } public ReturnTypeEncoder(BlobBuilder builder) { Builder = builder; } public CustomModifiersEncoder CustomModifiers() { return new CustomModifiersEncoder(Builder); } public SignatureTypeEncoder Type(bool isByRef = false) { if (isByRef) { Builder.WriteByte((byte)SignatureTypeCode.ByReference); } return new SignatureTypeEncoder(Builder); } public void TypedReference() { Builder.WriteByte((byte)SignatureTypeCode.TypedReference); } public void Void() { Builder.WriteByte((byte)SignatureTypeCode.Void); } } public struct ParametersEncoder { public BlobBuilder Builder { get; } public bool HasVarArgs { get; } public ParametersEncoder(BlobBuilder builder, bool hasVarArgs) { Builder = builder; HasVarArgs = hasVarArgs; } public ParameterTypeEncoder AddParameter() { return new ParameterTypeEncoder(Builder); } public ParametersEncoder StartVarArgs() { if (!HasVarArgs) { Throw.SignatureNotVarArg(); } Builder.WriteByte((byte)SignatureTypeCode.Sentinel); return new ParametersEncoder(Builder, hasVarArgs: false); } } }
using System; using System.ComponentModel.Composition; using System.Linq; using EnvDTE; using Microsoft.VisualStudio.Shell.Interop; namespace NuGet.VisualStudio { [PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(IVsPackageManagerFactory))] public class VsPackageManagerFactory : IVsPackageManagerFactory { private readonly IPackageRepositoryFactory _repositoryFactory; private readonly ISolutionManager _solutionManager; private readonly IFileSystemProvider _fileSystemProvider; private readonly IRepositorySettings _repositorySettings; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly VsPackageInstallerEvents _packageEvents; private readonly IPackageRepository _activePackageSourceRepository; private readonly IVsFrameworkMultiTargeting _frameworkMultiTargeting; private RepositoryInfo _repositoryInfo; private readonly IMachineWideSettings _machineWideSettings; [ImportingConstructor] public VsPackageManagerFactory(ISolutionManager solutionManager, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IFileSystemProvider fileSystemProvider, IRepositorySettings repositorySettings, VsPackageInstallerEvents packageEvents, IPackageRepository activePackageSourceRepository, IMachineWideSettings machineWideSettings) : this(solutionManager, repositoryFactory, packageSourceProvider, fileSystemProvider, repositorySettings, packageEvents, activePackageSourceRepository, ServiceLocator.GetGlobalService<SVsFrameworkMultiTargeting, IVsFrameworkMultiTargeting>(), machineWideSettings) { } public VsPackageManagerFactory(ISolutionManager solutionManager, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IFileSystemProvider fileSystemProvider, IRepositorySettings repositorySettings, VsPackageInstallerEvents packageEvents, IPackageRepository activePackageSourceRepository, IVsFrameworkMultiTargeting frameworkMultiTargeting, IMachineWideSettings machineWideSettings) { if (solutionManager == null) { throw new ArgumentNullException("solutionManager"); } if (repositoryFactory == null) { throw new ArgumentNullException("repositoryFactory"); } if (packageSourceProvider == null) { throw new ArgumentNullException("packageSourceProvider"); } if (fileSystemProvider == null) { throw new ArgumentNullException("fileSystemProvider"); } if (repositorySettings == null) { throw new ArgumentNullException("repositorySettings"); } if (packageEvents == null) { throw new ArgumentNullException("packageEvents"); } if (activePackageSourceRepository == null) { throw new ArgumentNullException("activePackageSourceRepository"); } _fileSystemProvider = fileSystemProvider; _repositorySettings = repositorySettings; _solutionManager = solutionManager; _repositoryFactory = repositoryFactory; _packageSourceProvider = packageSourceProvider; _packageEvents = packageEvents; _activePackageSourceRepository = activePackageSourceRepository; _frameworkMultiTargeting = frameworkMultiTargeting; _machineWideSettings = machineWideSettings; _solutionManager.SolutionClosing += (sender, e) => { _repositoryInfo = null; }; } /// <summary> /// Creates an VsPackageManagerInstance that uses the Active Repository (the repository selected in the console drop down) and uses a fallback repository for dependencies. /// </summary> public IVsPackageManager CreatePackageManager() { return CreatePackageManager(_activePackageSourceRepository, useFallbackForDependencies: true); } /// <summary> /// Creates a VsPackageManager that is used to manage install packages. /// The local repository is used as the primary source, and other active sources are /// used as fall back repository. When all needed packages are available in the local /// repository, which is the normal case, this package manager will not need to query /// any remote sources at all. Other active sources are /// used as fall back repository so that it still works even if user has used /// install-package -IgnoreDependencies. /// </summary> /// <returns>The VsPackageManager created.</returns> public IVsPackageManager CreatePackageManagerToManageInstalledPackages() { RepositoryInfo info = GetRepositoryInfo(); var aggregateRepository = _packageSourceProvider.CreateAggregateRepository( _repositoryFactory, ignoreFailingRepositories: true); aggregateRepository.ResolveDependenciesVertically = true; var fallbackRepository = new FallbackRepository(info.Repository, aggregateRepository); return CreatePackageManager(fallbackRepository, useFallbackForDependencies: false); } public IVsPackageManager CreatePackageManager(IPackageRepository repository, bool useFallbackForDependencies) { if (useFallbackForDependencies) { repository = CreateFallbackRepository(repository); } RepositoryInfo info = GetRepositoryInfo(); return new VsPackageManager(_solutionManager, repository, _fileSystemProvider, info.FileSystem, info.Repository, // We ensure DeleteOnRestartManager is initialized with a PhysicalFileSystem so the // .deleteme marker files that get created don't get checked into version control new DeleteOnRestartManager(() => new PhysicalFileSystem(info.FileSystem.Root)), _packageEvents, _frameworkMultiTargeting); } public IVsPackageManager CreatePackageManagerWithAllPackageSources() { return CreatePackageManagerWithAllPackageSources(_activePackageSourceRepository); } internal IVsPackageManager CreatePackageManagerWithAllPackageSources(IPackageRepository repository) { if (IsAggregateRepository(repository)) { return CreatePackageManager(repository, false); } var priorityRepository = _packageSourceProvider.CreatePriorityPackageRepository(_repositoryFactory, repository); return CreatePackageManager(priorityRepository, useFallbackForDependencies: false); } /// <summary> /// Creates a FallbackRepository with an aggregate repository that also contains the primaryRepository. /// </summary> internal IPackageRepository CreateFallbackRepository(IPackageRepository primaryRepository) { if (IsAggregateRepository(primaryRepository)) { // If we're using the aggregate repository, we don't need to create a fall back repo. return primaryRepository; } var aggregateRepository = _packageSourceProvider.CreateAggregateRepository(_repositoryFactory, ignoreFailingRepositories: true); aggregateRepository.ResolveDependenciesVertically = true; return new FallbackRepository(primaryRepository, aggregateRepository); } private static bool IsAggregateRepository(IPackageRepository repository) { if (repository is AggregateRepository) { // This test should be ok as long as any aggregate repository that we encounter here means the true Aggregate repository // of all repositories in the package source. // Since the repository created here comes from the UI, this holds true. return true; } var vsPackageSourceRepository = repository as VsPackageSourceRepository; if (vsPackageSourceRepository != null) { return IsAggregateRepository(vsPackageSourceRepository.GetActiveRepository()); } return false; } private RepositoryInfo GetRepositoryInfo() { // Update the path if it needs updating string path = _repositorySettings.RepositoryPath; string configFolderPath = _repositorySettings.ConfigFolderPath; if (_repositoryInfo == null || !_repositoryInfo.Path.Equals(path, StringComparison.OrdinalIgnoreCase) || !_repositoryInfo.ConfigFolderPath.Equals(configFolderPath, StringComparison.OrdinalIgnoreCase) || _solutionManager.IsSourceControlBound != _repositoryInfo.IsSourceControlBound) { IFileSystem fileSystem = _fileSystemProvider.GetFileSystem(path); IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath); // this file system is used to access the repositories.config file. We want to use Source Control-bound // file system to access it even if the 'disableSourceControlIntegration' setting is set. IFileSystem storeFileSystem = _fileSystemProvider.GetFileSystem(path, ignoreSourceControlSetting: true); ISharedPackageRepository repository = new SharedPackageRepository( new DefaultPackagePathResolver(fileSystem), fileSystem, storeFileSystem, configSettingsFileSystem); var settings = Settings.LoadDefaultSettings( configSettingsFileSystem, configFileName: null, machineWideSettings: _machineWideSettings); repository.PackageSaveMode = CalculatePackageSaveMode(settings); _repositoryInfo = new RepositoryInfo(path, configFolderPath, fileSystem, repository); } return _repositoryInfo; } private PackageSaveModes CalculatePackageSaveMode(ISettings settings) { PackageSaveModes retValue = PackageSaveModes.None; if (settings != null) { string packageSaveModeValue = settings.GetConfigValue("PackageSaveMode"); // TODO: remove following block of code when shipping NuGet version post 2.8 if (string.IsNullOrEmpty(packageSaveModeValue)) { packageSaveModeValue = settings.GetConfigValue("SaveOnExpand"); } // end of block of code to remove when shipping NuGet version post 2.8 if (!string.IsNullOrEmpty(packageSaveModeValue)) { foreach (var v in packageSaveModeValue.Split(';')) { if (v.Equals(PackageSaveModes.Nupkg.ToString(), StringComparison.OrdinalIgnoreCase)) { retValue |= PackageSaveModes.Nupkg; } else if (v.Equals(PackageSaveModes.Nuspec.ToString(), StringComparison.OrdinalIgnoreCase)) { retValue |= PackageSaveModes.Nuspec; } } } } if (retValue == PackageSaveModes.None) { retValue = PackageSaveModes.Nupkg; } return retValue; } protected internal virtual IFileSystem GetConfigSettingsFileSystem(string configFolderPath) { return new SolutionFolderFileSystem(ServiceLocator.GetInstance<DTE>().Solution, VsConstants.NuGetSolutionSettingsFolder, configFolderPath); } private class RepositoryInfo { public RepositoryInfo(string path, string configFolderPath, IFileSystem fileSystem, ISharedPackageRepository repository) { Path = path; FileSystem = fileSystem; Repository = repository; ConfigFolderPath = configFolderPath; } public bool IsSourceControlBound { get { return FileSystem is ISourceControlFileSystem; } } public IFileSystem FileSystem { get; private set; } public string Path { get; private set; } public string ConfigFolderPath { get; private set; } public ISharedPackageRepository Repository { get; private set; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace TestConsole.OutputFormatting { /// <summary> /// This class implements the <see cref="IConsoleOutInterface"/> and captures the console output in a format that facilitates /// examination of console output in a unit test. /// </summary> public class OutputBuffer : IConsoleInterface { private readonly List<string> _buffer = new List<string>(); /// <summary> /// The current cursor position. /// </summary> private int _cursorTop; /// <summary> /// The current cursor position. /// </summary> private int _cursorLeft; /// <summary> /// The console encoding. /// </summary> private Encoding _encoding; /// <summary> /// The input stream supplying input for the console. /// </summary> private TextReader _inputStream; /// <summary> /// The maximum number of lines the buffer may contain. Zero or less means no limit. /// </summary> private int _lengthLimit; /// <summary> /// The width of the buffer. /// </summary> public int BufferWidth { get; set; } /// <summary> /// The current cursor position. /// </summary> public int CursorLeft { get { return _cursorLeft; } set { _cursorLeft = value; } } /// <summary> /// The current cursor position. /// </summary> public int CursorTop { get { return _cursorTop; } set { _cursorTop = value; } } public Encoding Encoding { get { return _encoding; } } /// <summary> /// The constructor sets default values for various console properties and allows an encoding to be specified. /// </summary> public OutputBuffer(Encoding encoding = null) { _encoding = encoding ?? Encoding.Default; BufferWidth = 95; } /// <summary> /// Write some text to the console buffer. Does not add a line feed. /// </summary> /// <param name="data">The text data to write. This must not contain colour instructions.</param> /// <param name="limitWidth">True indicates that the buffer width should be respected.</param> public void Write(string data, bool limitWidth = true) { while (data.Contains(Environment.NewLine) || (data.Length + _cursorLeft > BufferWidth && limitWidth)) { string nextData; var usableLength = limitWidth ? BufferWidth - _cursorLeft : data.Length; var newlinePos = data.IndexOf(Environment.NewLine, StringComparison.Ordinal); if (newlinePos >= 0 && newlinePos < usableLength) { nextData = data.Substring(0, newlinePos); data = data.Substring(newlinePos + Environment.NewLine.Length); Write(nextData); NewLine(); } else { nextData = data.Substring(0, usableLength); data = data.Substring(usableLength); Write(nextData, limitWidth); } } CreateBufferTo(_cursorTop); OverWrite(_buffer, _cursorTop, _cursorLeft, data, limitWidth); _cursorLeft += data.Length; if (_cursorLeft >= BufferWidth && limitWidth) { _cursorTop++; _cursorLeft = 0; CreateBufferTo(_cursorTop); } } /// <summary> /// Overlay some text in an existing buffer. The method will discard any data that would overflow the buffer width. /// </summary> /// <param name="buffer">The buffer line array.</param> /// <param name="lineIndex">The index of the line to overwrite</param> /// <param name="overwritePosition">The position within the line to overwrite.</param> /// <param name="data">The text to place in the buffer at the specified position.</param> /// <param name="limitWidth">True indicates that the buffer width should be respected.</param> private void OverWrite(IList<string> buffer, int lineIndex, int overwritePosition, string data, bool limitWidth) { var line = buffer[lineIndex]; if (overwritePosition >= line.Length) return; var newLine = overwritePosition > 0 ? line.Substring(0, overwritePosition) : string.Empty; newLine += data; if (newLine.Length < line.Length) newLine += line.Substring(newLine.Length); //copy the remainder of the line from the original data if (newLine.Length > BufferWidth && limitWidth) newLine = newLine.Substring(0, BufferWidth); else if (newLine.Length < BufferWidth) newLine += new string(' ', BufferWidth - newLine.Length); buffer[lineIndex] = newLine; } /// <summary> /// Ensure that the buffer contains the specified line. /// </summary> /// <param name="ix">The zero based index of the line that must exist.</param> private void CreateBufferTo(int ix) { // ReSharper disable once LoopVariableIsNeverChangedInsideLoop while (ix >= _buffer.Count) { _buffer.Add(new string(' ', BufferWidth)); } if (_lengthLimit > 0) { while (_buffer.Count > _lengthLimit) { _buffer.RemoveAt(0); } if (CursorTop >= _lengthLimit) CursorTop = _lengthLimit - 1; } } /// <summary> /// Write a newline to the buffer. /// </summary> public void NewLine() { _cursorTop++; _cursorLeft = 0; CreateBufferTo(_cursorTop); } /// <summary> /// Return the entire buffer for testing purposes. It is possible to get just the text, just the colour information or all of the data. /// </summary> /// <returns>A large string containing the requested data.</returns> public string GetBuffer() { return string.Join(Environment.NewLine, _buffer); } /// <summary> /// Provide a text stream to provide the data for the console input stream. /// </summary> /// <param name="stream">The stream to use.</param> public void SetInputStream(TextReader stream) { _inputStream = stream; } public void LimitBuffer(int maxLines) { _lengthLimit = maxLines; } } }
// // Options.cs // // Authors: // Jonathan Pryor <jpryor@novell.com> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif namespace NDesk.Options { public class OptionValueCollection : IList, IList<string> { List<string> values = new List<string>(); OptionContext c; internal OptionValueCollection(OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); } bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } } object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } } #endregion #region ICollection<T> public void Add(string item) { values.Add(item); } public void Clear() { values.Clear(); } public bool Contains(string item) { return values.Contains(item); } public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); } public bool Remove(string item) { return values.Remove(item); } public int Count { get { return values.Count; } } public bool IsReadOnly { get { return false; } } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator() { return values.GetEnumerator(); } #endregion #region IList int IList.Add(object value) { return (values as IList).Add(value); } bool IList.Contains(object value) { return (values as IList).Contains(value); } int IList.IndexOf(object value) { return (values as IList).IndexOf(value); } void IList.Insert(int index, object value) { (values as IList).Insert(index, value); } void IList.Remove(object value) { (values as IList).Remove(value); } void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); } bool IList.IsFixedSize { get { return false; } } object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } } #endregion #region IList<T> public int IndexOf(string item) { return values.IndexOf(item); } public void Insert(int index, string item) { values.Insert(index, item); } public void RemoveAt(int index) { values.RemoveAt(index); } private void AssertValid(int index) { if (c.Option == null) throw new InvalidOperationException("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException(string.Format( c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this[int index] { get { AssertValid(index); return index >= values.Count ? null : values[index]; } set { values[index] = value; } } #endregion public List<string> ToList() { return new List<string>(values); } public string[] ToArray() { return values.ToArray(); } public override string ToString() { return string.Join(", ", values.ToArray()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public OptionContext(OptionSet set) { this.set = set; this.c = new OptionValueCollection(this); } public Option Option { get { return option; } set { option = value; } } public string OptionName { get { return name; } set { name = value; } } public int OptionIndex { get { return index; } set { index = value; } } public OptionSet OptionSet { get { return set; } } public OptionValueCollection OptionValues { get { return c; } } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { string prototype, description; string[] names; OptionValueType type; int count; string[] separators; protected Option(string prototype, string description) : this(prototype, description, 1) { } protected Option(string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException("prototype"); if (prototype.Length == 0) throw new ArgumentException("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException("maxValueCount"); this.prototype = prototype; this.names = prototype.Split('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype(); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException( string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf(names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype { get { return prototype; } } public string Description { get { return description; } } public OptionValueType OptionValueType { get { return type; } } public int MaxValueCount { get { return count; } } public string[] GetNames() { return (string[])names.Clone(); } public string[] GetValueSeparators() { if (separators == null) return new string[0]; return (string[])separators.Clone(); } protected static T Parse<T>(string value, OptionContext c) { TypeConverter conv = TypeDescriptor.GetConverter(typeof(T)); T t = default(T); try { if (value != null) t = (T)conv.ConvertFromString(value); } catch (Exception e) { throw new OptionException( string.Format( c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."), value, typeof(T).Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names { get { return names; } } internal string[] ValueSeparators { get { return separators; } } static readonly char[] NameTerminator = new char[] { '=', ':' }; private OptionValueType ParsePrototype() { char type = '\0'; List<string> seps = new List<string>(); for (int i = 0; i < names.Length; ++i) { string name = names[i]; if (name.Length == 0) throw new ArgumentException("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny(NameTerminator); if (end == -1) continue; names[i] = name.Substring(0, end); if (type == '\0' || type == name[end]) type = name[end]; else throw new ArgumentException( string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]), "prototype"); AddSeparators(name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException( string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[] { ":", "=" }; else if (seps.Count == 1 && seps[0].Length == 0) this.separators = null; else this.separators = seps.ToArray(); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators(string name, int end, ICollection<string> seps) { int start = -1; for (int i = end + 1; i < name.Length; ++i) { switch (name[i]) { case '{': if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i + 1; break; case '}': if (start == -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add(name.Substring(start, i - start)); start = -1; break; default: if (start == -1) seps.Add(name[i].ToString()); break; } } if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke(OptionContext c) { OnParseComplete(c); c.OptionName = null; c.Option = null; c.OptionValues.Clear(); } protected abstract void OnParseComplete(OptionContext c); public override string ToString() { return Prototype; } } [Serializable] public class OptionException : Exception { private string option; public OptionException() { } public OptionException(string message, string optionName) : base(message) { this.option = optionName; } public OptionException(string message, string optionName, Exception innerException) : base(message, innerException) { this.option = optionName; } protected OptionException(SerializationInfo info, StreamingContext context) : base(info, context) { this.option = info.GetString("OptionName"); } public string OptionName { get { return this.option; } } [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("OptionName", option); } } public delegate void OptionAction<TKey, TValue>(TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { public OptionSet() : this(delegate (string f) { return f; }) { } public OptionSet(Converter<string, string> localizer) { this.localizer = localizer; } Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get { return localizer; } } protected override string GetKeyForItem(Option item) { if (item == null) throw new ArgumentNullException("option"); if (item.Names != null && item.Names.Length > 0) return item.Names[0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException("Option has no names!"); } [Obsolete("Use KeyedCollection.this[string]")] protected Option GetOptionForName(string option) { if (option == null) throw new ArgumentNullException("option"); try { return base[option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem(int index, Option item) { base.InsertItem(index, item); AddImpl(item); } protected override void RemoveItem(int index) { base.RemoveItem(index); Option p = Items[index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove(p.Names[i]); } } protected override void SetItem(int index, Option item) { base.SetItem(index, item); RemoveItem(index); AddImpl(item); } private void AddImpl(Option option) { if (option == null) throw new ArgumentNullException("option"); List<string> added = new List<string>(option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add(option.Names[i], option); added.Add(option.Names[i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove(name); throw; } } public new OptionSet Add(Option option) { base.Add(option); return this; } sealed class ActionOption : Option { Action<OptionValueCollection> action; public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action) : base(prototype, description, count) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action(c.OptionValues); } } public OptionSet Add(string prototype, Action<string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException("action"); Option p = new ActionOption(prototype, description, 1, delegate (OptionValueCollection v) { action(v[0]); }); base.Add(p); return this; } public OptionSet Add(string prototype, OptionAction<string, string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException("action"); Option p = new ActionOption(prototype, description, 2, delegate (OptionValueCollection v) { action(v[0], v[1]); }); base.Add(p); return this; } sealed class ActionOption<T> : Option { Action<T> action; public ActionOption(string prototype, string description, Action<T> action) : base(prototype, description, 1) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action(Parse<T>(c.OptionValues[0], c)); } } sealed class ActionOption<TKey, TValue> : Option { OptionAction<TKey, TValue> action; public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action) : base(prototype, description, 2) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action( Parse<TKey>(c.OptionValues[0], c), Parse<TValue>(c.OptionValues[1], c)); } } public OptionSet Add<T>(string prototype, Action<T> action) { return Add(prototype, null, action); } public OptionSet Add<T>(string prototype, string description, Action<T> action) { return Add(new ActionOption<T>(prototype, description, action)); } public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action) { return Add(prototype, null, action); } public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action) { return Add(new ActionOption<TKey, TValue>(prototype, description, action)); } protected virtual OptionContext CreateOptionContext() { return new OptionContext(this); } #if LINQ public List<string> Parse (IEnumerable<string> arguments) { bool process = true; OptionContext c = CreateOptionContext (); c.OptionIndex = -1; var def = GetOptionForName ("<>"); var unprocessed = from argument in arguments where ++c.OptionIndex >= 0 && (process || def != null) ? process ? argument == "--" ? (process = false) : !Parse (argument, c) ? def != null ? Unprocessed (null, def, c, argument) : true : false : def != null ? Unprocessed (null, def, c, argument) : true : true select argument; List<string> r = unprocessed.ToList (); if (c.Option != null) c.Option.Invoke (c); return r; } #else public List<string> Parse(IEnumerable<string> arguments) { OptionContext c = CreateOptionContext(); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string>(); Option def = Contains("<>") ? this["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed(unprocessed, def, c, argument); continue; } if (!Parse(argument, c)) Unprocessed(unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke(c); return unprocessed; } #endif private static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add(argument); return false; } c.OptionValues.Add(argument); c.Option = def; c.Option.Invoke(c); return false; } private readonly Regex ValueOption = new Regex( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException("argument"); flag = name = sep = value = null; Match m = ValueOption.Match(argument); if (!m.Success) { return false; } flag = m.Groups["flag"].Value; name = m.Groups["name"].Value; if (m.Groups["sep"].Success && m.Groups["value"].Success) { sep = m.Groups["sep"].Value; value = m.Groups["value"].Value; } return true; } protected virtual bool Parse(string argument, OptionContext c) { if (c.Option != null) { ParseValue(argument, c); return true; } string f, n, s, v; if (!GetOptionParts(argument, out f, out n, out s, out v)) return false; Option p; if (Contains(n)) { p = this[n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add(n); c.Option.Invoke(c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue(v, c); break; } return true; } // no match; is it a bool option? if (ParseBool(argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue(f, string.Concat(n + s + v), c)) return true; return false; } private void ParseValue(string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split(c.Option.ValueSeparators, StringSplitOptions.None) : new string[] { option }) { c.OptionValues.Add(o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke(c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException(localizer(string.Format( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool(string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') && Contains((rn = n.Substring(0, n.Length - 1)))) { p = this[rn]; string v = n[n.Length - 1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add(v); p.Invoke(c); return true; } return false; } private bool ParseBundledValue(string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n[i].ToString(); string rn = n[i].ToString(); if (!Contains(rn)) { if (i == 0) return false; throw new OptionException(string.Format(localizer( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this[rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke(c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring(i + 1); c.Option = p; c.OptionName = opt; ParseValue(v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke(OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add(value); option.Invoke(c); } private const int OptionWidth = 29; public void WriteOptionDescriptions(TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype(o, p, ref written)) continue; if (written < OptionWidth) o.Write(new string(' ', OptionWidth - written)); else { o.WriteLine(); o.Write(new string(' ', OptionWidth)); } List<string> lines = GetLines(localizer(GetDescription(p.Description))); o.WriteLine(lines[0]); string prefix = new string(' ', OptionWidth + 2); for (int i = 1; i < lines.Count; ++i) { o.Write(prefix); o.WriteLine(lines[i]); } } } bool WriteOptionPrototype(TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex(names, 0); if (i == names.Length) return false; if (names[i].Length == 1) { Write(o, ref written, " -"); Write(o, ref written, names[0]); } else { Write(o, ref written, " --"); Write(o, ref written, names[0]); } for (i = GetNextOptionIndex(names, i + 1); i < names.Length; i = GetNextOptionIndex(names, i + 1)) { Write(o, ref written, ", "); Write(o, ref written, names[i].Length == 1 ? "-" : "--"); Write(o, ref written, names[i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, localizer("[")); } Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators[0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, localizer("]")); } } return true; } static int GetNextOptionIndex(string[] names, int i) { while (i < names.Length && names[i] == "<>") { ++i; } return i; } static void Write(TextWriter o, ref int n, string s) { n += s.Length; o.Write(s); } private static string GetArgumentName(int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[] { "{0:", "{" }; else nameStart = new string[] { "{" + index + ":" }; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf(nameStart[i], j); } while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf("}", start); if (end == -1) continue; return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription(string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder(description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description[i]) { case '{': if (i == start) { sb.Append('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i + 1) == description.Length || description[i + 1] != '}') throw new InvalidOperationException("Invalid option description: " + description); ++i; sb.Append("}"); } else { sb.Append(description.Substring(start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append(description[i]); break; } } return sb.ToString(); } private static List<string> GetLines(string description) { List<string> lines = new List<string>(); if (string.IsNullOrEmpty(description)) { lines.Add(string.Empty); return lines; } int length = 80 - OptionWidth - 2; int start = 0, end; do { end = GetLineEnd(start, length, description); bool cont = false; if (end < description.Length) { char c = description[end]; if (c == '-' || (char.IsWhiteSpace(c) && c != '\n')) ++end; else if (c != '\n') { cont = true; --end; } } lines.Add(description.Substring(start, end - start)); if (cont) { lines[lines.Count - 1] += "-"; } start = end; if (start < description.Length && description[start] == '\n') ++start; } while (end < description.Length); return lines; } private static int GetLineEnd(int start, int length, string description) { int end = Math.Min(start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { switch (description[i]) { case ' ': case '\t': case '\v': case '-': case ',': case '.': case ';': sep = i; break; case '\n': return i; } } if (sep == -1 || end == description.Length) return end; return sep; } } }
// // 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.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Parameters supplied to the Create Virtual Machine VM Image operation. /// </summary> public partial class VirtualMachineVMImageCreateParameters { private IList<DataDiskConfigurationCreateParameters> _dataDiskConfigurations; /// <summary> /// Optional. Specifies configuration information for the data disks /// that are associated with the image. A VM Image might not have data /// disks associated with it. /// </summary> public IList<DataDiskConfigurationCreateParameters> DataDiskConfigurations { get { return this._dataDiskConfigurations; } set { this._dataDiskConfigurations = value; } } private string _description; /// <summary> /// Optional. Gets or sets the description of the image. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _eula; /// <summary> /// Optional. Gets or sets the End User License Agreement that is /// associated with the image. The value for this element is a string, /// but it is recommended that the value be a URL that points to a /// EULA. /// </summary> public string Eula { get { return this._eula; } set { this._eula = value; } } private string _iconUri; /// <summary> /// Optional. Gets or sets the URI to the icon that is displayed for /// the image in the Management Portal. /// </summary> public string IconUri { get { return this._iconUri; } set { this._iconUri = value; } } private string _imageFamily; /// <summary> /// Optional. Gets or sets a value that can be used to group VM Images. /// </summary> public string ImageFamily { get { return this._imageFamily; } set { this._imageFamily = value; } } private string _label; /// <summary> /// Required. Gets or sets an identifier for the image. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _language; /// <summary> /// Optional. Gets or sets the language of the image. /// </summary> public string Language { get { return this._language; } set { this._language = value; } } private string _name; /// <summary> /// Required. Gets or sets the name of the image. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private OSDiskConfigurationCreateParameters _oSDiskConfiguration; /// <summary> /// Required. Gets or sets configuration information for the operating /// system disk that is associated with the image. /// </summary> public OSDiskConfigurationCreateParameters OSDiskConfiguration { get { return this._oSDiskConfiguration; } set { this._oSDiskConfiguration = value; } } private Uri _privacyUri; /// <summary> /// Optional. Gets or sets the URI that points to a document that /// contains the privacy policy related to the image. /// </summary> public Uri PrivacyUri { get { return this._privacyUri; } set { this._privacyUri = value; } } private System.DateTime? _publishedDate; /// <summary> /// Optional. Gets or sets the date when the image was added to the /// image repository. /// </summary> public System.DateTime? PublishedDate { get { return this._publishedDate; } set { this._publishedDate = value; } } private string _recommendedVMSize; /// <summary> /// Optional. Gets or sets the size to use for the Virtual Machine that /// is created from the VM Image. /// </summary> public string RecommendedVMSize { get { return this._recommendedVMSize; } set { this._recommendedVMSize = value; } } private bool? _showInGui; /// <summary> /// Optional. Gets or sets whether the VM Images should be listed in /// the portal. /// </summary> public bool? ShowInGui { get { return this._showInGui; } set { this._showInGui = value; } } private string _smallIconUri; /// <summary> /// Optional. Gets or sets the URI to the small icon that is displayed /// for the image in the Management Portal. /// </summary> public string SmallIconUri { get { return this._smallIconUri; } set { this._smallIconUri = value; } } /// <summary> /// Initializes a new instance of the /// VirtualMachineVMImageCreateParameters class. /// </summary> public VirtualMachineVMImageCreateParameters() { this.DataDiskConfigurations = new LazyList<DataDiskConfigurationCreateParameters>(); } /// <summary> /// Initializes a new instance of the /// VirtualMachineVMImageCreateParameters class with required /// arguments. /// </summary> public VirtualMachineVMImageCreateParameters(string name, string label, OSDiskConfigurationCreateParameters oSDiskConfiguration) : this() { if (name == null) { throw new ArgumentNullException("name"); } if (label == null) { throw new ArgumentNullException("label"); } if (oSDiskConfiguration == null) { throw new ArgumentNullException("oSDiskConfiguration"); } this.Name = name; this.Label = label; this.OSDiskConfiguration = oSDiskConfiguration; } } }
using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Threading; using System.Xml; using System.Runtime.InteropServices; using System.Diagnostics; using System.Drawing; using System.IO; namespace UnitTests { public class TestBase { public class NodeInfo { XmlNodeType nt; string name; string value; public NodeInfo(XmlReader r) { this.nt = r.NodeType; this.name = r.Name; this.value = Normalize(r.Value); } public bool Equals(NodeInfo other) { return this.nt == other.nt && this.name == other.name && this.value == other.value; } public XmlNodeType NodeType { get { return nt; } } string Normalize(string value) { // So text indented different still compares as the same. if (string.IsNullOrEmpty(value)) return null; StringBuilder sb = new StringBuilder(); bool wasnewline = true; // collapse leading spaces for (int i = 0, n = value.Length; i < n; i++) { char ch = value[i]; if (ch == '\r'){ if (i + 1 < n && value[i + 1] == '\n') { i++; } sb.Append('\n'); wasnewline = true; } else if (ch == '\n'){ sb.Append(ch); wasnewline = true; } else if (Char.IsWhiteSpace(ch)) { if (!wasnewline) sb.Append(' '); } else { sb.Append(ch); wasnewline = false; } } return sb.ToString(); } } public void Sleep(int ms) { Thread.Sleep(ms); } public Window LaunchApp(string exeFileName, string args, string rootElementName) { ProcessStartInfo info = new ProcessStartInfo(); info.FileName = exeFileName; info.Arguments = args; Process p = new Process(); p.StartInfo = info; if (!p.Start()) { string msg = "Error launching " + exeFileName; MessageBox.Show("Error Creating Process", msg, MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception(msg); } if (p.HasExited) { throw new Exception(string.Format("Failed to launch '{0'}, exit code {1}", exeFileName, p.ExitCode.ToString())); } Window w = new Window(p, null, rootElementName); w.TestBase = this; return w; } protected Window window; public void CloseApp() { if (this.window != null) { this.window.Dispose(); this.window = null; } } public void DeleteFile(string fname) { if (File.Exists(fname)) File.Delete(fname); } public void CompareResults(List<NodeInfo> nodes, string outFile) { int pos = 0; XmlReader reader = XmlReader.Create(outFile); IXmlLineInfo li = (IXmlLineInfo)reader; XmlNodeType previousNodeType = XmlNodeType.None; using (reader) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace || reader.NodeType == XmlNodeType.XmlDeclaration) continue; NodeInfo node = new NodeInfo(reader); if (pos >= nodes.Count) { throw new ApplicationException("Found too many nodes"); } NodeInfo other = nodes[pos++]; if (!node.Equals(other)) { throw new ApplicationException( string.Format("Mismatching nodes at line {0},{1}", li.LineNumber, li.LinePosition)); } previousNodeType = node.NodeType; } } } public List<NodeInfo> ReadNodes(string fileName) { XmlReader reader = XmlReader.Create(fileName); return ReadNodes(reader); } public List<NodeInfo> ReadNodes(XmlReader reader) { List<NodeInfo> nodes = new List<NodeInfo>(); using (reader) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace || reader.NodeType == XmlNodeType.XmlDeclaration) continue; nodes.Add(new NodeInfo(reader)); } } return nodes; } public virtual void CheckClipboard(string expected) { if (!Clipboard.ContainsText()) { throw new ApplicationException("clipboard does not contain any text!"); } string text = Clipboard.GetText(); if (text != expected) { throw new ApplicationException("clipboard does not match expected cut node"); } } public Window LaunchIE(string args) { // when IE launches it creates a new process instead of the process we create, so we have to track that jump. // so this means watching for a new process to appear. HashSet<int> runningProcesses = new HashSet<int>(); foreach (Process e in Process.GetProcesses()) { Debug.WriteLine("Found Process " + e.Id + " : " + e.ProcessName); if (e.ProcessName == "iexplore") { try { e.Kill(); } catch { } } else { runningProcesses.Add(e.Id); } } ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Environment.GetEnvironmentVariable("ProgramFiles") + "\\Internet Explorer\\iexplore.exe";; info.Arguments = args; Process p = new Process(); p.StartInfo = info; if (!p.Start()) { string msg = "Error launching " + info.FileName; MessageBox.Show("Error Creating Process", msg, MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception(msg); } // find the new process that has a window whose ClassName is "IEFrame". Process ie = null; int retry = 5; while (retry-- > 0) { foreach (Process np in Process.GetProcesses()) { if (!runningProcesses.Contains(np.Id)) { Debug.WriteLine("Checking Process " + np.Id + " : " + np.ProcessName); AutomationWrapper wrapper = Window.FindWindowForProcessId(np.Id, "IEFrame", null); if (wrapper != null) { // found it! ie = np; p = np; break; } } } if (ie != null) { break; } Sleep(500); } if (ie != null) { Window w = new Window(p, "IEFrame", null); w.TestBase = this; return w; } throw new Exception("Not finding the new IE process, perhaps you need to shutdown existing IE instances"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace AutoMapperSample.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; using System.Text.RegularExpressions; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Transactions; /// <summary> /// Managed environment. Acts as a gateway for native code. /// </summary> internal static class ExceptionUtils { /** NoClassDefFoundError fully-qualified class name which is important during startup phase. */ private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError"; /** NoSuchMethodError fully-qualified class name which is important during startup phase. */ private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError"; /** InteropCachePartialUpdateException. */ private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException"; /** Map with predefined exceptions. */ private static readonly IDictionary<string, ExceptionFactory> Exs = new Dictionary<string, ExceptionFactory>(); /** Inner class regex. */ private static readonly Regex InnerClassRegex = new Regex(@"class ([^\s]+): (.*)", RegexOptions.Compiled); /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability")] static ExceptionUtils() { // Common Java exceptions mapped to common .NET exceptions. Exs["java.lang.IllegalArgumentException"] = (c, m, e, i) => new ArgumentException(m, e); Exs["java.lang.IllegalStateException"] = (c, m, e, i) => new InvalidOperationException(m, e); Exs["java.lang.UnsupportedOperationException"] = (c, m, e, i) => new NotSupportedException(m, e); Exs["java.lang.InterruptedException"] = (c, m, e, i) => new ThreadInterruptedException(m, e); // Generic Ignite exceptions. Exs["org.apache.ignite.IgniteException"] = (c, m, e, i) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteCheckedException"] = (c, m, e, i) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteClientDisconnectedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); Exs["org.apache.ignite.internal.IgniteClientDisconnectedCheckedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); Exs["org.apache.ignite.binary.BinaryObjectException"] = (c, m, e, i) => new BinaryObjectException(m, e); // Cluster exceptions. Exs["org.apache.ignite.cluster.ClusterGroupEmptyException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e); Exs["org.apache.ignite.internal.cluster.ClusterGroupEmptyCheckedException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e); Exs["org.apache.ignite.cluster.ClusterTopologyException"] = (c, m, e, i) => new ClusterTopologyException(m, e); // Compute exceptions. Exs["org.apache.ignite.compute.ComputeExecutionRejectedException"] = (c, m, e, i) => new ComputeExecutionRejectedException(m, e); Exs["org.apache.ignite.compute.ComputeJobFailoverException"] = (c, m, e, i) => new ComputeJobFailoverException(m, e); Exs["org.apache.ignite.compute.ComputeTaskCancelledException"] = (c, m, e, i) => new ComputeTaskCancelledException(m, e); Exs["org.apache.ignite.compute.ComputeTaskTimeoutException"] = (c, m, e, i) => new ComputeTaskTimeoutException(m, e); Exs["org.apache.ignite.compute.ComputeUserUndeclaredException"] = (c, m, e, i) => new ComputeUserUndeclaredException(m, e); // Cache exceptions. Exs["javax.cache.CacheException"] = (c, m, e, i) => new CacheException(m, e); Exs["javax.cache.integration.CacheLoaderException"] = (c, m, e, i) => new CacheStoreException(m, e); Exs["javax.cache.integration.CacheWriterException"] = (c, m, e, i) => new CacheStoreException(m, e); Exs["javax.cache.processor.EntryProcessorException"] = (c, m, e, i) => new CacheEntryProcessorException(m, e); Exs["org.apache.ignite.cache.CacheAtomicUpdateTimeoutException"] = (c, m, e, i) => new CacheAtomicUpdateTimeoutException(m, e); // Transaction exceptions. Exs["org.apache.ignite.transactions.TransactionOptimisticException"] = (c, m, e, i) => new TransactionOptimisticException(m, e); Exs["org.apache.ignite.transactions.TransactionTimeoutException"] = (c, m, e, i) => new TransactionTimeoutException(m, e); Exs["org.apache.ignite.transactions.TransactionRollbackException"] = (c, m, e, i) => new TransactionRollbackException(m, e); Exs["org.apache.ignite.transactions.TransactionHeuristicException"] = (c, m, e, i) => new TransactionHeuristicException(m, e); Exs["org.apache.ignite.transactions.TransactionDeadlockException"] = (c, m, e, i) => new TransactionDeadlockException(m, e); // Security exceptions. Exs["org.apache.ignite.IgniteAuthenticationException"] = (c, m, e, i) => new SecurityException(m, e); Exs["org.apache.ignite.plugin.security.GridSecurityException"] = (c, m, e, i) => new SecurityException(m, e); // Future exceptions Exs["org.apache.ignite.lang.IgniteFutureCancelledException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e); Exs["org.apache.ignite.internal.IgniteFutureCancelledCheckedException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e); } /// <summary> /// Creates exception according to native code class and message. /// </summary> /// <param name="ignite">The ignite.</param> /// <param name="clsName">Exception class name.</param> /// <param name="msg">Exception message.</param> /// <param name="stackTrace">Native stack trace.</param> /// <param name="reader">Error data reader.</param> /// <param name="innerException">Inner exception.</param> /// <returns>Exception.</returns> public static Exception GetException(Ignite ignite, string clsName, string msg, string stackTrace, BinaryReader reader = null, Exception innerException = null) { // Set JavaException as inner only if there is no InnerException. if (innerException == null) innerException = new JavaException(clsName, msg, stackTrace); ExceptionFactory ctor; if (Exs.TryGetValue(clsName, out ctor)) { var match = InnerClassRegex.Match(msg ?? string.Empty); ExceptionFactory innerCtor; if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor)) { return ctor(clsName, msg, innerCtor(match.Groups[1].Value, match.Groups[2].Value, innerException, ignite), ignite); } return ctor(clsName, msg, innerException, ignite); } if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " + "variable?): " + msg, innerException); if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " + "variable?): " + msg, innerException); if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return ProcessCachePartialUpdateException(ignite, msg, stackTrace, reader); // Predefined mapping not found - check plugins. if (ignite != null) { ctor = ignite.PluginProcessor.GetExceptionMapping(clsName); if (ctor != null) { return ctor(clsName, msg, innerException, ignite); } } // Return default exception. return new IgniteException(string.Format("Java exception occurred [class={0}, message={1}]", clsName, msg), innerException); } /// <summary> /// Process cache partial update exception. /// </summary> /// <param name="ignite">The ignite.</param> /// <param name="msg">Message.</param> /// <param name="stackTrace">Stack trace.</param> /// <param name="reader">Reader.</param> /// <returns>CachePartialUpdateException.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static Exception ProcessCachePartialUpdateException(Ignite ignite, string msg, string stackTrace, BinaryReader reader) { if (reader == null) return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available.")); bool dataExists = reader.ReadBoolean(); Debug.Assert(dataExists); if (reader.ReadBoolean()) { bool keepBinary = reader.ReadBoolean(); BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary); try { return new CachePartialUpdateException(msg, ReadNullableList(keysReader)); } catch (Exception e) { // Failed to deserialize data. return new CachePartialUpdateException(msg, e); } } // Was not able to write keys. string innerErrCls = reader.ReadString(); string innerErrMsg = reader.ReadString(); Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg, stackTrace); return new CachePartialUpdateException(msg, innerErr); } /// <summary> /// Create JVM initialization exception. /// </summary> /// <param name="clsName">Class name.</param> /// <param name="msg">Message.</param> /// <param name="stackTrace">Stack trace.</param> /// <returns>Exception.</returns> [ExcludeFromCodeCoverage] // Covered by a test in a separate process. public static Exception GetJvmInitializeException(string clsName, string msg, string stackTrace) { if (clsName != null) return new IgniteException("Failed to initialize JVM.", GetException(null, clsName, msg, stackTrace)); if (msg != null) return new IgniteException("Failed to initialize JVM: " + msg + "\n" + stackTrace); return new IgniteException("Failed to initialize JVM."); } /// <summary> /// Reads nullable list. /// </summary> /// <param name="reader">Reader.</param> /// <returns>List.</returns> private static List<object> ReadNullableList(BinaryReader reader) { if (!reader.ReadBoolean()) return null; var size = reader.ReadInt(); var list = new List<object>(size); for (int i = 0; i < size; i++) list.Add(reader.ReadObject<object>()); return list; } } }
// 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 Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals); /// <summary> /// Synthesized expression evaluation method. /// </summary> internal sealed class EEMethodSymbol : MethodSymbol { // We only create a single EE method (per EE type) that represents an arbitrary expression, // whose lowering may produce synthesized members (lambdas, dynamic sites, etc). // We may thus assume that the method ordinal is always 0. // // Consider making the implementation more flexible in order to avoid this assumption. // In future we might need to compile multiple expression and then we'll need to assign // a unique method ordinal to each of them to avoid duplicate synthesized member names. private const int _methodOrdinal = 0; internal readonly TypeMap TypeMap; internal readonly MethodSymbol SubstitutedSourceMethod; internal readonly ImmutableArray<LocalSymbol> Locals; internal readonly ImmutableArray<LocalSymbol> LocalsForBinding; private readonly EENamedTypeSymbol _container; private readonly string _name; private readonly ImmutableArray<Location> _locations; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<ParameterSymbol> _parameters; private readonly ParameterSymbol _thisParameter; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; /// <summary> /// Invoked at most once to generate the method body. /// (If the compilation has no errors, it will be invoked /// exactly once, otherwise it may be skipped.) /// </summary> private readonly GenerateMethodBody _generateMethodBody; private TypeSymbol _lazyReturnType; // NOTE: This is only used for asserts, so it could be conditional on DEBUG. private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters; internal EEMethodSymbol( EENamedTypeSymbol container, string name, Location location, MethodSymbol sourceMethod, ImmutableArray<LocalSymbol> sourceLocals, ImmutableArray<LocalSymbol> sourceLocalsForBinding, ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables, GenerateMethodBody generateMethodBody) { Debug.Assert(sourceMethod.IsDefinition); Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition); Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod)); _container = container; _name = name; _locations = ImmutableArray.Create(location); // What we want is to map all original type parameters to the corresponding new type parameters // (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: // 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. // 2) The map cannot be constructed until all new type parameters exist. // Our solution is to pass each new type parameter a lazy reference to the type map. We then // initialize the map as soon as the new type parameters are available - and before they are // handed out - so that there is never a period where they can require the type map and find // it uninitialized. var sourceMethodTypeParameters = sourceMethod.TypeParameters; var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters); var getTypeMap = new Func<TypeMap>(() => this.TypeMap); _typeParameters = sourceMethodTypeParameters.SelectAsArray( (tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap), (object)null); _allTypeParameters = container.TypeParameters.Concat(_typeParameters); this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters); EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters); var substitutedSourceType = container.SubstitutedSourceType; this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType); if (sourceMethod.Arity > 0) { this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>()); } TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters); // Create a map from original parameter to target parameter. var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(); var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter; var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null; if (substitutedSourceHasThisParameter) { _thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter); Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType); parameterBuilder.Add(_thisParameter); } var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0); foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters) { var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset; Debug.Assert(ordinal == parameterBuilder.Count); var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter); parameterBuilder.Add(parameter); } _parameters = parameterBuilder.ToImmutableAndFree(); var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocals) { var local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); localsBuilder.Add(local); } this.Locals = localsBuilder.ToImmutableAndFree(); localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocalsForBinding) { LocalSymbol local; if (!localsMap.TryGetValue(sourceLocal, out local)) { local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); } localsBuilder.Add(local); } this.LocalsForBinding = localsBuilder.ToImmutableAndFree(); // Create a map from variable name to display class field. var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var pair in sourceDisplayClassVariables) { var variable = pair.Value; var oldDisplayClassInstance = variable.DisplayClassInstance; // Note: we don't call ToOtherMethod in the local case because doing so would produce // a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. var oldDisplayClassInstanceFromLocal = oldDisplayClassInstance as DisplayClassInstanceFromLocal; var newDisplayClassInstance = (oldDisplayClassInstanceFromLocal == null) ? oldDisplayClassInstance.ToOtherMethod(this, this.TypeMap) : new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[oldDisplayClassInstanceFromLocal.Local]); variable = variable.SubstituteFields(newDisplayClassInstance, this.TypeMap); displayClassVariables.Add(pair.Key, variable); } _displayClassVariables = displayClassVariables.ToImmutableDictionary(); displayClassVariables.Free(); localsMap.Free(); _generateMethodBody = generateMethodBody; } private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter) { return new SynthesizedParameterSymbol(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers, sourceParameter.CountOfCustomModifiersPrecedingByRef); } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override string Name { get { return _name; } } public override int Arity { get { return _typeParameters.Length; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return true; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData GetDllImportData() { return null; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = null; return true; } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return this.SubstitutedSourceMethod.IsVararg; } } internal override RefKind RefKind { get { return this.SubstitutedSourceMethod.RefKind; } } public override bool ReturnsVoid { get { return this.ReturnType.SpecialType == SpecialType.System_Void; } } public override bool IsAsync { get { return false; } } public override TypeSymbol ReturnType { get { if (_lazyReturnType == null) { throw new InvalidOperationException(); } return _lazyReturnType; } } public override ImmutableArray<TypeSymbol> TypeArguments { get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { throw ExceptionUtilities.Unreachable; } internal override Cci.CallingConvention CallingConvention { get { Debug.Assert(this.IsStatic); var cc = Cci.CallingConvention.Default; if (this.IsVararg) { cc |= Cci.CallingConvention.ExtraArguments; } if (this.IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } return cc; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { throw ExceptionUtilities.Unreachable; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Internal; } } public override bool IsStatic { get { return true; } } public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { throw ExceptionUtilities.Unreachable; } } internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> declaredLocalsArray; var body = _generateMethodBody(this, diagnostics, out declaredLocalsArray); var compilation = compilationState.Compilation; _lazyReturnType = CalculateReturnType(compilation, body); // Can't do this until the return type has been computed. TypeParameterChecker.Check(this, _allTypeParameters); if (diagnostics.HasAnyErrors()) { return; } DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this); if (diagnostics.HasAnyErrors()) { return; } // Check for use-site diagnostics (e.g. missing types in the signature). DiagnosticInfo useSiteDiagnosticInfo = null; this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo); if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]); return; } try { var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance(); try { // Rewrite local declaration statement. body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body, declaredLocalsArray); // Verify local declaration names. foreach (var local in declaredLocals) { Debug.Assert(local.Locations.Length > 0); var name = local.Name; if (name.StartsWith("$", StringComparison.Ordinal)) { diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]); return; } } // Rewrite references to placeholder "locals". body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body, diagnostics); if (diagnostics.HasAnyErrors()) { return; } } finally { declaredLocals.Free(); } var syntax = body.Syntax; var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(); statementsBuilder.Add(body); // Insert an implicit return statement if necessary. if (body.Kind != BoundKind.ReturnStatement) { statementsBuilder.Add(new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null)); } var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsSet = PooledHashSet<LocalSymbol>.GetInstance(); foreach (var local in this.LocalsForBinding) { Debug.Assert(!localsSet.Contains(local)); localsBuilder.Add(local); localsSet.Add(local); } foreach (var local in this.Locals) { if (!localsSet.Contains(local)) { Debug.Assert(!localsSet.Contains(local)); localsBuilder.Add(local); localsSet.Add(local); } } localsSet.Free(); body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true }; Debug.Assert(!diagnostics.HasAnyErrors()); Debug.Assert(!body.HasErrors); bool sawLambdas; bool sawLocalFunctions; bool sawAwaitInExceptionHandler; ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty; body = LocalRewriter.Rewrite( compilation: this.DeclaringCompilation, method: this, methodOrdinal: _methodOrdinal, containingType: _container, statement: body, compilationState: compilationState, previousSubmissionFields: null, allowOmissionOfConditionalCalls: false, instrumentForDynamicAnalysis: false, debugDocumentProvider: null, dynamicAnalysisSpans: ref dynamicAnalysisSpans, diagnostics: diagnostics, sawLambdas: out sawLambdas, sawLocalFunctions: out sawLocalFunctions, sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler); Debug.Assert(!sawAwaitInExceptionHandler); Debug.Assert(dynamicAnalysisSpans.Length == 0); if (body.HasErrors) { return; } // Variables may have been captured by lambdas in the original method // or in the expression, and we need to preserve the existing values of // those variables in the expression. This requires rewriting the variables // in the expression based on the closure classes from both the original // method and the expression, and generating a preamble that copies // values into the expression closure classes. // // Consider the original method: // static void M() // { // int x, y, z; // ... // F(() => x + y); // } // and the expression in the EE: "F(() => x + z)". // // The expression is first rewritten using the closure class and local <1> // from the original method: F(() => <1>.x + z) // Then lambda rewriting introduces a new closure class that includes // the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z) // And a preamble is added to initialize the fields of <2>: // <2> = new <>c__DisplayClass0(); // <2>.<1> = <1>; // <2>.z = z; // Rewrite "this" and "base" references to parameter in this method. // Rewrite variables within body to reference existing display classes. body = (BoundStatement)CapturedVariableRewriter.Rewrite( this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0], compilation.Conversions, _displayClassVariables, body, diagnostics); if (body.HasErrors) { Debug.Assert(false, "Please add a test case capturing whatever caused this assert."); return; } if (diagnostics.HasAnyErrors()) { return; } if (sawLambdas || sawLocalFunctions) { var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); body = LambdaRewriter.Rewrite( loweredBody: body, thisType: this.SubstitutedSourceMethod.ContainingType, thisParameter: _thisParameter, method: this, methodOrdinal: _methodOrdinal, substitutedSourceMethod: this.SubstitutedSourceMethod.OriginalDefinition, closureDebugInfoBuilder: closureDebugInfoBuilder, lambdaDebugInfoBuilder: lambdaDebugInfoBuilder, slotAllocatorOpt: null, compilationState: compilationState, diagnostics: diagnostics, assignLocals: true); // we don't need this information: closureDebugInfoBuilder.Free(); lambdaDebugInfoBuilder.Free(); } // Insert locals from the original method, // followed by any new locals. var block = (BoundBlock)body; var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in this.Locals) { Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count)); localBuilder.Add(local); } foreach (var local in block.Locals) { var oldLocal = local as EELocalSymbol; if (oldLocal != null) { Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal); continue; } localBuilder.Add(local); } body = block.Update(localBuilder.ToImmutableAndFree(), block.LocalFunctions, block.Statements); TypeParameterChecker.Check(body, _allTypeParameters); compilationState.AddSynthesizedMethod(this, body); } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); } } private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt) { if (bodyOpt == null) { // If the method doesn't do anything, then it doesn't return anything. return compilation.GetSpecialType(SpecialType.System_Void); } switch (bodyOpt.Kind) { case BoundKind.ReturnStatement: return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type; case BoundKind.ExpressionStatement: case BoundKind.LocalDeclaration: case BoundKind.MultipleLocalDeclarations: case BoundKind.LocalDeconstructionDeclaration: return compilation.GetSpecialType(SpecialType.System_Void); default: throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind); } } internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedReturnTypeAttributes(ref attributes); if (this.ReturnType.ContainsDynamic()) { var compilation = this.DeclaringCompilation; if ((object)compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor) != null) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(this.ReturnType, this.ReturnTypeCustomModifiers.Length)); } } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return localPosition; } } }
#if UNITY_EDITOR #if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 #define BEFORE_UNITY_4_3 #else #define AFTER_UNITY_4_3 #endif using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using SpriteScaleMode = Uni2DSprite.SpriteScaleMode; using SpriteRenderMesh = Uni2DSprite.SpriteRenderMesh; using PivotType = Uni2DSprite.PivotType; using CollisionType = Uni2DSprite.CollisionType; using PhysicsMode = Uni2DSprite.PhysicsMode; using DimensionMode = Uni2DSprite.DimensionMode; using BuildSettings = Uni2DEditorSerializedSprite_BuildSettings; using InteracteBuildSettings = Uni2DEditorSerializedSprite_InteractiveBuildSettings; using AnimationGUIAction = Uni2DEditorGUIUtils.AnimationGUIAction; using BoneEditMode = Uni2DEditorSmoothBindingUtils.BoneEditMode; /* * Uni2DSpriteInspector * * Creates the Uni2DSprite inspector which allows to tweak and update the sprite build settings and * to regenerate the sprite(s) in consequence. * * This inspector is a bit special because it handles "interactive" values * and "non-interactive" values: * _ Interactive values can be easily updated and need light/quick computations that can be done on-the-fly * _ Non-interactive values are harder to update (i.e. must regenerate the sprite) and need much more heavier/longer computations * * Before Uni2D v2, because of the regeneration duration, * the user had to press a button to validate his settings and to regenerate the sprite. * This behaviour hints the user that the operation would be a bit "long" (~1.5s) but it was not very Unity-like. * * Since Uni2D v2, the inspector tries to rebuild the sprite the best it can. * To avoid long delays when tweaking a sprite (or more sprites, via multi-selection), * the inspector manages a timer which is started when the user is typing * a non-interactive value. At each key press, the timer is reinitialized. * After a while (when the value is assumed to be "fully typed"), * the inspector inits the sprite regeneration. * * Editor use only. * */ [CustomEditor( typeof( Uni2DSprite ) )] [CanEditMultipleObjects] public class Uni2DSpriteInspector : Editor { #if BEFORE_UNITY_4_3 private static string ms_GUIWarningMessage2DModeOnlyAfterUnity4_3 = "2D physics is only available from Unity 4.3 and later."; #endif private static string ms_GUIWarningMessagePrefabEdition = "Prefab edition is restricted.\nOnly in-scene sprite objects can be edited."; private static string ms_GUIWarningMessageSmoothBindingInAnimationModeEdition = "Sprite can't be edited in animation mode.\nBone edition is still available."; // private static string ms_GUIWarningMessageSettingsChanged = "Settings have been changed.\nPress \"Apply\" to save them."; // private static string ms_GUIDialogTitleUnappliedSettings = "Unapplied sprite settings"; // private static string ms_GUIDialogMessageUnappliedSettings = "Unapplied settings for '{0}'"; // private static string ms_GUIDialogOKUnappliedSettings = "Apply"; // private static string ms_GUIDialogCancelUnappliedSettings = "Revert"; // private static string ms_GUIButtonLabelOK = "Apply"; // private static string ms_GUIButtonLabelCancel = "Revert"; private static string ms_GUILabelSpriteTexture = "Sprite Texture"; private static string ms_GUILabelSharedMaterial = "Shared Material"; private static string ms_GUILabelInfoTriangleCount = "Collider Triangles"; private const string mc_GUISelectLabel = "Select"; private const float mc_GUISmallButtonWidth = 80.0f; private const float mc_GUIMediumButtonWidth = 120.0f; // Editor window GUI private const string mc_oGUILabelScale = "Sprite Scale"; private const string mc_oGUILabelPivot = "Pivot"; private const string mc_oGUILabelCustomPivotPoint = "Custom pivot point"; private const string mc_oGUILabelCollider = "Advanced Collider Settings"; private const string mc_oGUILabelDimensionMode = "Dimension"; private const string mc_oGUILabelAlphaCutOff = "Alpha Cut Off"; private const string mc_oGUILabelAccuracy = "Edge Simplicity"; private const string mc_oGUILabelExtrusion = "Extrusion Depth"; private const string mc_oGUILabelHoles = "Polygonize Holes"; private const string mc_oGUILabelOnlyBorder = "Only Border"; private const string mc_oGUILabelSubdivide = "Subdivide"; private const string mc_oGUILabelSubdivisionCount = "Subdivision Count"; private const string mc_oGUILabelBoneInfluenceFalloff = "Bone Influence Falloff"; private const string mc_oGUILabelSkinQuality = "Skin Quality"; private const string mc_oGUILabelHorizontalSubDivs = "Horizontal Sub Divs"; private const string mc_oGUILabelVerticalSubDivs = "Vertical Sub Divs"; // Foldouts states private static bool ms_bGUIFoldoutPhysicMode = true; private static bool ms_bGUIFoldoutRenderMeshSettings = true; private static bool ms_bGUIFoldoutPivot = true; private static bool ms_bGUIFoldoutColliderSettings = false; private static bool ms_bGUIFoldoutAnimation = true; private static bool ms_bGUIFoldoutSkeletalSmoothBinding = true; // Used to prevent a unintended cleanup (in OnDisable) when the target Renderer has changed // (because Unity editor reloads the inspector) private static bool ms_bIgnoreInspectorChanges; private BuildSettings m_oBuildSettings = null; private InteracteBuildSettings m_oInteractiveBuildSettings = null; //private RegularSettings m_oRegularSettings = null; // Delay to regen when tweaking non interactive settings private static float ms_fRegenDelay = 0.75f; private float m_fTimeToRegenAt = -1.0f; // Animation preview private Uni2DAnimationPlayer m_oAnimationPlayer = new Uni2DAnimationPlayer( ); private long m_lLastTimeTicks; // Skeletal animation editor //private Uni2DEditorSmoothBindingGUI m_oSmoothBindingEditor = null; // Init inspector void OnEnable( ) { m_oBuildSettings = new BuildSettings( serializedObject ); m_oInteractiveBuildSettings = new InteracteBuildSettings( serializedObject ); this.SetupAnimationPlayers( ); //m_oSmoothBindingEditor = new Uni2DEditorSmoothBindingGUI( (Uni2DSprite) this.target ); } // Inspector cleanup void OnDisable( ) { if( ms_bIgnoreInspectorChanges == false ) { // Stop timer and try to rebuild a last time if necessary this.StopRegenTimer( ); RegenerateSpriteData( ); //m_oSmoothBindingEditor.OnDisable( ); } } // Inspector GUI draw pass public override void OnInspectorGUI() { // Update serialized representation of the target object(s) serializedObject.Update( ); SerializedSetting<CollisionType> rSerializedCollisionType = m_oBuildSettings.serializedCollisionType; SerializedSetting<PhysicsMode> rSerializedPhysicsMode = m_oBuildSettings.serializedPhysicsMode; SerializedSetting<Texture2D> rSerializedSpriteTexture = m_oInteractiveBuildSettings.serializedTexture; SerializedSetting<string> rSerializedSpriteTextureGUID = m_oInteractiveBuildSettings.serializedTextureGUID; SerializedSetting<Material> rSerializedSharedMaterial = m_oInteractiveBuildSettings.serializedSharedMaterial; SerializedSetting<SpriteRenderMesh> rSerializedSpriteRenderMesh = m_oBuildSettings.serializedRenderMesh; // Update animation player used in clip header m_oAnimationPlayer.Update( this.ComputeDeltaTime( ref m_lLastTimeTicks ) ); ms_bIgnoreInspectorChanges = false; // Check persistence and editor mode bool bIsSelectionPersistent = Uni2DEditorUtils.IsThereAtLeastOnePersistentObject( serializedObject.targetObjects ); bool bIsInAnimationMode = MultiUnityVersionSupportUtility.InAnimationMode(); // Message not editable in animation mode if( bIsInAnimationMode ) { EditorGUILayout.BeginVertical( ); { EditorGUILayout.HelpBox( ms_GUIWarningMessageSmoothBindingInAnimationModeEdition, MessageType.Warning, true ); } EditorGUILayout.EndVertical( ); } SerializedSetting<bool> rSerializedIsPhysicsDirty = m_oBuildSettings.serializedIsPhysicsDirty; // Message not editable in resource if( bIsSelectionPersistent && bIsInAnimationMode == false ) { EditorGUILayout.BeginVertical( ); { EditorGUILayout.HelpBox( ms_GUIWarningMessagePrefabEdition, MessageType.Warning, true ); } EditorGUILayout.EndVertical( ); } // Can we edit? bool bForceUpdate; bool bNotEditable = bIsSelectionPersistent || bIsInAnimationMode; int iTargetCount = targets.Length; EditorGUILayout.BeginVertical( ); { EditorGUI.BeginDisabledGroup( bNotEditable ); { ///// Help message ///// if( rSerializedPhysicsMode.HasMultipleDifferentValues == false && rSerializedCollisionType.HasMultipleDifferentValues == false ) { EditorGUILayout.HelpBox( GetHelpMessage( rSerializedPhysicsMode.Value, rSerializedCollisionType.Value ), MessageType.Info, true ); EditorGUILayout.Space( ); } if( rSerializedSpriteTextureGUID.HasMultipleDifferentValues == false && rSerializedSpriteTextureGUID.Value == null ) { EditorGUILayout.HelpBox( "The sprite has no texture. Settings have been reverted.", MessageType.Warning, true ); EditorGUILayout.Space( ); } } EditorGUI.EndDisabledGroup( ); // Update physic? EditorGUI.BeginDisabledGroup( bIsInAnimationMode ); { string oUpdatePhysicButtonLabel = "Force Update"; if( rSerializedIsPhysicsDirty.HasMultipleDifferentValues == false && rSerializedIsPhysicsDirty.Value ) { EditorGUILayout.HelpBox( "The texture has changed since the last physics computation. Press the \"Update Physics\" button to update the physics shape.", MessageType.Warning, true ); oUpdatePhysicButtonLabel = "Update Physics"; } EditorGUILayout.BeginHorizontal( ); { GUILayout.FlexibleSpace( ); bForceUpdate = GUILayout.Button( oUpdatePhysicButtonLabel, EditorStyles.miniButton ); } EditorGUILayout.EndHorizontal( ); } EditorGUI.EndDisabledGroup( ); EditorGUI.BeginDisabledGroup( bNotEditable ); { ///// Sprite texture ///// SerializedTexture2DField( rSerializedSpriteTextureGUID, ms_GUILabelSpriteTexture, false ); if( rSerializedSpriteTextureGUID.IsDefined ) { // Revert the texture and physics dirty setting // if no texture is selected if( string.IsNullOrEmpty( rSerializedSpriteTextureGUID.Value ) ) { //rSerializedSpriteTexture.Revert( ); rSerializedSpriteTextureGUID.Revert( ); rSerializedIsPhysicsDirty.Revert( ); } else // New texture set => mark the physic part of the sprite as dirty { //rSerializedSpriteTextureGUID.Value = Uni2DEditorUtils.GetUnityAssetGUID( rSerializedSpriteTexture.Value ); rSerializedSpriteTexture.Value = null; rSerializedIsPhysicsDirty.Value = true; } } ///// Atlas ///// EditorGUILayout.BeginHorizontal( ); { string[ ] rTextureGUIDsToContain = new string[ iTargetCount ]; for( int iTargetIndex = 0; iTargetIndex < iTargetCount; ++iTargetIndex ) { rTextureGUIDsToContain[ iTargetIndex ] = ( (Uni2DSprite) targets[ iTargetIndex ] ).SpriteSettings.textureContainer.GUID; } Uni2DTextureAtlas rSelectedAtlas; EditorGUI.BeginDisabledGroup( bNotEditable ); { EditorGUILayout.PrefixLabel( "Use Atlas" ); rSelectedAtlas = Uni2DEditorGUIUtils.SerializedAtlasPopup( m_oInteractiveBuildSettings.serializedAtlas, rTextureGUIDsToContain ); } EditorGUI.EndDisabledGroup( ); EditorGUI.BeginDisabledGroup( rSelectedAtlas == null ); { if( GUILayout.Button( mc_GUISelectLabel, GUILayout.Width( mc_GUISmallButtonWidth ) ) ) { EditorGUIUtility.PingObject( rSelectedAtlas.gameObject ); } } EditorGUI.EndDisabledGroup( ); if( m_oInteractiveBuildSettings.serializedAtlas.IsDefined && rSelectedAtlas != null && !rSelectedAtlas.Contains( rTextureGUIDsToContain ) ) { bool bBuildAtlas = EditorUtility.DisplayDialog( "Uni2D", "The selected Uni2D atlas does not contain the sprite(s) texture(s)." + " Adding them implies to rebuild the atlas and can be a long process.\n\n" + "Do it anyway?", "Yes, Build Atlas", "Cancel" ); if( bBuildAtlas ) { rSelectedAtlas.AddTextures( rTextureGUIDsToContain ); rSelectedAtlas.ApplySettings( true ); } else { m_oInteractiveBuildSettings.serializedAtlas.Revert( ); rSelectedAtlas = m_oInteractiveBuildSettings.serializedAtlas.Value; } } } EditorGUILayout.EndHorizontal( ); EditorGUI.BeginDisabledGroup( m_oInteractiveBuildSettings.serializedAtlas.HasMultipleDifferentValues || m_oInteractiveBuildSettings.serializedAtlas.Value != null); { ///// Shared Material ///// SerializedMaterialField( rSerializedSharedMaterial, ms_GUILabelSharedMaterial ); } EditorGUI.EndDisabledGroup( ); ///// Vertex color ///// if( Application.isPlaying == false ) { SerializedColorField( m_oInteractiveBuildSettings.serializedVertexColor, "Vertex Color" ); } else { EditorGUI.showMixedValue = m_oInteractiveBuildSettings.serializedVertexColor.HasMultipleDifferentValues; { Color f4VertexColor; EditorGUI.BeginChangeCheck( ); { f4VertexColor = EditorGUILayout.ColorField( "Vertex Color", m_oInteractiveBuildSettings.serializedVertexColor.Value ); } if( EditorGUI.EndChangeCheck( ) ) { foreach( Uni2DSprite rSprite in targets ) { rSprite.VertexColor = f4VertexColor; } } } EditorGUI.showMixedValue = false; } #if AFTER_UNITY_4_3 ///// Sorting Layer ///// bool bMixedSortingOrderLayerNameValue = false; string oSortingLayerName = ""; bool bFirstSortingLayerNameValue = true; foreach(Uni2DSprite rSprite in targets ) { string oCurrentSortingLayerNameValue = rSprite.SortingLayerName; if(bFirstSortingLayerNameValue == false && oCurrentSortingLayerNameValue != oSortingLayerName) { bMixedSortingOrderLayerNameValue = true; oSortingLayerName = ""; break; } else { oSortingLayerName = oCurrentSortingLayerNameValue; bFirstSortingLayerNameValue = false; } } EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = bMixedSortingOrderLayerNameValue; { System.Reflection.PropertyInfo oPropertyInfo_SortingLayerNames = null; try { System.Type oInternalEditorUtilityType = System.Type.GetType("UnityEditorInternal.InternalEditorUtility,UnityEditor"); if (oInternalEditorUtilityType != null) { oPropertyInfo_SortingLayerNames = oInternalEditorUtilityType.GetProperty("sortingLayerNames", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); } } catch{} if(oPropertyInfo_SortingLayerNames != null) { string[] oSortingLayerNames = oPropertyInfo_SortingLayerNames.GetValue(null, null) as string[]; int iSelectedItem = 0; string oLayerName = oSortingLayerName; if(oLayerName == "") { oLayerName = "Default"; } for(int i = 0; i < oSortingLayerNames.Length; ++i) { if(oSortingLayerNames[i] == oLayerName) { iSelectedItem = i; break; } } oSortingLayerName = oSortingLayerNames[EditorGUILayout.Popup("Sorting Layer", iSelectedItem, oSortingLayerNames)]; } } EditorGUI.showMixedValue = false; } if( EditorGUI.EndChangeCheck( ) ) { foreach( Uni2DSprite rSprite in targets ) { Undo.RecordObject(rSprite.GetComponent<Renderer>(), "Sorting Layer"); rSprite.SortingLayerName = oSortingLayerName; EditorUtility.SetDirty(rSprite); } } ///// Sorting Order ///// bool bMixedSortingOrderValue = false; int iSortingOrder = 0; bool bFirstSortingOrderValue = true; foreach(Uni2DSprite rSprite in targets ) { int iCurrentSortingOrderValue = rSprite.SortingOrder; if(bFirstSortingOrderValue == false && iCurrentSortingOrderValue != iSortingOrder) { bMixedSortingOrderValue = true; iSortingOrder = 0; break; } else { iSortingOrder = iCurrentSortingOrderValue; bFirstSortingOrderValue = false; } } EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = bMixedSortingOrderValue; { iSortingOrder = EditorGUILayout.IntField( "Order in Layer", iSortingOrder); } EditorGUI.showMixedValue = false; } if( EditorGUI.EndChangeCheck( ) ) { foreach( Uni2DSprite rSprite in targets ) { Undo.RecordObject(rSprite.GetComponent<Renderer>(), "Order in Layer"); rSprite.SortingOrder = iSortingOrder; EditorUtility.SetDirty(rSprite); } } #endif ///// Collider triangle count ///// SerializedProperty rSerializedTriangleCount = serializedObject.FindProperty( "m_rSpriteData.colliderTriangleCount" ); if( rSerializedTriangleCount != null ) { EditorGUILayout.LabelField( ms_GUILabelInfoTriangleCount, rSerializedTriangleCount.hasMultipleDifferentValues ? "-" : rSerializedTriangleCount.intValue.ToString( ) ); } SerializedSetting<float> rSerializedExtrusionDepth = m_oInteractiveBuildSettings.serializedExtrusionDepth; SerializedSetting<SpriteScaleMode> rSerializedSpriteScaleMode = m_oInteractiveBuildSettings.serializedSpriteScaleMode; SerializedSetting<float> rSerializedSpriteScale = m_oInteractiveBuildSettings.serializedSpriteScale; SerializedSetting<Vector2> rSerializedSpriteScaleNotUniform = m_oInteractiveBuildSettings.serializedSpriteScaleNotUniform; // Sprite settings EditorGUILayout.BeginVertical( ); { EditorGUI.BeginChangeCheck(); { Uni2DEditorGUIUtils.SerializedEnumPopup<SpriteScaleMode>(rSerializedSpriteScaleMode, "Sprite Scale Mode"); } if(EditorGUI.EndChangeCheck()) { for(int iTargetIndex = 0; iTargetIndex < iTargetCount; ++iTargetIndex) { Uni2DEditorSpriteSettings rSpriteSettings = ((Uni2DSprite) targets[iTargetIndex]).SpriteSettings; if(rSpriteSettings.spriteScaleMode != rSerializedSpriteScaleMode.Value) { switch(rSerializedSpriteScaleMode.Value) { case SpriteScaleMode.NotUniform: { rSpriteSettings.spriteScaleNotUniform = rSpriteSettings.spriteScale * Vector2.one; } break; case SpriteScaleMode.Uniform: { rSpriteSettings.spriteScale = rSpriteSettings.spriteScaleNotUniform.x; } break; } } } serializedObject.Update(); } // Scale EditorGUILayout.BeginHorizontal( ); { if(rSerializedSpriteScaleMode.HasMultipleDifferentValues == false) { switch(rSerializedSpriteScaleMode.Value) { case SpriteScaleMode.NotUniform: { EditorGUI.BeginChangeCheck( ); { SerializedVector2Field(rSerializedSpriteScaleNotUniform, mc_oGUILabelScale); } if(EditorGUI.EndChangeCheck()) { rSerializedSpriteScale.Value = rSerializedSpriteScaleNotUniform.Value.x; } } break; case SpriteScaleMode.Uniform: { EditorGUI.BeginChangeCheck( ); { SerializedFloatField(rSerializedSpriteScale, mc_oGUILabelScale); } if(EditorGUI.EndChangeCheck()) { rSerializedSpriteScaleNotUniform.Value = rSerializedSpriteScale.Value * Vector2.one; } } break; } } } EditorGUILayout.EndHorizontal( ); // Pixel perfect EditorGUI.BeginDisabledGroup(rSerializedSpriteScale.HasMultipleDifferentValues == false && rSerializedSpriteScaleNotUniform.HasMultipleDifferentValues == false && rSerializedSpriteScale.Value == 1.0f && rSerializedSpriteScaleNotUniform.Value == Vector2.one); { if(GUILayout.Button( "Pixel Perfect", GUILayout.Width(mc_GUISmallButtonWidth))) { rSerializedSpriteScale.Value = 1.0f; rSerializedSpriteScaleNotUniform.Value = Vector2.one; } } EditorGUI.EndDisabledGroup( ); ///// Pivot ///// // Type SerializedSetting<PivotType> rSerializedPivotType = m_oInteractiveBuildSettings.serializedPivotType; ms_bGUIFoldoutPivot = EditorGUILayout.Foldout( ms_bGUIFoldoutPivot, mc_oGUILabelPivot ); if( ms_bGUIFoldoutPivot ) { ++EditorGUI.indentLevel; { Uni2DEditorGUIUtils.SerializedEnumPopup<PivotType>( rSerializedPivotType, "Position" ); bool bDisablePivotCoordsField = rSerializedPivotType.HasMultipleDifferentValues || rSerializedPivotType.Value != Uni2DSprite.PivotType.Custom; // Coords EditorGUI.BeginDisabledGroup( bDisablePivotCoordsField ); { SerializedVector2Field( m_oInteractiveBuildSettings.serializedPivotCustomCoords, mc_oGUILabelCustomPivotPoint ); } EditorGUI.EndDisabledGroup( ); } --EditorGUI.indentLevel; EditorGUILayout.Space( ); } bool bDisablePhysicGroup = rSerializedPhysicsMode.HasMultipleDifferentValues || rSerializedPhysicsMode.Value == Uni2DSprite.PhysicsMode.NoPhysics; ///// Render mesh ///// ms_bGUIFoldoutRenderMeshSettings = EditorGUILayout.Foldout( ms_bGUIFoldoutRenderMeshSettings, "Sprite Mesh" ); if( ms_bGUIFoldoutRenderMeshSettings ) { ++EditorGUI.indentLevel; { Uni2DEditorGUIUtils.SerializedEnumPopup<SpriteRenderMesh>( rSerializedSpriteRenderMesh, "Mesh" ); if( rSerializedSpriteRenderMesh.HasMultipleDifferentValues == false ) { switch( rSerializedSpriteRenderMesh.Value ) { default: break; case SpriteRenderMesh.TextureToMesh: { SerializedSetting<bool> rSerializedUsePhysicBuildSettings = m_oBuildSettings.serializedUsePhysicBuildSettings; EditorGUI.BeginDisabledGroup( bDisablePhysicGroup == false && ( rSerializedUsePhysicBuildSettings.HasMultipleDifferentValues || rSerializedUsePhysicBuildSettings.Value ) ); { EditorGUI.BeginChangeCheck( ); { SerializedSlider( m_oBuildSettings.serializedRenderMeshAlphaCutOff, Uni2DEditorSpriteSettings.AlphaCutOffMin, Uni2DEditorSpriteSettings.AlphaCutOffMax, mc_oGUILabelAlphaCutOff ); SerializedSlider( m_oBuildSettings.serializedRenderMeshPolygonizationAccuracy, Uni2DEditorSpriteSettings.PolygonizationAccuracyMin, Uni2DEditorSpriteSettings.PolygonizationAccuracyMax, mc_oGUILabelAccuracy ); } if( EditorGUI.EndChangeCheck( ) ) { this.StopRegenTimer( ); this.StartRegenTimer( ); } } EditorGUI.EndDisabledGroup( ); EditorGUI.BeginDisabledGroup( bDisablePhysicGroup ); { SerializedToggle( rSerializedUsePhysicBuildSettings, "Use Physics Settings" ); } EditorGUI.EndDisabledGroup( ); SerializedToggle( m_oBuildSettings.serializedRenderMeshPolygonizeHoles, mc_oGUILabelHoles ); } break; case SpriteRenderMesh.Grid: { EditorGUI.BeginChangeCheck( ); { SerializedSlider( m_oBuildSettings.serializedRenderMeshAlphaCutOff, Uni2DEditorSpriteSettings.AlphaCutOffMin, Uni2DEditorSpriteSettings.AlphaCutOffMax, mc_oGUILabelAlphaCutOff ); SerializedSlider( m_oBuildSettings.serializedRenderMeshGridHorizontalSubDivs, Uni2DEditorSpriteSettings.RenderMeshGridSubDivsMin, Uni2DEditorSpriteSettings.RenderMeshGridSubDivsMax, mc_oGUILabelHorizontalSubDivs ); SerializedSlider( m_oBuildSettings.serializedRenderMeshGridVerticalSubDivs, Uni2DEditorSpriteSettings.RenderMeshGridSubDivsMin, Uni2DEditorSpriteSettings.RenderMeshGridSubDivsMax, mc_oGUILabelVerticalSubDivs ); } if( EditorGUI.EndChangeCheck( ) ) { this.StopRegenTimer( ); this.StartRegenTimer( ); } } break; } } } --EditorGUI.indentLevel; EditorGUILayout.Space( ); } ///// Physics ///// ms_bGUIFoldoutPhysicMode = EditorGUILayout.Foldout( ms_bGUIFoldoutPhysicMode, "Physics" ); if( ms_bGUIFoldoutPhysicMode ) { ++EditorGUI.indentLevel; { // Mode Uni2DEditorGUIUtils.SerializedEnumPopup<PhysicsMode>( rSerializedPhysicsMode, "Physics Mode" ); // Physic settings group EditorGUI.BeginDisabledGroup( bDisablePhysicGroup ); { // Is Trigger SerializedToggle(m_oInteractiveBuildSettings.serializedIsTrigger, "Is Trigger"); // Is Kinematic bool bDisableIsKinematicToggle = rSerializedPhysicsMode.HasMultipleDifferentValues || rSerializedPhysicsMode.Value != Uni2DSprite.PhysicsMode.Dynamic; EditorGUI.BeginDisabledGroup( bDisableIsKinematicToggle ); { SerializedToggle( m_oInteractiveBuildSettings.serializedIsKinematic, "Is Kinematic" ); } EditorGUI.EndDisabledGroup( ); // DimensionMode Mode Uni2DEditorGUIUtils.SerializedEnumPopup<DimensionMode>(m_oBuildSettings.serializedDimensionMode, mc_oGUILabelDimensionMode); bool bUnavailablePhysicMode = false; #if BEFORE_UNITY_4_3 bool b2DSelected = m_oBuildSettings.serializedDimensionMode.HasMultipleDifferentValues || m_oBuildSettings.serializedDimensionMode.Value == DimensionMode._2D; if(b2DSelected) { bUnavailablePhysicMode = true; EditorGUILayout.HelpBox(ms_GUIWarningMessage2DModeOnlyAfterUnity4_3, MessageType.Warning, true); } #endif EditorGUI.BeginDisabledGroup(bUnavailablePhysicMode); { bool bDisable3DSettings = m_oBuildSettings.serializedDimensionMode.HasMultipleDifferentValues || m_oBuildSettings.serializedDimensionMode.Value == DimensionMode._2D; EditorGUI.BeginDisabledGroup( bDisable3DSettings ); { // Collision type Uni2DEditorGUIUtils.SerializedEnumPopup<CollisionType>( m_oBuildSettings.serializedCollisionType, "Collision Type" ); } EditorGUI.EndDisabledGroup(); // Collider settings ms_bGUIFoldoutColliderSettings = EditorGUILayout.Foldout( ms_bGUIFoldoutColliderSettings, mc_oGUILabelCollider ); if( ms_bGUIFoldoutColliderSettings ) { ++EditorGUI.indentLevel; { EditorGUI.BeginChangeCheck( ); { // Alpha cut off SerializedSlider( m_oBuildSettings.serializedAlphaCutOff, Uni2DEditorSpriteSettings.AlphaCutOffMin, Uni2DEditorSpriteSettings.AlphaCutOffMax, mc_oGUILabelAlphaCutOff ); // Threshold or cut-out? // Polygonization accuracy SerializedSlider( m_oBuildSettings.serializedPolygonizationAccuracy, Uni2DEditorSpriteSettings.PolygonizationAccuracyMin, Uni2DEditorSpriteSettings.PolygonizationAccuracyMax, mc_oGUILabelAccuracy ); } // If the user has typed/tweaked non-interactive values, // start the timer if( EditorGUI.EndChangeCheck( ) ) { // Reset timer this.StopRegenTimer( ); this.StartRegenTimer( ); } // Subdivide SerializedToggle( m_oBuildSettings.serializedSubdivide, mc_oGUILabelSubdivide ); // Subdivision Step bool bDisableSubdivisionStep = m_oBuildSettings.serializedSubdivide.HasMultipleDifferentValues || m_oBuildSettings.serializedSubdivide.Value == false; EditorGUI.BeginDisabledGroup( bDisableSubdivisionStep ); { EditorGUI.BeginChangeCheck( ); { SerializedSlider( m_oBuildSettings.serializedSubdivisionCount, Uni2DEditorSpriteSettings.SubdivisionCountMin, Uni2DEditorSpriteSettings.SubdivisionCountMax, mc_oGUILabelSubdivisionCount ); } if( EditorGUI.EndChangeCheck( ) ) { this.StopRegenTimer( ); this.StartRegenTimer( ); } } EditorGUI.EndDisabledGroup(); // Polygonize holes bool bDisablePolygonizeHoles = rSerializedCollisionType.HasMultipleDifferentValues || (rSerializedCollisionType.Value == Uni2DSprite.CollisionType.Convex && m_oBuildSettings.serializedDimensionMode.HasMultipleDifferentValues == false && m_oBuildSettings.serializedDimensionMode.Value == DimensionMode._3D); EditorGUI.BeginDisabledGroup( bDisablePolygonizeHoles ); { SerializedToggle( m_oBuildSettings.serializedPolygonizeHoles, mc_oGUILabelHoles ); } EditorGUI.EndDisabledGroup(); // Extrusion EditorGUI.BeginDisabledGroup(bDisable3DSettings); { // Extrusion depth SerializedFloatField( rSerializedExtrusionDepth, mc_oGUILabelExtrusion ); // Only border bool bDisableOnlyBorder = rSerializedCollisionType.HasMultipleDifferentValues || rSerializedCollisionType.Value == Uni2DSprite.CollisionType.Compound || rSerializedCollisionType.Value == Uni2DSprite.CollisionType.Convex; EditorGUI.BeginDisabledGroup( bDisableOnlyBorder ); { SerializedToggle( m_oBuildSettings.serializedOnlyBorder, mc_oGUILabelOnlyBorder ); } EditorGUI.EndDisabledGroup(); } EditorGUI.EndDisabledGroup(); } --EditorGUI.indentLevel; } } EditorGUI.EndDisabledGroup(); } EditorGUI.EndDisabledGroup(); } --EditorGUI.indentLevel; EditorGUILayout.Space( ); } } EditorGUILayout.EndVertical( ); // Sprite scale if( rSerializedSpriteScale.IsDefined ) { rSerializedSpriteScale.Value = ClampScale(rSerializedSpriteScale.Value); } if( rSerializedSpriteScaleNotUniform.IsDefined ) { rSerializedSpriteScaleNotUniform.Value = ClampScale(rSerializedSpriteScaleNotUniform.Value); } // Extrusion depth if( rSerializedExtrusionDepth.IsDefined ) { rSerializedExtrusionDepth.Value = Mathf.Clamp( rSerializedExtrusionDepth.Value, Uni2DEditorSpriteSettings.ExtrusionMin, float.MaxValue ); } } EditorGUI.EndDisabledGroup( ); ///// Skeletal animation section ///// ms_bGUIFoldoutSkeletalSmoothBinding = EditorGUILayout.Foldout( ms_bGUIFoldoutSkeletalSmoothBinding, "Skeletal Smooth Binding" ); if( ms_bGUIFoldoutSkeletalSmoothBinding ) { ++EditorGUI.indentLevel; { SerializedSetting<float> rSerializedBoneInfluenceFalloff = m_oInteractiveBuildSettings.serializedBoneInfluenceFalloff; SerializedSetting<SkinQuality> rSerializedSkinQuality = m_oInteractiveBuildSettings.serializedSkinQuality; SerializedSetting<Uni2DSprite.EPhysicsSkinMode> rSerializedPhysicsSkinMode = m_oInteractiveBuildSettings.serializedPhysicsSkinMode; SerializedSetting<Uni2DSprite.ERenderSkinMode> rSerializedRenderSkinMode = m_oInteractiveBuildSettings.serializedRenderSkinMode; EditorGUI.BeginDisabledGroup( bNotEditable ); { Uni2DEditorGUIUtils.SerializedEnumPopup<SkinQuality>( rSerializedSkinQuality, mc_oGUILabelSkinQuality ); SerializedFloatField( rSerializedBoneInfluenceFalloff, mc_oGUILabelBoneInfluenceFalloff ); Uni2DEditorGUIUtils.SerializedEnumPopup<Uni2DSprite.EPhysicsSkinMode>( rSerializedPhysicsSkinMode, "Physics Skin Mode" ); Uni2DEditorGUIUtils.SerializedEnumPopup<Uni2DSprite.ERenderSkinMode>( rSerializedRenderSkinMode, "Render Skin Mode" ); EditorGUILayout.BeginHorizontal( ); { GUILayout.FlexibleSpace( ); if( GUILayout.Button( "Open Skeletal Animation Editor", GUILayout.Width( 225.0f ) ) ) { Uni2DEditorSmoothBindingWindow.CreateEditorWindow( ); } GUILayout.FlexibleSpace( ); } EditorGUILayout.EndHorizontal( ); } EditorGUI.EndDisabledGroup( ); } --EditorGUI.indentLevel; EditorGUILayout.Space( ); } EditorGUI.BeginDisabledGroup( bNotEditable ); { ///// Animation section ///// this.DisplaySpriteAnimationSection( ); } EditorGUI.EndDisabledGroup( ); EditorGUILayout.Space( ); } EditorGUILayout.EndVertical( ); if( Application.isPlaying == false ) { // Retrieve inspector area // Handle drag'n'drop this.CheckAnimationClipDragAndDrop( GUILayoutUtility.GetLastRect( ) ); } // Force repaint if animation player enabled if( m_oAnimationPlayer.Enabled ) { this.Repaint( ); } // Apply non-interactive settings // Check texture value if( rSerializedSpriteTextureGUID.HasMultipleDifferentValues == false && string.IsNullOrEmpty( rSerializedSpriteTextureGUID.Value ) ) { this.StopRegenTimer( ); //m_oBuildSettings.RevertValues( ); //m_oInteractiveBuildSettings.RevertValues( ); //m_oRegularSettings.RevertValues( ); } else { if( this.IsTimerStarted == false && m_oBuildSettings.AreValuesModified( ) ) { this.StopRegenTimer( ); //this.StartRegenTimer( ); RegenerateSpriteData( ); return; /* if( this.IsTimerStarted == false ) { this.StopRegenTimer( ); RegenerateSpriteData( ); return; }*/ } if( m_oInteractiveBuildSettings.AreValuesModified( ) ) { this.StopRegenTimer( ); RegenerateSpriteInteractiveData( ); } if( bForceUpdate ) { RegenerateSpriteData( true ); } } } ////////// Timer methods ////////// // Tells if the timer has started private bool IsTimerStarted { get { return m_fTimeToRegenAt != -1.0f; } } // Starts the timer private void StartRegenTimer( ) { if( this.IsTimerStarted == false ) { m_fTimeToRegenAt = Time.realtimeSinceStartup + ms_fRegenDelay; EditorApplication.delayCall += RegenerateSpriteDataDelegate; } } // Stops the timer private void StopRegenTimer( ) { EditorApplication.delayCall -= RegenerateSpriteDataDelegate; m_fTimeToRegenAt = -1.0f; } // Timer delegate private void RegenerateSpriteDataDelegate( ) { if( Time.realtimeSinceStartup >= m_fTimeToRegenAt ) { this.StopRegenTimer( ); this.RegenerateSpriteData( ); } else { EditorApplication.delayCall += RegenerateSpriteDataDelegate; } } ////////// Sprite building ////////// // Regenerates the sprite data private void RegenerateSpriteData( bool a_bForceFullRegeneration = false ) { if( a_bForceFullRegeneration || m_oBuildSettings.AreValuesModified( ) ) // Non interactive data update { ms_bIgnoreInspectorChanges = true; m_oBuildSettings.serializedIsPhysicsDirty.Value = true; // Apply ALL settings m_oBuildSettings.ApplyValues( ); m_oInteractiveBuildSettings.ApplyValues( ); serializedObject.ApplyModifiedProperties( ); // Regenerate in a batch List<Uni2DSprite> oSpritesToRegenerate = new List<Uni2DSprite>( serializedObject.targetObjects.Length ); foreach( Object rTargetObject in serializedObject.targetObjects ) { oSpritesToRegenerate.Add( (Uni2DSprite) rTargetObject ); } Uni2DEditorSpriteBuilderUtils.RegenerateSpritesInABatch( oSpritesToRegenerate, a_bForceFullRegeneration ); } } // Regenerates sprite interactive data only private void RegenerateSpriteInteractiveData( bool a_bForce = false ) { if( a_bForce || m_oInteractiveBuildSettings.AreValuesModified( ) ) { ms_bIgnoreInspectorChanges = true; // Apply only interactive and regular settings m_oInteractiveBuildSettings.ApplyValues( ); //m_oRegularSettings.ApplyValues( ); serializedObject.ApplyModifiedProperties( ); foreach( Object rTargetObject in serializedObject.targetObjects ) { ( (Uni2DSprite) rTargetObject ).RegenerateInteractiveData( ); } } } ////////// Custom GUI ////////// // Get help message private string GetHelpMessage( Uni2DSprite.PhysicsMode a_ePhysicMode, Uni2DSprite.CollisionType a_eCollisionType ) { string oHelpMessage = ""; if(a_ePhysicMode == Uni2DSprite.PhysicsMode.NoPhysics) { oHelpMessage = "In no physics mode, there is no collider attached to the sprite."; } else if(a_ePhysicMode == Uni2DSprite.PhysicsMode.Static) { if(a_eCollisionType == Uni2DSprite.CollisionType.Convex) { oHelpMessage = "In static convex mode, the mesh collider does not respond to collisions (e.g. not a rigidbody) as a convex mesh.\n" + "Unity computes a convex hull if the mesh collider is not convex."; } else if(a_eCollisionType == Uni2DSprite.CollisionType.Concave) { oHelpMessage = "In static concave mode, mesh collider does not respond to collisions (e.g. not a rigidbody) as a concave mesh.\n" + "A mesh collider marked as concave only interacts with primitive colliders (boxes, spheres...) and convex meshes."; } else if(a_eCollisionType == Uni2DSprite.CollisionType.Compound) { oHelpMessage = "In static compound mode, mesh collider does not respond to collisions (e.g. not a rigidbody) as a concave mesh composed of small convex meshes.\n" + "It allows the collider to block any other collider at the expense of performances."; } } else if(a_ePhysicMode == Uni2DSprite.PhysicsMode.Dynamic) { if(a_eCollisionType == Uni2DSprite.CollisionType.Convex) { oHelpMessage = "In dynamic convex mode, mesh collider does respond to collisions (e.g. rigidbody) as a convex mesh.\n" + "Unity computes a convex hull if the mesh collider is not convex."; } else if(a_eCollisionType == Uni2DSprite.CollisionType.Concave) { oHelpMessage = "In dynamic concave mode, mesh collider does respond to collisions (e.g. rigidbody) as a concave mesh.\n" + "A mesh collider marked as concave only interacts with primitive colliders (boxes, spheres...)."; } else if(a_eCollisionType == Uni2DSprite.CollisionType.Compound) { oHelpMessage = "In dynamic compound mode, mesh collider does respond to collisions (e.g. rigidbody) as a concave mesh composed of small convex meshes.\n" + "It allows the collider to interact with any other collider at the expense of performances."; } } return oHelpMessage; } ///// Animation ///// private void DisplaySpriteAnimationSection( ) { /// Animation clip /// ms_bGUIFoldoutAnimation = EditorGUILayout.Foldout( ms_bGUIFoldoutAnimation, "Sprite Animation" ); if( ms_bGUIFoldoutAnimation ) { // The sprite animation object Uni2DSpriteAnimation rSpriteAnimation = ( (Uni2DSprite) target ).spriteAnimation; int iClipCount = rSpriteAnimation.ClipCount; bool bSingleEdit = ( targets.Length == 1 ); SerializedProperty rSerializedProperty_PlayAutomatically = serializedObject.FindProperty( "spriteAnimation.playAutomatically" ); SerializedProperty rSerializedProperty_StartClipIndex = serializedObject.FindProperty( "spriteAnimation.m_iStartClipIndex" ); ///// Sprite animation settings ///// EditorGUI.BeginDisabledGroup( Application.isPlaying ); { EditorGUILayout.BeginVertical( ); { ++EditorGUI.indentLevel; { int iStartClipIndex; // Play automatically EditorGUI.BeginChangeCheck( ); { EditorGUILayout.PropertyField( rSerializedProperty_PlayAutomatically ); } if( EditorGUI.EndChangeCheck( ) ) { serializedObject.ApplyModifiedProperties( ); } // Start clip //EditorGUI.BeginDisabledGroup( rSerializedProperty_PlayAutomatically.hasMultipleDifferentValues || rSerializedProperty_PlayAutomatically.boolValue == false ); //{ EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = rSerializedProperty_StartClipIndex.hasMultipleDifferentValues; { iStartClipIndex = EditorGUILayout.IntField( "Start Clip Index", rSerializedProperty_StartClipIndex.intValue ); } EditorGUI.showMixedValue = false; } if( EditorGUI.EndChangeCheck( ) ) { this.SetSpriteAnimationStartClip( iStartClipIndex ); serializedObject.SetIsDifferentCacheDirty( ); } //} //EditorGUI.EndDisabledGroup( ); } --EditorGUI.indentLevel; if( bSingleEdit ) { // Iterate clips for( int iClipIndex = 0; iClipIndex < iClipCount; ++iClipIndex ) { // Clip Uni2DAnimationClip rAnimationClip = rSpriteAnimation.GetClipByIndex( iClipIndex ); // Clip header AnimationGUIAction eAnimationClipHeaderAction; EditorGUILayout.BeginHorizontal( ); { GUILayout.Space( 12.0f ); EditorGUI.BeginChangeCheck( ); { eAnimationClipHeaderAction = Uni2DEditorGUIUtils.DisplayCompactAnimationClipHeader( rAnimationClip, m_oAnimationPlayer, iClipIndex ); } if( EditorGUI.EndChangeCheck( ) ) { // Update animation preview player settings m_oAnimationPlayer.FrameRate = rAnimationClip.frameRate; m_oAnimationPlayer.WrapMode = rAnimationClip.wrapMode; } } EditorGUILayout.EndHorizontal( ); // Handle returned action (if any) switch( eAnimationClipHeaderAction ) { // No action case AnimationGUIAction.None: default: break; case AnimationGUIAction.MoveUp: { if( iClipIndex != 0 ) { rSpriteAnimation.SwapClips( iClipIndex, iClipIndex - 1 ); EditorUtility.SetDirty( target ); } } break; case AnimationGUIAction.MoveDown: { if( iClipIndex != iClipCount - 1 ) { rSpriteAnimation.SwapClips( iClipIndex, iClipIndex + 1 ); EditorUtility.SetDirty( target ); } } break; case AnimationGUIAction.Close: { rSpriteAnimation.RemoveClip( iClipIndex ); --iClipIndex; --iClipCount; EditorUtility.SetDirty( target ); } break; } // End of eAnimationFrameAction handling } // End for clip ///// Add / new clip ///// EditorGUILayout.BeginHorizontal( ); { // Add menu Uni2DAnimationClip rAddedAnimationClip; GUILayout.FlexibleSpace( ); if( Uni2DEditorGUIUtils.AddClipPopup( "Add Animation Clip", out rAddedAnimationClip, GUILayout.Width( 225.0f ) ) ) { // Add to sprite animation ( (Uni2DSprite) target ).spriteAnimation.AddClip( rAddedAnimationClip ); EditorUtility.SetDirty( target ); } GUILayout.FlexibleSpace( ); } EditorGUILayout.EndHorizontal( ); } // End targets.length == 1 } EditorGUILayout.EndVertical( ); } EditorGUI.EndDisabledGroup( ); } // End animation } ///// Animation player utils ///// private float ComputeDeltaTime( ref long a_lBaseTicks ) { // Current tick count long lNow = System.DateTime.Now.Ticks; // Compute delta time. 1ms = 10,000 ticks => divide by 10,000,000 to have seconds float fDeltaTime = ( lNow - a_lBaseTicks ) * 0.0000001f; // Save tick count a_lBaseTicks = lNow; return fDeltaTime; } private void SetupAnimationPlayers( ) { m_oAnimationPlayer.onAnimationNewFrameEvent += this.ForceRepaint; m_oAnimationPlayer.onAnimationInactiveEvent += this.RestartAnimationPlayer; m_oAnimationPlayer.Play( ( (Uni2DSprite) target ).spriteAnimation.Clip ); m_oAnimationPlayer.Stop( false ); ComputeDeltaTime( ref m_lLastTimeTicks ); } private void ForceRepaint( Uni2DAnimationPlayer a_rAnimationPlayer ) { this.Repaint( ); } private void RestartAnimationPlayer( Uni2DAnimationPlayer a_rAnimationPlayer ) { a_rAnimationPlayer.Play( ( (Uni2DSprite) target ).spriteAnimation.Clip ); a_rAnimationPlayer.Stop( false ); } ////////// Animation clip utils ////////// // Handles animation clips drag'n'drops private void CheckAnimationClipDragAndDrop( Rect a_rDropAreaRect ) { // Handle drag and drop only if inspecting a single element if( targets.Length == 1 ) { Event rCurrentEvent = Event.current; EventType rCurrentEventType = rCurrentEvent.type; Vector2 f2MousePos = rCurrentEvent.mousePosition; if( a_rDropAreaRect.Contains( f2MousePos ) ) { bool bShouldAccept = false; foreach( Object rObject in DragAndDrop.objectReferences ) { if( ( rObject is GameObject ) && ( (GameObject) rObject ).GetComponent<Uni2DAnimationClip>( ) != null ) { bShouldAccept = true; break; } } if( bShouldAccept ) { if( rCurrentEventType == EventType.DragPerform ) { DragAndDrop.AcceptDrag( ); rCurrentEvent.Use( ); DragAndDrop.activeControlID = 0; Uni2DSpriteAnimation rSpriteAnimation = ( (Uni2DSprite) target ).spriteAnimation; foreach( Object rObject in DragAndDrop.objectReferences ) { if( rObject is GameObject ) { Uni2DAnimationClip rAnimationClip = ( (GameObject) rObject ).GetComponent<Uni2DAnimationClip>( ); if( rAnimationClip != null ) { rSpriteAnimation.AddClip( rAnimationClip ); EditorUtility.SetDirty( target ); } } } } else if( rCurrentEventType == EventType.DragUpdated ) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; } } else { DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; } } } } /* private void ApplyAnimationClipGlobalAtlas( Uni2DTextureAtlas a_rGlobalAtlas ) { if( targets.Length == 1 ) { Uni2DSpriteAnimation rSpriteAnimation = ( (Uni2DSprite) target ).spriteAnimation; Uni2DAnimationClip[ ] rAnimationClips = rSpriteAnimation.Clips; for( int iClipIndex = 0, iClipCount = rSpriteAnimation.ClipCount; iClipIndex < iClipCount; ++iClipIndex ) { Uni2DAnimationClip rAnimationClip = rAnimationClips[ iClipIndex ]; rAnimationClip.globalAtlas = a_rGlobalAtlas; for( int iFrameIndex = 0, iFrameCount = rAnimationClip.FrameCount; iFrameIndex < iFrameCount; ++iFrameIndex ) { rAnimationClip.frames[ iFrameIndex ].atlas = a_rGlobalAtlas; } EditorUtility.SetDirty( rAnimationClip ); } } } */ private void SetSpriteAnimationStartClip( int a_iStartClipIndex ) { for( int iTargetIndex = 0, iTargetCount = targets.Length; iTargetIndex < iTargetCount; ++iTargetIndex ) { Uni2DSpriteAnimation rSpriteAnimation = ( (Uni2DSprite) targets[ iTargetIndex ] ).spriteAnimation; rSpriteAnimation.StartClipIndex = a_iStartClipIndex; EditorUtility.SetDirty( targets[ iTargetIndex ] ); } } ////////// Serialized controls ////////// // Templated object field control for serialized object //public void SerializedObjectField<T>( SerializedSetting<T> a_rSerializedSetting, string a_rLabel = "", bool a_bAllowSceneObject = false ) where T : Object public void SerializedTexture2DField( SerializedSetting<string> a_rSerializedTextureGUID, string a_rLabel = "", bool a_bAllowSceneObject = false ) { Texture2D rObject; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedTextureGUID.HasMultipleDifferentValues; rObject = Uni2DEditorUtils.GetAssetFromUnityGUID<Texture2D>( a_rSerializedTextureGUID.Value ); rObject = (Texture2D) EditorGUILayout.ObjectField( a_rLabel, rObject, typeof( Texture2D ), a_bAllowSceneObject ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedTextureGUID.Value = Uni2DEditorUtils.GetUnityAssetGUID( rObject ); } EditorGUI.showMixedValue = bSavedShowMixedValue; } // Templated object field control for serialized object //public void SerializedObjectField<T>( SerializedSetting<T> a_rSerializedSetting, string a_rLabel = "", bool a_bAllowSceneObject = false ) where T : Object public void SerializedMaterialField(SerializedSetting<Material> a_rSerializedMaterial, string a_rLabel = "") { Material rObject; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedMaterial.HasMultipleDifferentValues; rObject = (Material) EditorGUILayout.ObjectField( a_rLabel, a_rSerializedMaterial.Value, typeof( Material ), false ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedMaterial.Value = rObject; } EditorGUI.showMixedValue = bSavedShowMixedValue; } // Slider control for serialized object public void SerializedSlider( SerializedSetting<float> a_rSerializedSetting, float a_fMinValue, float a_fMaxValue, string a_rLabel = "" ) { float fNewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; fNewValue = EditorGUILayout.Slider( a_rLabel, a_rSerializedSetting.Value, a_fMinValue, a_fMaxValue ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = fNewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; } // Slider control for serialized object public void SerializedSlider( SerializedSetting<int> a_rSerializedSetting, int a_iMinValue, int a_iMaxValue, string a_rLabel = "" ) { int iNewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; iNewValue = EditorGUILayout.IntSlider( a_rLabel, a_rSerializedSetting.Value, a_iMinValue, a_iMaxValue ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = iNewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; } // Toggle control for serialized object public void SerializedToggle( SerializedSetting<bool> a_rSerializedSetting, string a_rLabel = "" ) { bool bNewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; bNewValue = EditorGUILayout.Toggle( a_rLabel, a_rSerializedSetting.Value ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = bNewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; } // Float field control for serialized object public float SerializedFloatField( SerializedSetting<float> a_rSerializedSetting, string a_rLabel = "" ) { float fNewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; fNewValue = EditorGUILayout.FloatField( a_rLabel, a_rSerializedSetting.Value ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = fNewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; return fNewValue; } // Int field control for serialized object public int SerializedIntField( SerializedSetting<int> a_rSerializedSetting, string a_rLabel = "" ) { int iNewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; iNewValue = EditorGUILayout.IntField( a_rLabel, a_rSerializedSetting.Value ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = iNewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; return iNewValue; } // Color field control for serialized object public Color SerializedColorField( SerializedSetting<Color> a_rSerializedSetting, string a_rLabel = "" ) { Color f4NewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; f4NewValue = EditorGUILayout.ColorField( a_rLabel, a_rSerializedSetting.Value ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = f4NewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; return f4NewValue; } // Vector2 field control for serialized object public Vector2 SerializedVector2Field( SerializedSetting<Vector2> a_rSerializedSetting, string a_rLabel = "" ) { Vector2 f2NewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; f2NewValue = EditorGUILayout.Vector2Field( a_rLabel, a_rSerializedSetting.Value ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = f2NewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; return f2NewValue; } // Vector3 field control for serialized object public Vector3 SerializedVector3Field( SerializedSetting<Vector3> a_rSerializedSetting, string a_rLabel = "" ) { Vector3 f3NewValue; bool bSavedShowMixedValue = EditorGUI.showMixedValue; EditorGUI.BeginChangeCheck( ); { EditorGUI.showMixedValue = a_rSerializedSetting.HasMultipleDifferentValues; f3NewValue = EditorGUILayout.Vector3Field( a_rLabel, a_rSerializedSetting.Value ); } if( EditorGUI.EndChangeCheck( ) ) { a_rSerializedSetting.Value = f3NewValue; } EditorGUI.showMixedValue = bSavedShowMixedValue; return f3NewValue; } private float ClampScale(float a_fScale) { return Mathf.Clamp(Mathf.Abs(a_fScale), Uni2DEditorSpriteSettings.ScaleMin, float.MaxValue) * Mathf.Sign(a_fScale); } private Vector2 ClampScale(Vector2 a_f2Scale) { a_f2Scale.x = ClampScale(a_f2Scale.x); a_f2Scale.y = ClampScale(a_f2Scale.y); return a_f2Scale; } } #endif
// ---------------------------------------------------------------------------- // <copyright file="PhotonView.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using UnityEngine; using System.Reflection; using System.Collections.Generic; using ExitGames.Client.Photon; #if UNITY_EDITOR using UnityEditor; #endif public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange } public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All } public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All } /// <summary> /// Options to define how Ownership Transfer is handled per PhotonView. /// </summary> /// <remarks> /// This setting affects how RequestOwnership and TransferOwnership work at runtime. /// </remarks> public enum OwnershipOption { /// <summary> /// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client. /// </summary> Fixed, /// <summary> /// Ownership can be taken away from the current owner who can't object. /// </summary> Takeover, /// <summary> /// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership. /// </summary> /// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks> Request } /// <summary> /// PUN's NetworkView replacement class for networking. Use it like a NetworkView. /// </summary> /// \ingroup publicApi [AddComponentMenu("Photon Networking/Photon View &v")] public class PhotonView : Photon.MonoBehaviour { #if UNITY_EDITOR [ContextMenu("Open PUN Wizard")] void OpenPunWizard() { EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking"); } #endif public int ownerId; public int group = 0; protected internal bool mixedModeIsReliable = false; // NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though! // NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore) public int prefix { get { if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null) { this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix; } return this.prefixBackup; } set { this.prefixBackup = value; } } // this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene public int prefixBackup = -1; /// <summary> /// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab) /// </summary> public object[] instantiationData { get { if (!this.didAwake) { // even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId); } return this.instantiationDataField; } set { this.instantiationDataField = value; } } internal object[] instantiationDataField; /// <summary> /// For internal use only, don't use /// </summary> protected internal object[] lastOnSerializeDataSent = null; /// <summary> /// For internal use only, don't use /// </summary> protected internal object[] lastOnSerializeDataReceived = null; public Component observed; public ViewSynchronization synchronization; public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation; public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All; /// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary> /// <remarks> /// Note that you can't edit this value at runtime. /// The options are described in enum OwnershipOption. /// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// </remarks> public OwnershipOption ownershipTransfer = OwnershipOption.Fixed; public List<Component> ObservedComponents; Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>(); #if UNITY_EDITOR // Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor #pragma warning disable 0414 [SerializeField] bool ObservedComponentsFoldoutOpen = true; #pragma warning restore 0414 #endif [SerializeField] private int viewIdField = 0; /// <summary> /// The ID of the PhotonView. Identifies it in a networked game (per room). /// </summary> /// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks> public int viewID { get { return this.viewIdField; } set { // if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup bool viewMustRegister = this.didAwake && this.viewIdField == 0; // TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea // check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object) // PhotonNetwork.networkingPeer.RemovePhotonView(this, true); this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS; this.viewIdField = value; if (viewMustRegister) { PhotonNetwork.networkingPeer.RegisterPhotonView(this); } //Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId); } } public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID) /// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary> /// <remarks> /// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their /// creator leaves the game and the current Master Client can control them (whoever that is). /// The ownerId is 0 (player IDs are 1 and up). /// </remarks> public bool isSceneView { get { return this.CreatorActorNr == 0; } } /// <summary> /// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// /// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request /// ownership by calling the PhotonView's RequestOwnership method. /// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// </remarks> public PhotonPlayer owner { get { return PhotonPlayer.Find(this.ownerId); } } public int OwnerActorNr { get { return this.ownerId; } } public bool isOwnerActive { get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); } } public int CreatorActorNr { get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; } } /// <summary> /// True if the PhotonView is "mine" and can be controlled by this client. /// </summary> /// <remarks> /// PUN has an ownership concept that defines who can control and destroy each PhotonView. /// True in case the owner matches the local PhotonPlayer. /// True if this is a scene photonview on the Master client. /// </remarks> public bool isMine { get { return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient); } } protected internal bool didAwake; [SerializeField] protected internal bool isRuntimeInstantiated; protected internal bool destroyedByPhotonNetworkOrQuit; internal MonoBehaviour[] RpcMonoBehaviours; private MethodInfo OnSerializeMethodInfo; private bool failedToFindOnSerialize; /// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary> protected internal void Awake() { if (this.viewID != 0) { // registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case PhotonNetwork.networkingPeer.RegisterPhotonView(this); this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId); } this.didAwake = true; } /// <summary> /// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView. /// </summary> /// <remarks> /// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that. /// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void RequestOwnership() { PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId); } /// <summary> /// Transfers the ownership of this PhotonView (and GameObject) to another player. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void TransferOwnership(PhotonPlayer newOwner) { this.TransferOwnership(newOwner.ID); } /// <summary> /// Transfers the ownership of this PhotonView (and GameObject) to another player. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void TransferOwnership(int newOwnerId) { PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId); this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client. } protected internal void OnApplicationQuit() { destroyedByPhotonNetworkOrQuit = true; // on stop-playing its ok Destroy is being called directly (not by PN.Destroy()) } protected internal void OnDestroy() { if (!this.destroyedByPhotonNetworkOrQuit) { PhotonNetwork.networkingPeer.LocalCleanPhotonView(this); } if (!this.destroyedByPhotonNetworkOrQuit && !Application.isLoadingLevel) { if (this.instantiationId > 0) { // if this viewID was not manually assigned (and we're not shutting down or loading a level), you should use PhotonNetwork.Destroy() to get rid of GOs with PhotonViews Debug.LogError("OnDestroy() seems to be called without PhotonNetwork.Destroy()?! GameObject: " + this.gameObject + " Application.isLoadingLevel: " + Application.isLoadingLevel); } else { // this seems to be a manually instantiated PV. if it's local, we could warn if the ID is not in the allocated-list if (this.viewID <= 0) { Debug.LogWarning(string.Format("OnDestroy manually allocated PhotonView {0}. The viewID is 0. Was it ever (manually) set?", this)); } else if (this.isMine && !PhotonNetwork.manuallyAllocatedViewIds.Contains(this.viewID)) { Debug.LogWarning(string.Format("OnDestroy manually allocated PhotonView {0}. The viewID is local (isMine) but not in manuallyAllocatedViewIds list. Use UnAllocateViewID() after you destroyed the PV.", this)); } } } } public void SerializeView(PhotonStream stream, PhotonMessageInfo info) { SerializeComponent(this.observed, stream, info); if (this.ObservedComponents != null && this.ObservedComponents.Count > 0) { for (int i = 0; i < this.ObservedComponents.Count; ++i) { SerializeComponent(this.ObservedComponents[i], stream, info); } } } public void DeserializeView(PhotonStream stream, PhotonMessageInfo info) { DeserializeComponent(this.observed, stream, info); if (this.ObservedComponents != null && this.ObservedComponents.Count > 0) { for (int i = 0; i < this.ObservedComponents.Count; ++i) { DeserializeComponent(this.ObservedComponents[i], stream, info); } } } protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info) { if (component == null) { return; } // Use incoming data according to observed type if (component is MonoBehaviour) { ExecuteComponentOnSerialize(component, stream, info); } else if (component is Transform) { Transform trans = (Transform) component; switch (this.onSerializeTransformOption) { case OnSerializeTransform.All: trans.localPosition = (Vector3) stream.ReceiveNext(); trans.localRotation = (Quaternion) stream.ReceiveNext(); trans.localScale = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyPosition: trans.localPosition = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyRotation: trans.localRotation = (Quaternion) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyScale: trans.localScale = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.PositionAndRotation: trans.localPosition = (Vector3) stream.ReceiveNext(); trans.localRotation = (Quaternion) stream.ReceiveNext(); break; } } else if (component is Rigidbody) { Rigidbody rigidB = (Rigidbody) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: rigidB.velocity = (Vector3) stream.ReceiveNext(); rigidB.angularVelocity = (Vector3) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyAngularVelocity: rigidB.angularVelocity = (Vector3) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyVelocity: rigidB.velocity = (Vector3) stream.ReceiveNext(); break; } } else if (component is Rigidbody2D) { Rigidbody2D rigidB = (Rigidbody2D) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: rigidB.velocity = (Vector2) stream.ReceiveNext(); rigidB.angularVelocity = (float) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyAngularVelocity: rigidB.angularVelocity = (float) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyVelocity: rigidB.velocity = (Vector2) stream.ReceiveNext(); break; } } else { Debug.LogError("Type of observed is unknown when receiving."); } } protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info) { if (component == null) { return; } if (component is MonoBehaviour) { ExecuteComponentOnSerialize(component, stream, info); } else if (component is Transform) { Transform trans = (Transform) component; switch (this.onSerializeTransformOption) { case OnSerializeTransform.All: stream.SendNext(trans.localPosition); stream.SendNext(trans.localRotation); stream.SendNext(trans.localScale); break; case OnSerializeTransform.OnlyPosition: stream.SendNext(trans.localPosition); break; case OnSerializeTransform.OnlyRotation: stream.SendNext(trans.localRotation); break; case OnSerializeTransform.OnlyScale: stream.SendNext(trans.localScale); break; case OnSerializeTransform.PositionAndRotation: stream.SendNext(trans.localPosition); stream.SendNext(trans.localRotation); break; } } else if (component is Rigidbody) { Rigidbody rigidB = (Rigidbody) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: stream.SendNext(rigidB.velocity); stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyAngularVelocity: stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyVelocity: stream.SendNext(rigidB.velocity); break; } } else if (component is Rigidbody2D) { Rigidbody2D rigidB = (Rigidbody2D) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: stream.SendNext(rigidB.velocity); stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyAngularVelocity: stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyVelocity: stream.SendNext(rigidB.velocity); break; } } else { Debug.LogError("Observed type is not serializable: " + component.GetType()); } } protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info) { if (component != null) { if (this.m_OnSerializeMethodInfos.ContainsKey(component) == false) { MethodInfo newMethod = null; bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out newMethod); if (foundMethod == false) { Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!"); newMethod = null; } this.m_OnSerializeMethodInfos.Add(component, newMethod); } if (this.m_OnSerializeMethodInfos[component] != null) { this.m_OnSerializeMethodInfos[component].Invoke(component, new object[] {stream, info}); } } } /// <summary> /// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true. /// </summary> /// <remarks> /// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching. /// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially). /// /// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect, /// because the list is refreshed when a RPC gets called. /// </remarks> public void RefreshRpcMonoBehaviourCache() { this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>(); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// RPC calls can target "All" or the "Others". /// Usually, the target "All" gets executed locally immediately after sending the RPC. /// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> /// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param> /// <param name="target">The group of targets and the way the RPC gets sent.</param> /// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RPC(string methodName, PhotonTargets target, params object[] parameters) { PhotonNetwork.RPC(this, methodName, target, false, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// RPC calls can target "All" or the "Others". /// Usually, the target "All" gets executed locally immediately after sending the RPC. /// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> ///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param> ///<param name="target">The group of targets and the way the RPC gets sent.</param> ///<param name="encrypt"> </param> ///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters) { PhotonNetwork.RPC(this, methodName, target, encrypt, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// This method allows you to make an RPC calls on a specific player's client. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> /// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param> /// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param> /// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters) { PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// This method allows you to make an RPC calls on a specific player's client. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> ///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param> ///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param> ///<param name="encrypt"> </param> ///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters) { PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters); } public static PhotonView Get(Component component) { return component.GetComponent<PhotonView>(); } public static PhotonView Get(GameObject gameObj) { return gameObj.GetComponent<PhotonView>(); } public static PhotonView Find(int viewID) { return PhotonNetwork.networkingPeer.GetPhotonView(viewID); } public override string ToString() { return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using Microsoft.Win32.SafeHandles; using SafeSslHandle = System.Net.SafeSslHandle; internal static partial class Interop { internal static partial class AppleCrypto { private static readonly IdnMapping s_idnMapping = new IdnMapping(); // Read data from connection (or an instance delegate captured context) and write it to data // dataLength comes in as the capacity of data, goes out as bytes written. // Note: the true type of dataLength is `size_t*`, but on macOS that's most equal to `void**` internal unsafe delegate int SSLReadFunc(void* connection, byte* data, void** dataLength); // (In the C decl for this function data is "const byte*", justifying the second type). // Read *dataLength from data and write it to connection (or an instance delegate captured context), // and set *dataLength to the number of bytes actually transferred. internal unsafe delegate int SSLWriteFunc(void* connection, byte* data, void** dataLength); private static readonly SafeCreateHandle s_cfHttp2Str = CoreFoundation.CFStringCreateWithCString("h2"); private static readonly SafeCreateHandle s_cfHttp11Str = CoreFoundation.CFStringCreateWithCString("http/1.1"); private static readonly IntPtr[] s_cfAlpnHttp2Protocol = new IntPtr[] { s_cfHttp2Str.DangerousGetHandle() }; private static readonly IntPtr[] s_cfAlpnHttp11Protocol = new IntPtr[] { s_cfHttp11Str.DangerousGetHandle() }; private static readonly IntPtr[] s_cfAlpnHttp211Protocol = new IntPtr[] { s_cfHttp2Str.DangerousGetHandle(), s_cfHttp11Str.DangerousGetHandle() }; private static readonly SafeCreateHandle s_cfAlpnHttp11Protocols = CoreFoundation.CFArrayCreate(s_cfAlpnHttp11Protocol, (UIntPtr)1); private static readonly SafeCreateHandle s_cfAlpnHttp2Protocols = CoreFoundation.CFArrayCreate(s_cfAlpnHttp2Protocol, (UIntPtr)1); private static readonly SafeCreateHandle s_cfAlpnHttp211Protocols = CoreFoundation.CFArrayCreate(s_cfAlpnHttp211Protocol , (UIntPtr)2); internal enum PAL_TlsHandshakeState { Unknown, Complete, WouldBlock, ServerAuthCompleted, ClientAuthCompleted, } internal enum PAL_TlsIo { Unknown, Success, WouldBlock, ClosedGracefully, Renegotiate, } // These come from the various SSL/TLS RFCs. internal enum TlsCipherSuite { TLS_NULL_WITH_NULL_NULL = 0x0000, SSL_NULL_WITH_NULL_NULL = 0x0000, TLS_RSA_WITH_NULL_MD5 = 0x0001, SSL_RSA_WITH_NULL_MD5 = 0x0001, TLS_RSA_WITH_NULL_SHA = 0x0002, SSL_RSA_WITH_NULL_SHA = 0x0002, SSL_RSA_EXPORT_WITH_RC4_40_MD5 = 0x0003, TLS_RSA_WITH_RC4_128_MD5 = 0x0004, SSL_RSA_WITH_RC4_128_MD5 = 0x0004, TLS_RSA_WITH_RC4_128_SHA = 0x0005, SSL_RSA_WITH_RC4_128_SHA = 0x0005, SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = 0x0006, //Windows has no value for IDEA, so .NET Framework didn't get one. //SSL_RSA_WITH_IDEA_CBC_SHA = 0x0007, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0008, SSL_RSA_WITH_DES_CBC_SHA = 0x0009, TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A, SSL_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A, SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x000B, SSL_DH_DSS_WITH_DES_CBC_SHA = 0x000C, TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0x000D, SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA = 0x000D, SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x000E, SSL_DH_RSA_WITH_DES_CBC_SHA = 0x000F, TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0x0010, SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA = 0x0010, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = 0x0011, SSL_DHE_DSS_WITH_DES_CBC_SHA = 0x0012, TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x0013, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x0013, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = 0x0014, SSL_DHE_RSA_WITH_DES_CBC_SHA = 0x0015, TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016, SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x0017, TLS_DH_anon_WITH_RC4_128_MD5 = 0x0018, SSL_DH_anon_WITH_RC4_128_MD5 = 0x0018, SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA = 0x0019, SSL_DH_anon_WITH_DES_CBC_SHA = 0x001A, TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B, SSL_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B, // Windows doesn't support FORTEZZA_DMS, so unclear what value to use. //SSL_FORTEZZA_DMS_WITH_NULL_SHA = 0x001C, // Windows doesn't support FORTEZZA_DMS, so unclear what value to use. //SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA = 0x001D, TLS_PSK_WITH_NULL_SHA = 0x002C, TLS_DHE_PSK_WITH_NULL_SHA = 0x002D, TLS_RSA_PSK_WITH_NULL_SHA = 0x002E, TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F, TLS_DH_DSS_WITH_AES_128_CBC_SHA = 0x0030, TLS_DH_RSA_WITH_AES_128_CBC_SHA = 0x0031, TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032, TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033, TLS_DH_anon_WITH_AES_128_CBC_SHA = 0x0034, TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035, TLS_DH_DSS_WITH_AES_256_CBC_SHA = 0x0036, TLS_DH_RSA_WITH_AES_256_CBC_SHA = 0x0037, TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038, TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039, TLS_DH_anon_WITH_AES_256_CBC_SHA = 0x003A, TLS_RSA_WITH_NULL_SHA256 = 0x003B, TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C, TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D, TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = 0x003E, TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = 0x003F, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x0040, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067, TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = 0x0068, TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = 0x0069, TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x006A, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B, TLS_DH_anon_WITH_AES_128_CBC_SHA256 = 0x006C, TLS_DH_anon_WITH_AES_256_CBC_SHA256 = 0x006D, TLS_PSK_WITH_RC4_128_SHA = 0x008A, TLS_PSK_WITH_3DES_EDE_CBC_SHA = 0x008B, TLS_PSK_WITH_AES_128_CBC_SHA = 0x008C, TLS_PSK_WITH_AES_256_CBC_SHA = 0x008D, TLS_DHE_PSK_WITH_RC4_128_SHA = 0x008E, TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA = 0x008F, TLS_DHE_PSK_WITH_AES_128_CBC_SHA = 0x0090, TLS_DHE_PSK_WITH_AES_256_CBC_SHA = 0x0091, TLS_RSA_PSK_WITH_RC4_128_SHA = 0x0092, TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA = 0x0093, TLS_RSA_PSK_WITH_AES_128_CBC_SHA = 0x0094, TLS_RSA_PSK_WITH_AES_256_CBC_SHA = 0x0095, TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C, TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F, TLS_DH_RSA_WITH_AES_128_GCM_SHA256 = 0x00A0, TLS_DH_RSA_WITH_AES_256_GCM_SHA384 = 0x00A1, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = 0x00A2, TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = 0x00A3, TLS_DH_DSS_WITH_AES_128_GCM_SHA256 = 0x00A4, TLS_DH_DSS_WITH_AES_256_GCM_SHA384 = 0x00A5, TLS_DH_anon_WITH_AES_128_GCM_SHA256 = 0x00A6, TLS_DH_anon_WITH_AES_256_GCM_SHA384 = 0x00A7, TLS_PSK_WITH_AES_128_GCM_SHA256 = 0x00A8, TLS_PSK_WITH_AES_256_GCM_SHA384 = 0x00A9, TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 = 0x00AA, TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 = 0x00AB, TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 = 0x00AC, TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 = 0x00AD, TLS_PSK_WITH_AES_128_CBC_SHA256 = 0x00AE, TLS_PSK_WITH_AES_256_CBC_SHA384 = 0x00AF, TLS_PSK_WITH_NULL_SHA256 = 0x00B0, TLS_PSK_WITH_NULL_SHA384 = 0x00B1, TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = 0x00B2, TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = 0x00B3, TLS_DHE_PSK_WITH_NULL_SHA256 = 0x00B4, TLS_DHE_PSK_WITH_NULL_SHA384 = 0x00B5, TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 = 0x00B6, TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 = 0x00B7, TLS_RSA_PSK_WITH_NULL_SHA256 = 0x00B8, TLS_RSA_PSK_WITH_NULL_SHA384 = 0x00B9, // Not a real CipherSuite //TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF, TLS_ECDH_ECDSA_WITH_NULL_SHA = 0xC001, TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0xC002, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC003, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0xC004, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0xC005, TLS_ECDHE_ECDSA_WITH_NULL_SHA = 0xC006, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0xC007, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC008, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A, TLS_ECDH_RSA_WITH_NULL_SHA = 0xC00B, TLS_ECDH_RSA_WITH_RC4_128_SHA = 0xC00C, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0xC00D, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014, TLS_ECDH_anon_WITH_NULL_SHA = 0xC015, TLS_ECDH_anon_WITH_RC4_128_SHA = 0xC016, TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA = 0xC017, TLS_ECDH_anon_WITH_AES_128_CBC_SHA = 0xC018, TLS_ECDH_anon_WITH_AES_256_CBC_SHA = 0xC019, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC025, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC026, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = 0xC029, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = 0xC02A, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02D, TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02E, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = 0xC031, TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = 0xC032, } [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslCreateContext")] internal static extern System.Net.SafeSslHandle SslCreateContext(int isServer); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetMinProtocolVersion( SafeSslHandle sslHandle, SslProtocols minProtocolId); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetMaxProtocolVersion( SafeSslHandle sslHandle, SslProtocols maxProtocolId); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslCopyCertChain( SafeSslHandle sslHandle, out SafeX509ChainHandle pTrustOut, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslCopyCADistinguishedNames( SafeSslHandle sslHandle, out SafeCFArrayHandle pArrayOut, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetBreakOnServerAuth( SafeSslHandle sslHandle, int setBreak, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetBreakOnClientAuth( SafeSslHandle sslHandle, int setBreak, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetCertificate( SafeSslHandle sslHandle, SafeCreateHandle cfCertRefs); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetTargetName( SafeSslHandle sslHandle, string targetName, int cbTargetName, out int osStatus); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SSLSetALPNProtocols")] internal static extern int SSLSetALPNProtocols(SafeSslHandle ctx, SafeCreateHandle cfProtocolsRefs, out int osStatus); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslGetAlpnSelected")] internal static extern int SslGetAlpnSelected(SafeSslHandle ssl, out SafeCFDataHandle protocol); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslHandshake")] internal static extern PAL_TlsHandshakeState SslHandshake(SafeSslHandle sslHandle); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetAcceptClientCert(SafeSslHandle sslHandle); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslSetIoCallbacks")] internal static extern int SslSetIoCallbacks( SafeSslHandle sslHandle, SSLReadFunc readCallback, SSLWriteFunc writeCallback); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslWrite")] internal static extern unsafe PAL_TlsIo SslWrite(SafeSslHandle sslHandle, byte* writeFrom, int count, out int bytesWritten); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslRead")] internal static extern unsafe PAL_TlsIo SslRead(SafeSslHandle sslHandle, byte* writeFrom, int count, out int bytesWritten); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslIsHostnameMatch( SafeSslHandle handle, SafeCreateHandle cfHostname, SafeCFDateHandle cfValidTime); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslShutdown")] internal static extern int SslShutdown(SafeSslHandle sslHandle); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslGetCipherSuite")] internal static extern int SslGetCipherSuite(SafeSslHandle sslHandle, out TlsCipherSuite cipherSuite); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslGetProtocolVersion")] internal static extern int SslGetProtocolVersion(SafeSslHandle sslHandle, out SslProtocols protocol); internal static void SslSetAcceptClientCert(SafeSslHandle sslHandle) { int osStatus = AppleCryptoNative_SslSetAcceptClientCert(sslHandle); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } internal static void SslSetMinProtocolVersion(SafeSslHandle sslHandle, SslProtocols minProtocolId) { int osStatus = AppleCryptoNative_SslSetMinProtocolVersion(sslHandle, minProtocolId); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } internal static void SslSetMaxProtocolVersion(SafeSslHandle sslHandle, SslProtocols maxProtocolId) { int osStatus = AppleCryptoNative_SslSetMaxProtocolVersion(sslHandle, maxProtocolId); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } internal static SafeX509ChainHandle SslCopyCertChain(SafeSslHandle sslHandle) { SafeX509ChainHandle chainHandle; int osStatus; int result = AppleCryptoNative_SslCopyCertChain(sslHandle, out chainHandle, out osStatus); if (result == 1) { return chainHandle; } chainHandle.Dispose(); if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslCopyCertChain returned {result}"); throw new SslException(); } internal static SafeCFArrayHandle SslCopyCADistinguishedNames(SafeSslHandle sslHandle) { SafeCFArrayHandle dnArray; int osStatus; int result = AppleCryptoNative_SslCopyCADistinguishedNames(sslHandle, out dnArray, out osStatus); if (result == 1) { return dnArray; } dnArray.Dispose(); if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslCopyCADistinguishedNames returned {result}"); throw new SslException(); } internal static void SslBreakOnServerAuth(SafeSslHandle sslHandle, bool setBreak) { int osStatus; int result = AppleCryptoNative_SslSetBreakOnServerAuth(sslHandle, setBreak ? 1 : 0, out osStatus); if (result == 1) { return; } if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslSetBreakOnServerAuth returned {result}"); throw new SslException(); } internal static void SslBreakOnClientAuth(SafeSslHandle sslHandle, bool setBreak) { int osStatus; int result = AppleCryptoNative_SslSetBreakOnClientAuth(sslHandle, setBreak ? 1 : 0, out osStatus); if (result == 1) { return; } if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslSetBreakOnClientAuth returned {result}"); throw new SslException(); } internal static void SslSetCertificate(SafeSslHandle sslHandle, IntPtr[] certChainPtrs) { using (SafeCreateHandle cfCertRefs = CoreFoundation.CFArrayCreate(certChainPtrs, (UIntPtr)certChainPtrs.Length)) { int osStatus = AppleCryptoNative_SslSetCertificate(sslHandle, cfCertRefs); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } } internal static void SslSetTargetName(SafeSslHandle sslHandle, string targetName) { Debug.Assert(!string.IsNullOrEmpty(targetName)); int osStatus; int cbTargetName = System.Text.Encoding.UTF8.GetByteCount(targetName); int result = AppleCryptoNative_SslSetTargetName(sslHandle, targetName, cbTargetName, out osStatus); if (result == 1) { return; } if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslSetTargetName returned {result}"); throw new SslException(); } internal static unsafe void SslCtxSetAlpnProtos(SafeSslHandle ctx, List<SslApplicationProtocol> protocols) { SafeCreateHandle cfProtocolsRefs = null; SafeCreateHandle[] cfProtocolsArrayRef = null; try { if (protocols.Count == 1 && protocols[0] == SslApplicationProtocol.Http2) { cfProtocolsRefs = s_cfAlpnHttp211Protocols; } else if (protocols.Count == 1 && protocols[0] == SslApplicationProtocol.Http11) { cfProtocolsRefs = s_cfAlpnHttp11Protocols; } else if (protocols.Count == 2 && protocols[0] == SslApplicationProtocol.Http2 && protocols[1] == SslApplicationProtocol.Http11) { cfProtocolsRefs = s_cfAlpnHttp211Protocols; } else { // we did not match common case. This is more expensive path allocating Core Foundation objects. cfProtocolsArrayRef = new SafeCreateHandle[protocols.Count]; IntPtr[] protocolsPtr = new System.IntPtr[protocols.Count]; for (int i = 0; i < protocols.Count; i++) { cfProtocolsArrayRef[i] = CoreFoundation.CFStringCreateWithCString(protocols[i].ToString()); protocolsPtr[i] = cfProtocolsArrayRef[i].DangerousGetHandle(); } cfProtocolsRefs = CoreFoundation.CFArrayCreate(protocolsPtr, (UIntPtr)protocols.Count); } int osStatus; int result = SSLSetALPNProtocols(ctx, cfProtocolsRefs, out osStatus); if (result != 1) { throw CreateExceptionForOSStatus(osStatus); } } finally { if (cfProtocolsArrayRef != null) { for (int i = 0; i < cfProtocolsArrayRef.Length ; i++) { cfProtocolsArrayRef[i]?.Dispose(); } cfProtocolsRefs?.Dispose(); } } } internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl) { SafeCFDataHandle protocol; if (SslGetAlpnSelected(ssl, out protocol) != 1 || protocol == null) { return null; } try { byte[] result = Interop.CoreFoundation.CFGetData(protocol); return result; } finally { protocol.Dispose(); } } public static bool SslCheckHostnameMatch(SafeSslHandle handle, string hostName, DateTime notBefore) { int result; // The IdnMapping converts Unicode input into the IDNA punycode sequence. // It also does host case normalization. The bypass logic would be something // like "all characters being within [a-z0-9.-]+" // // The SSL Policy (SecPolicyCreateSSL) has been verified as not inherently supporting // IDNA as of macOS 10.12.1 (Sierra). If it supports low-level IDNA at a later date, // this code could be removed. // // It was verified as supporting case invariant match as of 10.12.1 (Sierra). string matchName = s_idnMapping.GetAscii(hostName); using (SafeCFDateHandle cfNotBefore = CoreFoundation.CFDateCreate(notBefore)) using (SafeCreateHandle cfHostname = CoreFoundation.CFStringCreateWithCString(matchName)) { result = AppleCryptoNative_SslIsHostnameMatch(handle, cfHostname, cfNotBefore); } switch (result) { case 0: return false; case 1: return true; default: Debug.Fail($"AppleCryptoNative_SslIsHostnameMatch returned {result}"); throw new SslException(); } } } } namespace System.Net { internal sealed class SafeSslHandle : SafeHandle { internal SafeSslHandle() : base(IntPtr.Zero, ownsHandle: true) { } internal SafeSslHandle(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle) { } protected override bool ReleaseHandle() { Interop.CoreFoundation.CFRelease(handle); SetHandle(IntPtr.Zero); return true; } public override bool IsInvalid => handle == IntPtr.Zero; } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; public class FlurryAgent : IDisposable { private static FlurryAgent _instance; public static FlurryAgent Instance { get { if(_instance == null) _instance = new FlurryAgent(); return _instance; } } #if UNITY_IPHONE [DllImport("__Internal")] private static extern void mStartSession(string apiKey); [DllImport("__Internal")] private static extern void mLogEvent(string eventId); [DllImport("__Internal")] private static extern void mStopSession(); public void onStartSession(string apiKey){ mStartSession(apiKey); } public void onEndSession(){ mStopSession(); } public void logEvent(string eventId){ mLogEvent(eventId); } public void setContinueSessionMillis(long milliseconds){} public void onError(string errorId, string message, string errorClass){} public void onPageView(){} public void setLogEnabled(bool enabled){} public void setUserID(string userId){} public void setAge(int age){} public void setReportLocation(bool reportLocation){} public void logEvent(string eventId, Dictionary<string, string> parameters){} public void Dispose(){} #elif UNITY_ANDROID private AndroidJavaClass cls_FlurryAgent = new AndroidJavaClass("com.flurry.android.FlurryAgent"); public void onStartSession(string apiKey) { Debug.Log ("****** onStartSession " +apiKey); using(AndroidJavaClass cls_UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { using(AndroidJavaObject obj_Activity = cls_UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) { cls_FlurryAgent.CallStatic("onStartSession", obj_Activity, apiKey); } } } public void onEndSession() { Debug.Log ("****** onEndSession "); using(AndroidJavaClass cls_UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { using(AndroidJavaObject obj_Activity = cls_UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) { cls_FlurryAgent.CallStatic("onEndSession", obj_Activity); } } } public void logEvent(string eventId) { Debug.Log ("****** log Event "+eventId); cls_FlurryAgent.CallStatic("logEvent", eventId); } public void setContinueSessionMillis(long milliseconds) { cls_FlurryAgent.CallStatic("setContinueSessionMillis", milliseconds); } public void onError(string errorId, string message, string errorClass) { cls_FlurryAgent.CallStatic("onError", errorId, message, errorClass); } public void onPageView() { cls_FlurryAgent.CallStatic("onPageView"); } public void setLogEnabled(bool enabled) { cls_FlurryAgent.CallStatic("setLogEnabled", enabled); } public void setUserID(string userId) { cls_FlurryAgent.CallStatic("setUserID", userId); } public void setAge(int age) { cls_FlurryAgent.CallStatic("setAge", age); } /* // Not working, and I don't need it, so I'm not going to worry about it private static AndroidJavaClass cls_FlurryAgentConstants = new AndroidJavaClass("com.flurry.android.FlurryAgent.Constants"); public enum Gender { Male, Female } public void setGender(Gender gender) { byte javaGender = (gender == Gender.Male ? cls_FlurryAgentConstants.Get<byte>("MALE") : cls_FlurryAgentConstants.Get<byte>("FEMALE")); cls_FlurryAgent.CallStatic("setGender", javaGender); } */ public void setReportLocation(bool reportLocation) { cls_FlurryAgent.CallStatic("setReportLocation", reportLocation); } public void logEvent(string eventId, Dictionary<string, string> parameters) { using(AndroidJavaObject obj_HashMap = new AndroidJavaObject("java.util.HashMap")) { // Call 'put' via the JNI instead of using helper classes to avoid: // "JNI: Init'd AndroidJavaObject with null ptr!" IntPtr method_Put = AndroidJNIHelper.GetMethodID(obj_HashMap.GetRawClass(), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); object[] args = new object[2]; foreach(KeyValuePair<string, string> kvp in parameters) { using(AndroidJavaObject k = new AndroidJavaObject("java.lang.String", kvp.Key)) { using(AndroidJavaObject v = new AndroidJavaObject("java.lang.String", kvp.Value)) { args[0] = k; args[1] = v; AndroidJNI.CallObjectMethod(obj_HashMap.GetRawObject(), method_Put, AndroidJNIHelper.CreateJNIArgArray(args)); } } } cls_FlurryAgent.CallStatic("logEvent", eventId, obj_HashMap); } } public void Dispose() { cls_FlurryAgent.Dispose(); } #else public void onStartSession(string apiKey){} public void onEndSession(){} public void logEvent(string eventId){} public void setContinueSessionMillis(long milliseconds){} public void onError(string errorId, string message, string errorClass){} public void onPageView(){} public void setLogEnabled(bool enabled){} public void setUserID(string userId){} public void setAge(int age){} public void setReportLocation(bool reportLocation){} public void logEvent(string eventId, Dictionary<string, string> parameters){} public void Dispose(){} #endif };
using System; #if __UNIFIED__ using CoreAnimation; using CoreGraphics; using Foundation; using ObjCRuntime; using UIKit; #else using MonoTouch.CoreAnimation; using MonoTouch.CoreGraphics; using MonoTouch.Foundation; using MonoTouch.ObjCRuntime; using MonoTouch.UIKit; using CGRect = global::System.Drawing.RectangleF; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; using nfloat = global::System.Single; using nint = global::System.Int32; using nuint = global::System.UInt32; #endif namespace Carousels { // @interface iCarousel : UIView [BaseType (typeof(UIView), Delegates = new [] { "Delegate" }, Events = new [] { typeof(iCarouselDelegate) })] interface iCarousel { [Export ("initWithFrame:")] IntPtr Constructor (CGRect frame); // @property (nonatomic, unsafe_unretained) id<iCarouselDataSource> dataSource; [Export ("dataSource", ArgumentSemantic.UnsafeUnretained)] iCarouselDataSource DataSource { get; set; } // @property (nonatomic, unsafe_unretained) id<iCarouselDelegate> delegate; [NullAllowed] [Export ("delegate", ArgumentSemantic.UnsafeUnretained)] iCarouselDelegate Delegate { get; set; } // @property (assign, nonatomic) iCarouselType type; [Export ("type", ArgumentSemantic.Assign)] iCarouselType Type { get; set; } // @property (assign, nonatomic) CGFloat perspective; [Export ("perspective", ArgumentSemantic.Assign)] nfloat Perspective { get; set; } // @property (assign, nonatomic) CGFloat decelerationRate; [Export ("decelerationRate", ArgumentSemantic.Assign)] nfloat DecelerationRate { get; set; } // @property (assign, nonatomic) CGFloat scrollSpeed; [Export ("scrollSpeed", ArgumentSemantic.Assign)] nfloat ScrollSpeed { get; set; } // @property (assign, nonatomic) CGFloat bounceDistance; [Export ("bounceDistance", ArgumentSemantic.Assign)] nfloat BounceDistance { get; set; } // @property (assign, nonatomic, getter = isScrollEnabled) BOOL scrollEnabled; [Export ("scrollEnabled", ArgumentSemantic.Assign)] bool ScrollEnabled { [Bind ("isScrollEnabled")] get; set; } // @property (assign, nonatomic, getter = isPagingEnabled) BOOL pagingEnabled; [Export ("pagingEnabled", ArgumentSemantic.Assign)] bool PagingEnabled { [Bind ("isPagingEnabled")] get; set; } // @property (assign, nonatomic, getter = isVertical) BOOL vertical; [Export ("vertical", ArgumentSemantic.Assign)] bool Vertical { [Bind ("isVertical")] get; set; } // @property (readonly, nonatomic, getter = isWrapEnabled) BOOL wrapEnabled; [Export ("wrapEnabled")] bool WrapEnabled { [Bind ("isWrapEnabled")] get; } // @property (assign, nonatomic) BOOL bounces; [Export ("bounces", ArgumentSemantic.Assign)] bool Bounces { get; set; } // @property (assign, nonatomic) CGFloat scrollOffset; [Export ("scrollOffset", ArgumentSemantic.Assign)] nfloat ScrollOffset { get; set; } // @property (readonly, nonatomic) CGFloat offsetMultiplier; [Export ("offsetMultiplier")] nfloat OffsetMultiplier { get; } // @property (assign, nonatomic) CGSize contentOffset; [Export ("contentOffset", ArgumentSemantic.Assign)] CGSize ContentOffset { get; set; } // @property (assign, nonatomic) CGSize viewpointOffset; [Export ("viewpointOffset", ArgumentSemantic.Assign)] CGSize ViewpointOffset { get; set; } // @property (readonly, nonatomic) NSInteger numberOfItems; [Export ("numberOfItems")] nint NumberOfItems { get; } // @property (readonly, nonatomic) NSInteger numberOfPlaceholders; [Export ("numberOfPlaceholders")] nint NumberOfPlaceholders { get; } // @property (assign, nonatomic) NSInteger currentItemIndex; [Export ("currentItemIndex", ArgumentSemantic.Assign)] nint CurrentItemIndex { get; set; } // @property (readonly, nonatomic, strong) UIView * currentItemView; [Export ("currentItemView", ArgumentSemantic.Retain)] UIView CurrentItemView { get; } // @property (readonly, nonatomic, strong) NSArray * indexesForVisibleItems; [Export ("indexesForVisibleItems", ArgumentSemantic.Retain)] NSObject [] IndexesForVisibleItems { get; } // @property (readonly, nonatomic) NSInteger numberOfVisibleItems; [Export ("numberOfVisibleItems")] nint NumberOfVisibleItems { get; } // @property (readonly, nonatomic, strong) NSArray * visibleItemViews; [Export ("visibleItemViews", ArgumentSemantic.Retain)] NSObject [] VisibleItemViews { get; } // @property (readonly, nonatomic) CGFloat itemWidth; [Export ("itemWidth")] nfloat ItemWidth { get; } // @property (readonly, nonatomic, strong) UIView * contentView; [Export ("contentView", ArgumentSemantic.Retain)] UIView ContentView { get; } // @property (readonly, nonatomic) CGFloat toggle; [Export ("toggle")] nfloat Toggle { get; } // @property (assign, nonatomic) CGFloat autoscroll; [Export ("autoscroll", ArgumentSemantic.Assign)] nfloat Autoscroll { get; set; } // @property (assign, nonatomic) BOOL stopAtItemBoundary; [Export ("stopAtItemBoundary", ArgumentSemantic.Assign)] bool StopAtItemBoundary { get; set; } // @property (assign, nonatomic) BOOL scrollToItemBoundary; [Export ("scrollToItemBoundary", ArgumentSemantic.Assign)] bool ScrollToItemBoundary { get; set; } // @property (assign, nonatomic) BOOL ignorePerpendicularSwipes; [Export ("ignorePerpendicularSwipes", ArgumentSemantic.Assign)] bool IgnorePerpendicularSwipes { get; set; } // @property (assign, nonatomic) BOOL centerItemWhenSelected; [Export ("centerItemWhenSelected", ArgumentSemantic.Assign)] bool CenterItemWhenSelected { get; set; } // @property (readonly, nonatomic, getter = isDragging) BOOL dragging; [Export ("dragging")] bool Dragging { [Bind ("isDragging")] get; } // @property (readonly, nonatomic, getter = isDecelerating) BOOL decelerating; [Export ("decelerating")] bool Decelerating { [Bind ("isDecelerating")] get; } // @property (readonly, nonatomic, getter = isScrolling) BOOL scrolling; [Export ("scrolling")] bool Scrolling { [Bind ("isScrolling")] get; } // -(void)scrollByOffset:(CGFloat)offset duration:(NSTimeInterval)duration; [Export ("scrollByOffset:duration:")] void ScrollBy (nfloat offset, double duration); // -(void)scrollToOffset:(CGFloat)offset duration:(NSTimeInterval)duration; [Export ("scrollToOffset:duration:")] void ScrollTo (nfloat offset, double duration); // -(void)scrollByNumberOfItems:(NSInteger)itemCount duration:(NSTimeInterval)duration; [Export ("scrollByNumberOfItems:duration:")] void ScrollByNumberOfItems (nint itemCount, double duration); // -(void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration; [Export ("scrollToItemAtIndex:duration:")] void ScrollToItemAt (nint index, double duration); // -(void)scrollToItemAtIndex:(NSInteger)index animated:(BOOL)animated; [Export ("scrollToItemAtIndex:animated:")] void ScrollToItemAt (nint index, bool animated); // -(UIView *)itemViewAtIndex:(NSInteger)index; [Export ("itemViewAtIndex:")] UIView GetItemViewAt (nint index); // -(NSInteger)indexOfItemView:(UIView *)view; [Export ("indexOfItemView:")] nint GetIndexOfItemView (UIView view); // -(NSInteger)indexOfItemViewOrSubview:(UIView *)view; [Export ("indexOfItemViewOrSubview:")] nint GetIndexOfItemViewOrSubview (UIView view); // -(CGFloat)offsetForItemAtIndex:(NSInteger)index; [Export ("offsetForItemAtIndex:")] nfloat GetOffsetForItemAt (nint index); // -(UIView *)itemViewAtPoint:(CGPoint)point; [Export ("itemViewAtPoint:")] UIView GetItemViewAt (CGPoint point); // -(void)removeItemAtIndex:(NSInteger)index animated:(BOOL)animated; [Export ("removeItemAtIndex:animated:")] void RemoveItemAt (nint index, bool animated); // -(void)insertItemAtIndex:(NSInteger)index animated:(BOOL)animated; [Export ("insertItemAtIndex:animated:")] void InsertItemAt (nint index, bool animated); // -(void)reloadItemAtIndex:(NSInteger)index animated:(BOOL)animated; [Export ("reloadItemAtIndex:animated:")] void ReloadItemAt (nint index, bool animated); // -(void)reloadData; [Export ("reloadData")] void ReloadData (); } // @protocol iCarouselDataSource <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface iCarouselDataSource { // @required -(NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel; [Export ("numberOfItemsInCarousel:")] [Abstract] nint GetNumberOfItems (iCarousel carousel); // @required -(UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view; [Export ("carousel:viewForItemAtIndex:reusingView:")] [Abstract] UIView GetViewForItem (iCarousel carousel, nint index, [NullAllowed] UIView view); // @optional -(NSInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel; [Export ("numberOfPlaceholdersInCarousel:")] nint GetNumberOfPlaceholders (iCarousel carousel); // @optional -(UIView *)carousel:(iCarousel *)carousel placeholderViewAtIndex:(NSInteger)index reusingView:(UIView *)view; [Export ("carousel:placeholderViewAtIndex:reusingView:")] UIView GetPlaceholderView (iCarousel carousel, nint index, [NullAllowed] UIView view); } // @protocol iCarouselDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface iCarouselDelegate { // @optional -(void)carouselWillBeginScrollingAnimation:(iCarousel *)carousel; [Export ("carouselWillBeginScrollingAnimation:")] [EventName("ScrollAnimationBegin")] void OnScrollAnimationBegin (iCarousel carousel); // @optional -(void)carouselDidEndScrollingAnimation:(iCarousel *)carousel; [Export ("carouselDidEndScrollingAnimation:")] [EventName("ScrollAnimationEnd")] void OnScrollAnimationEnd (iCarousel carousel); // @optional -(void)carouselDidScroll:(iCarousel *)carousel; [Export ("carouselDidScroll:")] [EventName("ScrollEnd")] void OnScrollEnd (iCarousel carousel); // @optional -(void)carouselCurrentItemIndexDidChange:(iCarousel *)carousel; [Export ("carouselCurrentItemIndexDidChange:")] [EventName("CurrentItemIndexChanged")] void OnCurrentItemIndexChanged (iCarousel carousel); // @optional -(void)carouselWillBeginDragging:(iCarousel *)carousel; [Export ("carouselWillBeginDragging:")] [EventName("DragStart")] void OnDragStart (iCarousel carousel); // @optional -(void)carouselDidEndDragging:(iCarousel *)carousel willDecelerate:(BOOL)decelerate; [Export ("carouselDidEndDragging:willDecelerate:")] [EventArgs ("iCarouselDragEnd")] [EventName("DragEnd")] void OnDragEnd (iCarousel carousel, bool decelerate); // @optional -(void)carouselWillBeginDecelerating:(iCarousel *)carousel; [Export ("carouselWillBeginDecelerating:")] [EventName("DecelerationBegin")] void OnDecelerationBegin (iCarousel carousel); // @optional -(void)carouselDidEndDecelerating:(iCarousel *)carousel; [Export ("carouselDidEndDecelerating:")] [EventName("DecelerationEnd")] void OnDecelerationEnd (iCarousel carousel); // @optional -(BOOL)carousel:(iCarousel *)carousel shouldSelectItemAtIndex:(NSInteger)index; [Export ("carousel:shouldSelectItemAtIndex:")] [DelegateName ("iCarouselSelectItemCondition"), DefaultValue ("true")] bool ShouldSelectItem (iCarousel carousel, nint index); // @optional -(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index; [Export ("carousel:didSelectItemAtIndex:")] [EventArgs ("iCarouselItemSelected")] [EventName("ItemSelected")] void OnItemSelected (iCarousel carousel, nint index); // @optional -(CGFloat)carouselItemWidth:(iCarousel *)carousel; [Export ("carouselItemWidth:")] [DelegateName ("iCarouselItemWidthCondition"), DefaultValue ("0")] nfloat GetItemWidth (iCarousel carousel); // @optional -(CATransform3D)carousel:(iCarousel *)carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform; [Export ("carousel:itemTransformForOffset:baseTransform:")] [DelegateName ("iCarouselItemTransformCondition"), DefaultValue ("transform")] CATransform3D GetItemTransform (iCarousel carousel, nfloat offset, CATransform3D transform); // @optional -(CGFloat)carousel:(iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value; [Export ("carousel:valueForOption:withDefault:")] [DelegateName ("iCarouselValueCondition"), DefaultValue ("value")] nfloat GetValue (iCarousel carousel, iCarouselOption option, nfloat value); } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data.Linq; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using JetBrains.Annotations; namespace LinqToDB.Extensions { public static class ReflectionExtensions { #region Type extensions public static bool IsGenericTypeEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsGenericType; #else return type.IsGenericType; #endif } public static bool IsValueTypeEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsValueType; #else return type.IsValueType; #endif } public static bool IsAbstractEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsAbstract; #else return type.IsAbstract; #endif } public static bool IsPublicEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsPublic; #else return type.IsPublic; #endif } public static bool IsClassEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsClass; #else return type.IsClass; #endif } public static bool IsEnumEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsEnum; #else return type.IsEnum; #endif } public static bool IsPrimitiveEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsPrimitive; #else return type.IsPrimitive; #endif } public static bool IsInterfaceEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsInterface; #else return type.IsInterface; #endif } public static Type BaseTypeEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().BaseType; #else return type.BaseType; #endif } public static Type[] GetInterfacesEx(this Type type) { return type.GetInterfaces(); } public static object[] GetCustomAttributesEx(this Type type, Type attributeType, bool inherit) { #if NETSTANDARD1_6 return type.GetTypeInfo().GetCustomAttributes(attributeType, inherit).Cast<object>().ToArray(); #else return type.GetCustomAttributes(attributeType, inherit); #endif } public static MemberInfo[] GetPublicInstanceMembersEx(this Type type) { return type.GetMembers(BindingFlags.Instance | BindingFlags.Public); } public static MemberInfo[] GetStaticMembersEx(this Type type, string name) { return type.GetMember(name, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); } /// <summary> /// Returns <see cref="MemberInfo"/> of <paramref name="type"/> described by <paramref name="memberInfo"/> /// It us useful when member's declared and reflected types are not the same /// </summary> /// <remarks>This method searches only properties, fields and methods</remarks> /// <param name="type"><see cref="Type"/> to find member info</param> /// <param name="memberInfo"><see cref="MemberInfo"/> </param> /// <returns><see cref="MemberInfo"/> or null</returns> public static MemberInfo GetMemberEx(this Type type, MemberInfo memberInfo) { if (memberInfo.IsPropertyEx()) return type.GetPropertyEx(memberInfo.Name); if (memberInfo.IsFieldEx()) return type.GetFieldEx (memberInfo.Name); if (memberInfo.IsMethodEx()) return type.GetMethodEx (memberInfo.Name, ((MethodInfo) memberInfo).GetParameters().Select(_ => _.ParameterType).ToArray()); return null; } public static MethodInfo GetMethodEx(this Type type, string name, params Type[] types) { #if NETSTANDARD1_6 // https://github.com/dotnet/corefx/issues/12921 return type.GetMethodsEx().FirstOrDefault(mi => { var res = mi.IsPublic && mi.Name == name; if (!res) return res; var pars = mi.GetParameters().Select(_ => _.ParameterType).ToArray(); if (types.Length == 0 && pars.Length == 0) return true; if (pars.Length != types.Length) return false; for (var i = 0; i < types.Length; i++) { if (types[i] != pars[i]) return false; } return true; }); #else return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, types, null); #endif } public static MethodInfo GetMethodEx(this Type type, string name) { return type.GetMethod(name); } public static ConstructorInfo GetDefaultConstructorEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(p => p.GetParameters().Length == 0); #else return type.GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Type.EmptyTypes, null); #endif } public static TypeCode GetTypeCodeEx(this Type type) { #if NETSTANDARD1_6 if (type == typeof(DBNull)) return (TypeCode)2; #endif return Type.GetTypeCode(type); } public static bool IsAssignableFromEx(this Type type, Type c) { return type.IsAssignableFrom(c); } public static FieldInfo[] GetFieldsEx(this Type type) { return type.GetFields(); } public static Type[] GetGenericArgumentsEx(this Type type) { return type.GetGenericArguments(); } public static MethodInfo GetGetMethodEx(this PropertyInfo propertyInfo, bool nonPublic) { return propertyInfo.GetGetMethod(nonPublic); } public static MethodInfo GetGetMethodEx(this PropertyInfo propertyInfo) { return propertyInfo.GetGetMethod(); } public static MethodInfo GetSetMethodEx(this PropertyInfo propertyInfo, bool nonPublic) { return propertyInfo.GetSetMethod(nonPublic); } public static MethodInfo GetSetMethodEx(this PropertyInfo propertyInfo) { return propertyInfo.GetSetMethod(); } public static object[] GetCustomAttributesEx(this Type type, bool inherit) { #if NETSTANDARD1_6 return type.GetTypeInfo().GetCustomAttributes(inherit).Cast<object>().ToArray(); #else return type.GetCustomAttributes(inherit); #endif } public static InterfaceMapping GetInterfaceMapEx(this Type type, Type interfaceType) { #if NETSTANDARD1_6 return type.GetTypeInfo().GetRuntimeInterfaceMap(interfaceType); #else return type.GetInterfaceMap(interfaceType); #endif } public static bool IsPropertyEx(this MemberInfo memberInfo) { return memberInfo.MemberType == MemberTypes.Property; } public static bool IsFieldEx(this MemberInfo memberInfo) { return memberInfo.MemberType == MemberTypes.Field; } public static bool IsMethodEx(this MemberInfo memberInfo) { return memberInfo.MemberType == MemberTypes.Method; } public static object[] GetCustomAttributesEx(this MemberInfo memberInfo, Type attributeType, bool inherit) { #if NETSTANDARD1_6 return memberInfo.GetCustomAttributes(attributeType, inherit).Cast<object>().ToArray(); #else return memberInfo.GetCustomAttributes(attributeType, inherit); #endif } public static bool IsSubclassOfEx(this Type type, Type c) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsSubclassOf(c); #else return type.IsSubclassOf(c); #endif } public static bool IsGenericTypeDefinitionEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().IsGenericTypeDefinition; #else return type.IsGenericTypeDefinition; #endif } public static PropertyInfo[] GetPropertiesEx(this Type type) { return type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); } public static PropertyInfo[] GetPropertiesEx(this Type type, BindingFlags flags) { return type.GetProperties(flags); } public static PropertyInfo[] GetNonPublicPropertiesEx(this Type type) { return type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance); } public static MethodInfo[] GetMethodsEx(this Type type) { return type.GetMethods(); } public static Assembly AssemblyEx(this Type type) { #if NETSTANDARD1_6 return type.GetTypeInfo().Assembly; #else return type.Assembly; #endif } public static ConstructorInfo[] GetConstructorsEx(this Type type) { return type.GetConstructors(); } public static ConstructorInfo GetConstructorEx(this Type type, Type[] parameterTypes) { return type.GetConstructor(parameterTypes); } public static PropertyInfo GetPropertyEx(this Type type, string propertyName) { return type.GetProperty(propertyName); } public static FieldInfo GetFieldEx(this Type type, string propertyName) { return type.GetField(propertyName); } public static Type ReflectedTypeEx(this MemberInfo memberInfo) { #if NETSTANDARD1_6 return memberInfo.DeclaringType; #else return memberInfo.ReflectedType; #endif } public static MemberInfo[] GetInstanceMemberEx(this Type type, string name) { return type.GetMember(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); } public static MemberInfo[] GetPublicMemberEx(this Type type, string name) { return type.GetMember(name); } public static object[] GetCustomAttributesEx(this MemberInfo memberInfo, bool inherit) { #if NETSTANDARD1_6 return memberInfo.GetCustomAttributes(inherit).Cast<object>().ToArray(); #else return memberInfo.GetCustomAttributes(inherit); #endif } public static object[] GetCustomAttributesEx(this ParameterInfo parameterInfo, bool inherit) { #if NETSTANDARD1_6 return parameterInfo.GetCustomAttributes(inherit).Cast<object>().ToArray(); #else return parameterInfo.GetCustomAttributes(inherit); #endif } static class CacheHelper<T> { public static readonly ConcurrentDictionary<Type,T[]> TypeAttributes = new ConcurrentDictionary<Type,T[]>(); } #region Attributes cache static readonly ConcurrentDictionary<Type, object[]> _typeAttributesTopInternal = new ConcurrentDictionary<Type, object[]>(); static void GetAttributesInternal(List<object> list, Type type) { object[] attrs; if (_typeAttributesTopInternal.TryGetValue(type, out attrs)) { list.AddRange(attrs); } else { GetAttributesTreeInternal(list, type); _typeAttributesTopInternal[type] = list.ToArray(); } } static readonly ConcurrentDictionary<Type, object[]> _typeAttributesInternal = new ConcurrentDictionary<Type, object[]>(); static void GetAttributesTreeInternal(List<object> list, Type type) { var attrs = _typeAttributesInternal.GetOrAdd(type, x => type.GetCustomAttributesEx(false)); list.AddRange(attrs); if (type.IsInterfaceEx()) return; // Reflection returns interfaces for the whole inheritance chain. // So, we are going to get some hemorrhoid here to restore the inheritance sequence. // var interfaces = type.GetInterfacesEx(); var nBaseInterfaces = type.BaseTypeEx() != null? type.BaseTypeEx().GetInterfacesEx().Length: 0; for (var i = 0; i < interfaces.Length; i++) { var intf = interfaces[i]; if (i < nBaseInterfaces) { var getAttr = false; foreach (var mi in type.GetInterfaceMapEx(intf).TargetMethods) { // Check if the interface is reimplemented. // if (mi.DeclaringType == type) { getAttr = true; break; } } if (getAttr == false) continue; } GetAttributesTreeInternal(list, intf); } if (type.BaseTypeEx() != null && type.BaseTypeEx() != typeof(object)) GetAttributesTreeInternal(list, type.BaseTypeEx()); } #endregion /// <summary> /// Returns an array of custom attributes applied to a type. /// </summary> /// <param name="type">A type instance.</param> /// <typeparam name="T">The type of attribute to search for. /// Only attributes that are assignable to this type are returned.</typeparam> /// <returns>An array of custom attributes applied to this type, /// or an array with zero (0) elements if no attributes have been applied.</returns> public static T[] GetAttributes<T>([NotNull] this Type type) where T : Attribute { if (type == null) throw new ArgumentNullException("type"); T[] attrs; if (!CacheHelper<T>.TypeAttributes.TryGetValue(type, out attrs)) { var list = new List<object>(); GetAttributesInternal(list, type); CacheHelper<T>.TypeAttributes[type] = attrs = list.OfType<T>().ToArray(); } return attrs; } /// <summary> /// Retrieves a custom attribute applied to a type. /// </summary> /// <param name="type">A type instance.</param> /// <typeparam name="T">The type of attribute to search for. /// Only attributes that are assignable to this type are returned.</typeparam> /// <returns>A reference to the first custom attribute of type attributeType /// that is applied to element, or null if there is no such attribute.</returns> public static T GetFirstAttribute<T>([NotNull] this Type type) where T : Attribute { var attrs = GetAttributes<T>(type); return attrs.Length > 0 ? attrs[0] : null; } /// <summary> /// Gets a value indicating whether a type (or type's element type) /// instance can be null in the underlying data store. /// </summary> /// <param name="type">A <see cref="System.Type"/> instance. </param> /// <returns> True, if the type parameter is a closed generic nullable type; otherwise, False.</returns> /// <remarks>Arrays of Nullable types are treated as Nullable types.</remarks> public static bool IsNullable([NotNull] this Type type) { return type.IsGenericTypeEx() && type.GetGenericTypeDefinition() == typeof(Nullable<>); } /// <summary> /// Returns the underlying type argument of the specified type. /// </summary> /// <param name="type">A <see cref="System.Type"/> instance. </param> /// <returns><list> /// <item>The type argument of the type parameter, /// if the type parameter is a closed generic nullable type.</item> /// <item>The underlying Type if the type parameter is an enum type.</item> /// <item>Otherwise, the type itself.</item> /// </list> /// </returns> public static Type ToUnderlying([NotNull] this Type type) { if (type == null) throw new ArgumentNullException("type"); if (type.IsNullable()) type = type.GetGenericArgumentsEx()[0]; if (type.IsEnumEx ()) type = Enum.GetUnderlyingType(type); return type; } public static Type ToNullableUnderlying([NotNull] this Type type) { if (type == null) throw new ArgumentNullException("type"); //return type.IsNullable() ? type.GetGenericArgumentsEx()[0] : type; return Nullable.GetUnderlyingType(type) ?? type; } public static IEnumerable<Type> GetDefiningTypes(this Type child, MemberInfo member) { if (member.IsPropertyEx()) { var prop = (PropertyInfo)member; member = prop.GetGetMethodEx(); } foreach (var inf in child.GetInterfacesEx()) { var pm = child.GetInterfaceMapEx(inf); for (var i = 0; i < pm.TargetMethods.Length; i++) { var method = pm.TargetMethods[i]; if (method == member || (method.DeclaringType == member.DeclaringType && method.Name == member.Name)) yield return inf; } } yield return member.DeclaringType; } /// <summary> /// Determines whether the specified types are considered equal. /// </summary> /// <param name="parent">A <see cref="System.Type"/> instance. </param> /// <param name="child">A type possible derived from the <c>parent</c> type</param> /// <returns>True, when an object instance of the type <c>child</c> /// can be used as an object of the type <c>parent</c>; otherwise, false.</returns> /// <remarks>Note that nullable types does not have a parent-child relation to it's underlying type. /// For example, the 'int?' type (nullable int) and the 'int' type /// aren't a parent and it's child.</remarks> public static bool IsSameOrParentOf([NotNull] this Type parent, [NotNull] Type child) { if (parent == null) throw new ArgumentNullException("parent"); if (child == null) throw new ArgumentNullException("child"); if (parent == child || child.IsEnumEx() && Enum.GetUnderlyingType(child) == parent || child.IsSubclassOfEx(parent)) { return true; } if (parent.IsGenericTypeDefinitionEx()) for (var t = child; t != typeof(object) && t != null; t = t.BaseTypeEx()) if (t.IsGenericTypeEx() && t.GetGenericTypeDefinition() == parent) return true; if (parent.IsInterfaceEx()) { var interfaces = child.GetInterfacesEx(); foreach (var t in interfaces) { if (parent.IsGenericTypeDefinitionEx()) { if (t.IsGenericTypeEx() && t.GetGenericTypeDefinition() == parent) return true; } else if (t == parent) return true; } } return false; } public static Type GetGenericType([NotNull] this Type genericType, Type type) { if (genericType == null) throw new ArgumentNullException("genericType"); while (type != null && type != typeof(object)) { if (type.IsGenericTypeEx() && type.GetGenericTypeDefinition() == genericType) return type; if (genericType.IsInterfaceEx()) { foreach (var interfaceType in type.GetInterfacesEx()) { var gType = GetGenericType(genericType, interfaceType); if (gType != null) return gType; } } type = type.BaseTypeEx(); } return null; } ///<summary> /// Gets the Type of a list item. ///</summary> /// <param name="list">A <see cref="System.Object"/> instance. </param> ///<returns>The Type instance that represents the exact runtime type of a list item.</returns> public static Type GetListItemType(this IEnumerable list) { var typeOfObject = typeof(object); if (list == null) return typeOfObject; if (list is Array) return list.GetType().GetElementType(); var type = list.GetType(); if (list is IList || list is ITypedList || list is IListSource) { PropertyInfo last = null; foreach (var pi in type.GetPropertiesEx()) { if (pi.GetIndexParameters().Length > 0 && pi.PropertyType != typeOfObject) { if (pi.Name == "Item") return pi.PropertyType; last = pi; } } if (last != null) return last.PropertyType; } if (list is IList) { foreach (var o in (IList)list) if (o != null && o.GetType() != typeOfObject) return o.GetType(); } else { foreach (var o in list) if (o != null && o.GetType() != typeOfObject) return o.GetType(); } return typeOfObject; } ///<summary> /// Gets the Type of a list item. ///</summary> /// <param name="listType">A <see cref="System.Type"/> instance. </param> ///<returns>The Type instance that represents the exact runtime type of a list item.</returns> public static Type GetListItemType(this Type listType) { if (listType.IsGenericTypeEx()) { var elementTypes = listType.GetGenericArguments(typeof(IList<>)); if (elementTypes != null) return elementTypes[0]; } if (typeof(IList). IsSameOrParentOf(listType) || typeof(ITypedList). IsSameOrParentOf(listType) || typeof(IListSource).IsSameOrParentOf(listType)) { var elementType = listType.GetElementType(); if (elementType != null) return elementType; PropertyInfo last = null; foreach (var pi in listType.GetPropertiesEx()) { if (pi.GetIndexParameters().Length > 0 && pi.PropertyType != typeof(object)) { if (pi.Name == "Item") return pi.PropertyType; last = pi; } } if (last != null) return last.PropertyType; } return typeof(object); } public static Type GetItemType(this Type type) { if (type == null) return null; if (type == typeof(object)) return type.HasElementType ? type.GetElementType(): null; if (type.IsArray) return type.GetElementType(); if (type.IsGenericTypeEx()) foreach (var aType in type.GetGenericArgumentsEx()) if (typeof(IEnumerable<>).MakeGenericType(new[] { aType }).IsAssignableFromEx(type)) return aType; var interfaces = type.GetInterfacesEx(); if (interfaces != null && interfaces.Length > 0) { foreach (var iType in interfaces) { var eType = iType.GetItemType(); if (eType != null) return eType; } } return type.BaseTypeEx().GetItemType(); } /// <summary> /// Gets a value indicating whether a type can be used as a db primitive. /// </summary> /// <param name="type">A <see cref="System.Type"/> instance. </param> /// <param name="checkArrayElementType">True if needed to check element type for arrays</param> /// <returns> True, if the type parameter is a primitive type; otherwise, False.</returns> /// <remarks><see cref="System.String"/>. <see cref="Stream"/>. /// <see cref="XmlReader"/>. <see cref="XmlDocument"/>. are specially handled by the library /// and, therefore, can be treated as scalar types.</remarks> public static bool IsScalar(this Type type, bool checkArrayElementType = true) { while (checkArrayElementType && type.IsArray) type = type.GetElementType(); return type.IsValueTypeEx() || type == typeof(string) || type == typeof(Binary) || type == typeof(Stream) || type == typeof(XmlReader) || type == typeof(XmlDocument) ; } ///<summary> /// Returns an array of Type objects that represent the type arguments /// of a generic type or the type parameters of a generic type definition. ///</summary> /// <param name="type">A <see cref="System.Type"/> instance.</param> ///<param name="baseType">Non generic base type.</param> ///<returns>An array of Type objects that represent the type arguments /// of a generic type. Returns an empty array if the current type is not a generic type.</returns> public static Type[] GetGenericArguments(this Type type, Type baseType) { var baseTypeName = baseType.Name; for (var t = type; t != typeof(object) && t != null; t = t.BaseTypeEx()) { if (t.IsGenericTypeEx()) { if (baseType.IsGenericTypeDefinitionEx()) { if (t.GetGenericTypeDefinition() == baseType) return t.GetGenericArgumentsEx(); } else if (baseTypeName == null || t.Name.Split('`')[0] == baseTypeName) { return t.GetGenericArgumentsEx(); } } } foreach (var t in type.GetInterfacesEx()) { if (t.IsGenericTypeEx()) { if (baseType.IsGenericTypeDefinitionEx()) { if (t.GetGenericTypeDefinition() == baseType) return t.GetGenericArgumentsEx(); } else if (baseTypeName == null || t.Name.Split('`')[0] == baseTypeName) { return t.GetGenericArgumentsEx(); } } } return null; } public static bool IsFloatType(this Type type) { if (type.IsNullable()) type = type.GetGenericArgumentsEx()[0]; switch (type.GetTypeCodeEx()) { case TypeCode.Single : case TypeCode.Double : case TypeCode.Decimal : return true; } return false; } public static bool IsIntegerType(this Type type) { if (type.IsNullable()) type = type.GetGenericArgumentsEx()[0]; switch (type.GetTypeCodeEx()) { case TypeCode.SByte : case TypeCode.Byte : case TypeCode.Int16 : case TypeCode.UInt16 : case TypeCode.Int32 : case TypeCode.UInt32 : case TypeCode.Int64 : case TypeCode.UInt64 : return true; } return false; } interface IGetDefaultValueHelper { object GetDefaultValue(); } class GetDefaultValueHelper<T> : IGetDefaultValueHelper { public object GetDefaultValue() { return default(T); } } public static object GetDefaultValue(this Type type) { var dtype = typeof(GetDefaultValueHelper<>).MakeGenericType(type); var helper = (IGetDefaultValueHelper)Activator.CreateInstance(dtype); return helper.GetDefaultValue(); } public static EventInfo GetEventEx(this Type type, string eventName) { return type.GetEvent(eventName); } #endregion #region MethodInfo extensions public static PropertyInfo GetPropertyInfo(this MethodInfo method) { if (method != null) { var type = method.DeclaringType; foreach (var info in type.GetPropertiesEx()) { if (info.CanRead && method == info.GetGetMethodEx(true)) return info; if (info.CanWrite && method == info.GetSetMethodEx(true)) return info; } } return null; } #endregion #region MemberInfo extensions public static Type GetMemberType(this MemberInfo memberInfo) { switch (memberInfo.MemberType) { case MemberTypes.Property : return ((PropertyInfo)memberInfo).PropertyType; case MemberTypes.Field : return ((FieldInfo) memberInfo).FieldType; case MemberTypes.Method : return ((MethodInfo) memberInfo).ReturnType; case MemberTypes.Constructor : return memberInfo. DeclaringType; } throw new InvalidOperationException(); } public static bool IsNullableValueMember(this MemberInfo member) { return member.Name == "Value" && member.DeclaringType.IsGenericTypeEx() && member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>); } public static bool IsNullableHasValueMember(this MemberInfo member) { return member.Name == "HasValue" && member.DeclaringType.IsGenericTypeEx() && member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>); } static readonly Dictionary<Type,HashSet<Type>> _castDic = new Dictionary<Type,HashSet<Type>> { { typeof(decimal), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char) } }, { typeof(double), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } }, { typeof(float), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } }, { typeof(ulong), new HashSet<Type> { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } }, { typeof(long), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } }, { typeof(uint), new HashSet<Type> { typeof(byte), typeof(ushort), typeof(char) } }, { typeof(int), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } }, { typeof(ushort), new HashSet<Type> { typeof(byte), typeof(char) } }, { typeof(short), new HashSet<Type> { typeof(byte) } } }; public static bool CanConvertTo(this Type fromType, Type toType) { if (fromType == toType) return true; if (_castDic.ContainsKey(toType) && _castDic[toType].Contains(fromType)) return true; var tc = TypeDescriptor.GetConverter(fromType); if (toType.IsAssignableFrom(fromType)) return true; if (tc.CanConvertTo(toType)) return true; tc = TypeDescriptor.GetConverter(toType); if (tc.CanConvertFrom(fromType)) return true; if (fromType.GetMethodsEx() .Any(m => m.IsStatic && m.IsPublic && m.ReturnType == toType && (m.Name == "op_Implicit" || m.Name == "op_Explicit"))) return true; return false; } public static bool EqualsTo(this MemberInfo member1, MemberInfo member2, Type declaringType = null) { if (ReferenceEquals(member1, member2)) return true; if (member1 == null || member2 == null) return false; if (member1.Name == member2.Name) { if (member1.DeclaringType == member2.DeclaringType) return true; if (member1 is PropertyInfo) { var isSubclass = member1.DeclaringType.IsSameOrParentOf(member2.DeclaringType) || member2.DeclaringType.IsSameOrParentOf(member1.DeclaringType); if (isSubclass) return true; if (declaringType != null && member2.DeclaringType.IsInterfaceEx()) { var getter1 = ((PropertyInfo)member1).GetGetMethodEx(); var getter2 = ((PropertyInfo)member2).GetGetMethodEx(); var map = declaringType.GetInterfaceMapEx(member2.DeclaringType); for (var i = 0; i < map.InterfaceMethods.Length; i++) if (getter2.Name == map.InterfaceMethods[i].Name && getter2.DeclaringType == map.InterfaceMethods[i].DeclaringType && getter1.Name == map.TargetMethods [i].Name && getter1.DeclaringType == map.TargetMethods [i].DeclaringType) return true; } } } if (member2.DeclaringType.IsInterfaceEx() && !member1.DeclaringType.IsInterfaceEx() && member1.Name.EndsWith(member2.Name)) { if (member1 is PropertyInfo) { var isSubclass = member2.DeclaringType.IsAssignableFromEx(member1.DeclaringType); if (isSubclass) { var getter1 = ((PropertyInfo)member1).GetGetMethodEx(); var getter2 = ((PropertyInfo)member2).GetGetMethodEx(); var map = member1.DeclaringType.GetInterfaceMapEx(member2.DeclaringType); for (var i = 0; i < map.InterfaceMethods.Length; i++) { var imi = map.InterfaceMethods[i]; var tmi = map.TargetMethods[i]; if ((getter2 == null || (getter2.Name == imi.Name && getter2.DeclaringType == imi.DeclaringType)) && (getter1 == null || (getter1.Name == tmi.Name && getter1.DeclaringType == tmi.DeclaringType))) { return true; } } } } } return false; } #endregion } }
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 1.1. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (C) 2007-2014 GoPivotal, 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. //--------------------------------------------------------------------------- // // The MPL v1.1: // //--------------------------------------------------------------------------- // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License // at http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and // limitations under the License. // // The Original Code is RabbitMQ. // // The Initial Developer of the Original Code is GoPivotal, Inc. // Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text.RegularExpressions; using RabbitMQ.Client.Impl; namespace RabbitMQ.Client { ///<summary>Represents a TCP-addressable AMQP peer: a host name and port ///number.</summary> ///<para> /// Some of the constructors take, as a convenience, a System.Uri /// instance representing an AMQP server address. The use of Uri /// here is not standardised - Uri is simply a convenient /// container for internet-address-like components. In particular, /// the Uri "Scheme" property is ignored: only the "Host" and /// "Port" properties are extracted. ///</para> public class AmqpTcpEndpoint { ///<summary>Indicates that the default port for the protocol should be used</summary> public const int DefaultAmqpSslPort = 5671; public const int UseDefaultPort = -1; ///<summary>Retrieve IProtocol of this AmqpTcpEndpoint.</summary> public IProtocol Protocol { get { return Protocols.DefaultProtocol; } } private string m_hostName; ///<summary>Retrieve or set the hostname of this AmqpTcpEndpoint.</summary> public string HostName { get { return m_hostName; } set { m_hostName = value; } } private int m_port; ///<summary>Retrieve or set the port number of this ///AmqpTcpEndpoint. A port number of -1 causes the default ///port number.</summary> public int Port { get { if (m_port != UseDefaultPort) return m_port; if (m_ssl.Enabled) return DefaultAmqpSslPort; return Protocol.DefaultPort; } set { m_port = value; } } private SslOption m_ssl; ///<summary>Retrieve the SSL options for this AmqpTcpEndpoint. ///If not set, null is returned</summary> public SslOption Ssl { get { return m_ssl; } set { m_ssl = value; } } ///<summary>Construct an AmqpTcpEndpoint with the given ///hostname, port number and ssl option. If the port ///number is -1, the default port number will be used.</summary> public AmqpTcpEndpoint(string hostName, int portOrMinusOne, SslOption ssl) { m_hostName = hostName; m_port = portOrMinusOne; m_ssl = ssl; } ///<summary>Construct an AmqpTcpEndpoint with the given ///hostname, and port number. If the port number is ///-1, the default port number will be ///used.</summary> public AmqpTcpEndpoint(string hostName, int portOrMinusOne) : this(hostName, portOrMinusOne, new SslOption()) { } ///<summary>Construct an AmqpTcpEndpoint with the given ///hostname, using the default port.</summary> public AmqpTcpEndpoint(string hostName) : this(hostName, -1) { } ///<summary>Construct an AmqpTcpEndpoint with "localhost" as ///the hostname, and using the default port.</summary> public AmqpTcpEndpoint() : this("localhost", -1) { } ///<summary>Construct an AmqpTcpEndpoint with the given ///Uri and ssl options.</summary> ///<remarks> /// Please see the class overview documentation for /// information about the Uri format in use. ///</remarks> public AmqpTcpEndpoint(Uri uri, SslOption ssl) : this(uri.Host, uri.Port, ssl) { } ///<summary>Construct an AmqpTcpEndpoint with the given Uri.</summary> ///<remarks> /// Please see the class overview documentation for /// information about the Uri format in use. ///</remarks> public AmqpTcpEndpoint(Uri uri) : this(uri.Host, uri.Port) { } ///<summary>Returns a URI-like string of the form ///amqp-PROTOCOL://HOSTNAME:PORTNUMBER</summary> ///<remarks> /// This method is intended mainly for debugging and logging use. ///</remarks> public override string ToString() { return "amqp://" + HostName + ":" + Port; } ///<summary>Compares this instance by value (protocol, ///hostname, port) against another instance</summary> public override bool Equals(object obj) { AmqpTcpEndpoint other = obj as AmqpTcpEndpoint; if (other == null) return false; if (other.HostName != HostName) return false; if (other.Port != Port) return false; return true; } ///<summary>Implementation of hash code depending on protocol, ///hostname and port, to line up with the implementation of ///Equals()</summary> public override int GetHashCode() { return HostName.GetHashCode() ^ Port; } ///<summary>Construct an instance from a protocol and an ///address in "hostname:port" format.</summary> ///<remarks> /// If the address string passed in contains ":", it is split /// into a hostname and a port-number part. Otherwise, the /// entire string is used as the hostname, and the port-number /// is set to -1 (meaning the default number for the protocol /// variant specified). /// Hostnames provided as IPv6 must appear in square brackets ([]). ///</remarks> public static AmqpTcpEndpoint Parse(string address) { Match match = Regex.Match(address, @"^\s*\[([%:0-9A-Fa-f]+)\](:(.*))?\s*$"); if (match.Success) { GroupCollection groups = match.Groups; int portNum = -1; if (groups[2].Success) { string portStr = groups[3].Value; portNum = (portStr.Length == 0) ? -1 : int.Parse(portStr); } return new AmqpTcpEndpoint(match.Groups[1].Value, portNum); } int index = address.LastIndexOf(':'); if (index == -1) { return new AmqpTcpEndpoint(address, -1); } else { string portStr = address.Substring(index + 1).Trim(); int portNum = (portStr.Length == 0) ? -1 : int.Parse(portStr); return new AmqpTcpEndpoint(address.Substring(0, index), portNum); } } ///<summary>Splits the passed-in string on ",", and passes the ///substrings to AmqpTcpEndpoint.Parse()</summary> ///<remarks> /// Accepts a string of the form "hostname:port, /// hostname:port, ...", where the ":port" pieces are /// optional, and returns a corresponding array of /// AmqpTcpEndpoints. ///</remarks> public static AmqpTcpEndpoint[] ParseMultiple(string addresses) { string[] partsArr = addresses.Split(new char[] { ',' }); List<AmqpTcpEndpoint> results = new List<AmqpTcpEndpoint>(); foreach (string partRaw in partsArr) { string part = partRaw.Trim(); if (part.Length > 0) { results.Add(Parse(part)); } } return results.ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Cats.Models.Hubs; using Cats.Services.Hub; using Cats.Models.Hubs.ViewModels; using Cats.Models.Hubs.ViewModels.Dispatch; using Cats.Web.Hub.Controllers.Allocations; using Moq; using NUnit.Framework; namespace Cats.Web.Hub.Tests { [TestFixture] public class DispatchAllocationControllerTest { #region SetUp / TearDown private DispatchAllocationController _dispatchAllocationController; [SetUp] public void Init() { var dispatchAllocationService = new Mock<IDispatchAllocationService>(); dispatchAllocationService.Setup(t => t.GetAvailableCommodities(It.IsAny<string>())).Returns(new List <Commodity>() { new Commodity () { CommodityID = 1, CommodityCode = "Com-1" } }); var list = new List<SIBalance>() { new SIBalance() { Commodity = "CSB", SINumberID = 1, CommitedToFDP = 20, ProjectCodeID = 1, SINumber = "1", AvailableBalance = 40, CommitedToOthers = 10, Dispatchable = 30, Program = "Relief", Project = "1", ReaminingExpectedReceipts = 1, TotalDispatchable = 20 }}; dispatchAllocationService.Setup( t => t.GetUncommitedSIBalance(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>())).Returns( (int hubId, int commodityId, string unitMeasure) => list ); var userProfileService = new Mock<IUserProfileService>(); var shippingInstructionService = new Mock<IShippingInstructionService>(); var projectCodeService = new Mock<IProjectCodeService>(); var otherDispatchAllocationService = new Mock<IOtherDispatchAllocationService>(); var transporterService = new Mock<TransporterService>(); var commonService = new Mock<ICommonService>(); var adminUnitService = new Mock<IAdminUnitService>(); var fdpService = new Mock<IFDPService>(); var hubService = new Mock<IHubService>(); var commodityTypeService = new Mock<ICommodityTypeService>(); this._dispatchAllocationController = new DispatchAllocationController( dispatchAllocationService.Object, userProfileService.Object, otherDispatchAllocationService.Object, shippingInstructionService.Object, projectCodeService.Object, transporterService.Object, commonService.Object, adminUnitService.Object, fdpService.Object, hubService.Object, commodityTypeService.Object); } [TearDown] public void Dispose() { _dispatchAllocationController.Dispose(); } #endregion #region Tests [Test] public void ShouldDisplayListOfRequisitionNumbers() { //Act var result = (ViewResult)_dispatchAllocationController.Index(); //Assert Assert.IsInstanceOf<List<string>>(result.Model); } [Test] public void ShouldDisplayListOfDispatchAllocations() { //Act var result = (ViewResult)_dispatchAllocationController.AllocationList(); //Assert Assert.IsInstanceOf<IEnumerable<DispatchAllocationViewModelDto>>(result.Model); } [Test] public void ShouldReturnListOfAvailableSINumbers() { //Act var result = _dispatchAllocationController.GetAvailableSINumbers(1); //Act Assert.IsInstanceOf<JsonResult>(result); } [Test] public void ShouldReturnEmptyForUnavailableRequisitionNo() { //Act var result = _dispatchAllocationController.GetCommodities(string.Empty); //Assert Assert.IsInstanceOf<EmptyResult>(result); } [Test] public void ShouldReturnSIBalance() { //Act var result = (ViewResult)_dispatchAllocationController.SiBalances("R-001"); //Assert var x = new JsonResult(); Assert.IsInstanceOf<List<SIBalance>>(result.Model); } [Test] public void ShouldDisplayFDPAllocationForOneCommodity() { //Act var result = (ViewResult)_dispatchAllocationController.GetAllocations("R-001", 1, true); //Assert Assert.IsInstanceOf<List<DispatchAllocationViewModelDto>>(result.Model); } [Test] public void ShouldDisplayAllSIBalances() { //Act var result = (ViewResult)_dispatchAllocationController.GetSIBalances(); //Assert Assert.IsInstanceOf<List<SIBalance>>(result.Model); } [Test] public void ShouldReturnAvailableRequisitions() { //Act var result = _dispatchAllocationController.AvailableRequistions(true); //Assert Assert.IsInstanceOf<JsonResult>(result); } [Test] public void ShouldPrepareForCreateDispatchAllocation() { //Act var result = (ViewResult)_dispatchAllocationController.Create(); //Assert Assert.IsInstanceOf<DispatchAllocationViewModel>(result.Model); } [Test] public void ShouldCrateDispatchAllocation() { //Act var id = Guid.NewGuid(); var dispatchAllocation = new DispatchAllocationViewModel() { CommodityID = 1, Amount = 10, Beneficiery = 120, BidRefNo = "1", CommodityTypeID = 1, DispatchAllocationID = id, DonorID = 1, FDPID = 1, HubID = 1, Month = 1, PartitionID = 1, ProgramID = 1, ProjectCodeID = 1, RegionID = 1, RequisitionNo = "R-001", Round = 1, ShippingInstructionID = 1, TransporterID = 1, Unit = 1, WoredaID = 3, Year = 2012, ZoneID = 2 }; _dispatchAllocationController.Create(dispatchAllocation); var result = (ViewResult)_dispatchAllocationController.Index(); //Assert Assert.AreEqual(2, ((List<string>)result.Model).Count); } [Test] public void CanPrepareCreateLoan() { //Act var result = (ViewResult)_dispatchAllocationController.CreateLoan(); //Assert Assert.IsInstanceOf<OtherDispatchAllocationViewModel>(result.Model); } [Test] public void CanPrepareEditLoan() { //Act var result = (ViewResult)_dispatchAllocationController.EditLoan("L-001"); //Assert Assert.IsInstanceOf<OtherDispatchAllocationViewModel>(result.Model); } [Test] public void SouldSaveLoan() { //Arrange var id = Guid.NewGuid(); var dispatchAllocation = new OtherDispatchAllocationViewModel() { CommodityID = 1, CommodityTypeID = 1, PartitionID = 1, ProgramID = 1, AgreementDate = DateTime.Today, EstimatedDispatchDate = DateTime.Today.AddDays(3), FromHubID = 2, ToHubID = 1, IsClosed = true, OtherDispatchAllocationID = id, ProjectCode = "P-001", QuantityInMT = 12, QuantityInUnit = 12, ReasonID = 1, ReferenceNumber = "Rf-001", UnitID = 1 }; //Act var result = _dispatchAllocationController.SaveLoan(dispatchAllocation); //Assert Assert.IsInstanceOf<RedirectToRouteResult>(result); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using System.Collections; using System.Collections.Generic; using CoreXml.Test.XLinq; using Xunit; namespace System.Xml.Linq.Tests { public class DeepEqualsTests { // equals => hashcode should be the same // - all "simple" node types // - text vs. CDATA // XDocument: // - Normal mode // - Concatenated text (Whitespace) nodes // - Diffs in XDecl // XElement: // - Normal mode // - same nodes, different order // - comments inside the texts // - same nodes, same order (positive) // // - Concatenated text nodes // - string content vs. text node/s // - empty string vs. empty text node // - Multiple text nodes but the same value // - adjacent text & CData // // - IsEmpty // - Attribute order // - Namespace declarations // - local vs. in-scope // - default redef. [InlineData("PI", "click", "PI", "click", true)] // normal [InlineData("PI", "PI", "PI", "PI", true)] // target=data [InlineData("PI", "", "PI", "", true)] // data = '' [InlineData("PI", "click", "PI", "", false)] // data1!=data2 [InlineData("AAAAP", "click", "AAAAQ", "click", false)] // target1!=target2 [InlineData("AAAAP", "AAAAQ", "AAAAP", "AAAAQ", true)] // hashconflict I [InlineData("PA", "PA", "PI", "PI", false)] // data=target [InlineData("AAAAP", "AAAAQ", "AAAAQ", "AAAAP", false)] // hashconflict II [Theory] public void ProcessingInstruction(string target1, string data1, string target2, string data2, bool checkHashCode) { var p1 = new XProcessingInstruction(target1, data1); var p2 = new XProcessingInstruction(target2, data2); VerifyComparison(checkHashCode, p1, p2); XDocument doc = new XDocument(p1); XElement e2 = new XElement("p2p", p2); VerifyComparison(checkHashCode, p1, p2); } [InlineData("AAAAP", "AAAAQ", false)] // not equals, hashconflict [InlineData("AAAAP", "AAAAP", true)] // equals [InlineData(" ", " ", false)] // Whitespaces (negative) [InlineData(" ", " ", true)] // Whitespaces [InlineData("", "", true)] // Empty [Theory] public void Comment(string value1, string value2, bool checkHashCode) { XComment c1 = new XComment(value1); XComment c2 = new XComment(value2); VerifyComparison(checkHashCode, c1, c2); XDocument doc = new XDocument(c1); XElement e2 = new XElement("p2p", c2); VerifyComparison(checkHashCode, c1, c2); } [InlineData(new[] { "root", "a", "b", "c" }, new[] { "root", "a", "b", "c" }, true)] // all field [InlineData(new[] { "root", null, null, null }, new[] { "root", null, null, null }, true)] // all nulls [InlineData(new[] { "root", null, null, "data" }, new[] { "root", null, null, "data" }, true)] // internal subset only [InlineData(new[] { "A", "", "", "" }, new[] { "B", "", "", "" }, false)] // (negative) : name diff [InlineData(new[] { "A", null, null, "aa" }, new[] { "A", null, null, "bb" }, false)] // (negative) : subset diff [InlineData(new[] { "A", "", "", "" }, new[] { "A", null, null, null }, false)] // (negative) : null vs. empty [Theory] public void DocumentType(string[] docType1, string[] docType2, bool checkHashCode) { var dtd1 = new XDocumentType(docType1[0], docType1[1], docType1[2], docType1[3]); var dtd2 = new XDocumentType(docType2[0], docType2[1], docType2[2], docType2[3]); VerifyComparison(checkHashCode, dtd1, dtd2); } [InlineData("same", "different", false)] // different [InlineData("same", "same", true)] // same [InlineData("", "", true)] // Empty [InlineData(" ", " ", true)] // Whitespaces [InlineData("\n", " ", false)] // Whitespaces (negative) [Theory] public void Text(string value1, string value2, bool checkHashCode) { XText t1 = new XText(value1); XText t2 = new XText(value2); VerifyComparison(checkHashCode, t1, t2); XElement e2 = new XElement("p2p", t2); e2.Add(t1); VerifyComparison(checkHashCode, t1, t2); } [InlineData("same", "different", false)] // different [InlineData("same", "same", true)] // same [InlineData("", "", true)] // Empty [InlineData(" ", " ", true)] // Whitespaces [InlineData("\n", " ", false)] // Whitespaces (negative) [Theory] public void CData(string value1, string value2, bool checkHashCode) { XCData t1 = new XCData(value1); XCData t2 = new XCData(value2); VerifyComparison(checkHashCode, t1, t2); XElement e2 = new XElement("p2p", t2); e2.Add(t1); VerifyComparison(checkHashCode, t1, t2); } [InlineData("same", "same", false)] [InlineData("", "", false)] [InlineData(" ", " ", false)] [Theory] public void TextVsCData(string value1, string value2, bool checkHashCode) { XText t1 = new XCData(value1); XText t2 = new XText(value2); VerifyComparison(checkHashCode, t1, t2); XElement e2 = new XElement("p2p", t2); e2.Add(t1); VerifyComparison(checkHashCode, t1, t2); } // do not concatenate inside [Fact] public void TextWholeVsConcatenate() { XElement e = new XElement("A", new XText("_start_"), new XText("_end_")); XNode[] pieces = new XNode[] { new XText("_start_"), new XText("_end_") }; XText together = new XText("_start__end_"); VerifyComparison(true, e.FirstNode, pieces[0]); VerifyComparison(true, e.LastNode, pieces[1]); VerifyComparison(false, e.FirstNode, together); VerifyComparison(false, e.LastNode, together); } [InlineData("<A/>", "<A></A>", false)] // smoke [InlineData("<A/>", "<A Id='a'/>", false)] // atribute missing [InlineData("<A Id='a'/>", "<A Id='a'/>", true)] // atributes [InlineData("<A at='1' Id='a'/>", "<A Id='a' at='1'/>", false)] // atributes (same, different order) [InlineData("<A at='1' Id='a'/>", "<A at='1' Id='a'/>", true)] // atributes (same, same order) [InlineData("<A at='1' Id='a'/>", "<A at='1' Id='ab'/>", false)] // atributes (same, same order, different value) [InlineData("<A p:at='1' xmlns:p='nsp'/>", "<A p:at='1' xmlns:p='nsp'/>", true)] // atributes (same, same order, namespace decl) [InlineData("<A p:at='1' xmlns:p='nsp'/>", "<A q:at='1' xmlns:q='nsp'/>", false)] // atributes (same, same order, namespace decl, different prefix) [InlineData("<A>text</A>", "<A>text</A>", true)] // String content [InlineData("<A>text<?PI click?></A>", "<A><?PI click?>text</A>", false)] // String + PI content (negative) [InlineData("<A>text<?PI click?></A>", "<A>text<?PI click?></A>", true)] // String + PI content [Theory] public void Element(string text1, string text2, bool checkHashCode) { XElement e1 = XElement.Parse(text1); XElement e2 = XElement.Parse(text2); VerifyComparison(checkHashCode, e1, e2); // Should always be the same ... VerifyComparison(true, e1, e1); VerifyComparison(true, e2, e2); } // String content vs. text node vs. CData [Fact] public void Element2() { XElement e1 = new XElement("A", "string_content"); XElement e2 = new XElement("A", new XText("string_content")); XElement e3 = new XElement("A", new XCData("string_content")); VerifyComparison(true, e1, e2); VerifyComparison(false, e1, e3); VerifyComparison(false, e2, e3); } // XElement - text node concatenations [Fact] public void Element3() { XElement e1 = new XElement("A", "string_content"); XElement e2 = new XElement("A", new XText("string"), new XText("_content")); XElement e3 = new XElement("A", new XText("string"), new XComment("comm"), new XText("_content")); XElement e4 = new XElement("A", new XText("string"), new XCData("_content")); VerifyComparison(true, e1, e2); VerifyComparison(false, e1, e3); VerifyComparison(false, e2, e3); VerifyComparison(false, e1, e4); VerifyComparison(false, e2, e4); VerifyComparison(false, e3, e4); e3.Nodes().First(n => n is XComment).Remove(); VerifyComparison(true, e1, e3); VerifyComparison(true, e2, e3); } [InlineData(1)] // XElement - text node incarnation - by touching [InlineData(2)] // XElement - text node incarnation - by adding new node [Theory] public void Element6(int param) { XElement e1 = new XElement("A", "datata"); XElement e2 = new XElement("A", "datata"); switch (param) { case 1: XComment c = new XComment("hele"); e2.Add(c); c.Remove(); break; case 2: break; } VerifyComparison(true, e1, e2); } // XElement - text node concatenations (negative) [Fact] public void Element4() { XElement e1 = new XElement("A", new XCData("string_content")); XElement e2 = new XElement("A", new XCData("string"), new XCData("_content")); XElement e3 = new XElement("A", new XCData("string"), "_content"); VerifyComparison(false, e1, e2); VerifyComparison(false, e1, e3); VerifyComparison(false, e3, e2); } // XElement - namespace prefixes [Fact] public void Element5() { XElement e1 = XElement.Parse("<A xmlns='nsa'><B><!--comm--><C xmlns=''/></B></A>").Elements().First(); XElement e2 = XElement.Parse("<A xmlns:p='nsa'><p:B><!--comm--><C xmlns=''/></p:B></A>").Elements().First(); VerifyComparison(true, e1, e2); // Should always be the same ... VerifyComparison(true, e1, e1); VerifyComparison(true, e2, e2); } [Fact] public void ElementDynamic() { XElement helper = new XElement("helper", new XText("ko"), new XText("ho")); object[] content = new object[] { "text1", new object[] { new string[] { "t1", null, "t2" }, "t1t2" }, new XProcessingInstruction("PI1", ""), new XProcessingInstruction("PI1", ""), new XProcessingInstruction("PI2", "click"), new object[] { new XElement("X", new XAttribute("id", "a1"), new XText("hula")), new XElement("X", new XText("hula"), new XAttribute("id", "a1")) }, new XElement("{nsp}X", new XAttribute("id", "a1"), "hula"), new object[] { new XText("koho"), helper.Nodes() }, new object[] { new XText[] { new XText("hele"), new XText(""), new XCData("youuu") }, new XText[] { new XText("hele"), new XCData("youuu") } }, new XComment(""), new XComment("comment"), new XAttribute("id1", "nono"), new XAttribute("id3", "nono2"), new XAttribute("{nsa}id3", "nono2"), new XAttribute("{nsb}id3", "nono2"), new XAttribute("xmlns", "default"), new XAttribute(XNamespace.Xmlns + "a", "nsa"), new XAttribute(XNamespace.Xmlns + "p", "nsp"), new XElement("{nsa}X", new XAttribute("id", "a1"), "hula", new XAttribute("{nsb}aB", "hele"), new XElement("{nsc}C")) }; foreach (object[] objs in content.NonRecursiveVariations(4)) { XElement e1 = new XElement("E", ExpandAndProtectTextNodes(objs, 0)); XElement e2 = new XElement("E", ExpandAndProtectTextNodes(objs, 1)); VerifyComparison(true, e1, e2); e1.RemoveAll(); e2.RemoveAll(); } } private IEnumerable<object> ExpandAndProtectTextNodes(IEnumerable<object> source, int position) { foreach (object o in source) { object t = (o is object[]) ? (o as object[])[position] : o; if (t is XText && !(t is XCData)) { yield return new XText(t as XText); // clone xtext node continue; } if (t is XText[]) { yield return (t as XText[]).Select(x => new XText(x)).ToArray(); // clone XText [] continue; } yield return t; } } [Fact] public void Document1() { object[] content = new object[] { new object[] { new string[] { " ", null, " " }, " " }, new object[] { new string[] { " ", " \t" }, new XText(" \t") }, new object[] { new XText[] { new XText(" "), new XText("\t") }, new XText(" \t") }, new XDocumentType("root", "", "", ""), new XProcessingInstruction("PI1", ""), new XText("\n"), new XText("\t"), new XText(" "), new XProcessingInstruction("PI1", ""), new XElement("myroot"), new XProcessingInstruction("PI2", "click"), new object[] { new XElement("X", new XAttribute("id", "a1"), new XText("hula")), new XElement("X", new XText("hula"), new XAttribute("id", "a1")) }, new XComment(""), new XComment("comment"), }; foreach (object[] objs in content.NonRecursiveVariations(4)) { XDocument doc1 = null; XDocument doc2 = null; try { object[] o1 = ExpandAndProtectTextNodes(objs, 0).ToArray(); object[] o2 = ExpandAndProtectTextNodes(objs, 1).ToArray(); if (o1.Select(x => new ExpectedValue(false, x)).IsXDocValid() || o2.Select(x => new ExpectedValue(false, x)).IsXDocValid()) continue; doc1 = new XDocument(o1); doc2 = new XDocument(o2); VerifyComparison(true, doc1, doc2); } catch (InvalidOperationException) { // some combination produced from the array are invalid continue; } finally { if (doc1 != null) doc1.RemoveNodes(); if (doc2 != null) doc2.RemoveNodes(); } } } [InlineData(true)] [InlineData(false)] [Theory] public void Document4(bool checkHashCode) { var doc1 = new XDocument(new object[] { (checkHashCode ? new XDocumentType("root", "", "", "") : null), new XElement("root") }); var doc2 = new XDocument(new object[] { new XDocumentType("root", "", "", ""), new XElement("root") }); VerifyComparison(checkHashCode, doc1, doc2); } private void VerifyComparison(bool expected, XNode n1, XNode n2) { Assert.Equal(XNode.EqualityComparer.Equals(n1, n2), XNode.EqualityComparer.Equals(n2, n1)); // commutative Assert.Equal(((IEqualityComparer)XNode.EqualityComparer).Equals(n1, n2), ((IEqualityComparer)XNode.EqualityComparer).Equals(n2, n1)); // commutative - interface Assert.Equal(expected, XNode.EqualityComparer.Equals(n1, n2)); Assert.Equal(expected, ((IEqualityComparer)XNode.EqualityComparer).Equals(n1, n2)); if (expected) { Assert.Equal(XNode.EqualityComparer.GetHashCode(n1), XNode.EqualityComparer.GetHashCode(n2)); Assert.Equal(((IEqualityComparer)XNode.EqualityComparer).GetHashCode(n1), ((IEqualityComparer)XNode.EqualityComparer).GetHashCode(n2)); } } [Fact] public void Nulls() { XElement e = new XElement("A"); Assert.False(XNode.EqualityComparer.Equals(e, null), "left null"); Assert.False(XNode.EqualityComparer.Equals(null, e), "right null"); Assert.True(XNode.EqualityComparer.Equals(null, null), "both null"); Assert.Equal(0, XNode.EqualityComparer.GetHashCode(null)); } } }
// // SyncPrefDialogController.cs // // Author: // Rashid Khan <rashood.khan@gmail.com> // // Copyright (c) 2014 Rashid Khan // // 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 MonoMac.Foundation; using MonoMac.AppKit; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using Tomboy; using Tomboy.OAuth; using Tomboy.Sync; using Tomboy.Sync.Filesystem; using Tomboy.Sync.Web; using System.Security.Cryptography.X509Certificates; namespace Tomboy { public partial class SyncPrefDialogController : MonoMac.AppKit.NSWindowController { #region Constructors // Called when created from unmanaged code public SyncPrefDialogController(IntPtr handle) : base (handle) { Initialize(); } // Called when created directly from a XIB file [Export("initWithCoder:")] public SyncPrefDialogController(NSCoder coder) : base (coder) { Initialize(); } // Call to load from the XIB/NIB file public SyncPrefDialogController() : base ("SyncPrefDialog") { Initialize(); } // Shared initialization code void Initialize () { } #endregion partial void SetSyncPath(NSObject sender) { bool webSync = false; if (!String.IsNullOrEmpty (AppDelegate.settings.webSyncURL) || !String.IsNullOrWhiteSpace (AppDelegate.settings.webSyncURL)) { webSync = true; NSAlert syncWarning = new NSAlert() { MessageText = "Web Sync Found", InformativeText = "Setting the File System Sync Path will override the Web Sync Authorization", AlertStyle = NSAlertStyle.Informational }; syncWarning.AddButton ("OK"); syncWarning.BeginSheet (this.Window,this,null,IntPtr.Zero); } var openPanel = new NSOpenPanel(); openPanel.ReleasedWhenClosed = true; openPanel.CanChooseDirectories = true; openPanel.CanChooseFiles = false; openPanel.CanCreateDirectories = true; openPanel.Prompt = "Select Directory"; var result = openPanel.RunModal(); if (result == 1) { SyncPathTextField.Cell.Title = openPanel.DirectoryUrl.Path; //AppDelegate.FilesystemSyncPath = openPanel.DirectoryUrl.Path; AppDelegate.settings.syncURL = openPanel.DirectoryUrl.Path; NSAlert alert = new NSAlert () { MessageText = "File System Sync", InformativeText = "File System Sync path has been set at:\n"+AppDelegate.settings.syncURL, AlertStyle = NSAlertStyle.Warning }; alert.AddButton ("OK"); alert.BeginSheet (this.Window, this, null, IntPtr.Zero); if (webSync) { AppDelegate.settings.webSyncURL = String.Empty; AppDelegate.settings.token = String.Empty; AppDelegate.settings.secret = String.Empty; } try { if (AppDelegate.settings != null){ SettingsSync.Write(AppDelegate.settings); Console.WriteLine ("WRITTEN PROPERLY"); } } catch (NullReferenceException ex) { Console.WriteLine ("ERROR - "+ex.Message); } } } partial void SetExportNotesPath (NSButton sender) { var openPanel = new NSOpenPanel(); openPanel.ReleasedWhenClosed = true; openPanel.CanChooseDirectories = true; openPanel.CanChooseFiles = false; openPanel.CanCreateDirectories = false; openPanel.Prompt = "Select Existing Notes Directory"; var result = openPanel.RunModal(); if (result == 1) { ExportPathTextField.Cell.Title = openPanel.DirectoryUrl.Path; } } partial void ExportNotesAction(NSObject sender) { if (ExportPathTextField.StringValue != null){ string rootDirectory = ExportPathTextField.StringValue; ExportNotes.Export(rootDirectory, AppDelegate.NoteEngine); NSAlert alert = new NSAlert () { MessageText = "Note Imported", InformativeText = "All the notes have been imported to local storage. Please restart the Tomboy to see your old notes", AlertStyle = NSAlertStyle.Warning }; alert.AddButton ("OK"); alert.BeginSheet (this.Window, this, null, IntPtr.Zero); } } // This method will be called automatically when the main window "wakes up". [Export ("awakeFromNib:")] public override void AwakeFromNib() { // set according to AppDelegate, which later should be a preference. // FIXME: Turn into a system setting. if (AppDelegate.settings.syncURL != null) SyncPathTextField.StringValue = AppDelegate.settings.syncURL; EnableAutoSyncing.Enabled = true; //Console.WriteLine(AppDelegate.settings.autoSync.ToString()); } partial void EnableAutoSyncingAction (NSObject sender) { if (EnableAutoSyncing.Enabled) AppDelegate.settings.autoSync = true; else AppDelegate.settings.autoSync = false; SettingsSync.Write(AppDelegate.settings); //Console.WriteLine("Enabled Auto Sync - "); //Console.WriteLine(AppDelegate.settings.autoSync.ToString()); } partial void StartFileSync(NSObject sender) { Console.WriteLine ("FAKE SYNC"); } partial void Authenticate (NSObject sender) { if (!String.IsNullOrEmpty (AppDelegate.settings.syncURL) || !String.IsNullOrWhiteSpace (AppDelegate.settings.syncURL)) { NSAlert alert = new NSAlert () { MessageText = "File System Sync Found", InformativeText = "The File System Sync option would be overriden with Rainy Web Sync.", AlertStyle = NSAlertStyle.Warning }; alert.AddButton ("Override File System Sync"); alert.AddButton ("Cancel"); alert.BeginSheet (this.Window, this, new MonoMac.ObjCRuntime.Selector ("alertDidEnd:returnCode:contextInfo:"), IntPtr.Zero); AppDelegate.settings.syncURL = ""; SettingsSync.Write (AppDelegate.settings); } else { SyncPrefDialogController.AuthorizeAction (this.Window, SyncURL.StringValue); } } [Export ("alertDidEnd:returnCode:contextInfo:")] void AlertDidEnd (NSAlert alert, int returnCode, IntPtr contextInfo) { if (alert == null) throw new ArgumentNullException("alert"); if (((NSAlertButtonReturn)returnCode) == NSAlertButtonReturn.First) { AppDelegate.settings.syncURL = String.Empty; SettingsSync.Write (AppDelegate.settings); SyncPrefDialogController.AuthorizeAction (this.Window, SyncURL.StringValue); } } public static void AuthorizeAction (NSWindow window, String serverURL) { if (String.IsNullOrEmpty (serverURL) || String.IsNullOrWhiteSpace (serverURL)) { NSAlert alert = new NSAlert () { MessageText = "Incorrect URL", InformativeText = "The Sync URL cannot be empty", AlertStyle = NSAlertStyle.Warning }; alert.AddButton ("OK"); alert.BeginSheet (window, null, null, IntPtr.Zero); //SyncURL.StringValue = ""; return; } else { if (!serverURL.EndsWith ("/")) serverURL += "/"; } HttpListener listener = new HttpListener (); string callbackURL = "http://localhost:9001/"; listener.Prefixes.Add (callbackURL); listener.Start (); var callback_delegate = new OAuthAuthorizationCallback ( url => { Process.Start (url); // wait (block) until the HttpListener has received a request var context = listener.GetContext (); // if we reach here the authentication has most likely been successfull and we have the // oauth_identifier in the request url query as a query parameter var request_url = context.Request.Url; string oauth_verifier = System.Web.HttpUtility.ParseQueryString (request_url.Query).Get("oauth_verifier"); if (string.IsNullOrEmpty (oauth_verifier)) { // authentication failed or error context.Response.StatusCode = 500; context.Response.StatusDescription = "Error"; context.Response.Close(); throw new ArgumentException ("oauth_verifier"); } else { // authentication successfull context.Response.StatusCode = 200; using (var writer = new StreamWriter (context.Response.OutputStream)) { writer.WriteLine("<h1>Authorization successfull!</h1>Go back to the Tomboy application window."); } context.Response.Close(); return oauth_verifier; } }); try{ //FIXME: see http://mono-project.com/UsingTrustedRootsRespectfully for SSL warning ServicePointManager.CertificatePolicy = new DummyCertificateManager (); IOAuthToken access_token = WebSyncServer.PerformTokenExchange (serverURL, callbackURL, callback_delegate); AppDelegate.settings.webSyncURL = serverURL; AppDelegate.settings.token = access_token.Token; AppDelegate.settings.secret = access_token.Secret; SettingsSync.Write (AppDelegate.settings); Console.WriteLine ("Received token {0} with secret key {1}",access_token.Token, access_token.Secret); listener.Stop (); NSAlert success = new NSAlert () { MessageText = "Authentication Successful", InformativeText = "The authentication with the server has been successful. You can sync with the web server now.", AlertStyle = NSAlertStyle.Informational }; success.AddButton ("OK"); success.BeginSheet (window, window, null, IntPtr.Zero); return; } catch (Exception ex) { if (ex is WebException || ex is System.Runtime.Serialization.SerializationException) { NSAlert alert = new NSAlert () { MessageText = "Incorrect URL", InformativeText = "The URL entered " + serverURL + " is not valid for syncing", AlertStyle = NSAlertStyle.Warning }; alert.AddButton ("OK"); alert.BeginSheet (window, null, null, IntPtr.Zero); listener.Abort (); return; } else { NSAlert alert = new NSAlert () { MessageText = "Some Issue has occured", InformativeText = "Something does not seem right!", AlertStyle = NSAlertStyle.Warning }; alert.AddButton ("OK"); alert.BeginSheet (window, null, null, IntPtr.Zero); listener.Abort (); } } } //strongly typed window accessor public new SyncPrefDialog Window { get { return (SyncPrefDialog)base.Window; } } } public class DummyCertificateManager : ICertificatePolicy { public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error) { return true; } } }
using System; using System.Collections.Generic; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Godot.Collections { class ArraySafeHandle : SafeHandle { public ArraySafeHandle(IntPtr handle) : base(IntPtr.Zero, true) { this.handle = handle; } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { Array.godot_icall_Array_Dtor(handle); return true; } } public class Array : IList, IDisposable { ArraySafeHandle safeHandle; bool disposed = false; public Array() { safeHandle = new ArraySafeHandle(godot_icall_Array_Ctor()); } public Array(IEnumerable collection) : this() { if (collection == null) throw new NullReferenceException($"Parameter '{nameof(collection)} cannot be null.'"); foreach (object element in collection) Add(element); } internal Array(ArraySafeHandle handle) { safeHandle = handle; } internal Array(IntPtr handle) { safeHandle = new ArraySafeHandle(handle); } internal IntPtr GetPtr() { if (disposed) throw new ObjectDisposedException(GetType().FullName); return safeHandle.DangerousGetHandle(); } public Array Duplicate(bool deep = false) { return new Array(godot_icall_Array_Duplicate(GetPtr(), deep)); } public Error Resize(int newSize) { return godot_icall_Array_Resize(GetPtr(), newSize); } // IDisposable public void Dispose() { if (disposed) return; if (safeHandle != null) { safeHandle.Dispose(); safeHandle = null; } disposed = true; } // IList public bool IsReadOnly => false; public bool IsFixedSize => false; public object this[int index] { get => godot_icall_Array_At(GetPtr(), index); set => godot_icall_Array_SetAt(GetPtr(), index, value); } public int Add(object value) => godot_icall_Array_Add(GetPtr(), value); public bool Contains(object value) => godot_icall_Array_Contains(GetPtr(), value); public void Clear() => godot_icall_Array_Clear(GetPtr()); public int IndexOf(object value) => godot_icall_Array_IndexOf(GetPtr(), value); public void Insert(int index, object value) => godot_icall_Array_Insert(GetPtr(), index, value); public void Remove(object value) => godot_icall_Array_Remove(GetPtr(), value); public void RemoveAt(int index) => godot_icall_Array_RemoveAt(GetPtr(), index); // ICollection public int Count => godot_icall_Array_Count(GetPtr()); public object SyncRoot => this; public bool IsSynchronized => false; public void CopyTo(System.Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array), "Value cannot be null."); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), "Number was less than the array's lower bound in the first dimension."); // Internal call may throw ArgumentException godot_icall_Array_CopyTo(GetPtr(), array, index); } // IEnumerable public IEnumerator GetEnumerator() { int count = Count; for (int i = 0; i < count; i++) { yield return this[i]; } } public override string ToString() { return godot_icall_Array_ToString(GetPtr()); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static IntPtr godot_icall_Array_Ctor(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_Dtor(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_Array_At(IntPtr ptr, int index); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_Array_At_Generic(IntPtr ptr, int index, int elemTypeEncoding, IntPtr elemTypeClass); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_SetAt(IntPtr ptr, int index, object value); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_Array_Count(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_Array_Add(IntPtr ptr, object item); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_Clear(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static bool godot_icall_Array_Contains(IntPtr ptr, object item); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_CopyTo(IntPtr ptr, System.Array array, int arrayIndex); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static IntPtr godot_icall_Array_Duplicate(IntPtr ptr, bool deep); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_Array_IndexOf(IntPtr ptr, object item); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_Insert(IntPtr ptr, int index, object item); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static bool godot_icall_Array_Remove(IntPtr ptr, object item); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_RemoveAt(IntPtr ptr, int index); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static Error godot_icall_Array_Resize(IntPtr ptr, int newSize); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_Generic_GetElementTypeInfo(Type elemType, out int elemTypeEncoding, out IntPtr elemTypeClass); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_Array_ToString(IntPtr ptr); } public class Array<T> : IList<T>, ICollection<T>, IEnumerable<T> { Array objectArray; internal static int elemTypeEncoding; internal static IntPtr elemTypeClass; static Array() { Array.godot_icall_Array_Generic_GetElementTypeInfo(typeof(T), out elemTypeEncoding, out elemTypeClass); } public Array() { objectArray = new Array(); } public Array(IEnumerable<T> collection) { if (collection == null) throw new NullReferenceException($"Parameter '{nameof(collection)} cannot be null.'"); objectArray = new Array(collection); } public Array(Array array) { objectArray = array; } internal Array(IntPtr handle) { objectArray = new Array(handle); } internal Array(ArraySafeHandle handle) { objectArray = new Array(handle); } internal IntPtr GetPtr() { return objectArray.GetPtr(); } public static explicit operator Array(Array<T> from) { return from.objectArray; } public Array<T> Duplicate(bool deep = false) { return new Array<T>(objectArray.Duplicate(deep)); } public Error Resize(int newSize) { return objectArray.Resize(newSize); } // IList<T> public T this[int index] { get { return (T)Array.godot_icall_Array_At_Generic(GetPtr(), index, elemTypeEncoding, elemTypeClass); } set { objectArray[index] = value; } } public int IndexOf(T item) { return objectArray.IndexOf(item); } public void Insert(int index, T item) { objectArray.Insert(index, item); } public void RemoveAt(int index) { objectArray.RemoveAt(index); } // ICollection<T> public int Count { get { return objectArray.Count; } } public bool IsReadOnly { get { return objectArray.IsReadOnly; } } public void Add(T item) { objectArray.Add(item); } public void Clear() { objectArray.Clear(); } public bool Contains(T item) { return objectArray.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array), "Value cannot be null."); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex), "Number was less than the array's lower bound in the first dimension."); // TODO This may be quite slow because every element access is an internal call. // It could be moved entirely to an internal call if we find out how to do the cast there. int count = objectArray.Count; if (array.Length < (arrayIndex + count)) throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds."); for (int i = 0; i < count; i++) { array[arrayIndex] = (T)this[i]; arrayIndex++; } } public bool Remove(T item) { return Array.godot_icall_Array_Remove(GetPtr(), item); } // IEnumerable<T> public IEnumerator<T> GetEnumerator() { int count = objectArray.Count; for (int i = 0; i < count; i++) { yield return (T)this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override string ToString() => objectArray.ToString(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; // For SR using System.Security; using System.Text; using System.Globalization; namespace System.Xml { public interface IXmlTextReaderInitializer { void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); } internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderInitializer { private const int MaxTextChunk = 2048; private PrefixHandle _prefix; private StringHandle _localName; private int[] _rowOffsets; private OnXmlDictionaryReaderClose _onClose; private bool _buffered; private int _maxBytesPerRead; private static byte[] s_charType = new byte[256] { /* 0 (.) */ CharType.None, /* 1 (.) */ CharType.None, /* 2 (.) */ CharType.None, /* 3 (.) */ CharType.None, /* 4 (.) */ CharType.None, /* 5 (.) */ CharType.None, /* 6 (.) */ CharType.None, /* 7 (.) */ CharType.None, /* 8 (.) */ CharType.None, /* 9 (.) */ CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace, /* A (.) */ CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace, /* B (.) */ CharType.None, /* C (.) */ CharType.None, /* D (.) */ CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace, /* E (.) */ CharType.None, /* F (.) */ CharType.None, /* 10 (.) */ CharType.None, /* 11 (.) */ CharType.None, /* 12 (.) */ CharType.None, /* 13 (.) */ CharType.None, /* 14 (.) */ CharType.None, /* 15 (.) */ CharType.None, /* 16 (.) */ CharType.None, /* 17 (.) */ CharType.None, /* 18 (.) */ CharType.None, /* 19 (.) */ CharType.None, /* 1A (.) */ CharType.None, /* 1B (.) */ CharType.None, /* 1C (.) */ CharType.None, /* 1D (.) */ CharType.None, /* 1E (.) */ CharType.None, /* 1F (.) */ CharType.None, /* 20 ( ) */ CharType.None|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.AttributeText|CharType.SpecialWhitespace, /* 21 (!) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 22 (") */ CharType.None|CharType.Comment|CharType.Text, /* 23 (#) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 24 ($) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 25 (%) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 26 (&) */ CharType.None|CharType.Comment, /* 27 (') */ CharType.None|CharType.Comment|CharType.Text, /* 28 (() */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 29 ()) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 2A (*) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 2B (+) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 2C (,) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 2D (-) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 2E (.) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 2F (/) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 30 (0) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 31 (1) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 32 (2) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 33 (3) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 34 (4) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 35 (5) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 36 (6) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 37 (7) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 38 (8) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 39 (9) */ CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText, /* 3A (:) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 3B (;) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 3C (<) */ CharType.None|CharType.Comment, /* 3D (=) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 3E (>) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 3F (?) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 40 (@) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 41 (A) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 42 (B) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 43 (C) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 44 (D) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 45 (E) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 46 (F) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 47 (G) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 48 (H) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 49 (I) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 4A (J) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 4B (K) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 4C (L) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 4D (M) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 4E (N) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 4F (O) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 50 (P) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 51 (Q) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 52 (R) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 53 (S) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 54 (T) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 55 (U) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 56 (V) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 57 (W) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 58 (X) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 59 (Y) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 5A (Z) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 5B ([) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 5C (\) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 5D (]) */ CharType.None|CharType.Comment|CharType.AttributeText, /* 5E (^) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 5F (_) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 60 (`) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 61 (a) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 62 (b) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 63 (c) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 64 (d) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 65 (e) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 66 (f) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 67 (g) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 68 (h) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 69 (i) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 6A (j) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 6B (k) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 6C (l) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 6D (m) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 6E (n) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 6F (o) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 70 (p) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 71 (q) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 72 (r) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 73 (s) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 74 (t) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 75 (u) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 76 (v) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 77 (w) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 78 (x) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 79 (y) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 7A (z) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 7B ({) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 7C (|) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 7D (}) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 7E (~) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 7F (.) */ CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText, /* 80 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 81 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 82 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 83 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 84 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 85 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 86 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 87 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 88 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 89 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 8A (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 8B (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 8C (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 8D (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 8E (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 8F (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 90 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 91 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 92 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 93 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 94 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 95 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 96 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 97 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 98 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 99 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 9A (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 9B (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 9C (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 9D (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 9E (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* 9F (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A0 (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A1 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A2 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A3 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A4 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A5 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A6 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A7 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A8 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* A9 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* AA (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* AB (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* AC (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* AD (.) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* AE (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* AF (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B0 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B1 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B2 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B3 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B4 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B5 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B6 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B7 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B8 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* B9 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* BA (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* BB (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* BC (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* BD (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* BE (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* BF (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C0 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C1 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C2 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C3 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C4 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C5 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C6 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C7 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C8 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* C9 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* CA (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* CB (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* CC (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* CD (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* CE (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* CF (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D0 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D1 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D2 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D3 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D4 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D5 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D6 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D7 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D8 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* D9 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* DA (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* DB (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* DC (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* DD (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* DE (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* DF (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E0 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E1 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E2 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E3 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E4 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E5 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E6 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E7 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E8 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* E9 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* EA (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* EB (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* EC (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* ED (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* EE (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* EF (?) */ CharType.None|CharType.FirstName|CharType.Name, /* F0 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F1 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F2 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F3 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F4 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F5 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F6 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F7 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F8 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* F9 (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* FA (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* FB (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* FC (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* FD (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* FE (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, /* FF (?) */ CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText, }; public XmlUTF8TextReader() { _prefix = new PrefixHandle(BufferReader); _localName = new StringHandle(BufferReader); } public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { if (buffer == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative))); if (offset > buffer.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative))); if (count > buffer.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset))); MoveToInitial(quotas, onClose); ArraySegment<byte> seg = EncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding); BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null); _buffered = true; } public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); MoveToInitial(quotas, onClose); stream = new EncodingStreamWrapper(stream, encoding); BufferReader.SetBuffer(stream, null, null); _buffered = false; } private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { MoveToInitial(quotas); _maxBytesPerRead = quotas.MaxBytesPerRead; _onClose = onClose; } public override void Close() { _rowOffsets = null; base.Close(); OnXmlDictionaryReaderClose onClose = _onClose; _onClose = null; if (onClose != null) { try { onClose(this); } catch (Exception e) { if (DiagnosticUtility.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } } private void SkipWhitespace() { while (!BufferReader.EndOfFile && (s_charType[BufferReader.GetByte()] & CharType.Whitespace) != 0) BufferReader.SkipByte(); } private void ReadDeclaration() { if (!_buffered) BufferElement(); int offset; byte[] buffer = BufferReader.GetBuffer(5, out offset); if (buffer[offset + 0] != (byte)'?' || buffer[offset + 1] != (byte)'x' || buffer[offset + 2] != (byte)'m' || buffer[offset + 3] != (byte)'l' || (s_charType[buffer[offset + 4]] & CharType.Whitespace) == 0) { XmlExceptionHelper.ThrowProcessingInstructionNotSupported(this); } // If anything came before the "<?xml ?>" it's an error. if (this.Node.ReadState != ReadState.Initial) { XmlExceptionHelper.ThrowDeclarationNotFirst(this); } BufferReader.Advance(5); int localNameOffset = offset + 1; int localNameLength = 3; int valueOffset = BufferReader.Offset; SkipWhitespace(); ReadAttributes(); int valueLength = BufferReader.Offset - valueOffset; // Backoff the spaces while (valueLength > 0) { byte ch = BufferReader.GetByte(valueOffset + valueLength - 1); if ((s_charType[ch] & CharType.Whitespace) == 0) break; valueLength--; } buffer = BufferReader.GetBuffer(2, out offset); if (buffer[offset + 0] != (byte)'?' || buffer[offset + 1] != (byte)'>') { XmlExceptionHelper.ThrowTokenExpected(this, "?>", Encoding.UTF8.GetString(buffer, offset, 2)); } BufferReader.Advance(2); XmlDeclarationNode declarationNode = MoveToDeclaration(); declarationNode.LocalName.SetValue(localNameOffset, localNameLength); declarationNode.Value.SetValue(ValueHandleType.UTF8, valueOffset, valueLength); } private void VerifyNCName(string s) { try { XmlConvert.VerifyNCName(s); } catch (XmlException exception) { XmlExceptionHelper.ThrowXmlException(this, exception); } } private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName) { int offset; int offsetMax; byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax); int ch = 0; int anyChar = 0; int prefixChar = 0; int prefixOffset = offset; if (offset < offsetMax) { ch = buffer[offset]; prefixChar = ch; if ((s_charType[ch] & CharType.FirstName) == 0) anyChar |= 0x80; anyChar |= ch; offset++; while (offset < offsetMax) { ch = buffer[offset]; if ((s_charType[ch] & CharType.Name) == 0) break; anyChar |= ch; offset++; } } else { anyChar |= 0x80; ch = 0; } if (ch == ':') { int prefixLength = offset - prefixOffset; if (prefixLength == 1 && prefixChar >= 'a' && prefixChar <= 'z') prefix.SetValue(PrefixHandle.GetAlphaPrefix(prefixChar - 'a')); else prefix.SetValue(prefixOffset, prefixLength); offset++; int localNameOffset = offset; if (offset < offsetMax) { ch = buffer[offset]; if ((s_charType[ch] & CharType.FirstName) == 0) anyChar |= 0x80; anyChar |= ch; offset++; while (offset < offsetMax) { ch = buffer[offset]; if ((s_charType[ch] & CharType.Name) == 0) break; anyChar |= ch; offset++; } } else { anyChar |= 0x80; ch = 0; } localName.SetValue(localNameOffset, offset - localNameOffset); if (anyChar >= 0x80) { VerifyNCName(prefix.GetString()); VerifyNCName(localName.GetString()); } } else { prefix.SetValue(PrefixHandleType.Empty); localName.SetValue(prefixOffset, offset - prefixOffset); if (anyChar >= 0x80) { VerifyNCName(localName.GetString()); } } BufferReader.Advance(offset - prefixOffset); } private int ReadAttributeText(byte[] buffer, int offset, int offsetMax) { byte[] charType = XmlUTF8TextReader.s_charType; int textOffset = offset; while (offset < offsetMax && (charType[buffer[offset]] & CharType.AttributeText) != 0) offset++; return offset - textOffset; } private void ReadAttributes() { int startOffset = 0; if (_buffered) startOffset = BufferReader.Offset; while (true) { byte ch; ReadQualifiedName(_prefix, _localName); if (BufferReader.GetByte() != '=') { SkipWhitespace(); if (BufferReader.GetByte() != '=') XmlExceptionHelper.ThrowTokenExpected(this, "=", (char)BufferReader.GetByte()); } BufferReader.SkipByte(); byte quoteChar = BufferReader.GetByte(); if (quoteChar != '"' && quoteChar != '\'') { SkipWhitespace(); quoteChar = BufferReader.GetByte(); if (quoteChar != '"' && quoteChar != '\'') XmlExceptionHelper.ThrowTokenExpected(this, "\"", (char)BufferReader.GetByte()); } BufferReader.SkipByte(); bool escaped = false; int valueOffset = BufferReader.Offset; while (true) { int offset, offsetMax; byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax); int length = ReadAttributeText(buffer, offset, offsetMax); BufferReader.Advance(length); ch = BufferReader.GetByte(); if (ch == quoteChar) break; if (ch == '&') { ReadCharRef(); escaped = true; } else if (ch == '\'' || ch == '"') { BufferReader.SkipByte(); } else if (ch == '\n' || ch == '\r' || ch == '\t') { BufferReader.SkipByte(); escaped = true; } else if (ch == 0xEF) { ReadNonFFFE(); } else { XmlExceptionHelper.ThrowTokenExpected(this, ((char)quoteChar).ToString(), (char)ch); } } int valueLength = BufferReader.Offset - valueOffset; XmlAttributeNode attributeNode; if (_prefix.IsXmlns) { Namespace ns = AddNamespace(); _localName.ToPrefixHandle(ns.Prefix); ns.Uri.SetValue(valueOffset, valueLength, escaped); attributeNode = AddXmlnsAttribute(ns); } else if (_prefix.IsEmpty && _localName.IsXmlns) { Namespace ns = AddNamespace(); ns.Prefix.SetValue(PrefixHandleType.Empty); ns.Uri.SetValue(valueOffset, valueLength, escaped); attributeNode = AddXmlnsAttribute(ns); } else if (_prefix.IsXml) { attributeNode = AddXmlAttribute(); attributeNode.Prefix.SetValue(_prefix); attributeNode.LocalName.SetValue(_localName); attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength); FixXmlAttribute(attributeNode); } else { attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(_prefix); attributeNode.LocalName.SetValue(_localName); attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength); } attributeNode.QuoteChar = (char)quoteChar; BufferReader.SkipByte(); ch = BufferReader.GetByte(); bool space = false; while ((s_charType[ch] & CharType.Whitespace) != 0) { space = true; BufferReader.SkipByte(); ch = BufferReader.GetByte(); } if (ch == '>' || ch == '/' || ch == '?') break; if (!space) XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlSpaceBetweenAttributes))); } if (_buffered && (BufferReader.Offset - startOffset) > _maxBytesPerRead) XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(this, _maxBytesPerRead); ProcessAttributes(); } // NOTE: Call only if 0xEF has been seen in the stream AND there are three valid bytes to check (buffer[offset], buffer[offset + 1], buffer[offset + 2]). // 0xFFFE and 0xFFFF are not valid characters per Unicode specification. The first byte in the UTF8 representation is 0xEF. private bool IsNextCharacterNonFFFE(byte[] buffer, int offset) { Fx.Assert(buffer[offset] == 0xEF, "buffer[offset] MUST be 0xEF."); if (buffer[offset + 1] == 0xBF && (buffer[offset + 2] == 0xBE || buffer[offset + 2] == 0xBF)) { // 0xFFFE : 0xEF 0xBF 0xBE // 0xFFFF : 0xEF 0xBF 0xBF // we know that buffer[offset] is already 0xEF, don't bother checking it. return false; } // no bad characters return true; } private void ReadNonFFFE() { int off; byte[] buff = BufferReader.GetBuffer(3, out off); if (buff[off + 1] == 0xBF && (buff[off + 2] == 0xBE || buff[off + 2] == 0xBF)) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE))); } BufferReader.Advance(3); } private void BufferElement() { int elementOffset = BufferReader.Offset; const int byteCount = 128; bool done = false; byte quoteChar = 0; while (!done) { int offset; int offsetMax; byte[] buffer = BufferReader.GetBuffer(byteCount, out offset, out offsetMax); if (offset + byteCount != offsetMax) break; for (int i = offset; i < offsetMax && !done; i++) { byte b = buffer[i]; if (quoteChar == 0) { if (b == '\'' || b == '"') quoteChar = b; if (b == '>') done = true; } else { if (b == quoteChar) { quoteChar = 0; } } } BufferReader.Advance(byteCount); } BufferReader.Offset = elementOffset; } private new void ReadStartElement() { if (!_buffered) BufferElement(); XmlElementNode elementNode = EnterScope(); elementNode.NameOffset = BufferReader.Offset; ReadQualifiedName(elementNode.Prefix, elementNode.LocalName); elementNode.NameLength = BufferReader.Offset - elementNode.NameOffset; byte ch = BufferReader.GetByte(); while ((s_charType[ch] & CharType.Whitespace) != 0) { BufferReader.SkipByte(); ch = BufferReader.GetByte(); } if (ch != '>' && ch != '/') { ReadAttributes(); ch = BufferReader.GetByte(); } elementNode.Namespace = LookupNamespace(elementNode.Prefix); bool isEmptyElement = false; if (ch == '/') { isEmptyElement = true; BufferReader.SkipByte(); } elementNode.IsEmptyElement = isEmptyElement; elementNode.ExitScope = isEmptyElement; if (BufferReader.GetByte() != '>') XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte()); BufferReader.SkipByte(); elementNode.BufferOffset = BufferReader.Offset; } private new void ReadEndElement() { BufferReader.SkipByte(); XmlElementNode elementNode = this.ElementNode; int nameOffset = elementNode.NameOffset; int nameLength = elementNode.NameLength; int offset; byte[] buffer = BufferReader.GetBuffer(nameLength, out offset); for (int i = 0; i < nameLength; i++) { if (buffer[offset + i] != buffer[nameOffset + i]) { ReadQualifiedName(_prefix, _localName); XmlExceptionHelper.ThrowTagMismatch(this, elementNode.Prefix.GetString(), elementNode.LocalName.GetString(), _prefix.GetString(), _localName.GetString()); } } BufferReader.Advance(nameLength); if (BufferReader.GetByte() != '>') { SkipWhitespace(); if (BufferReader.GetByte() != '>') XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte()); } BufferReader.SkipByte(); MoveToEndElement(); } private void ReadComment() { BufferReader.SkipByte(); if (BufferReader.GetByte() != '-') XmlExceptionHelper.ThrowTokenExpected(this, "--", (char)BufferReader.GetByte()); BufferReader.SkipByte(); int commentOffset = BufferReader.Offset; while (true) { while (true) { byte b = BufferReader.GetByte(); if (b == '-') break; if ((s_charType[b] & CharType.Comment) == 0) { if (b == 0xEF) ReadNonFFFE(); else XmlExceptionHelper.ThrowInvalidXml(this, b); } else { BufferReader.SkipByte(); } } int offset; byte[] buffer = BufferReader.GetBuffer(3, out offset); if (buffer[offset + 0] == (byte)'-' && buffer[offset + 1] == (byte)'-') { if (buffer[offset + 2] == (byte)'>') break; XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidCommentChars))); } BufferReader.SkipByte(); } int commentLength = BufferReader.Offset - commentOffset; MoveToComment().Value.SetValue(ValueHandleType.UTF8, commentOffset, commentLength); BufferReader.Advance(3); } private void ReadCData() { int offset; byte[] buffer = BufferReader.GetBuffer(7, out offset); if (buffer[offset + 0] != (byte)'[' || buffer[offset + 1] != (byte)'C' || buffer[offset + 2] != (byte)'D' || buffer[offset + 3] != (byte)'A' || buffer[offset + 4] != (byte)'T' || buffer[offset + 5] != (byte)'A' || buffer[offset + 6] != (byte)'[') { XmlExceptionHelper.ThrowTokenExpected(this, "[CDATA[", Encoding.UTF8.GetString(buffer, offset, 7)); } BufferReader.Advance(7); int cdataOffset = BufferReader.Offset; while (true) { byte b; while (true) { b = BufferReader.GetByte(); if (b == ']') break; if (b == 0xEF) ReadNonFFFE(); else BufferReader.SkipByte(); } buffer = BufferReader.GetBuffer(3, out offset); if (buffer[offset + 0] == (byte)']' && buffer[offset + 1] == (byte)']' && buffer[offset + 2] == (byte)'>') break; BufferReader.SkipByte(); } int cdataLength = BufferReader.Offset - cdataOffset; MoveToCData().Value.SetValue(ValueHandleType.UTF8, cdataOffset, cdataLength); BufferReader.Advance(3); } private int ReadCharRef() { DiagnosticUtility.DebugAssert(BufferReader.GetByte() == '&', ""); int charEntityOffset = BufferReader.Offset; BufferReader.SkipByte(); while (BufferReader.GetByte() != ';') BufferReader.SkipByte(); BufferReader.SkipByte(); int charEntityLength = BufferReader.Offset - charEntityOffset; BufferReader.Offset = charEntityOffset; int ch = BufferReader.GetCharEntity(charEntityOffset, charEntityLength); BufferReader.Advance(charEntityLength); return ch; } private void ReadWhitespace() { byte[] buffer; int offset; int offsetMax; int length; if (_buffered) { buffer = BufferReader.GetBuffer(out offset, out offsetMax); length = ReadWhitespace(buffer, offset, offsetMax); } else { buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax); length = ReadWhitespace(buffer, offset, offsetMax); length = BreakText(buffer, offset, length); } BufferReader.Advance(length); MoveToWhitespaceText().Value.SetValue(ValueHandleType.UTF8, offset, length); } private int ReadWhitespace(byte[] buffer, int offset, int offsetMax) { byte[] charType = XmlUTF8TextReader.s_charType; int wsOffset = offset; while (offset < offsetMax && (charType[buffer[offset]] & CharType.SpecialWhitespace) != 0) offset++; return offset - wsOffset; } private int ReadText(byte[] buffer, int offset, int offsetMax) { byte[] charType = XmlUTF8TextReader.s_charType; int textOffset = offset; while (offset < offsetMax && (charType[buffer[offset]] & CharType.Text) != 0) offset++; return offset - textOffset; } // Read Unicode codepoints 0xFvvv private int ReadTextAndWatchForInvalidCharacters(byte[] buffer, int offset, int offsetMax) { byte[] charType = XmlUTF8TextReader.s_charType; int textOffset = offset; while (offset < offsetMax && ((charType[buffer[offset]] & CharType.Text) != 0 || buffer[offset] == 0xEF)) { if (buffer[offset] != 0xEF) { offset++; } else { // Ensure that we have three bytes (buffer[offset], buffer[offset + 1], buffer[offset + 2]) // available for IsNextCharacterNonFFFE to check. if (offset + 2 < offsetMax) { if (IsNextCharacterNonFFFE(buffer, offset)) { // if first byte is 0xEF, UTF8 mandates a 3-byte character representation of this Unicode code point offset += 3; } else { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE))); } } else { if (BufferReader.Offset < offset) { // We have read some characters already // Let the outer ReadText advance the bufferReader and return text node to caller break; } else { // Get enough bytes for us to process next character, then go back to top of while loop int dummy; BufferReader.GetBuffer(3, out dummy); } } } } return offset - textOffset; } // bytes bits UTF-8 representation // ----- ---- ----------------------------------- // 1 7 0vvvvvvv // 2 11 110vvvvv 10vvvvvv // 3 16 1110vvvv 10vvvvvv 10vvvvvv // 4 21 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv // ----- ---- ----------------------------------- private int BreakText(byte[] buffer, int offset, int length) { // See if we might be breaking a utf8 sequence if (length > 0 && (buffer[offset + length - 1] & 0x80) == 0x80) { // Find the lead char of the utf8 sequence (0x11xxxxxx) int originalLength = length; do { length--; } while (length > 0 && (buffer[offset + length] & 0xC0) != 0xC0); // Couldn't find the lead char if (length == 0) return originalLength; // Invalid utf8 sequence - can't break // Count how many bytes follow the lead char byte b = (byte)(buffer[offset + length] << 2); int byteCount = 2; while ((b & 0x80) == 0x80) { b = (byte)(b << 1); byteCount++; // There shouldn't be more than 3 bytes following the lead char if (byteCount > 4) return originalLength; // Invalid utf8 sequence - can't break } if (length + byteCount == originalLength) return originalLength; // sequence fits exactly } return length; } private void ReadText(bool hasLeadingByteOf0xEF) { byte[] buffer; int offset; int offsetMax; int length; if (_buffered) { buffer = BufferReader.GetBuffer(out offset, out offsetMax); if (hasLeadingByteOf0xEF) { length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax); } else { length = ReadText(buffer, offset, offsetMax); } } else { buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax); if (hasLeadingByteOf0xEF) { length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax); } else { length = ReadText(buffer, offset, offsetMax); } length = BreakText(buffer, offset, length); } BufferReader.Advance(length); if (offset < offsetMax - 1 - length && (buffer[offset + length] == (byte)'<' && buffer[offset + length + 1] != (byte)'!')) { MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, length); } else { MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, length); } } private void ReadEscapedText() { int ch = ReadCharRef(); if (ch < 256 && (s_charType[ch] & CharType.Whitespace) != 0) MoveToWhitespaceText().Value.SetCharValue(ch); else MoveToComplexText().Value.SetCharValue(ch); } public override bool Read() { if (this.Node.ReadState == ReadState.Closed) return false; if (this.Node.CanMoveToElement) { // If we're positioned on an attribute or attribute text on an empty element, we need to move back // to the element in order to get the correct setting of ExitScope MoveToElement(); } if (this.Node.ExitScope) { ExitScope(); } if (!_buffered) BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead); if (BufferReader.EndOfFile) { MoveToEndOfFile(); return false; } byte ch = BufferReader.GetByte(); if (ch == (byte)'<') { BufferReader.SkipByte(); ch = BufferReader.GetByte(); if (ch == (byte)'/') ReadEndElement(); else if (ch == (byte)'!') { BufferReader.SkipByte(); ch = BufferReader.GetByte(); if (ch == '-') { ReadComment(); } else { if (OutsideRootElement) XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCDATAInvalidAtTopLevel))); ReadCData(); } } else if (ch == (byte)'?') ReadDeclaration(); else ReadStartElement(); } else if ((s_charType[ch] & CharType.SpecialWhitespace) != 0) { ReadWhitespace(); } else if (OutsideRootElement && ch != '\r') { XmlExceptionHelper.ThrowInvalidRootData(this); } else if ((s_charType[ch] & CharType.Text) != 0) { ReadText(false); } else if (ch == '&') { ReadEscapedText(); } else if (ch == '\r') { BufferReader.SkipByte(); if (!BufferReader.EndOfFile && BufferReader.GetByte() == '\n') ReadWhitespace(); else MoveToComplexText().Value.SetCharValue('\n'); } else if (ch == ']') { int offset; byte[] buffer = BufferReader.GetBuffer(3, out offset); if (buffer[offset + 0] == (byte)']' && buffer[offset + 1] == (byte)']' && buffer[offset + 2] == (byte)'>') { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCloseCData))); } BufferReader.SkipByte(); MoveToComplexText().Value.SetCharValue(']'); // Need to get past the ']' and keep going. } else if (ch == 0xEF) // Watch for invalid characters 0xfffe and 0xffff { ReadText(true); } else { XmlExceptionHelper.ThrowInvalidXml(this, ch); } return true; } public bool HasLineInfo() { return true; } public int LineNumber { get { int row, column; GetPosition(out row, out column); return row; } } public int LinePosition { get { int row, column; GetPosition(out row, out column); return column; } } private void GetPosition(out int row, out int column) { if (_rowOffsets == null) { _rowOffsets = BufferReader.GetRows(); } int offset = BufferReader.Offset; int j = 0; while (j < _rowOffsets.Length - 1 && _rowOffsets[j + 1] < offset) j++; row = j + 1; column = offset - _rowOffsets[j] + 1; } private static class CharType { public const byte None = 0x00; public const byte FirstName = 0x01; public const byte Name = 0x02; public const byte Whitespace = 0x04; public const byte Text = 0x08; public const byte AttributeText = 0x10; public const byte SpecialWhitespace = 0x20; public const byte Comment = 0x40; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Net.Mail; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using ASC.Web.People.Classes; using ASC.Web.People.Resources; namespace ASC.Web.People.Core.Import { public class FileParameters { public int Encode { get; set; } public int Separator { get; set; } public int Delimiter { get; set; } public int Position { get; set; } public string UserHeader { get; set; } public bool IsRaw { get; set; } } public class MultiFormatTextFileUserImporter : TextFileUserImporter { public MultiFormatTextFileUserImporter(Stream stream, FileParameters param) : base(stream, param) { } protected override ContactInfo GetExportedUser(string line, IDictionary<int, PropertyInfo> mappedProperties, int fieldsCount) { try { var address = new MailAddress(line); var info = new ContactInfo { Email = address.Address }; if (!string.IsNullOrEmpty(address.DisplayName)) { if (address.DisplayName.Contains(' ')) { info.FirstName = address.DisplayName.Split(' ')[0]; info.LastName = address.DisplayName.Split(' ')[1]; } else { info.FirstName = address.DisplayName; } } return info; } catch (Exception) { //thats bad. Failed to parse an address } return base.GetExportedUser(line, mappedProperties, fieldsCount); } } public class TextFileUserImporter : IUserImporter { private readonly Stream stream; protected Dictionary<string, string> NameMapping { get; set; } protected IList<string> ExcludeList { get; private set; } internal bool HasHeader { get; set; } internal string Separators { get; set; } internal string TextDelmiter { get; set; } internal string UserHeader { get; set; } internal int FirstPosition { get; set; } private Encoding Encoding { get; set; } public TextFileUserImporter(Stream stream, FileParameters param) { this.stream = stream; ExcludeList = new List<string> { "ID", "Status" }; Encoding = EncodingParameters.GetById(param.Encode); Separators = SeparatorParameters.GetById(param.Separator); TextDelmiter = DelimiterParameters.GetById(param.Delimiter); FirstPosition = param.Position; UserHeader = param.UserHeader; } public List<Tuple<string[], string[]>> GetRawUsers() { var users = new List<Tuple<string[], string[]>>(); var fileLines = new List<string>(); if (stream != null) { using (var reader = new StreamReader(stream, Encoding)) { fileLines.AddRange(reader.ReadToEnd().HtmlEncode().Split(new[] { Environment.NewLine, "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); } } for (var i = FirstPosition; i < fileLines.Count; i++) { users.Add(new Tuple<string[], string[]>(GetDataFields(fileLines[0]), GetDataFields(fileLines[i]))); } return users; } public IEnumerable<ContactInfo> GetDiscoveredUsers() { var users = new List<ContactInfo>(); var fileLines = new List<string>(); var splitedHeader = new List<string>(); var splitedFileLines = new List<string>(); var replaceComplHeader = new List<string>(); var columns = ContactInfo.GetColumns(); if (stream != null) { using (var reader = new StreamReader(stream, Encoding)) { fileLines.AddRange(reader.ReadToEnd().Split(new[] { Environment.NewLine, "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); } splitedHeader = new List<string>(fileLines[0].Split(new[] { Separators }, StringSplitOptions.None)); replaceComplHeader = new List<string>(UserHeader.Split(new[] { "," }, StringSplitOptions.None)); for (var i = 0; i < replaceComplHeader.Count; i++) { splitedHeader[i] = replaceComplHeader[i].Replace(" ", ""); } UserHeader = string.Join(Separators, splitedHeader); if (FirstPosition == 0) { fileLines.Insert(FirstPosition, UserHeader); } else { fileLines.Insert(FirstPosition - 1, UserHeader); } } if (0 < fileLines.Count) { var lastPosition = fileLines.Count; var mappedProperties = new Dictionary<int, PropertyInfo>(); var infos = typeof(ContactInfo).GetProperties(BindingFlags.Public | BindingFlags.Instance); var fieldsCount = GetFieldsMapping(fileLines[0], infos, mappedProperties); for (int i = FirstPosition; i < fileLines.Count; i++) { users.Add(GetExportedUser(fileLines[i], mappedProperties, fieldsCount)); } } return users; } protected virtual ContactInfo GetExportedUser(string line, IDictionary<int, PropertyInfo> mappedProperties, int fieldsCount) { var exportedUser = new ContactInfo(); var dataFields = GetDataFields(line.HtmlEncode()); for (int j = 0; j < Math.Min(fieldsCount, dataFields.Length); j++) { var propinfo = mappedProperties[j]; if (propinfo != null) { var value = ConvertFromString(dataFields[j], propinfo.PropertyType); if (value != null) { value = Regex.Replace(value.ToString(), "(^')|(^\")|(\"$)|('$)", String.Empty); propinfo.SetValue(exportedUser, value, null); } } } try { if (string.IsNullOrEmpty(exportedUser.FirstName) && string.IsNullOrEmpty(exportedUser.LastName) && !string.IsNullOrEmpty(exportedUser.Email)) { var username = exportedUser.Email.Contains('@') ? exportedUser.Email.Substring(0, exportedUser.Email.IndexOf('@')) : exportedUser.Email; if (username.Contains('.')) { exportedUser.FirstName = username.Split('.')[0]; exportedUser.LastName = username.Split('.')[1]; } } } catch { } return exportedUser; } private string[] GetDataFields(string line) { var regFormat = "[{0}](?=(?:[^\"]*" + TextDelmiter + "[^\"]*" + TextDelmiter + ")*(?![^\"]*" + TextDelmiter + "))"; var pattern = String.Format(regFormat, string.Join("|", Separators)); var result = Regex.Split(line, pattern); return result.Select( original => original.StartsWith(TextDelmiter) && original.EndsWith(TextDelmiter) ? original.Substring(1, original.Length - 2).Trim() : original.Trim() ).ToArray(); } private int GetFieldsMapping(string firstLine, IEnumerable<PropertyInfo> infos, IDictionary<int, PropertyInfo> mappedProperties) { var fields = firstLine.Split(new string[] { Separators }, StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < fields.Length; i++) { var field = fields[i]; foreach (var info in infos) { var propertyField = field.Trim(); propertyField = propertyField.Trim(Convert.ToChar(TextDelmiter)); var title = info.GetCustomAttribute<ResourceAttribute>().Title; if (NameMapping != null && NameMapping.ContainsKey(propertyField)) { propertyField = NameMapping[propertyField]; } propertyField.Replace(" ", ""); if (!string.IsNullOrEmpty(propertyField) && !ExcludeList.Contains(propertyField) && (propertyField.Equals(PeopleResource.ResourceManager.GetString(title), StringComparison.OrdinalIgnoreCase) || propertyField.Equals(info.Name, StringComparison.OrdinalIgnoreCase))) { mappedProperties.Add(i, info); } } if (!mappedProperties.ContainsKey(i)) { mappedProperties.Add(i, null); } } return fields.Length; } private static object ConvertFromString(string value, Type type) { var converter = TypeDescriptor.GetConverter(type); return converter.CanConvertFrom(typeof(string)) ? converter.ConvertFromString(value) : null; } } }
using System; using Xunit; namespace TIKSN.Web.Tests { public class SitemapPageTests { [Fact] public void Equality001() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); Sitemap.Page p2 = null; Assert.False(null == p1); Assert.True(null == p2); } [Fact] public void Equals001() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var p2 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); Assert.True(p1.Equals(p1)); Assert.True(p1.Equals(p2)); Assert.True(p1 == p1); Assert.True(p1 == p2); Assert.False(p1 != p1); Assert.False(p1 != p2); Assert.True(p1.GetHashCode() == p2.GetHashCode()); } [Fact] public void Equals002() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var p2 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now.AddDays(10d), Sitemap.Page.Frequency.Monthly, 0.2); Assert.True(p1.Equals(p1)); Assert.True(p1.Equals(p2)); Assert.True(p1 == p1); Assert.True(p1 == p2); Assert.False(p1 != p1); Assert.False(p1 != p2); Assert.True(p1.GetHashCode() == p2.GetHashCode()); } [Fact] public void Equals003() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var p2 = new Sitemap.Page(new Uri("http://www.microsoft.com/sitemap.aspx"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); Assert.True(p1.Equals(p1)); Assert.False(p1.Equals(p2)); Assert.True(p1 == p1); Assert.False(p1 == p2); Assert.False(p1 != p1); Assert.True(p1 != p2); Assert.True(p1.GetHashCode() != p2.GetHashCode()); } [Fact] public void Equals004() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); Assert.False(p1.Equals(null)); Assert.False(p1 == null); Assert.True(p1 != null); } [Fact] public void Equals005() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var pages = new System.Collections.Generic.HashSet<Sitemap.Page>(); Assert.True(pages.Add(p1)); Assert.False(pages.Add(p1)); } [Fact] public void Equals007() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var p2 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now.AddDays(10d), Sitemap.Page.Frequency.Monthly, 0.2); var pages = new System.Collections.Generic.HashSet<Sitemap.Page>(); Assert.True(pages.Add(p1)); Assert.False(pages.Add(p2)); } [Fact] public void Equals008() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var pages = new System.Collections.Generic.List<Sitemap.Page> { p1 }; Assert.Contains(p1, pages); pages.Add(p1); Assert.Contains(p1, pages); } [Fact] public void Equals009() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var p2 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now.AddDays(10d), Sitemap.Page.Frequency.Monthly, 0.2); var pages = new System.Collections.Generic.List<Sitemap.Page> { p1 }; Assert.Contains(p1, pages); pages.Add(p2); Assert.Contains(p2, pages); } [Fact] public void Equals010() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var pages = new System.Collections.Generic.Dictionary<Sitemap.Page, int> { { p1, 1 } }; Assert.True(pages.ContainsKey(p1)); _ = Assert.Throws<ArgumentException>(() => pages.Add(p1, 2)); Assert.True(pages.ContainsKey(p1)); } [Fact] public void Equals011() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var p2 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now.AddDays(10d), Sitemap.Page.Frequency.Monthly, 0.2); var pages = new System.Collections.Generic.Dictionary<Sitemap.Page, int> { { p1, 1 } }; Assert.True(pages.ContainsKey(p1)); _ = Assert.Throws<ArgumentException>(() => pages.Add(p2, 2)); Assert.True(pages.ContainsKey(p2)); } [Fact] public void Equals012() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); object p2 = null; Assert.False(p1.Equals(p2)); } [Fact] public void Equals013() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var p2 = p1; Assert.True(p1.Equals(p2)); } [Fact] public void Equals014() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); var s1 = new Sitemap(); Assert.False(p1.Equals(s1)); } [Fact] public void Equals015() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); object p2 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now.AddDays(10d), Sitemap.Page.Frequency.Monthly, 0.2); Assert.True(p1.Equals(p2)); } [Fact] public void Equals016() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); object p2 = p1; Assert.True(p1.Equals(p2)); } [Fact] public void Inequality001() { var p1 = new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 0.5); Sitemap.Page p2 = null; Assert.True(null != p1); Assert.False(null != p2); } [Fact] public void Page001() => Assert.Throws<ArgumentNullException>(() => new Sitemap.Page(null, null, null, null)); [Fact] public void Page002() => Assert.Throws<ArgumentNullException>( () => new Sitemap.Page(null, DateTime.Now, Sitemap.Page.Frequency.Always, 0.5)); [Fact] public void Page003() { var p1 = new Sitemap.Page(new Uri("http://microsoft.com/"), null, null, null); Assert.Equal("http://microsoft.com/", p1.Address.AbsoluteUri); Assert.False(p1.ChangeFrequency.HasValue); Assert.False(p1.LastModified.HasValue); Assert.False(p1.Priority.HasValue); } [Fact] public void Page004() => Assert.Throws<ArgumentOutOfRangeException>( () => new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, 1.5)); [Fact] public void Page005() => Assert.Throws<ArgumentOutOfRangeException>( () => new Sitemap.Page(new Uri("http://www.microsoft.com/"), DateTime.Now, Sitemap.Page.Frequency.Always, -0.5)); } }
//----------------------------------------------------------------------- // <copyright file="BasicTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #endif namespace Csla.Test.Basic { [TestClass] public class BasicTests { [TestMethod] public void TestNotUndoableField() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Csla.Test.DataBinding.ParentEntity p = Csla.Test.DataBinding.ParentEntity.NewParentEntity(); p.NotUndoable = "something"; p.Data = "data"; p.BeginEdit(); p.NotUndoable = "something else"; p.Data = "new data"; p.CancelEdit(); //NotUndoable property points to a private field marked with [NotUndoable()] //so its state is never copied when BeginEdit() is called Assert.AreEqual("something else", p.NotUndoable); //the Data property points to a field that is undoable, so it reverts Assert.AreEqual("data", p.Data); } [TestMethod] public void TestReadOnlyList() { //ReadOnlyList list = ReadOnlyList.GetReadOnlyList(); // Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["ReadOnlyList"]); } [TestMethod] public void TestNameValueList() { NameValueListObj nvList = NameValueListObj.GetNameValueListObj(); #pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["NameValueListObj"]); #pragma warning restore CS0618 // Type or member is obsolete Assert.AreEqual("element_1", nvList[1].Value); //won't work, because IsReadOnly is set to true after object is populated in the for //loop in DataPortal_Fetch //NameValueListObj.NameValuePair newPair = new NameValueListObj.NameValuePair(45, "something"); //nvList.Add(newPair); //Assert.AreEqual("something", nvList[45].Value); } [TestMethod] public void TestCommandBase() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete CommandObject obj = new CommandObject(); Assert.AreEqual("Executed", obj.ExecuteServerCode().AProperty); } [TestMethod] public void CreateGenRoot() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete GenRoot root; root = GenRoot.NewRoot(); Assert.IsNotNull(root); Assert.AreEqual("<new>", root.Data); #pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["GenRoot"]); #pragma warning restore CS0618 // Type or member is obsolete Assert.AreEqual(true, root.IsNew); Assert.AreEqual(false, root.IsDeleted); Assert.AreEqual(true, root.IsDirty); } [TestMethod] public void InheritanceUndo() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete GenRoot root; root = GenRoot.NewRoot(); root.BeginEdit(); root.Data = "abc"; root.CancelEdit(); #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete root = GenRoot.NewRoot(); root.BeginEdit(); root.Data = "abc"; root.ApplyEdit(); } [TestMethod] public void CreateRoot() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root; root = Csla.Test.Basic.Root.NewRoot(); Assert.IsNotNull(root); Assert.AreEqual("<new>", root.Data); #pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["Root"]); #pragma warning restore CS0618 // Type or member is obsolete Assert.AreEqual(true, root.IsNew); Assert.AreEqual(false, root.IsDeleted); Assert.AreEqual(true, root.IsDirty); } [TestMethod] public void AddChild() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); Assert.AreEqual(1, root.Children.Count); Assert.AreEqual("1", root.Children[0].Data); } [TestMethod] public void AddRemoveChild() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.Children.Remove(root.Children[0]); Assert.AreEqual(0, root.Children.Count); } [TestMethod] public void AddRemoveAddChild() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.BeginEdit(); root.Children.Remove(root.Children[0]); root.Children.Add("2"); root.CancelEdit(); Assert.AreEqual(1, root.Children.Count); Assert.AreEqual("1", root.Children[0].Data); } [TestMethod] public void AddGrandChild() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); Child child = root.Children[0]; child.GrandChildren.Add("1"); Assert.AreEqual(1, child.GrandChildren.Count); Assert.AreEqual("1", child.GrandChildren[0].Data); } [TestMethod] public void AddRemoveGrandChild() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); Child child = root.Children[0]; child.GrandChildren.Add("1"); child.GrandChildren.Remove(child.GrandChildren[0]); Assert.AreEqual(0, child.GrandChildren.Count); } [TestMethod] public void ClearChildList() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("A"); root.Children.Add("B"); root.Children.Add("C"); root.Children.Clear(); Assert.AreEqual(0, root.Children.Count, "Count should be 0"); Assert.AreEqual(3, root.Children.DeletedCount, "Deleted count should be 3"); } [TestMethod] public void NestedAddAcceptchild() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.BeginEdit(); root.Children.Add("A"); root.BeginEdit(); root.Children.Add("B"); root.BeginEdit(); root.Children.Add("C"); root.ApplyEdit(); root.ApplyEdit(); root.ApplyEdit(); Assert.AreEqual(3, root.Children.Count); } [TestMethod] public void NestedAddDeleteAcceptChild() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.BeginEdit(); root.Children.Add("A"); root.BeginEdit(); root.Children.Add("B"); root.BeginEdit(); root.Children.Add("C"); Child childC = root.Children[2]; Assert.AreEqual(true, root.Children.Contains(childC), "Child should be in collection"); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); Assert.AreEqual(false, root.Children.Contains(childC), "Child should not be in collection"); Assert.AreEqual(true, root.Children.ContainsDeleted(childC), "Deleted child should be in deleted collection"); root.ApplyEdit(); Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after first applyedit"); root.ApplyEdit(); Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after ApplyEdit"); root.ApplyEdit(); Assert.AreEqual(0, root.Children.Count, "No children should remain"); Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after third applyedit"); } [TestMethod] public void BasicEquality() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root r1 = Root.NewRoot(); r1.Data = "abc"; Assert.AreEqual(true, r1.Equals(r1), "objects should be equal on instance compare"); Assert.AreEqual(true, Equals(r1, r1), "objects should be equal on static compare"); #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root r2 = Root.NewRoot(); r2.Data = "xyz"; Assert.AreEqual(false, r1.Equals(r2), "objects should not be equal"); Assert.AreEqual(false, Equals(r1, r2), "objects should not be equal"); Assert.AreEqual(false, r1.Equals(null), "Objects should not be equal"); Assert.AreEqual(false, Equals(r1, null), "Objects should not be equal"); Assert.AreEqual(false, Equals(null, r2), "Objects should not be equal"); } [TestMethod] public void ChildEquality() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Root.NewRoot(); root.Children.Add("abc"); root.Children.Add("xyz"); root.Children.Add("123"); Child c1 = root.Children[0]; Child c2 = root.Children[1]; Child c3 = root.Children[2]; root.Children.Remove(c3); Assert.AreEqual(true, c1.Equals(c1), "objects should be equal"); Assert.AreEqual(true, Equals(c1, c1), "objects should be equal"); Assert.AreEqual(false, c1.Equals(c2), "objects should not be equal"); Assert.AreEqual(false, Equals(c1, c2), "objects should not be equal"); Assert.AreEqual(false, c1.Equals(null), "objects should not be equal"); Assert.AreEqual(false, Equals(c1, null), "objects should not be equal"); Assert.AreEqual(false, Equals(null, c2), "objects should not be equal"); Assert.AreEqual(true, root.Children.Contains(c1), "Collection should contain c1"); Assert.AreEqual(true, root.Children.Contains(c2), "collection should contain c2"); Assert.AreEqual(false, root.Children.Contains(c3), "collection should not contain c3"); Assert.AreEqual(true, root.Children.ContainsDeleted(c3), "Deleted collection should contain c3"); } [TestMethod] public void DeletedListTest() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.Children.Add("2"); root.Children.Add("3"); root.BeginEdit(); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); root.ApplyEdit(); Root copy = root.Clone(); var deleted = copy.Children.GetDeletedList(); Assert.AreEqual(2, deleted.Count); Assert.AreEqual("1", deleted[0].Data); Assert.AreEqual("2", deleted[1].Data); Assert.AreEqual(1, root.Children.Count); } [TestMethod] public void DeletedListTestWithCancel() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete Root root = Csla.Test.Basic.Root.NewRoot(); root.Children.Add("1"); root.Children.Add("2"); root.Children.Add("3"); root.BeginEdit(); root.Children.Remove(root.Children[0]); root.Children.Remove(root.Children[0]); Root copy = root.Clone(); var deleted = copy.Children.GetDeletedList(); Assert.AreEqual(2, deleted.Count); Assert.AreEqual("1", deleted[0].Data); Assert.AreEqual("2", deleted[1].Data); Assert.AreEqual(1, root.Children.Count); root.CancelEdit(); deleted = root.Children.GetDeletedList(); Assert.AreEqual(0, deleted.Count); Assert.AreEqual(3, root.Children.Count); } [TestMethod] public void SuppressListChangedEventsDoNotRaiseCollectionChanged() { bool changed = false; var obj = new RootList(); obj.ListChanged += (o, e) => { changed = true; }; var child = new RootListChild(); // object is marked as child Assert.IsTrue(obj.RaiseListChangedEvents); using (obj.SuppressListChangedEvents) { Assert.IsFalse(obj.RaiseListChangedEvents); obj.Add(child); } Assert.IsFalse(changed, "Should not raise ListChanged event"); Assert.IsTrue(obj.RaiseListChangedEvents); Assert.AreEqual(child, obj[0]); } [TestMethod] public async Task ChildEditLevelClone() { var list = await Csla.DataPortal.CreateAsync<RootList>(); list.BeginEdit(); list.AddNew(); var clone = (RootList)((ICloneable)list).Clone(); clone.ApplyEdit(); } [TestMethod] public async Task ChildEditLevelDeleteClone() { var list = await Csla.DataPortal.CreateAsync<RootList>(); list.BeginEdit(); list.AddNew(); list.RemoveAt(0); var clone = (RootList)((ICloneable)list).Clone(); clone.ApplyEdit(); } [TestMethod] public async Task UndoStateStack() { var obj = await Csla.DataPortal.CreateAsync<Root>(new Root.Criteria("")); Assert.AreEqual("", obj.Data); obj.BeginEdit(); obj.Data = "1"; obj.BeginEdit(); obj.Data = "2"; Assert.AreEqual("2", obj.Data); obj.CancelEdit(); Assert.AreEqual("1", obj.Data); obj.BeginEdit(); obj.Data = "2"; Assert.AreEqual(2, obj.GetEditLevel()); var clone = obj.Clone(); Assert.AreEqual(2, clone.GetEditLevel()); Assert.AreEqual("2", clone.Data); clone.CancelEdit(); Assert.AreEqual("1", clone.Data); clone.CancelEdit(); Assert.AreEqual("", clone.Data); } [TestCleanup] public void ClearContextsAfterEachTest() { #pragma warning disable CS0618 // Type or member is obsolete Csla.ApplicationContext.GlobalContext.Clear(); #pragma warning restore CS0618 // Type or member is obsolete } } public class FormSimulator { private readonly Core.BusinessBase _obj; public FormSimulator(Core.BusinessBase obj) { this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Obj_IsDirtyChanged); this._obj = obj; } private void Obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { } } [Serializable()] public class SerializableListener { private readonly Core.BusinessBase _obj; public SerializableListener(Core.BusinessBase obj) { this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Obj_IsDirtyChanged); this._obj = obj; } public void Obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Xunit; using Microsoft.Extensions.DependencyModel; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.Tracing { public class GivenThatICareAboutTracing : IClassFixture<GivenThatICareAboutTracing.SharedTestState> { private SharedTestState sharedTestState; // Trace messages currently expected for a passing app (somewhat randomly selected) private const String ExpectedVerboseMessage = "--- Begin breadcrumb write"; private const String ExpectedInfoMessage = "Deps file:"; private const String ExpectedBadPathMessage = "Unable to open COREHOST_TRACEFILE="; public GivenThatICareAboutTracing(GivenThatICareAboutTracing.SharedTestState fixture) { sharedTestState = fixture; } [Fact] public void TracingOff() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .NotHaveStdErrContaining(ExpectedInfoMessage) .And .NotHaveStdErrContaining(ExpectedVerboseMessage); } [Fact] public void TracingOnDefault() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .HaveStdErrContaining(ExpectedInfoMessage) .And .HaveStdErrContaining(ExpectedVerboseMessage); } [Fact] public void TracingOnVerbose() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("COREHOST_TRACE_VERBOSITY", "4") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .HaveStdErrContaining(ExpectedInfoMessage) .And .HaveStdErrContaining(ExpectedVerboseMessage); } [Fact] public void TracingOnInfo() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("COREHOST_TRACE_VERBOSITY", "3") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .HaveStdErrContaining(ExpectedInfoMessage) .And .NotHaveStdErrContaining(ExpectedVerboseMessage); } [Fact] public void TracingOnWarning() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("COREHOST_TRACE_VERBOSITY", "2") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .NotHaveStdErrContaining(ExpectedInfoMessage) .And .NotHaveStdErrContaining(ExpectedVerboseMessage); } [Fact] public void TracingOnToFileDefault() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("COREHOST_TRACEFILE", "TracingOnToFileDefault.log") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .NotHaveStdErrContaining(ExpectedInfoMessage) .And .NotHaveStdErrContaining(ExpectedVerboseMessage) .And .FileExists("TracingOnToFileDefault.log") .And .FileContains("TracingOnToFileDefault.log", ExpectedVerboseMessage); } [Fact] public void TracingOnToFileBadPathDefault() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("COREHOST_TRACEFILE", "badpath/TracingOnToFileBadPathDefault.log") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .HaveStdErrContaining(ExpectedInfoMessage) .And .HaveStdErrContaining(ExpectedVerboseMessage) .And .HaveStdErrContaining(ExpectedBadPathMessage); } public class SharedTestState : IDisposable { // Entry point projects public TestProjectFixture PreviouslyPublishedAndRestoredPortableAppProjectFixture { get; set; } public RepoDirectoriesProvider RepoDirectories { get; set; } public SharedTestState() { RepoDirectories = new RepoDirectoriesProvider(); // Entry point projects PreviouslyPublishedAndRestoredPortableAppProjectFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); } public void Dispose() { // Entry point projects PreviouslyPublishedAndRestoredPortableAppProjectFixture.Dispose(); } } } }
// // RecolorTool.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // 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 Cairo; using Gtk; namespace Pinta.Core { public class RecolorTool : BaseBrushTool { protected ToolBarLabel tolerance_label; protected ToolBarSlider tolerance_slider; private Point last_point = point_empty; private bool[,] stencil; private int myTolerance; public RecolorTool () { } #region Properties public override string Name { get { return "Recolor"; } } public override string Icon { get { return "Tools.Recolor.png"; } } public override string StatusBarText { get { return "Left click to replace the secondary color with the primary color."; } } protected float Tolerance { get { return (float)(tolerance_slider.Slider.Value / 100); } } #endregion #region ToolBar protected override void OnBuildToolBar (Gtk.Toolbar tb) { base.OnBuildToolBar (tb); if (tolerance_label == null) tolerance_label = new ToolBarLabel (" Tolerance: "); tb.AppendItem (tolerance_label); if (tolerance_slider == null) tolerance_slider = new ToolBarSlider (0, 100, 1, 50); tb.AppendItem (tolerance_slider); } #endregion #region Mouse Handlers protected override void OnMouseDown (DrawingArea canvas, ButtonPressEventArgs args, PointD point) { PintaCore.Layers.ToolLayer.Clear (); stencil = new bool[PintaCore.Workspace.ImageSize.X, PintaCore.Workspace.ImageSize.Y]; base.OnMouseDown (canvas, args, point); } protected unsafe override void OnMouseMove (object o, Gtk.MotionNotifyEventArgs args, Cairo.PointD point) { ColorBgra old_color; ColorBgra new_color; if (mouse_button == 1) { old_color = PintaCore.Palette.PrimaryColor.ToColorBgra (); new_color = PintaCore.Palette.SecondaryColor.ToColorBgra (); } else if (mouse_button == 3) { old_color = PintaCore.Palette.SecondaryColor.ToColorBgra (); new_color = PintaCore.Palette.PrimaryColor.ToColorBgra (); } else { last_point = point_empty; return; } int x = (int)point.X; int y = (int)point.Y; if (last_point.Equals (point_empty)) last_point = new Point (x, y); if (PintaCore.Workspace.PointInCanvas (point)) surface_modified = true; ImageSurface surf = PintaCore.Layers.CurrentLayer.Surface; ImageSurface tmp_layer = PintaCore.Layers.ToolLayer.Surface; Gdk.Rectangle roi = GetRectangleFromPoints (last_point, new Point (x, y)); roi = PintaCore.Workspace.ClampToImageSize (roi); myTolerance = (int)(Tolerance * 256); ColorBgra* tmp_data_ptr = (ColorBgra*)tmp_layer.DataPtr; int tmp_width = tmp_layer.Width; ColorBgra* surf_data_ptr = (ColorBgra*)surf.DataPtr; int surf_width = surf.Width; // The stencil lets us know if we've already checked this // pixel, providing a nice perf boost // Maybe this should be changed to a BitVector2DSurfaceAdapter? for (int i = roi.X; i < roi.Right; i++) for (int j = roi.Y; j < roi.Bottom; j++) { if (stencil[i, j]) continue; if (IsColorInTolerance (new_color, surf.GetColorBgra (surf_data_ptr, surf_width, i, j))) *tmp_layer.GetPointAddressUnchecked (tmp_data_ptr, tmp_width, i, j) = AdjustColorDifference (new_color, old_color, surf.GetColorBgra (surf_data_ptr, surf_width, i, j)); stencil[i, j] = true; } using (Context g = new Context (surf)) { g.AppendPath (PintaCore.Layers.SelectionPath); g.FillRule = FillRule.EvenOdd; g.Clip (); g.Antialias = Antialias.Subpixel; g.MoveTo (last_point.X, last_point.Y); g.LineTo (x, y); g.LineWidth = BrushWidth; g.LineJoin = LineJoin.Round; g.LineCap = LineCap.Round; g.SetSource (tmp_layer); g.Stroke (); } PintaCore.Workspace.Invalidate (roi); last_point = new Point (x, y); } #endregion #region Private PDN Methods private bool IsColorInTolerance (ColorBgra colorA, ColorBgra colorB) { return Utility.ColorDifference (colorA, colorB) <= myTolerance; } private static bool CheckColor (ColorBgra a, ColorBgra b, int tolerance) { int sum = 0; int diff; diff = a.R - b.R; sum += (1 + diff * diff) * a.A / 256; diff = a.G - b.G; sum += (1 + diff * diff) * a.A / 256; diff = a.B - b.B; sum += (1 + diff * diff) * a.A / 256; diff = a.A - b.A; sum += diff * diff; return (sum <= tolerance * tolerance * 4); } private ColorBgra AdjustColorDifference (ColorBgra oldColor, ColorBgra newColor, ColorBgra basisColor) { ColorBgra returnColor; // eliminate testing for the "equal to" case returnColor = basisColor; returnColor.B = AdjustColorByte (oldColor.B, newColor.B, basisColor.B); returnColor.G = AdjustColorByte (oldColor.G, newColor.G, basisColor.G); returnColor.R = AdjustColorByte (oldColor.R, newColor.R, basisColor.R); return returnColor; } private byte AdjustColorByte (byte oldByte, byte newByte, byte basisByte) { if (oldByte > newByte) return Utility.ClampToByte (basisByte - (oldByte - newByte)); else return Utility.ClampToByte (basisByte + (newByte - oldByte)); } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.FirebaseHosting.v1 { /// <summary>The FirebaseHosting Service.</summary> public class FirebaseHostingService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public FirebaseHostingService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public FirebaseHostingService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Operations = new OperationsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "firebasehosting"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://firebasehosting.googleapis.com/"; #else "https://firebasehosting.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://firebasehosting.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Gets the Operations resource.</summary> public virtual OperationsResource Operations { get; } } /// <summary>A base abstract class for FirebaseHosting requests.</summary> public abstract class FirebaseHostingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new FirebaseHostingBaseServiceRequest instance.</summary> protected FirebaseHostingBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes FirebaseHosting parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "operations" collection of methods.</summary> public class OperationsResource { private const string Resource = "operations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public OperationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the /// operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="name">The name of the operation resource to be cancelled.</param> public virtual CancelRequest Cancel(Google.Apis.FirebaseHosting.v1.Data.CancelOperationRequest body, string name) { return new CancelRequest(service, body, name); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the /// operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. /// </summary> public class CancelRequest : FirebaseHostingBaseServiceRequest<Google.Apis.FirebaseHosting.v1.Data.Empty> { /// <summary>Constructs a new Cancel request.</summary> public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.FirebaseHosting.v1.Data.CancelOperationRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The name of the operation resource to be cancelled.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.FirebaseHosting.v1.Data.CancelOperationRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "cancel"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}:cancel"; /// <summary>Initializes Cancel parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations/.*$", }); } } /// <summary> /// Deletes a long-running operation. This method indicates that the client is no longer interested in the /// operation result. It does not cancel the operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="name">The name of the operation resource to be deleted.</param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is no longer interested in the /// operation result. It does not cancel the operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> public class DeleteRequest : FirebaseHostingBaseServiceRequest<Google.Apis.FirebaseHosting.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation resource to be deleted.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "delete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "DELETE"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations/.*$", }); } } /// <summary> /// Lists operations that match the specified filter in the request. If the server doesn't support this method, /// it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use /// different resource name schemes, such as `users/*/operations`. To override the binding, API services can add /// a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards /// compatibility, the default name includes the operations collection id, however overriding users must ensure /// the name binding is the parent resource, without the operations collection id. /// </summary> /// <param name="name">The name of the operation's parent resource.</param> public virtual ListRequest List(string name) { return new ListRequest(service, name); } /// <summary> /// Lists operations that match the specified filter in the request. If the server doesn't support this method, /// it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use /// different resource name schemes, such as `users/*/operations`. To override the binding, API services can add /// a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards /// compatibility, the default name includes the operations collection id, however overriding users must ensure /// the name binding is the parent resource, without the operations collection id. /// </summary> public class ListRequest : FirebaseHostingBaseServiceRequest<Google.Apis.FirebaseHosting.v1.Data.ListOperationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation's parent resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The standard list filter.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary>The standard list page size.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>The standard list page token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations$", }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.FirebaseHosting.v1.Data { /// <summary>The request message for Operations.CancelOperation.</summary> public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response message for Operations.ListOperations.</summary> public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The standard List next-page token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A list of operations that matches the specified filter in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operations")] public virtual System.Collections.Generic.IList<Operation> Operations { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>This resource represents a long-running operation that is the result of a network API call.</summary> public class Operation : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, /// and either `error` or `response` is available. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("done")] public virtual System.Nullable<bool> Done { get; set; } /// <summary>The error result of the operation in case of failure or cancellation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("error")] public virtual Status Error { get; set; } /// <summary> /// Service-specific metadata associated with the operation. It typically contains progress information and /// common metadata such as create time. Some services might not provide such metadata. Any method that returns /// a long-running operation should document the metadata type, if any. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; } /// <summary> /// The server-assigned name, which is only unique within the same service that originally returns it. If you /// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// The normal response of the operation in case of success. If the original method returns no data on success, /// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard /// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have /// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is /// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("response")] public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The `Status` type defines a logical error model that is suitable for different programming environments, /// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains /// three pieces of data: error code, error message, and error details. You can find out more about this error model /// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). /// </summary> public class Status : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary> /// A list of messages that carry the error details. There is a common set of message types for APIs to use. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; } /// <summary> /// A developer-facing error message, which should be in English. Any user-facing error message should be /// localized and sent in the google.rpc.Status.details field, or localized by the client. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
/// <summary> /// Custom font. Author Cesar Rios 2013 /// </summary> using UnityEngine; using System.Collections; using System.Collections.Generic; using System; [RequireComponent (typeof (MeshRenderer))] [RequireComponent (typeof (MeshFilter))] [ExecuteInEditMode] public class EasyFontTextMesh : MonoBehaviour { public enum TEXT_ANCHOR { UpperLeft, UpperRight, UpperCenter, MiddleLeft, MiddleRight, MiddleCenter, LowerLeft, LowerRight, LowerCenter } public enum TEXT_ALIGNMENT { left, right, center } /// <summary> /// Define if we are drawing the main font, the shadow or the outline /// </summary> private enum TEXT_COMPONENT { Main, Shadow, Outline } [System.Serializable] public class TextProperties { public string text = "Hello World!"; public Font font; public Material customFillMaterial; public int fontSize = 16; public float size = 16; public TEXT_ANCHOR textAnchor; public TEXT_ALIGNMENT textAlignment; public float lineSpacing = 1; public Color fontColorTop = new Color(1,1,1,1); public Color fontColorBottom = new Color(1,1,1,1); public bool enableShadow; public Color shadowColor = new Color(0,0,0,1); public Vector3 shadowDistance = new Vector3(0,-1,0); public bool enableOutline; public Color outlineColor = new Color(0,0,0,1); public float outLineWidth = 0.3f; public bool highQualityOutline = false; } /// <summary> /// DO NOT CHANGE THIS DIRECTLY /// </summary> [HideInInspector] public TextProperties _privateProperties; //WARNING!: do not change it directly #region properties // If you have some problematic text that appears corrupt when enabling it, try to enable this variable public bool updateAlwaysOnEnable; /// <summary> /// For complex setups with a lot of materials override the auto setting may not be usefull. WARNING!: You will /// have to setup all the materials by hand. /// </summary> public bool dontOverrideMaterials; /// <summary> /// Gets or sets the text to show /// </summary> public string Text { get { return _privateProperties.text;} set { _privateProperties.text = value; isDirty = true;} } /// <summary> /// Gets or sets the Font Type /// </summary> public Font FontType { get { return _privateProperties.font;} set { _privateProperties.font = value; ChangeFont();} } /// <summary> /// Gets or sets the filling material (for having patterns inside the letters) /// </summary> public Material CustomFillMaterial { get { return _privateProperties.customFillMaterial;} set { _privateProperties.customFillMaterial = value; isDirty = true;} } /// <summary> /// Gets or sets the font size. This will increase the resolution of the text and the font texure size /// </summary> public int FontSize { get { return _privateProperties.fontSize;} set { _privateProperties.fontSize = value; isDirty = true;} } /// <summary> /// Gets or sets the size of the letters. The proportional quad size for the letters /// </summary> public float Size { get { return _privateProperties.size;} set { _privateProperties.size = value; isDirty = true;} } /// <summary> /// Gets or sets the Text anchor /// </summary> public TEXT_ANCHOR Textanchor { get { return _privateProperties.textAnchor;} set { _privateProperties.textAnchor = value; isDirty = true;} } /// <summary> /// Gets or sets the text alignment. Only for paragraphs /// </summary> public TEXT_ALIGNMENT Textalignment { get { return _privateProperties.textAlignment;} set { _privateProperties.textAlignment = value; isDirty = true;} } /// <summary> /// Gets or sets the space between lines of a paragraph /// </summary> public float LineSpacing { get { return _privateProperties.lineSpacing;} set { _privateProperties.lineSpacing = value; isDirty = true;} } /// <summary> /// Gets or sets the top font color /// </summary> public Color FontColorTop { get { return _privateProperties.fontColorTop;} set { _privateProperties.fontColorTop = value; SetColor(_privateProperties.fontColorTop,_privateProperties.fontColorBottom);} } /// <summary> /// Gets or sets the bottom font color /// </summary> public Color FontColorBottom { get { return _privateProperties.fontColorBottom;} set { _privateProperties.fontColorBottom = value; SetColor(_privateProperties.fontColorTop,_privateProperties.fontColorBottom);} } /// <summary> /// Enable or deisable proyected shadow. This will draw the text twice /// </summary> public bool EnableShadow { get { return _privateProperties.enableShadow;} set { _privateProperties.enableShadow = value; isDirty = true;} } /// <summary> /// Gets or sets the shadow color /// </summary> public Color ShadowColor { get { return _privateProperties.shadowColor;} set { _privateProperties.shadowColor = value; SetShadowColor(_privateProperties.shadowColor);} } /// <summary> /// Gets or sets the shadow offset distance. Note: Normally you don't want to change the Z coordinate. /// </summary> public Vector3 ShadowDistance { get { return _privateProperties.shadowDistance;} set { _privateProperties.shadowDistance = value; isDirty = true;} } /// <summary> /// Enable or disable the font outline. This will draw the text 4 times more /// </summary> public bool EnableOutline { get { return _privateProperties.enableOutline;} set { _privateProperties.enableOutline = value; isDirty = true;} } /// <summary> /// Gets or sets the outline color /// </summary> public Color OutlineColor { get { return _privateProperties.outlineColor;} set { _privateProperties.outlineColor = value; SetOutlineColor(_privateProperties.outlineColor);} } /// <summary> /// Gets or sets the outline width /// </summary> public float OutLineWidth { get { return _privateProperties.outLineWidth;} set { _privateProperties.outLineWidth = value; isDirty = true;} } // Gets or set the high quality outline. It increases the vertex count public bool HighQualityOutline { get { return _privateProperties.highQualityOutline;} set { _privateProperties.highQualityOutline = value; isDirty = true;} } #endregion #region Private vars //Cache vars private Mesh textMesh; private MeshFilter textMeshFilter; private Material fontMaterial; private Renderer textRenderer; private char[] textChars; /// <summary> /// When flagged true will refresh the text mesh. For avoifing refreshing the mesh to often (Right now at the end of LateUpdate) /// </summary> private bool isDirty; /// <summary> /// The current line break. /// </summary> private int currentLineBreak = 0; /// <summary> /// The accumulate height of the paragraph /// </summary> private float heightSum; /// <summary> /// Store in wich character there is a line break /// </summary> private List<int> lineBreakCharCounter = new List<int>(); /// <summary> /// The distance between characters accumulated before each line break /// </summary> private List<float> lineBreakAccumulatedDistance = new List<float>(); //Mesh data Vector3[] vertices; int[] triangles; Vector2[] uv; Vector2[] uv2; Color[] colors; #endregion [HideInInspector] public bool GUIChanged = false; #region special char codes private char LINE_BREAK = Convert.ToChar(10); //This is the character code for the alt+enter character that Unity includes in the text #endregion void Awake() { #if UNITY_EDITOR if (_privateProperties == null) _privateProperties = new TextProperties(); if (_privateProperties.font == null) _privateProperties.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font; #endif CacheTextVars(); RefreshMesh(true); } void OnEnable() { _privateProperties.font.textureRebuildCallback += FontTexureRebuild; //Register to the texture change event if (updateAlwaysOnEnable) RefreshMesh(true); } /// <summary> /// Initialize the text variables /// </summary> public void CacheTextVars() { textMeshFilter = GetComponent<MeshFilter>(); if (textMeshFilter == null) textMeshFilter = gameObject.AddComponent<MeshFilter>(); //Setup renderer objects textMesh = textMeshFilter.sharedMesh; if (textMesh == null) { textMesh = new Mesh(); textMesh.name = gameObject.name + GetInstanceID().ToString(); //Rename to something textMeshFilter.sharedMesh = textMesh; } textRenderer = renderer; if (textRenderer == null) textRenderer = gameObject.AddComponent<MeshRenderer>(); //Set materials if (!dontOverrideMaterials) { if (_privateProperties.customFillMaterial != null) { if (_privateProperties.enableShadow || _privateProperties.enableOutline) { if (textRenderer.sharedMaterials.Length < 2) textRenderer.sharedMaterials = new Material[2]{_privateProperties.font.material , _privateProperties.customFillMaterial}; _privateProperties.customFillMaterial.mainTexture = _privateProperties.font.material.mainTexture; textRenderer.sharedMaterial = _privateProperties.font.material; } else { _privateProperties.customFillMaterial.mainTexture = _privateProperties.font.material.mainTexture; textRenderer.sharedMaterial = _privateProperties.customFillMaterial; } } else { if (textRenderer.sharedMaterials == null) textRenderer.sharedMaterials = new Material[1]{_privateProperties.font.material}; else { textRenderer.sharedMaterials = new Material[1]{textRenderer.sharedMaterial}; } } } } /// <summary> /// Refreshs the mesh. /// </summary> /// <param name='_updateTexureInfo'> /// _update texure info. /// </param> void RefreshMesh(bool _updateTexureInfo) { //Update texture if (_updateTexureInfo) _privateProperties.font.RequestCharactersInTexture(_privateProperties.text, _privateProperties.fontSize); textChars = null; textChars = _privateProperties.text.ToCharArray(); AnalizeText(); //Check for special characters //The vertex count must increase if we are going to use high quality outline int highQualityOutlineModifier = 0; if (_privateProperties.highQualityOutline) highQualityOutlineModifier = 4; //If we use shadow or/and outline we have to change the number of vertex, triangles... int meshOptionMultipler = 1; if (_privateProperties.enableShadow && _privateProperties.enableOutline) meshOptionMultipler = 6 + highQualityOutlineModifier; else if (_privateProperties.enableOutline) meshOptionMultipler = 5 + highQualityOutlineModifier; else if (_privateProperties.enableShadow) meshOptionMultipler = 2; vertices = new Vector3[textChars.Length*4*meshOptionMultipler]; triangles = new int[textChars.Length*6*meshOptionMultipler]; uv = new Vector2[textChars.Length*4*meshOptionMultipler]; uv2 = new Vector2[textChars.Length*4*meshOptionMultipler]; colors = new Color[textChars.Length*4*meshOptionMultipler]; int characterPosition = 0; int alignmentPass = 0; //Shadow if (_privateProperties.enableShadow) { ResetHelperVariables(); foreach (char iteratorChar in textChars) { CreateCharacter(iteratorChar, characterPosition, _privateProperties.shadowDistance, _privateProperties.shadowColor, _privateProperties.shadowColor); characterPosition++; } SetAlignment(alignmentPass++); } //Outline if (_privateProperties.enableOutline) { float angleIncrement = 90; if (_privateProperties.highQualityOutline) angleIncrement = 45; for(float ang = 0.0f; ang < 360.0f; ang += angleIncrement) { Vector3 dir = Vector3.right; dir.x = Mathf.Cos(ang * Mathf.Deg2Rad); dir.y = Mathf.Sin(ang * Mathf.Deg2Rad); ResetHelperVariables(); foreach (char iteratorChar in textChars) { CreateCharacter(iteratorChar, characterPosition, dir*_privateProperties.outLineWidth, _privateProperties.outlineColor, _privateProperties.outlineColor); characterPosition++; } SetAlignment(alignmentPass++); } } //Normal text ResetHelperVariables(); foreach (char iteratorChar in textChars) { CreateCharacter(iteratorChar, characterPosition, Vector3.zero, _privateProperties.fontColorTop, _privateProperties.fontColorBottom); characterPosition++; } SetAlignment(alignmentPass++); //Asign mesh data if (textMesh != null) { textMesh.Clear(true); SetAnchor(); textMesh.vertices = vertices; textMesh.uv = uv; //SetUV2(); textMesh.uv2 = uv2; if (_privateProperties.customFillMaterial != null && (_privateProperties.enableShadow || _privateProperties.enableOutline)) SetTrianglesForMultimesh(); else textMesh.triangles = triangles; textMesh.colors = colors; } } void ResetHelperVariables() { lineBreakAccumulatedDistance.Clear(); lineBreakCharCounter.Clear(); currentLineBreak = 0; heightSum = 0; } /// <summary> /// Analizes the text for keycodes and prepare it for rendering. Right now only \n is supported /// </summary> void AnalizeText() { //Test characters for know keycodes bool recheckCharArray = true; while (recheckCharArray) { recheckCharArray = false; for (int i = 0; i < textChars.Length ; i++) { if (textChars[i] == '\\' && i+1 < textChars.Length && textChars[i+1] == 'n') //Check for \n for a line break { char[] tempCharArray = new char[textChars.Length -1]; int k = 0; for (int j = 0; j < textChars.Length ; j++) { if (j == i) { tempCharArray[k] = LINE_BREAK; k++; continue; } else if (j == i+1) //Jump this character { j++; if (j >= textChars.Length) continue; } tempCharArray[k] = textChars[j]; k++; } textChars = tempCharArray; recheckCharArray = true; break; } } } } /// <summary> /// Creates the character. /// </summary> /// <param name='_character'> /// The character to draw /// </param> /// <param name='_arrayPosition'> /// The position in the text /// </param> /// <param name='_offset'> /// Do we have to draw it with an offset? (Used in ourline and shado2) /// </param> /// <param name='_colorTop'> /// _color top. /// </param> /// <param name='_colorBottom'> /// _color bottom. /// </param> void CreateCharacter(char _character, int _arrayPosition, Vector3 _offset, Color _colorTop, Color _colorBottom ) { if (lineBreakAccumulatedDistance.Count == 0) lineBreakAccumulatedDistance.Add(0); if (lineBreakCharCounter.Count == 0) lineBreakCharCounter.Add(0); CharacterInfo charInfo = new CharacterInfo(); if (!_privateProperties.font.GetCharacterInfo(_character,out charInfo,_privateProperties.fontSize)) { lineBreakCharCounter.Add(lineBreakCharCounter[currentLineBreak]); lineBreakAccumulatedDistance.Add(0); currentLineBreak++; return; } lineBreakCharCounter[currentLineBreak]++; //print("Character: " + _character +" Vertex: " + charInfo.vert + "UV: " +charInfo.uv + "Char size: " + charInfo.size + "Char width: " + charInfo.width + " Is flipped: "+ charInfo.flipped); float sizeModifier = _privateProperties.size/_privateProperties.fontSize; _offset *= _privateProperties.size*0.1f; float characterWidth = charInfo.vert.width * sizeModifier; float characterHeight = charInfo.vert.height * sizeModifier; Vector2 betweenLefttersOffset = new Vector2(charInfo.vert.x,charInfo.vert.y)*sizeModifier; //for vertical adjustments if (_character != ' ') //Don't acumulate height if its a space heightSum += (charInfo.vert.y+charInfo.vert.height*0.5f)*sizeModifier; Vector3 currentAcumulatedCharacterDistance = new Vector3(lineBreakAccumulatedDistance[currentLineBreak]*sizeModifier,- _privateProperties.size*currentLineBreak*_privateProperties.lineSpacing,0) ; //Create a quad with the size of the character if (charInfo.flipped == true) { vertices[4*_arrayPosition] = new Vector3(betweenLefttersOffset.x + characterWidth , characterHeight+betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; vertices[4*_arrayPosition+1] = new Vector3(betweenLefttersOffset.x , characterHeight+betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; vertices[4*_arrayPosition+2] = new Vector3(betweenLefttersOffset.x , betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; vertices[4*_arrayPosition+3] = new Vector3(betweenLefttersOffset.x + characterWidth , betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; } else { vertices[4*_arrayPosition] = new Vector3(betweenLefttersOffset.x + characterWidth , characterHeight+betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; vertices[4*_arrayPosition+1] = new Vector3(betweenLefttersOffset.x , characterHeight+betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; vertices[4*_arrayPosition+2] = new Vector3(betweenLefttersOffset.x , betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; vertices[4*_arrayPosition+3] = new Vector3(betweenLefttersOffset.x + characterWidth , betweenLefttersOffset.y , 0 ) + _offset + currentAcumulatedCharacterDistance; } lineBreakAccumulatedDistance[currentLineBreak] += charInfo.width; //Set triangles triangles[6*_arrayPosition] = _arrayPosition*4; triangles[6*_arrayPosition+1] = _arrayPosition*4+1; triangles[6*_arrayPosition+2] = _arrayPosition*4+2; triangles[6*_arrayPosition+3] = _arrayPosition*4; triangles[6*_arrayPosition+4] = _arrayPosition*4+2; triangles[6*_arrayPosition+5] = _arrayPosition*4+3; //Set UVs if (charInfo.flipped == true) { uv[4*_arrayPosition] = new Vector2(charInfo.uv.x,charInfo.uv.y+charInfo.uv.height); uv[4*_arrayPosition+1] = new Vector2(charInfo.uv.x,charInfo.uv.y); uv[4*_arrayPosition+2] = new Vector2(charInfo.uv.x+charInfo.uv.width,charInfo.uv.y); uv[4*_arrayPosition+3] = new Vector2(charInfo.uv.x+charInfo.uv.width,charInfo.uv.y+charInfo.uv.height); } else { uv[4*_arrayPosition] = new Vector2(charInfo.uv.x+charInfo.uv.width,charInfo.uv.y); uv[4*_arrayPosition+1] = new Vector2(charInfo.uv.x,charInfo.uv.y); uv[4*_arrayPosition+2] = new Vector2(charInfo.uv.x,charInfo.uv.y+charInfo.uv.height); uv[4*_arrayPosition+3] = new Vector2(charInfo.uv.x+charInfo.uv.width,charInfo.uv.y+charInfo.uv.height); } //Set uv2 if (_privateProperties.customFillMaterial != null) //Only if we need them { Vector2 uvOffset = new Vector2(_offset.x,_offset.y); Vector2 uvAccumulatedDistance = new Vector2(currentAcumulatedCharacterDistance.x,currentAcumulatedCharacterDistance.y); uv2[4*_arrayPosition] = new Vector2(betweenLefttersOffset.x + characterWidth , characterHeight+betweenLefttersOffset.y) + uvOffset + uvAccumulatedDistance; uv2[4*_arrayPosition+1] = new Vector2(betweenLefttersOffset.x , characterHeight+betweenLefttersOffset.y) + uvOffset + uvAccumulatedDistance; uv2[4*_arrayPosition+2] = new Vector2(betweenLefttersOffset.x , betweenLefttersOffset.y) + uvOffset + uvAccumulatedDistance; uv2[4*_arrayPosition+3] = new Vector2(betweenLefttersOffset.x + characterWidth , betweenLefttersOffset.y) + uvOffset + uvAccumulatedDistance; } //Set colors colors[4*_arrayPosition] = _colorBottom; colors[4*_arrayPosition+1] = _colorBottom; colors[4*_arrayPosition+2] = _colorTop; colors[4*_arrayPosition+3] = _colorTop; } /// <summary> /// Sets the anchor. /// </summary> void SetAnchor() { Vector2 textOffset = Vector2.zero; float maxDistance = 0; for (int i = 0; i< lineBreakAccumulatedDistance.Count; i++) { if (lineBreakAccumulatedDistance[i] > maxDistance) maxDistance = lineBreakAccumulatedDistance[i]; } switch (_privateProperties.textAnchor) { case TEXT_ANCHOR.MiddleLeft: case TEXT_ANCHOR.UpperLeft: case TEXT_ANCHOR.LowerLeft: switch(_privateProperties.textAlignment) { case TEXT_ALIGNMENT.left: textOffset.x = 0; break; case TEXT_ALIGNMENT.right: textOffset.x = maxDistance*_privateProperties.size/_privateProperties.fontSize; break; case TEXT_ALIGNMENT.center: textOffset.x += maxDistance*0.5f*_privateProperties.size/_privateProperties.fontSize; break; } break; case TEXT_ANCHOR.MiddleRight: case TEXT_ANCHOR.UpperRight: case TEXT_ANCHOR.LowerRight: switch(_privateProperties.textAlignment) { case TEXT_ALIGNMENT.left: textOffset.x -= maxDistance*_privateProperties.size/_privateProperties.fontSize; break; case TEXT_ALIGNMENT.right: textOffset.x = 0; break; case TEXT_ALIGNMENT.center: textOffset.x -= maxDistance*0.5f*_privateProperties.size/_privateProperties.fontSize; break; } break; case TEXT_ANCHOR.MiddleCenter: case TEXT_ANCHOR.UpperCenter: case TEXT_ANCHOR.LowerCenter: switch(_privateProperties.textAlignment) { case TEXT_ALIGNMENT.left: textOffset.x -= maxDistance*_privateProperties.size*0.5f/_privateProperties.fontSize; break; case TEXT_ALIGNMENT.right: textOffset.x = maxDistance*0.5f*_privateProperties.size/_privateProperties.fontSize; break; case TEXT_ALIGNMENT.center: textOffset.x = 0; break; } break; } if (_privateProperties.textAnchor == TEXT_ANCHOR.UpperLeft || _privateProperties.textAnchor == TEXT_ANCHOR.UpperRight || _privateProperties.textAnchor == TEXT_ANCHOR.UpperCenter) { textOffset.y = -heightSum/textChars.Length; } else if (_privateProperties.textAnchor == TEXT_ANCHOR.MiddleCenter || _privateProperties.textAnchor == TEXT_ANCHOR.MiddleLeft || _privateProperties.textAnchor == TEXT_ANCHOR.MiddleRight) { textOffset.y = - (heightSum/textChars.Length) + _privateProperties.size*currentLineBreak*_privateProperties.lineSpacing*0.5f; } else if (_privateProperties.textAnchor == TEXT_ANCHOR.LowerLeft || _privateProperties.textAnchor == TEXT_ANCHOR.LowerRight || _privateProperties.textAnchor == TEXT_ANCHOR.LowerCenter) { textOffset.y = -heightSum/textChars.Length + _privateProperties.size*currentLineBreak*_privateProperties.lineSpacing; } for (int i = 0; i<vertices.Length; i++) { vertices[i].x += textOffset.x; vertices[i].y += textOffset.y; } } /// <summary> /// Sets the alignment. /// </summary> /// <param name='_pass'> /// _pass. The pass set what are we drawing (shadow, main, oituline up, outline down...) /// </param> void SetAlignment(int _pass) { //if (lineBreakCharCounter.Count <= 1) //If there is no linebreak alignment does nothing // return; int vertexPassOffset = _pass*textChars.Length*4; // We have to align the outline,shadow and main. float charOffset = 0; for (int i = 0; i<lineBreakCharCounter.Count; i++) { switch (_privateProperties.textAlignment) { case TEXT_ALIGNMENT.left: break; case TEXT_ALIGNMENT.right: charOffset = -lineBreakAccumulatedDistance[i]*_privateProperties.size/_privateProperties.fontSize; break; case TEXT_ALIGNMENT.center: charOffset = -lineBreakAccumulatedDistance[i]*0.5f*_privateProperties.size/_privateProperties.fontSize; break; } int firstCharVertex; if (i == 0) firstCharVertex = 0; else firstCharVertex = lineBreakCharCounter[i-1]*4; int lastCharVertex = lineBreakCharCounter[i]*4-1; for (int j = firstCharVertex+i*4+vertexPassOffset ; j<=lastCharVertex + i*4+vertexPassOffset; j++) // i*4 the "line break" characters are in the char array, so we have to jump them { vertices[j].x += charOffset; } } } /// <summary> /// Sets the triangles for multimesh. This is used for the fill material /// </summary> void SetTrianglesForMultimesh() { int triangleMultiplier = 0; if (_privateProperties.enableOutline && _privateProperties.enableShadow) triangleMultiplier = 5; else if (_privateProperties.enableOutline) triangleMultiplier = 4; else if (_privateProperties.enableShadow) triangleMultiplier = 1; int firstTriangleNormalText = triangleMultiplier*6*textChars.Length; int[] mainTriangleSubmesh = new int[textChars.Length*6]; int k = 0; for (int i = firstTriangleNormalText; i<triangles.Length; i++) { mainTriangleSubmesh[k] = triangles[i]; k++; } k = 0; int styleTextTriangleNumber = textChars.Length*triangleMultiplier*6; int[] secondaryTriangleStyleText = new int[styleTextTriangleNumber]; for (int i = 0; i<styleTextTriangleNumber; i++) { secondaryTriangleStyleText[k] = triangles[i]; k++; } //Asign meshes textMeshFilter.sharedMesh.subMeshCount = 2; textMeshFilter.sharedMesh.SetTriangles(mainTriangleSubmesh, 1); textMeshFilter.sharedMesh.SetTriangles(secondaryTriangleStyleText, 0); } /// <summary> /// Fonts the texure rebuild. /// </summary> void FontTexureRebuild() { RefreshMesh(true); } void OnDisable() { _privateProperties.font.textureRebuildCallback -= FontTexureRebuild; } /// <summary> /// Refreshs the mesh editor. Only used by the custom inspector /// </summary> public void RefreshMeshEditor() { CacheTextVars(); DestroyImmediate(textMesh); textMesh = new Mesh(); //We have to recreate the mesh to avoid problems with mesh references when duplicating objects textMesh.name = GetInstanceID().ToString(); MeshFilter textMeshFilter = GetComponent<MeshFilter>(); if (textMeshFilter != null) { textMeshFilter.sharedMesh = textMesh; if (renderer.sharedMaterial == null) renderer.sharedMaterial = _privateProperties.font.material; RefreshMesh(true); } } public int GetVertexCount() { if (vertices != null) return vertices.Length; else return 0; } void LateUpdate() { #if UNITY_EDITOR if (!Application.isPlaying && GUIChanged == false) return; #endif if (isDirty) { isDirty = false; RefreshMesh(true); } } /// <summary> /// Sets the color hidden. This will not change the values in inspector, but its more efficent for changing vertex colors /// </summary> /// <param name='_topColor'> /// _top color. /// </param> void SetColor(Color _topColor, Color _bottomColor) { #if UNITY_EDITOR if (!Application.isPlaying && GUIChanged == false) return; #endif if (colors == null || textMesh == null) return; int initialVertex = GetInitialVertexToColorize(TEXT_COMPONENT.Main); int j = 0; for (int i = initialVertex; i<GetFinalVertexToColorize(TEXT_COMPONENT.Main); i ++ ) { if (j == 0 || j == 1) colors[i] = _bottomColor; else colors[i] = _topColor; j++; if (j > 3) j = 0; } textMesh.colors = colors; } /// <summary> /// Sets the top and bottom color at the same time /// </summary> /// <param name='_color'> /// _color. /// </param> public void SetColor(Color _color) { if (colors == null || textMesh == null) return; int initalVertex = GetInitialVertexToColorize(TEXT_COMPONENT.Main); for (int i = initalVertex; i<GetFinalVertexToColorize(TEXT_COMPONENT.Main); i ++ ) { colors[i] = _color; } textMesh.colors = colors; } /// <summary> /// Sets the shadow's color /// </summary> /// <param name='_color'> /// _color. /// </param> void SetShadowColor(Color _color) { #if UNITY_EDITOR if (!Application.isPlaying && GUIChanged == false) return; #endif if (colors == null || textMesh == null ) return; int initalVertex = GetInitialVertexToColorize(TEXT_COMPONENT.Shadow); for (int i = initalVertex; i<GetFinalVertexToColorize(TEXT_COMPONENT.Shadow); i ++ ) { colors[i] = _color; } textMesh.colors = colors; } /// <summary> /// Sets the outline colour /// </summary> /// <param name='_color'> /// _color. /// </param> void SetOutlineColor(Color _color) { #if UNITY_EDITOR if (!Application.isPlaying && GUIChanged == false) return; #endif if (colors == null || textMesh == null) return; int initalVertex = GetInitialVertexToColorize(TEXT_COMPONENT.Outline); for (int i = initalVertex; i<GetFinalVertexToColorize(TEXT_COMPONENT.Outline); i ++ ) { colors[i] = _color; } textMesh.colors = colors; } /// <summary> /// Gets the initial vertex to colorize. /// </summary> /// <returns> /// The initial vertex to colorize. /// </returns> /// <param name='_textComponent'> /// _text component. /// </param> private int GetInitialVertexToColorize(TEXT_COMPONENT _textComponent) { if (textChars == null) textChars = _privateProperties.text.ToCharArray(); int meshOptionMultipler = 0; switch (_textComponent) { case TEXT_COMPONENT.Main: if (_privateProperties.enableShadow && _privateProperties.enableOutline) meshOptionMultipler = 5; else if (_privateProperties.enableOutline) meshOptionMultipler = 4; else if (_privateProperties.enableShadow) meshOptionMultipler = 1; break; case TEXT_COMPONENT.Shadow: meshOptionMultipler = 0; break; case TEXT_COMPONENT.Outline: if (_privateProperties.enableShadow) meshOptionMultipler = 1; else meshOptionMultipler = 0; break; } return textChars.Length*4*meshOptionMultipler; } private int GetFinalVertexToColorize(TEXT_COMPONENT _textComponent) { if (textChars == null) textChars = _privateProperties.text.ToCharArray(); int lastVertex = 0; int meshOptionMultipler = 0; switch (_textComponent) { case TEXT_COMPONENT.Main: if (_privateProperties.enableShadow && _privateProperties.enableOutline) meshOptionMultipler = 6; else if (_privateProperties.enableOutline) meshOptionMultipler = 5; else if (_privateProperties.enableShadow) meshOptionMultipler = 2; lastVertex = textChars.Length*4*meshOptionMultipler; break; case TEXT_COMPONENT.Shadow: lastVertex = textChars.Length*4; break; case TEXT_COMPONENT.Outline: if (_privateProperties.enableShadow) meshOptionMultipler = 1; else meshOptionMultipler = 0; lastVertex = textChars.Length*4*(meshOptionMultipler +4); break; } return lastVertex; } void ChangeFont() { #if UNITY_EDITOR if (!Application.isPlaying && GUIChanged == false) return; #endif if (!dontOverrideMaterials && _privateProperties.customFillMaterial == null) { //Material currentMaterial = new Material(textRenderer.sharedMaterial); //currentMaterial.mainTexture = _privateProperties.font.material.mainTexture; //textRenderer.sharedMaterial = currentMaterial; textRenderer.sharedMaterial = _privateProperties.font.material; } isDirty = true; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Timers; using System.Text.RegularExpressions; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.World.AutoBackup { /// <summary> /// Choose between ways of naming the backup files that are generated. /// </summary> /// <remarks>Time: OARs are named by a timestamp. /// Sequential: OARs are named by counting (Region_1.oar, Region_2.oar, etc.) /// Overwrite: Only one file per region is created; it's overwritten each time a backup is made.</remarks> public enum NamingType { Time, Sequential, Overwrite } ///<summary> /// AutoBackupModule: save OAR region backups to disk periodically /// </summary> /// <remarks> /// Config Settings Documentation. /// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini. /// If specified in Regions.ini, the settings should be within the region's section name. /// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section. /// Region-specific settings take precedence. /// /// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis. /// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings! /// AutoBackup: True/False. Default: False. If True, activate auto backup functionality. /// This is the only required option for enabling auto-backup; the other options have sane defaults. /// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored. /// If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality. /// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours). /// The number of minutes between each backup attempt. /// If a negative or zero value is given, it is equivalent to setting AutoBackup = False. /// AutoBackupBusyCheck: True/False. Default: True. /// If True, we will only take an auto-backup if a set of conditions are met. /// These conditions are heuristics to try and avoid taking a backup when the sim is busy. /// AutoBackupScript: String. Default: not specified (disabled). /// File path to an executable script or binary to run when an automatic backup is taken. /// The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary. /// Trying to "run" directories, or things with weird file associations on Win32, might cause unexpected results! /// argv[1] of the executed file/script will be the file name of the generated OAR. /// If the process can't be spawned for some reason (file not found, no execute permission, etc), write a warning to the console. /// AutoBackupNaming: string. Default: Time. /// One of three strings (case insensitive): /// "Time": Current timestamp is appended to file name. An existing file will never be overwritten. /// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten. /// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file. /// AutoBackupDir: String. Default: "." (the current directory). /// A directory (absolute or relative) where backups should be saved. /// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass. /// If the time dilation is below this value, don't take a backup right now. /// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass. /// If the number of agents is greater than this value, don't take a backup right now /// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions. /// Also helps if you don't want AutoBackup at all. /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")] public class AutoBackupModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Dictionary<Guid, IScene> m_pendingSaves = new Dictionary<Guid, IScene>(1); private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState(); private readonly Dictionary<IScene, AutoBackupModuleState> m_states = new Dictionary<IScene, AutoBackupModuleState>(1); private readonly Dictionary<Timer, List<IScene>> m_timerMap = new Dictionary<Timer, List<IScene>>(1); private readonly Dictionary<double, Timer> m_timers = new Dictionary<double, Timer>(1); private delegate T DefaultGetter<T>(string settingName, T defaultValue); private bool m_enabled; /// <summary> /// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState! /// </summary> private bool m_closed; private IConfigSource m_configSource; /// <summary> /// Required by framework. /// </summary> public bool IsSharedModule { get { return true; } } #region ISharedRegionModule Members /// <summary> /// Identifies the module to the system. /// </summary> string IRegionModuleBase.Name { get { return "AutoBackupModule"; } } /// <summary> /// We don't implement an interface, this is a single-use module. /// </summary> Type IRegionModuleBase.ReplaceableInterface { get { return null; } } /// <summary> /// Called once in the lifetime of the module at startup. /// </summary> /// <param name="source">The input config source for OpenSim.ini.</param> void IRegionModuleBase.Initialise(IConfigSource source) { // Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module this.m_configSource = source; IConfig moduleConfig = source.Configs["AutoBackupModule"]; if (moduleConfig == null) { this.m_enabled = false; return; } else { this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false); if (this.m_enabled) { m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled"); } else { return; } } Timer defTimer = new Timer(43200000); this.m_defaultState.Timer = defTimer; this.m_timers.Add(43200000, defTimer); defTimer.Elapsed += this.HandleElapsed; defTimer.AutoReset = true; defTimer.Start(); AutoBackupModuleState abms = this.ParseConfig(null, true); m_log.Debug("[AUTO BACKUP]: Here is the default config:"); m_log.Debug(abms.ToString()); } /// <summary> /// Called once at de-init (sim shutting down). /// </summary> void IRegionModuleBase.Close() { if (!this.m_enabled) { return; } // We don't want any timers firing while the sim's coming down; strange things may happen. this.StopAllTimers(); } /// <summary> /// Currently a no-op for AutoBackup because we have to wait for region to be fully loaded. /// </summary> /// <param name="scene"></param> void IRegionModuleBase.AddRegion(Scene scene) { } /// <summary> /// Here we just clean up some resources and stop the OAR backup (if any) for the given scene. /// </summary> /// <param name="scene">The scene (region) to stop performing AutoBackup on.</param> void IRegionModuleBase.RemoveRegion(Scene scene) { if (!this.m_enabled) { return; } if (this.m_states.ContainsKey(scene)) { AutoBackupModuleState abms = this.m_states[scene]; // Remove this scene out of the timer map list Timer timer = abms.Timer; List<IScene> list = this.m_timerMap[timer]; list.Remove(scene); // Shut down the timer if this was the last scene for the timer if (list.Count == 0) { this.m_timerMap.Remove(timer); this.m_timers.Remove(timer.Interval); timer.Close(); } this.m_states.Remove(scene); } } /// <summary> /// Most interesting/complex code paths in AutoBackup begin here. /// We read lots of Nini config, maybe set a timer, add members to state tracking Dictionaries, etc. /// </summary> /// <param name="scene">The scene to (possibly) perform AutoBackup on.</param> void IRegionModuleBase.RegionLoaded(Scene scene) { if (!this.m_enabled) { return; } // This really ought not to happen, but just in case, let's pretend it didn't... if (scene == null) { return; } AutoBackupModuleState abms = this.ParseConfig(scene, false); m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName); m_log.Debug((abms == null ? "DEFAULT" : abms.ToString())); } /// <summary> /// Currently a no-op. /// </summary> void ISharedRegionModule.PostInitialise() { } #endregion /// <summary> /// Set up internal state for a given scene. Fairly complex code. /// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene. /// </summary> /// <param name="scene">The scene to look at.</param> /// <param name="parseDefault">Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).</param> /// <returns>An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.</returns> private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault) { string sRegionName; string sRegionLabel; // string prepend; AutoBackupModuleState state; if (parseDefault) { sRegionName = null; sRegionLabel = "DEFAULT"; // prepend = ""; state = this.m_defaultState; } else { sRegionName = scene.RegionInfo.RegionName; sRegionLabel = sRegionName; // prepend = sRegionName + "."; state = null; } // Read the config settings and set variables. IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null); IConfig config = this.m_configSource.Configs["AutoBackupModule"]; if (config == null) { // defaultState would be disabled too if the section doesn't exist. state = this.m_defaultState; return state; } bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig); if (state == null && tmpEnabled != this.m_defaultState.Enabled) //Varies from default state { state = new AutoBackupModuleState(); } if (state != null) { state.Enabled = tmpEnabled; } // If you don't want AutoBackup, we stop. if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled)) { return state; } else { m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED."); } // Borrow an existing timer if one exists for the same interval; otherwise, make a new one. double interval = this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes, config, regionConfig) * 60000.0; if (state == null && interval != this.m_defaultState.IntervalMinutes*60000.0) { state = new AutoBackupModuleState(); } if (this.m_timers.ContainsKey(interval)) { if (state != null) { state.Timer = this.m_timers[interval]; } m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " + sRegionLabel); } else { // 0 or negative interval == do nothing. if (interval <= 0.0 && state != null) { state.Enabled = false; return state; } if (state == null) { state = new AutoBackupModuleState(); } Timer tim = new Timer(interval); state.Timer = tim; //Milliseconds -> minutes this.m_timers.Add(interval, tim); tim.Elapsed += this.HandleElapsed; tim.AutoReset = true; tim.Start(); } // Add the current region to the list of regions tied to this timer. if (scene != null) { if (state != null) { if (this.m_timerMap.ContainsKey(state.Timer)) { this.m_timerMap[state.Timer].Add(scene); } else { List<IScene> scns = new List<IScene>(1); scns.Add(scene); this.m_timerMap.Add(state.Timer, scns); } } else { if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer)) { this.m_timerMap[this.m_defaultState.Timer].Add(scene); } else { List<IScene> scns = new List<IScene>(1); scns.Add(scene); this.m_timerMap.Add(this.m_defaultState.Timer, scns); } } } bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck", this.m_defaultState.BusyCheck, config, regionConfig); if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck) { state = new AutoBackupModuleState(); } if (state != null) { state.BusyCheck = tmpBusyCheck; } // Set file naming algorithm string stmpNamingType = ResolveString("AutoBackupNaming", this.m_defaultState.NamingType.ToString(), config, regionConfig); NamingType tmpNamingType; if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase)) { tmpNamingType = NamingType.Time; } else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase)) { tmpNamingType = NamingType.Sequential; } else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase)) { tmpNamingType = NamingType.Overwrite; } else { m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " + stmpNamingType); tmpNamingType = NamingType.Time; } if (state == null && tmpNamingType != this.m_defaultState.NamingType) { state = new AutoBackupModuleState(); } if (state != null) { state.NamingType = tmpNamingType; } string tmpScript = ResolveString("AutoBackupScript", this.m_defaultState.Script, config, regionConfig); if (state == null && tmpScript != this.m_defaultState.Script) { state = new AutoBackupModuleState(); } if (state != null) { state.Script = tmpScript; } string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig); if (state == null && tmpBackupDir != this.m_defaultState.BackupDir) { state = new AutoBackupModuleState(); } if (state != null) { state.BackupDir = tmpBackupDir; // Let's give the user some convenience and auto-mkdir if (state.BackupDir != ".") { try { DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir); if (!dirinfo.Exists) { dirinfo.Create(); } } catch (Exception e) { m_log.Warn( "BAD NEWS. You won't be able to save backups to directory " + state.BackupDir + " because it doesn't exist or there's a permissions issue with it. Here's the exception.", e); } } } return state; } /// <summary> /// Helper function for ParseConfig. /// </summary> /// <param name="settingName"></param> /// <param name="defaultValue"></param> /// <param name="global"></param> /// <param name="local"></param> /// <returns></returns> private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local) { if(local != null) { return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue)); } else { return global.GetBoolean(settingName, defaultValue); } } /// <summary> /// Helper function for ParseConfig. /// </summary> /// <param name="settingName"></param> /// <param name="defaultValue"></param> /// <param name="global"></param> /// <param name="local"></param> /// <returns></returns> private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local) { if (local != null) { return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue)); } else { return global.GetDouble(settingName, defaultValue); } } /// <summary> /// Helper function for ParseConfig. /// </summary> /// <param name="settingName"></param> /// <param name="defaultValue"></param> /// <param name="global"></param> /// <param name="local"></param> /// <returns></returns> private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local) { if (local != null) { return local.GetInt(settingName, global.GetInt(settingName, defaultValue)); } else { return global.GetInt(settingName, defaultValue); } } /// <summary> /// Helper function for ParseConfig. /// </summary> /// <param name="settingName"></param> /// <param name="defaultValue"></param> /// <param name="global"></param> /// <param name="local"></param> /// <returns></returns> private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local) { if (local != null) { return local.GetString(settingName, global.GetString(settingName, defaultValue)); } else { return global.GetString(settingName, defaultValue); } } /// <summary> /// Called when any auto-backup timer expires. This starts the code path for actually performing a backup. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void HandleElapsed(object sender, ElapsedEventArgs e) { // TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region // XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to // check whether the region is too busy! Especially on sims with LOTS of regions. // Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible, // but would allow us to be semantically correct while being easier on perf. // Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi... // Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter. // Since this is pretty experimental, I haven't decided which alternative makes the most sense. if (this.m_closed) { return; } bool heuristicsRun = false; bool heuristicsPassed = false; if (!this.m_timerMap.ContainsKey((Timer) sender)) { m_log.Debug("Code-up error: timerMap doesn't contain timer " + sender); } List<IScene> tmap = this.m_timerMap[(Timer) sender]; if (tmap != null && tmap.Count > 0) { foreach (IScene scene in tmap) { AutoBackupModuleState state = this.m_states[scene]; bool heuristics = state.BusyCheck; // Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region. if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics) { this.DoRegionBackup(scene); // Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off! } else if (heuristicsRun) { m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " + scene.RegionInfo.RegionName + " right now."); continue; // Logical Deduction: heuristics are on but haven't been run } else { heuristicsPassed = this.RunHeuristics(scene); heuristicsRun = true; if (!heuristicsPassed) { m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " + scene.RegionInfo.RegionName + " right now."); continue; } this.DoRegionBackup(scene); } } } } /// <summary> /// Save an OAR, register for the callback for when it's done, then call the AutoBackupScript (if applicable). /// </summary> /// <param name="scene"></param> private void DoRegionBackup(IScene scene) { if (scene.RegionStatus != RegionStatus.Up) { // We won't backup a region that isn't operating normally. m_log.Warn("[AUTO BACKUP]: Not backing up region " + scene.RegionInfo.RegionName + " because its status is " + scene.RegionStatus); return; } AutoBackupModuleState state = this.m_states[scene]; IRegionArchiverModule iram = scene.RequestModuleInterface<IRegionArchiverModule>(); string savePath = BuildOarPath(scene.RegionInfo.RegionName, state.BackupDir, state.NamingType); if (savePath == null) { m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed"); return; } Guid guid = Guid.NewGuid(); m_pendingSaves.Add(guid, scene); state.LiveRequests.Add(guid, savePath); ((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved); iram.ArchiveRegion(savePath, guid, null); } /// <summary> /// Called by the Event Manager when the OnOarFileSaved event is fired. /// </summary> /// <param name="guid"></param> /// <param name="message"></param> void EventManager_OnOarFileSaved(Guid guid, string message) { // Ignore if the OAR save is being done by some other part of the system if (m_pendingSaves.ContainsKey(guid)) { AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])]; ExecuteScript(abms.Script, abms.LiveRequests[guid]); m_pendingSaves.Remove(guid); abms.LiveRequests.Remove(guid); } } /// <summary>This format may turn out to be too unwieldy to keep... /// Besides, that's what ctimes are for. But then how do I name each file uniquely without using a GUID? /// Sequential numbers, right? We support those, too!</summary> private static string GetTimeString() { StringWriter sw = new StringWriter(); sw.Write("_"); DateTime now = DateTime.Now; sw.Write(now.Year); sw.Write("y_"); sw.Write(now.Month); sw.Write("M_"); sw.Write(now.Day); sw.Write("d_"); sw.Write(now.Hour); sw.Write("h_"); sw.Write(now.Minute); sw.Write("m_"); sw.Write(now.Second); sw.Write("s"); sw.Flush(); string output = sw.ToString(); sw.Close(); return output; } /// <summary>Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.</summary> private bool RunHeuristics(IScene region) { try { return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region); } catch (Exception e) { m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e); return false; } } /// <summary> /// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5), /// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR). /// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy". /// </summary> /// <param name="region"></param> /// <returns>Returns true if we're not too busy; false means we've got worse time dilation than the threshold.</returns> private bool RunTimeDilationHeuristic(IScene region) { string regionName = region.RegionInfo.RegionName; return region.TimeDilation >= this.m_configSource.Configs["AutoBackupModule"].GetFloat( regionName + ".AutoBackupDilationThreshold", 0.5f); } /// <summary> /// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10), /// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR). /// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy". /// </summary> /// <param name="region"></param> /// <returns>Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.</returns> private bool RunAgentLimitHeuristic(IScene region) { string regionName = region.RegionInfo.RegionName; try { Scene scene = (Scene) region; // TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful... return scene.GetRootAgentCount() <= this.m_configSource.Configs["AutoBackupModule"].GetInt( regionName + ".AutoBackupAgentThreshold", 10); } catch (InvalidCastException ice) { m_log.Debug( "[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!", ice); return true; // Non-obstructionist safest answer... } } /// <summary> /// Run the script or executable specified by the "AutoBackupScript" config setting. /// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script. /// But there are plenty of other nasty things that can be done with an untrusted OpenSim.ini, such as running high threat level scripting functions. /// </summary> /// <param name="scriptName"></param> /// <param name="savePath"></param> private static void ExecuteScript(string scriptName, string savePath) { // Do nothing if there's no script. if (scriptName == null || scriptName.Length <= 0) { return; } try { FileInfo fi = new FileInfo(scriptName); if (fi.Exists) { ProcessStartInfo psi = new ProcessStartInfo(scriptName); psi.Arguments = savePath; psi.CreateNoWindow = true; Process proc = Process.Start(psi); proc.ErrorDataReceived += HandleProcErrorDataReceived; } } catch (Exception e) { m_log.Warn( "Exception encountered when trying to run script for oar backup " + savePath, e); } } /// <summary> /// Called if a running script process writes to stderr. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void HandleProcErrorDataReceived(object sender, DataReceivedEventArgs e) { m_log.Warn("ExecuteScript hook " + ((Process) sender).ProcessName + " is yacking on stderr: " + e.Data); } /// <summary> /// Quickly stop all timers from firing. /// </summary> private void StopAllTimers() { foreach (Timer t in this.m_timerMap.Keys) { t.Close(); } this.m_closed = true; } /// <summary> /// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType. /// </summary> /// <param name="dirName"></param> /// <param name="regionName"></param> /// <returns></returns> private static string GetNextFile(string dirName, string regionName) { FileInfo uniqueFile = null; long biggestExistingFile = GetNextOarFileNumber(dirName, regionName); biggestExistingFile++; // We don't want to overwrite the biggest existing file; we want to write to the NEXT biggest. uniqueFile = new FileInfo(dirName + Path.DirectorySeparatorChar + regionName + "_" + biggestExistingFile + ".oar"); return uniqueFile.FullName; } /// <summary> /// Top-level method for creating an absolute path to an OAR backup file based on what naming scheme the user wants. /// </summary> /// <param name="regionName">Name of the region to save.</param> /// <param name="baseDir">Absolute or relative path to the directory where the file should reside.</param> /// <param name="naming">The naming scheme for the file name.</param> /// <returns></returns> private static string BuildOarPath(string regionName, string baseDir, NamingType naming) { FileInfo path = null; switch (naming) { case NamingType.Overwrite: path = new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName + ".oar"); return path.FullName; case NamingType.Time: path = new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName + GetTimeString() + ".oar"); return path.FullName; case NamingType.Sequential: // All codepaths in GetNextFile should return a file name ending in .oar path = new FileInfo(GetNextFile(baseDir, regionName)); return path.FullName; default: m_log.Warn("VERY BAD: Unhandled case element " + naming); break; } return null; } /// <summary> /// Helper function for Sequential file naming type (see BuildOarPath and GetNextFile). /// </summary> /// <param name="dirName"></param> /// <param name="regionName"></param> /// <returns></returns> private static long GetNextOarFileNumber(string dirName, string regionName) { long retval = 1; DirectoryInfo di = new DirectoryInfo(dirName); FileInfo[] fi = di.GetFiles(regionName, SearchOption.TopDirectoryOnly); Array.Sort(fi, (f1, f2) => StringComparer.CurrentCultureIgnoreCase.Compare(f1.Name, f2.Name)); if (fi.LongLength > 0) { long subtract = 1L; bool worked = false; Regex reg = new Regex(regionName + "_([0-9])+" + ".oar"); while (!worked && subtract <= fi.LongLength) { // Pick the file with the last natural ordering string biggestFileName = fi[fi.LongLength - subtract].Name; MatchCollection matches = reg.Matches(biggestFileName); long l = 1; if (matches.Count > 0 && matches[0].Groups.Count > 0) { try { long.TryParse(matches[0].Groups[1].Value, out l); retval = l; worked = true; } catch (FormatException fe) { m_log.Warn( "[AUTO BACKUP]: Error: Can't parse long value from file name to determine next OAR backup file number!", fe); subtract++; } } else { subtract++; } } } return retval; } } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; #if CLR_2_0 || CLR_4_0 using System.Collections.Generic; #endif namespace NUnit.Framework.Constraints { #region ConstraintOperator Base Class /// <summary> /// The ConstraintOperator class is used internally by a /// ConstraintBuilder to represent an operator that /// modifies or combines constraints. /// /// Constraint operators use left and right precedence /// values to determine whether the top operator on the /// stack should be reduced before pushing a new operator. /// </summary> public abstract class ConstraintOperator { private object leftContext; private object rightContext; /// <summary> /// The precedence value used when the operator /// is about to be pushed to the stack. /// </summary> protected int left_precedence; /// <summary> /// The precedence value used when the operator /// is on the top of the stack. /// </summary> protected int right_precedence; /// <summary> /// The syntax element preceding this operator /// </summary> public object LeftContext { get { return leftContext; } set { leftContext = value; } } /// <summary> /// The syntax element folowing this operator /// </summary> public object RightContext { get { return rightContext; } set { rightContext = value; } } /// <summary> /// The precedence value used when the operator /// is about to be pushed to the stack. /// </summary> public virtual int LeftPrecedence { get { return left_precedence; } } /// <summary> /// The precedence value used when the operator /// is on the top of the stack. /// </summary> public virtual int RightPrecedence { get { return right_precedence; } } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public abstract void Reduce(ConstraintBuilder.ConstraintStack stack); } #endregion #region Prefix Operators #region PrefixOperator /// <summary> /// PrefixOperator takes a single constraint and modifies /// it's action in some way. /// </summary> public abstract class PrefixOperator : ConstraintOperator { /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { stack.Push(ApplyPrefix(stack.Pop())); } /// <summary> /// Returns the constraint created by applying this /// prefix to another constraint. /// </summary> /// <param name="constraint"></param> /// <returns></returns> public abstract Constraint ApplyPrefix(Constraint constraint); } #endregion #region NotOperator /// <summary> /// Negates the test of the constraint it wraps. /// </summary> public class NotOperator : PrefixOperator { /// <summary> /// Constructs a new NotOperator /// </summary> public NotOperator() { // Not stacks on anything and only allows other // prefix ops to stack on top of it. this.left_precedence = this.right_precedence = 1; } /// <summary> /// Returns a NotConstraint applied to its argument. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new NotConstraint(constraint); } } #endregion #region Collection Operators /// <summary> /// Abstract base for operators that indicate how to /// apply a constraint to items in a collection. /// </summary> public abstract class CollectionOperator : PrefixOperator { /// <summary> /// Constructs a CollectionOperator /// </summary> public CollectionOperator() { // Collection Operators stack on everything // and allow all other ops to stack on them this.left_precedence = 1; this.right_precedence = 10; } } /// <summary> /// Represents a constraint that succeeds if all the /// members of a collection match a base constraint. /// </summary> public class AllOperator : CollectionOperator { /// <summary> /// Returns a constraint that will apply the argument /// to the members of a collection, succeeding if /// they all succeed. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new AllItemsConstraint(constraint); } } /// <summary> /// Represents a constraint that succeeds if any of the /// members of a collection match a base constraint. /// </summary> public class SomeOperator : CollectionOperator { /// <summary> /// Returns a constraint that will apply the argument /// to the members of a collection, succeeding if /// any of them succeed. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new SomeItemsConstraint(constraint); } } /// <summary> /// Represents a constraint that succeeds if none of the /// members of a collection match a base constraint. /// </summary> public class NoneOperator : CollectionOperator { /// <summary> /// Returns a constraint that will apply the argument /// to the members of a collection, succeeding if /// none of them succeed. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new NoItemConstraint(constraint); } } /// <summary> /// Represents a constraint that succeeds if the specified /// count of members of a collection match a base constraint. /// </summary> public class ExactCountOperator : CollectionOperator { private int expectedCount; /// <summary> /// Construct an ExactCountOperator for a specified count /// </summary> /// <param name="expectedCount">The expected count</param> public ExactCountOperator(int expectedCount) { this.expectedCount = expectedCount; } /// <summary> /// Returns a constraint that will apply the argument /// to the members of a collection, succeeding if /// none of them succeed. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new ExactCountConstraint(expectedCount, constraint); } } #endregion #region WithOperator /// <summary> /// Represents a constraint that simply wraps the /// constraint provided as an argument, without any /// further functionality, but which modifes the /// order of evaluation because of its precedence. /// </summary> public class WithOperator : PrefixOperator { /// <summary> /// Constructor for the WithOperator /// </summary> public WithOperator() { this.left_precedence = 1; this.right_precedence = 4; } /// <summary> /// Returns a constraint that wraps its argument /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return constraint; } } #endregion #region SelfResolving Operators #region SelfResolvingOperator /// <summary> /// Abstract base class for operators that are able to reduce to a /// constraint whether or not another syntactic element follows. /// </summary> public abstract class SelfResolvingOperator : ConstraintOperator { } #endregion #region PropOperator /// <summary> /// Operator used to test for the presence of a named Property /// on an object and optionally apply further tests to the /// value of that property. /// </summary> public class PropOperator : SelfResolvingOperator { private string name; /// <summary> /// Gets the name of the property to which the operator applies /// </summary> public string Name { get { return name; } } /// <summary> /// Constructs a PropOperator for a particular named property /// </summary> public PropOperator(string name) { this.name = name; // Prop stacks on anything and allows only // prefix operators to stack on it. this.left_precedence = this.right_precedence = 1; } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { if (RightContext == null || RightContext is BinaryOperator) stack.Push(new PropertyExistsConstraint(name)); else stack.Push(new PropertyConstraint(name, stack.Pop())); } } #endregion #region AttributeOperator /// <summary> /// Operator that tests for the presence of a particular attribute /// on a type and optionally applies further tests to the attribute. /// </summary> public class AttributeOperator : SelfResolvingOperator { private Type type; /// <summary> /// Construct an AttributeOperator for a particular Type /// </summary> /// <param name="type">The Type of attribute tested</param> public AttributeOperator(Type type) { this.type = type; // Attribute stacks on anything and allows only // prefix operators to stack on it. this.left_precedence = this.right_precedence = 1; } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { if (RightContext == null || RightContext is BinaryOperator) stack.Push(new AttributeExistsConstraint(type)); else stack.Push(new AttributeConstraint(type, stack.Pop())); } } #endregion #region ThrowsOperator /// <summary> /// Operator that tests that an exception is thrown and /// optionally applies further tests to the exception. /// </summary> public class ThrowsOperator : SelfResolvingOperator { /// <summary> /// Construct a ThrowsOperator /// </summary> public ThrowsOperator() { // ThrowsOperator stacks on everything but // it's always the first item on the stack // anyway. It is evaluated last of all ops. this.left_precedence = 1; this.right_precedence = 100; } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { if (RightContext == null || RightContext is BinaryOperator) stack.Push(new ThrowsConstraint(null)); else stack.Push(new ThrowsConstraint(stack.Pop())); } } #endregion #endregion #endregion #region Binary Operators #region BinaryOperator /// <summary> /// Abstract base class for all binary operators /// </summary> public abstract class BinaryOperator : ConstraintOperator { /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { Constraint right = stack.Pop(); Constraint left = stack.Pop(); stack.Push(ApplyOperator(left, right)); } /// <summary> /// Gets the left precedence of the operator /// </summary> public override int LeftPrecedence { get { return RightContext is CollectionOperator ? base.LeftPrecedence + 10 : base.LeftPrecedence; } } /// <summary> /// Gets the right precedence of the operator /// </summary> public override int RightPrecedence { get { return RightContext is CollectionOperator ? base.RightPrecedence + 10 : base.RightPrecedence; } } /// <summary> /// Abstract method that produces a constraint by applying /// the operator to its left and right constraint arguments. /// </summary> public abstract Constraint ApplyOperator(Constraint left, Constraint right); } #endregion #region AndOperator /// <summary> /// Operator that requires both it's arguments to succeed /// </summary> public class AndOperator : BinaryOperator { /// <summary> /// Construct an AndOperator /// </summary> public AndOperator() { this.left_precedence = this.right_precedence = 2; } /// <summary> /// Apply the operator to produce an AndConstraint /// </summary> public override Constraint ApplyOperator(Constraint left, Constraint right) { return new AndConstraint(left, right); } } #endregion #region OrOperator /// <summary> /// Operator that requires at least one of it's arguments to succeed /// </summary> public class OrOperator : BinaryOperator { /// <summary> /// Construct an OrOperator /// </summary> public OrOperator() { this.left_precedence = this.right_precedence = 3; } /// <summary> /// Apply the operator to produce an OrConstraint /// </summary> public override Constraint ApplyOperator(Constraint left, Constraint right) { return new OrConstraint(left, right); } } #endregion #endregion }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Development; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Performance; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.IO.Stores; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Database; using osu.Game.Graphics; using osu.Game.Graphics.Cursor; using osu.Game.Input; using osu.Game.Input.Bindings; using osu.Game.IO; using osu.Game.Online; using osu.Game.Online.API; using osu.Game.Online.Chat; using osu.Game.Online.Multiplayer; using osu.Game.Online.Spectator; using osu.Game.Overlays; using osu.Game.Resources; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Scoring; using osu.Game.Skinning; using osu.Game.Utils; using RuntimeInfo = osu.Framework.RuntimeInfo; namespace osu.Game { /// <summary> /// The most basic <see cref="Game"/> that can be used to host osu! components and systems. /// Unlike <see cref="OsuGame"/>, this class will not load any kind of UI, allowing it to be used /// for provide dependencies to test cases without interfering with them. /// </summary> public partial class OsuGameBase : Framework.Game, ICanAcceptFiles { public const string CLIENT_STREAM_NAME = @"lazer"; public const int SAMPLE_CONCURRENCY = 6; /// <summary> /// Length of debounce (in milliseconds) for commonly occuring sample playbacks that could stack. /// </summary> public const int SAMPLE_DEBOUNCE_TIME = 20; /// <summary> /// The maximum volume at which audio tracks should playback. This can be set lower than 1 to create some head-room for sound effects. /// </summary> internal const double GLOBAL_TRACK_VOLUME_ADJUST = 0.8; public bool UseDevelopmentServer { get; } public virtual Version AssemblyVersion => Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(); /// <summary> /// MD5 representation of the game executable. /// </summary> public string VersionHash { get; private set; } public bool IsDeployedBuild => AssemblyVersion.Major > 0; public virtual string Version { get { if (!IsDeployedBuild) return @"local " + (DebugUtils.IsDebugBuild ? @"debug" : @"release"); var version = AssemblyVersion; return $@"{version.Major}.{version.Minor}.{version.Build}-lazer"; } } protected OsuConfigManager LocalConfig { get; private set; } protected SessionStatics SessionStatics { get; private set; } protected BeatmapManager BeatmapManager { get; private set; } protected ScoreManager ScoreManager { get; private set; } protected SkinManager SkinManager { get; private set; } protected RulesetStore RulesetStore { get; private set; } protected RealmKeyBindingStore KeyBindingStore { get; private set; } protected MenuCursorContainer MenuCursorContainer { get; private set; } protected MusicController MusicController { get; private set; } protected IAPIProvider API { get; set; } protected Storage Storage { get; set; } protected Bindable<WorkingBeatmap> Beatmap { get; private set; } // cached via load() method [Cached] [Cached(typeof(IBindable<RulesetInfo>))] protected readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>(); /// <summary> /// The current mod selection for the local user. /// </summary> /// <remarks> /// If a mod select overlay is present, mod instances set to this value are not guaranteed to remain as the provided instance and will be overwritten by a copy. /// In such a case, changes to settings of a mod will *not* propagate after a mod is added to this collection. /// As such, all settings should be finalised before adding a mod to this collection. /// </remarks> [Cached] [Cached(typeof(IBindable<IReadOnlyList<Mod>>))] protected readonly Bindable<IReadOnlyList<Mod>> SelectedMods = new Bindable<IReadOnlyList<Mod>>(Array.Empty<Mod>()); /// <summary> /// Mods available for the current <see cref="Ruleset"/>. /// </summary> public readonly Bindable<Dictionary<ModType, IReadOnlyList<Mod>>> AvailableMods = new Bindable<Dictionary<ModType, IReadOnlyList<Mod>>>(); private BeatmapDifficultyCache difficultyCache; private UserLookupCache userCache; private FileStore fileStore; private RulesetConfigCache rulesetConfigCache; private SpectatorClient spectatorClient; private MultiplayerClient multiplayerClient; private DatabaseContextFactory contextFactory; private RealmContextFactory realmFactory; protected override Container<Drawable> Content => content; private Container content; private DependencyContainer dependencies; private Bindable<bool> fpsDisplayVisible; private readonly BindableNumber<double> globalTrackVolumeAdjust = new BindableNumber<double>(GLOBAL_TRACK_VOLUME_ADJUST); public OsuGameBase() { UseDevelopmentServer = DebugUtils.IsDebugBuild; Name = @"osu!"; } [BackgroundDependencyLoader] private void load() { try { using (var str = File.OpenRead(typeof(OsuGameBase).Assembly.Location)) VersionHash = str.ComputeMD5Hash(); } catch { // special case for android builds, which can't read DLLs from a packed apk. // should eventually be handled in a better way. VersionHash = $"{Version}-{RuntimeInfo.OS}".ComputeMD5Hash(); } Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly)); dependencies.Cache(contextFactory = new DatabaseContextFactory(Storage)); dependencies.Cache(realmFactory = new RealmContextFactory(Storage, "client")); dependencies.CacheAs(Storage); var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures"))); largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore())); dependencies.Cache(largeStore); dependencies.CacheAs(this); dependencies.CacheAs(LocalConfig); InitialiseFonts(); Audio.Samples.PlaybackConcurrency = SAMPLE_CONCURRENCY; runMigrations(); dependencies.Cache(SkinManager = new SkinManager(Storage, contextFactory, Host, Resources, Audio)); dependencies.CacheAs<ISkinSource>(SkinManager); // needs to be done here rather than inside SkinManager to ensure thread safety of CurrentSkinInfo. SkinManager.ItemRemoved.BindValueChanged(weakRemovedInfo => { if (weakRemovedInfo.NewValue.TryGetTarget(out var removedInfo)) { Schedule(() => { // check the removed skin is not the current user choice. if it is, switch back to default. if (removedInfo.ID == SkinManager.CurrentSkinInfo.Value.ID) SkinManager.CurrentSkinInfo.Value = SkinInfo.Default; }); } }); EndpointConfiguration endpoints = UseDevelopmentServer ? (EndpointConfiguration)new DevelopmentEndpointConfiguration() : new ProductionEndpointConfiguration(); MessageFormatter.WebsiteRootUrl = endpoints.WebsiteRootUrl; dependencies.CacheAs(API ??= new APIAccess(LocalConfig, endpoints, VersionHash)); dependencies.CacheAs(spectatorClient = new OnlineSpectatorClient(endpoints)); dependencies.CacheAs(multiplayerClient = new OnlineMultiplayerClient(endpoints)); var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures); dependencies.Cache(RulesetStore = new RulesetStore(contextFactory, Storage)); dependencies.Cache(fileStore = new FileStore(contextFactory, Storage)); // ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup() dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, API, contextFactory, Scheduler, Host, () => difficultyCache, LocalConfig)); dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, contextFactory, RulesetStore, API, Audio, Resources, Host, defaultBeatmap, performOnlineLookups: true)); // this should likely be moved to ArchiveModelManager when another case appears where it is necessary // to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to // allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete. List<ScoreInfo> getBeatmapScores(BeatmapSetInfo set) { var beatmapIds = BeatmapManager.QueryBeatmaps(b => b.BeatmapSetInfoID == set.ID).Select(b => b.ID).ToList(); return ScoreManager.QueryScores(s => beatmapIds.Contains(s.BeatmapInfo.ID)).ToList(); } BeatmapManager.ItemRemoved.BindValueChanged(i => { if (i.NewValue.TryGetTarget(out var item)) ScoreManager.Delete(getBeatmapScores(item), true); }); BeatmapManager.ItemUpdated.BindValueChanged(i => { if (i.NewValue.TryGetTarget(out var item)) ScoreManager.Undelete(getBeatmapScores(item), true); }); dependencies.Cache(difficultyCache = new BeatmapDifficultyCache()); AddInternal(difficultyCache); dependencies.Cache(userCache = new UserLookupCache()); AddInternal(userCache); var scorePerformanceManager = new ScorePerformanceCache(); dependencies.Cache(scorePerformanceManager); AddInternal(scorePerformanceManager); migrateDataToRealm(); dependencies.Cache(rulesetConfigCache = new RulesetConfigCache(realmFactory, RulesetStore)); var powerStatus = CreateBatteryInfo(); if (powerStatus != null) dependencies.CacheAs(powerStatus); dependencies.Cache(SessionStatics = new SessionStatics()); dependencies.Cache(new OsuColour()); RegisterImportHandler(BeatmapManager); RegisterImportHandler(ScoreManager); RegisterImportHandler(SkinManager); // drop track volume game-wide to leave some head-room for UI effects / samples. // this means that for the time being, gameplay sample playback is louder relative to the audio track, compared to stable. // we may want to revisit this if users notice or complain about the difference (consider this a bit of a trial). Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, globalTrackVolumeAdjust); Beatmap = new NonNullableBindable<WorkingBeatmap>(defaultBeatmap); dependencies.CacheAs<IBindable<WorkingBeatmap>>(Beatmap); dependencies.CacheAs(Beatmap); fileStore.Cleanup(); // add api components to hierarchy. if (API is APIAccess apiAccess) AddInternal(apiAccess); AddInternal(spectatorClient); AddInternal(multiplayerClient); AddInternal(rulesetConfigCache); GlobalActionContainer globalBindings; var mainContent = new Drawable[] { MenuCursorContainer = new MenuCursorContainer { RelativeSizeAxes = Axes.Both }, // to avoid positional input being blocked by children, ensure the GlobalActionContainer is above everything. globalBindings = new GlobalActionContainer(this) }; MenuCursorContainer.Child = content = new OsuTooltipContainer(MenuCursorContainer.Cursor) { RelativeSizeAxes = Axes.Both }; base.Content.Add(CreateScalingContainer().WithChildren(mainContent)); KeyBindingStore = new RealmKeyBindingStore(realmFactory); KeyBindingStore.Register(globalBindings, RulesetStore.AvailableRulesets); dependencies.Cache(globalBindings); PreviewTrackManager previewTrackManager; dependencies.Cache(previewTrackManager = new PreviewTrackManager()); Add(previewTrackManager); AddInternal(MusicController = new MusicController()); dependencies.CacheAs(MusicController); Ruleset.BindValueChanged(onRulesetChanged); } protected virtual void InitialiseFonts() { AddFont(Resources, @"Fonts/osuFont"); AddFont(Resources, @"Fonts/Torus/Torus-Regular"); AddFont(Resources, @"Fonts/Torus/Torus-Light"); AddFont(Resources, @"Fonts/Torus/Torus-SemiBold"); AddFont(Resources, @"Fonts/Torus/Torus-Bold"); AddFont(Resources, @"Fonts/Torus-Alternate/Torus-Alternate-Regular"); AddFont(Resources, @"Fonts/Torus-Alternate/Torus-Alternate-Light"); AddFont(Resources, @"Fonts/Torus-Alternate/Torus-Alternate-SemiBold"); AddFont(Resources, @"Fonts/Torus-Alternate/Torus-Alternate-Bold"); AddFont(Resources, @"Fonts/Inter/Inter-Regular"); AddFont(Resources, @"Fonts/Inter/Inter-RegularItalic"); AddFont(Resources, @"Fonts/Inter/Inter-Light"); AddFont(Resources, @"Fonts/Inter/Inter-LightItalic"); AddFont(Resources, @"Fonts/Inter/Inter-SemiBold"); AddFont(Resources, @"Fonts/Inter/Inter-SemiBoldItalic"); AddFont(Resources, @"Fonts/Inter/Inter-Bold"); AddFont(Resources, @"Fonts/Inter/Inter-BoldItalic"); AddFont(Resources, @"Fonts/Noto/Noto-Basic"); AddFont(Resources, @"Fonts/Noto/Noto-Hangul"); AddFont(Resources, @"Fonts/Noto/Noto-CJK-Basic"); AddFont(Resources, @"Fonts/Noto/Noto-CJK-Compatibility"); AddFont(Resources, @"Fonts/Noto/Noto-Thai"); AddFont(Resources, @"Fonts/Venera/Venera-Light"); AddFont(Resources, @"Fonts/Venera/Venera-Bold"); AddFont(Resources, @"Fonts/Venera/Venera-Black"); } protected override void LoadComplete() { base.LoadComplete(); // TODO: This is temporary until we reimplement the local FPS display. // It's just to allow end-users to access the framework FPS display without knowing the shortcut key. fpsDisplayVisible = LocalConfig.GetBindable<bool>(OsuSetting.ShowFpsDisplay); fpsDisplayVisible.ValueChanged += visible => { FrameStatistics.Value = visible.NewValue ? FrameStatisticsMode.Minimal : FrameStatisticsMode.None; }; fpsDisplayVisible.TriggerChange(); FrameStatistics.ValueChanged += e => fpsDisplayVisible.Value = e.NewValue != FrameStatisticsMode.None; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); public override void SetHost(GameHost host) { base.SetHost(host); // may be non-null for certain tests Storage ??= host.Storage; LocalConfig ??= UseDevelopmentServer ? new DevelopmentOsuConfigManager(Storage) : new OsuConfigManager(Storage); } /// <summary> /// Use to programatically exit the game as if the user was triggering via alt-f4. /// Will keep persisting until an exit occurs (exit may be blocked multiple times). /// </summary> public void GracefullyExit() { if (!OnExiting()) Exit(); else Scheduler.AddDelayed(GracefullyExit, 2000); } public void Migrate(string path) { Logger.Log($@"Migrating osu! data from ""{Storage.GetFullPath(string.Empty)}"" to ""{path}""..."); IDisposable realmBlocker = null; try { ManualResetEventSlim readyToRun = new ManualResetEventSlim(); Scheduler.Add(() => { realmBlocker = realmFactory.BlockAllOperations(); contextFactory.FlushConnections(); readyToRun.Set(); }, false); readyToRun.Wait(); (Storage as OsuStorage)?.Migrate(Host.GetStorage(path)); } finally { realmBlocker?.Dispose(); } Logger.Log(@"Migration complete!"); } protected override UserInputManager CreateUserInputManager() => new OsuUserInputManager(); protected virtual BatteryInfo CreateBatteryInfo() => null; protected virtual Container CreateScalingContainer() => new DrawSizePreservingFillContainer(); protected override Storage CreateStorage(GameHost host, Storage defaultStorage) => new OsuStorage(host, defaultStorage); private void migrateDataToRealm() { using (var db = contextFactory.GetForWrite()) using (var realm = realmFactory.CreateContext()) using (var transaction = realm.BeginWrite()) { // migrate ruleset settings. can be removed 20220315. var existingSettings = db.Context.DatabasedSetting; // only migrate data if the realm database is empty. if (!realm.All<RealmRulesetSetting>().Any()) { foreach (var dkb in existingSettings) { if (dkb.RulesetID == null) continue; realm.Add(new RealmRulesetSetting { Key = dkb.Key, Value = dkb.StringValue, RulesetID = dkb.RulesetID.Value, Variant = dkb.Variant ?? 0, }); } } db.Context.RemoveRange(existingSettings); transaction.Commit(); } } private void onRulesetChanged(ValueChangedEvent<RulesetInfo> r) { if (r.NewValue?.Available != true) { // reject the change if the ruleset is not available. Ruleset.Value = r.OldValue?.Available == true ? r.OldValue : RulesetStore.AvailableRulesets.First(); return; } var dict = new Dictionary<ModType, IReadOnlyList<Mod>>(); foreach (ModType type in Enum.GetValues(typeof(ModType))) dict[type] = r.NewValue.CreateInstance().GetModsFor(type).ToList(); if (!SelectedMods.Disabled) SelectedMods.Value = Array.Empty<Mod>(); AvailableMods.Value = dict; } private void runMigrations() { try { using (var db = contextFactory.GetForWrite(false)) db.Context.Migrate(); } catch (Exception e) { Logger.Error(e.InnerException ?? e, "Migration failed! We'll be starting with a fresh database.", LoggingTarget.Database); // if we failed, let's delete the database and start fresh. // todo: we probably want a better (non-destructive) migrations/recovery process at a later point than this. contextFactory.ResetDatabase(); Logger.Log("Database purged successfully.", LoggingTarget.Database); // only run once more, then hard bail. using (var db = contextFactory.GetForWrite(false)) db.Context.Migrate(); } } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); RulesetStore?.Dispose(); BeatmapManager?.Dispose(); LocalConfig?.Dispose(); contextFactory?.FlushConnections(); realmFactory?.Dispose(); } } }
// // MimeEntity.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2012 Jeffrey Stedfast // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Linq; using System.Threading; using System.Reflection; using System.Collections.Generic; using MimeKit.Cryptography; using MimeKit.Utils; namespace MimeKit { /// <summary> /// An abstract MIME entity. /// </summary> public abstract class MimeEntity { static readonly Dictionary<string, ConstructorInfo> CustomMimeTypes = new Dictionary<string, ConstructorInfo> (); static readonly Type[] ConstructorArgTypes = new Type[] { typeof (MimeEntityConstructorInfo) }; ContentDisposition disposition; string contentId; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MimeEntity"/> class /// based on the <see cref="MimeEntityConstructorInfo"/>. /// </summary> /// <param name="entity">Information used by the constructor.</param> /// <remarks> /// Custom <see cref="MimeEntity"/> subclasses MUST implement this constructor /// in order to register it using <see cref="MimeEntity.Register"/>. /// </remarks> protected MimeEntity (MimeEntityConstructorInfo entity) { if (entity == null) throw new ArgumentNullException ("entity"); Headers = new HeaderList (entity.ParserOptions); ContentType = entity.ContentType; ContentType.Changed += ContentTypeChanged; Headers.Changed += HeadersChanged; IsInitializing = true; foreach (var header in entity.Headers) { if (entity.IsTopLevel && !header.Field.StartsWith ("Content-", StringComparison.OrdinalIgnoreCase)) continue; Headers.Add (header); } IsInitializing = false; } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MimeEntity"/> class. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="mediaSubtype">The media subtype.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mediaType"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="mediaSubtype"/> is <c>null</c>.</para> /// </exception> protected MimeEntity (string mediaType, string mediaSubtype) { ContentType = new ContentType (mediaType, mediaSubtype); Headers = new HeaderList (); ContentType.Changed += ContentTypeChanged; Headers.Changed += HeadersChanged; SerializeContentType (); } /// <summary> /// Try to use given object to initialize itself. /// </summary> /// <param name="obj">The object.</param> /// <returns><c>true</c> if the object was recognized and used; <c>false</c> otherwise.</returns> protected bool TryInit (object obj) { // The base MimeEntity class only knows about Headers. var header = obj as Header; if (header != null) { Headers.Add (header); return true; } var headers = obj as IEnumerable<Header>; if (headers != null) { foreach (Header h in headers) Headers.Add (h); return true; } return false; } /// <summary> /// Gets a value indicating whether this instance is initializing. /// </summary> /// <value><c>true</c> if this instance is initializing; otherwise, <c>false</c>.</value> protected bool IsInitializing { get; private set; } /// <summary> /// Gets the list of headers. /// </summary> /// <value>The list of headers.</value> public HeaderList Headers { get; private set; } /// <summary> /// Gets or sets the content disposition. /// </summary> /// <value>The content disposition.</value> public ContentDisposition ContentDisposition { get { return disposition; } set { if (disposition == value) return; if (disposition != null) { disposition.Changed -= ContentDispositionChanged; RemoveHeader ("Content-Disposition"); } disposition = value; if (disposition != null) { disposition.Changed += ContentDispositionChanged; SerializeContentDisposition (); } OnChanged (); } } /// <summary> /// Gets the type of the content. /// </summary> /// <value>The type of the content.</value> public ContentType ContentType { get; private set; } /// <summary> /// Gets or sets the content identifier. /// </summary> /// <value>The content identifier.</value> public string ContentId { get { return contentId; } set { if (contentId == value) return; if (value == null) { RemoveHeader ("Content-Id"); contentId = null; return; } var buffer = Encoding.ASCII.GetBytes (value); InternetAddress addr; int index = 0; if (!InternetAddress.TryParse (Headers.Options, buffer, ref index, buffer.Length, false, out addr) || !(addr is MailboxAddress)) throw new ArgumentException ("Invalid Content-Id format."); contentId = "<" + ((MailboxAddress) addr).Address + ">"; SetHeader ("Content-Id", contentId); } } /// <summary> /// Writes the <see cref="MimeKit.MimeEntity"/> to the specified output stream. /// </summary> /// <param name="options">The formatting options.</param> /// <param name="stream">The output stream.</param> /// <param name="token">A cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public virtual void WriteTo (FormatOptions options, Stream stream, CancellationToken token) { if (options.WriteHeaders) Headers.WriteTo (options, stream, token); else options.WriteHeaders = true; stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length); } /// <summary> /// Writes the <see cref="MimeKit.MimeEntity"/> to the specified output stream. /// </summary> /// <param name="options">The formatting options.</param> /// <param name="stream">The output stream.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public void WriteTo (FormatOptions options, Stream stream) { WriteTo (options, stream, CancellationToken.None); } /// <summary> /// Writes the <see cref="MimeKit.MimeEntity"/> to the specified output stream. /// </summary> /// <param name="stream">The output stream.</param> /// <param name="token">A cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public void WriteTo (Stream stream, CancellationToken token) { WriteTo (FormatOptions.Default, stream, token); } /// <summary> /// Writes the <see cref="MimeKit.MimeEntity"/> to the specified output stream. /// </summary> /// <param name="stream">The output stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public void WriteTo (Stream stream) { WriteTo (FormatOptions.Default, stream); } /// <summary> /// Removes the header. /// </summary> /// <param name="name">The name of the header.</param> protected void RemoveHeader (string name) { Headers.Changed -= HeadersChanged; Headers.RemoveAll (name); Headers.Changed += HeadersChanged; } /// <summary> /// Sets the header. /// </summary> /// <param name="name">The name of the header.</param> /// <param name="value">The value of the header.</param> protected void SetHeader (string name, string value) { Headers.Changed -= HeadersChanged; Headers[name] = value; Headers.Changed += HeadersChanged; } /// <summary> /// Sets the header using the raw value. /// </summary> /// <param name="name">The name of the header.</param> /// <param name="rawValue">The raw value of the header.</param> protected void SetHeader (string name, byte[] rawValue) { Header header = new Header (Headers.Options, name, rawValue); Headers.Changed -= HeadersChanged; Headers.Replace (header); Headers.Changed += HeadersChanged; } void SerializeContentDisposition () { var text = disposition.Encode (FormatOptions.Default, Encoding.UTF8); var raw = Encoding.ASCII.GetBytes (text); SetHeader ("Content-Disposition", raw); } void SerializeContentType () { var text = ContentType.Encode (FormatOptions.Default, Encoding.UTF8); var raw = Encoding.ASCII.GetBytes (text); SetHeader ("Content-Type", raw); } void ContentDispositionChanged (object sender, EventArgs e) { Headers.Changed -= HeadersChanged; SerializeContentDisposition (); Headers.Changed += HeadersChanged; OnChanged (); } void ContentTypeChanged (object sender, EventArgs e) { Headers.Changed -= HeadersChanged; SerializeContentType (); Headers.Changed += HeadersChanged; OnChanged (); } /// <summary> /// Called when the headers change in some way. /// </summary> /// <param name="action">The type of change.</param> /// <param name="header">The header being added, changed or removed.</param> protected virtual void OnHeadersChanged (HeaderListChangedAction action, Header header) { switch (action) { case HeaderListChangedAction.Added: case HeaderListChangedAction.Changed: switch (header.Id) { case HeaderId.ContentDisposition: if (disposition != null) disposition.Changed -= ContentDispositionChanged; if (ContentDisposition.TryParse (Headers.Options, header.RawValue, out disposition)) disposition.Changed += ContentDispositionChanged; break; case HeaderId.ContentId: contentId = MimeUtils.EnumerateReferences (header.RawValue, 0, header.RawValue.Length).FirstOrDefault (); break; } break; case HeaderListChangedAction.Removed: switch (header.Id) { case HeaderId.ContentDisposition: if (disposition != null) disposition.Changed -= ContentDispositionChanged; disposition = null; break; case HeaderId.ContentId: contentId = null; break; } break; case HeaderListChangedAction.Cleared: if (disposition != null) disposition.Changed -= ContentDispositionChanged; disposition = null; contentId = null; break; default: throw new ArgumentOutOfRangeException (); } } void HeadersChanged (object sender, HeaderListChangedEventArgs e) { OnHeadersChanged (e.Action, e.Header); OnChanged (); } internal event EventHandler Changed; /// <summary> /// Raises the changed event. /// </summary> protected void OnChanged () { if (Changed != null) Changed (this, EventArgs.Empty); } /// <summary> /// Load a <see cref="MimeEntity"/> from the specified stream. /// </summary> /// <returns>The parsed MIME entity.</returns> /// <param name="options">The parser options.</param> /// <param name="stream">The stream.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// </exception> public static MimeEntity Load (ParserOptions options, Stream stream) { if (options == null) throw new ArgumentNullException ("options"); if (stream == null) throw new ArgumentNullException ("stream"); var parser = new MimeParser (options, stream, MimeFormat.Entity); return parser.ParseEntity (); } /// <summary> /// Load a <see cref="MimeEntity"/> from the specified stream. /// </summary> /// <returns>The parsed MIME entity.</returns> /// <param name="stream">The stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> public static MimeEntity Load (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); var parser = new MimeParser (stream, MimeFormat.Entity); return parser.ParseEntity (); } /// <summary> /// Load a <see cref="MimeEntity"/> from the specified file. /// </summary> /// <returns>The parsed entity.</returns> /// <param name="options">The parser options.</param> /// <param name="fileName">The name of the file to load.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="fileName"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// The specified file path is empty. /// </exception> /// <exception cref="System.IO.FileNotFoundException"> /// The specified file could not be found. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to read the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the file. /// </exception> public static MimeEntity Load (ParserOptions options, string fileName) { if (options == null) throw new ArgumentNullException ("options"); if (fileName == null) throw new ArgumentNullException ("fileName"); using (var stream = File.OpenRead (fileName)) { return Load (options, stream); } } /// <summary> /// Load a <see cref="MimeEntity"/> from the specified file. /// </summary> /// <returns>The parsed entity.</returns> /// <param name="fileName">The name of the file to load.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="fileName"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// The specified file path is empty. /// </exception> /// <exception cref="System.IO.FileNotFoundException"> /// The specified file could not be found. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to read the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the file. /// </exception> public static MimeEntity Load (string fileName) { if (fileName == null) throw new ArgumentNullException ("fileName"); using (var stream = File.OpenRead (fileName)) { return Load (stream); } } /// <summary> /// Registers the custom MIME entity. Once registered, all <see cref="MimeKit.MimeParser"/> /// instances will instantiate your custom <see cref="MimeEntity"/> when the specified /// mime-type is encountered. /// </summary> /// <param name="mimeType">The MIME type.</param> /// <param name="type">A custom subclass of <see cref="MimeEntity"/>.</param> /// <remarks> /// Your custom <see cref="MimeEntity"/> class should not subclass /// <see cref="MimeEntity"/> directly, but rather it should subclass /// <see cref="Multipart"/>, <see cref="MimePart"/>, /// <see cref="MessagePart"/>, or one of their derivatives. /// </remarks> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mimeType"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="type"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="type"/> is not a subclass of <see cref="Multipart"/>, /// <see cref="MimePart"/>, or <see cref="MessagePart"/>.</para> /// <para>-or-</para> /// <para><paramref name="type"/> does not have a constructor that takes /// only a <see cref="MimeEntityConstructorInfo"/> argument.</para> /// </exception> public static void Register (string mimeType, Type type) { if (mimeType == null) throw new ArgumentNullException ("mimeType"); if (type == null) throw new ArgumentNullException ("type"); mimeType = mimeType.ToLowerInvariant (); if (!type.IsSubclassOf (typeof (MessagePart)) && !type.IsSubclassOf (typeof (Multipart)) && !type.IsSubclassOf (typeof (MimePart))) throw new ArgumentException ("The specified type must be a subclass of MessagePart, Multipart, or MimePart.", "type"); var ctor = type.GetConstructor (ConstructorArgTypes); if (ctor == null) throw new ArgumentException ("The specified type must have a constructor that takes a MimeEntityConstructorInfo argument.", "type"); lock (CustomMimeTypes) { CustomMimeTypes[mimeType] = ctor; } } internal static MimeEntity Create (ParserOptions options, ContentType ctype, IEnumerable<Header> headers, bool toplevel) { var entity = new MimeEntityConstructorInfo (options, ctype, headers, toplevel); var subtype = ctype.MediaSubtype.ToLowerInvariant (); var type = ctype.MediaType.ToLowerInvariant (); if (CustomMimeTypes.Count > 0) { var mimeType = string.Format ("{0}/{1}", type, subtype); lock (CustomMimeTypes) { ConstructorInfo ctor; if (CustomMimeTypes.TryGetValue (mimeType, out ctor)) return (MimeEntity) ctor.Invoke (new object[] { entity }); } } if (type == "message") { if (subtype == "partial") return new MessagePartial (entity); return new MessagePart (entity); } if (type == "multipart") { if (subtype == "encrypted") return new MultipartEncrypted (entity); if (subtype == "signed") return new MultipartSigned (entity); return new Multipart (entity); } if (type == "application") { switch (subtype) { case "x-pkcs7-signature": case "pkcs7-signature": return new ApplicationPkcs7Signature (entity); case "x-pgp-encrypted": case "pgp-encrypted": return new ApplicationPgpEncrypted (entity); case "x-pgp-signature": case "pgp-signature": return new ApplicationPgpSignature (entity); case "x-pkcs7-mime": case "pkcs7-mime": return new ApplicationPkcs7Mime (entity); } } if (type == "text") return new TextPart (entity); return new MimePart (entity); } } }
using System; using System.Collections.Generic; using System.IO; namespace NntpClientLib { public delegate void ReceiveLine(string line); public class Rfc977NntpClientWithExtensions : Rfc977NntpClient { private List<string> m_supportedCommands = new List<string>(); private bool m_supportsXover; /// <summary> /// Gets a value indicating whether [supports xover]. /// </summary> /// <value><c>true</c> if [supports xover]; otherwise, <c>false</c>.</value> public bool SupportsXover { get { return m_supportsXover; } } private bool m_supportsListActive; /// <summary> /// Gets a value indicating whether [supports list active]. /// </summary> /// <value><c>true</c> if [supports list active]; otherwise, <c>false</c>.</value> public bool SupportsListActive { get { return m_supportsListActive; } } private bool m_supportsXhdr; /// <summary> /// Gets a value indicating whether [supports XHDR]. /// </summary> /// <value><c>true</c> if [supports XHDR]; otherwise, <c>false</c>.</value> public bool SupportsXhdr { get { return m_supportsXhdr; } } private bool m_supportsXgtitle; /// <summary> /// Gets a value indicating whether [supports xgtitle]. /// </summary> /// <value><c>true</c> if [supports xgtitle]; otherwise, <c>false</c>.</value> public bool SupportsXgtitle { get { return m_supportsXgtitle; } } private bool m_supportsXpat; public bool SupportsXpat { get { return m_supportsXpat; } } /// <summary> /// Connects using the specified host name and port number. /// </summary> /// <param name="hostName">Name of the host.</param> /// <param name="port">The port.</param> public override void Connect(string hostName, int port) { base.Connect(hostName, port); CheckToSupportedExtensions(); } /// <summary> /// Connects the specified host name. /// </summary> /// <param name="hostName">Name of the host.</param> /// <param name="port">The port.</param> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> public virtual void Connect(string hostName, int port, string userName, string password) { Open(hostName, port); AuthenticateUser(userName, password); CheckToSupportedExtensions(); } /// <summary> /// Checks to supported extensions. /// </summary> private void CheckToSupportedExtensions() { foreach (string hs in RetrieveHelp()) { string s = hs.ToLower(System.Globalization.CultureInfo.InvariantCulture); if (s.IndexOf("xover") != -1) { m_supportsXover = true; } else if (s.IndexOf("list") != -1) { if (s.IndexOf("active") != -1) { m_supportsListActive = true; } } else if (s.IndexOf("xhdr") != -1) { m_supportsXhdr = true; } else if (s.IndexOf("xgtitle") != -1) { m_supportsXgtitle = true; } m_supportedCommands.Add(s); } } /// <summary> /// Authenticates the user. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> public virtual void AuthenticateUser(string userName, string password) { NntpReaderWriter.WriteCommand("AUTHINFO USER " + userName); NntpReaderWriter.ReadResponse(); if (NntpReaderWriter.LastResponseCode == Rfc4643ResponseCodes.PasswordRequired) { NntpReaderWriter.WriteCommand("AUTHINFO PASS " + password); NntpReaderWriter.ReadResponse(); if (NntpReaderWriter.LastResponseCode != Rfc4643ResponseCodes.AuthenticationAccepted) { throw new NntpNotAuthorizedException(Resource.ErrorMessage30); } } else { throw new NntpNotAuthorizedException(Resource.ErrorMessage31); } } /// <summary> /// Sends the mode reader. /// </summary> public void SendModeReader() { NntpReaderWriter.WriteCommand("MODE READER"); NntpReaderWriter.ReadResponse(); if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyPostingAllowed) { PostingAllowed = true; } else if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyNoPostingAllowed) { PostingAllowed = false; } else if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.CommandUnavailable) { throw new NntpException(); } } /// <summary> /// Retrieves the newsgroups. /// </summary> /// <returns></returns> public override IEnumerable<NewsgroupHeader> RetrieveNewsgroups() { if (m_supportsListActive) { foreach (string s in DoBasicCommand("LIST ACTIVE", Rfc977ResponseCodes.NewsgroupsFollow)) { yield return NewsgroupHeader.Parse(s); } } else { // I can't use the base class to do this. foreach (string s in DoBasicCommand("LIST", Rfc977ResponseCodes.NewsgroupsFollow)) { yield return NewsgroupHeader.Parse(s); } } } /// <summary> /// Retrieves the newsgroups. /// </summary> /// <param name="wildcardMatch">The wildcard match.</param> /// <returns></returns> public virtual IEnumerable<NewsgroupHeader> RetrieveNewsgroups(string wildcardMatch) { if (m_supportsListActive) { foreach (string s in DoBasicCommand("LIST ACTIVE " + wildcardMatch, Rfc977ResponseCodes.NewsgroupsFollow)) { yield return NewsgroupHeader.Parse(s); } } else { throw new NotImplementedException(); } } /// <summary> /// Retrieves the article headers for the specified range. /// </summary> /// <param name="firstArticleId">The first article id.</param> /// <param name="lastArticleId">The last article id.</param> /// <returns></returns> public override IEnumerable<ArticleHeadersDictionary> RetrieveArticleHeaders(int firstArticleId, int lastArticleId) { if (!CurrentGroupSelected) { throw new NntpGroupNotSelectedException(); } if (m_supportsXover) { string[] headerNames = new string[] { "Article-ID", "Subject", "From", "Date", "Message-ID", "Xref", "Bytes", "Lines"}; foreach (string s in DoArticleCommand("XOVER " + firstArticleId + "-" + lastArticleId, 224)) { ArticleHeadersDictionary headers = new ArticleHeadersDictionary(); string[] fields = s.Split('\t'); for (int i = 0; i < headerNames.Length; i++) { headers.AddHeader(headerNames[i], fields[i]); } yield return headers; } } else { // I can't use the base class to do this. for (; firstArticleId < lastArticleId; firstArticleId++) { yield return RetrieveArticleHeader(firstArticleId); } } } /// <summary> /// Gets the abbreviated article headers. /// </summary> /// <param name="firstArticleId">The first article id.</param> /// <param name="lastArticleId">The last article id.</param> /// <param name="receiveLine">The receive line.</param> public void GetAbbreviatedArticleHeaders(int firstArticleId, int lastArticleId, ReceiveLine receiveLine) { if (!CurrentGroupSelected) { throw new NntpGroupNotSelectedException(); } if (m_supportsXover) { foreach (string s in DoArticleCommand("XOVER " + firstArticleId + "-" + lastArticleId, 224)) { receiveLine(s); } } } /// <summary> /// Retrieves the specific header. /// </summary> /// <param name="headerLine">The header line.</param> /// <param name="messageId">The message id.</param> /// <returns></returns> public IEnumerable<string> RetrieveSpecificArticleHeader(string headerLine, string messageId) { return RetrieveSpecificArticleHeaderCore("XHDR " + headerLine + " " + messageId); } /// <summary> /// Retrieves the specific header. /// </summary> /// <param name="headerLine">The header line.</param> /// <param name="articleId">The article id.</param> /// <returns></returns> public IEnumerable<string> RetrieveSpecificArticleHeader(string headerLine, int articleId) { return RetrieveSpecificArticleHeaderCore("XHDR " + headerLine + " " + articleId); } /// <summary> /// Retrieves the specific header. /// </summary> /// <param name="headerLine">The header line.</param> /// <param name="firstArticleId">The first article id.</param> /// <param name="lastArticleId">The last article id.</param> /// <returns></returns> public IEnumerable<string> RetrieveSpecificArticleHeaders(string headerLine, int firstArticleId, int lastArticleId) { return RetrieveSpecificArticleHeaderCore("XHDR " + headerLine + " " + firstArticleId + "-" + lastArticleId); } /// <summary> /// Retrieves the specific header. This core method implements the iteration of the XHDR command. /// </summary> /// <param name="command">The command.</param> /// <returns></returns> protected virtual IEnumerable<string> RetrieveSpecificArticleHeaderCore(string command) { if (!m_supportsXhdr) { throw new NotImplementedException(); } foreach (string s in DoArticleCommand(command, Rfc977ResponseCodes.ArticleRetrievedHeadFollows)) { if (!s.StartsWith("(none)")) { yield return s; } } } /// <summary> /// Retrieves the specific article header using pattern. This method implements the XPAT NNTP extension /// command. /// </summary> /// <param name="header">The header.</param> /// <param name="messageId">The message id.</param> /// <param name="patterns">The patterns.</param> /// <returns></returns> public IEnumerable<string> RetrieveSpecificArticleHeaderUsingPattern(string header, string messageId, string[] patterns) { if (!SupportsXpat) { throw new NotImplementedException(); } ValidateMessageIdArgument(messageId); return DoBasicCommand("XPAT " + header + " " + messageId + " " + string.Join(" ", patterns), 221); } /// <summary> /// Retrieves the specific article header using pattern. This method implements the XPAT NNTP extension /// command. /// </summary> /// <param name="header">The header.</param> /// <param name="articleId">The article id.</param> /// <param name="patterns">The patterns.</param> /// <returns></returns> public IEnumerable<string> RetrieveSpecificArticleHeaderUsingPattern(string header, int articleId, string[] patterns) { if (!SupportsXpat) { throw new NotImplementedException(); } return DoBasicCommand("XPAT " + header + " " + articleId + " " + string.Join(" ", patterns), 221); } /// <summary> /// Retrieves the specific article header using pattern. This method implements the XPAT NNTP extension /// command. /// </summary> /// <param name="header">The header.</param> /// <param name="firstArticleId">The first article id.</param> /// <param name="lastArticleId">The last article id.</param> /// <param name="patterns">The patterns.</param> /// <returns></returns> public IEnumerable<string> RetrieveSpecificArticleHeadersUsingPattern(string header, int firstArticleId, int lastArticleId, string[] patterns) { if (!SupportsXpat) { throw new NotImplementedException(); } if (lastArticleId == -1) { return DoBasicCommand("XPAT " + header + " " + firstArticleId + "- " + string.Join(" ", patterns), 221); } else { return DoBasicCommand("XPAT " + header + " " + firstArticleId + "-" + lastArticleId + " " + string.Join(" ", patterns), 221); } } /// <summary> /// Retrieves the group descriptions. /// </summary> /// <returns></returns> public IEnumerable<string> RetrieveGroupDescriptions() { if (!SupportsXgtitle) { throw new NotImplementedException(); } return DoBasicCommand("XGTITLE", 282); } /// <summary> /// Retrieves the group descriptions. /// </summary> /// <param name="wildcardMatch">The wildcard match.</param> /// <returns></returns> public IEnumerable<string> RetrieveGroupDescriptions(string wildcardMatch) { if (!SupportsXgtitle) { throw new NotImplementedException(); } return DoBasicCommand("XGTITLE " + wildcardMatch, 282); } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LTConfig.FieldBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LTConfigClassInstanceKey))] public partial class LTConfigField : iControlInterface { public LTConfigField() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // get_application_data //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_application_data( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_application_data", new object [] { class_names, field_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_application_data(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_application_data", new object[] { class_names, field_names}, callback, asyncState); } public string [] [] Endget_application_data(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_clustered_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] [] get_clustered_state( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_clustered_state", new object [] { class_names, field_names}); return ((CommonEnabledState [] [])(results[0])); } public System.IAsyncResult Beginget_clustered_state(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_clustered_state", new object[] { class_names, field_names}, callback, asyncState); } public CommonEnabledState [] [] Endget_clustered_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [] [])(results[0])); } //----------------------------------------------------------------------- // get_configsyncd_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] [] get_configsyncd_state( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_configsyncd_state", new object [] { class_names, field_names}); return ((CommonEnabledState [] [])(results[0])); } public System.IAsyncResult Beginget_configsyncd_state(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_configsyncd_state", new object[] { class_names, field_names}, callback, asyncState); } public CommonEnabledState [] [] Endget_configsyncd_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [] [])(results[0])); } //----------------------------------------------------------------------- // get_db_variable_mirror_information //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_db_variable_mirror_information( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_db_variable_mirror_information", new object [] { class_names, field_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_db_variable_mirror_information(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_db_variable_mirror_information", new object[] { class_names, field_names}, callback, asyncState); } public string [] [] Endget_db_variable_mirror_information(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_default //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_default( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_default", new object [] { class_names, field_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_default(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default", new object[] { class_names, field_names}, callback, asyncState); } public string [] [] Endget_default(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_display_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_display_name( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_display_name", new object [] { class_names, field_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_display_name(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_display_name", new object[] { class_names, field_names}, callback, asyncState); } public string [] [] Endget_display_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_list( string [] class_names ) { object [] results = this.Invoke("get_list", new object [] { class_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_list(string [] class_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[] { class_names}, callback, asyncState); } public string [] [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_required_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] [] get_required_state( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_required_state", new object [] { class_names, field_names}); return ((CommonEnabledState [] [])(results[0])); } public System.IAsyncResult Beginget_required_state(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_required_state", new object[] { class_names, field_names}, callback, asyncState); } public CommonEnabledState [] [] Endget_required_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [] [])(results[0])); } //----------------------------------------------------------------------- // get_type_information //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_type_information( string [] class_names, string [] [] field_names ) { object [] results = this.Invoke("get_type_information", new object [] { class_names, field_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_type_information(string [] class_names,string [] [] field_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_type_information", new object[] { class_names, field_names}, callback, asyncState); } public string [] [] Endget_type_information(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_value( LTConfigClassInstanceKey class_instance_key, string field_instance_name ) { object [] results = this.Invoke("get_value", new object [] { class_instance_key, field_instance_name}); return ((string)(results[0])); } public System.IAsyncResult Beginget_value(LTConfigClassInstanceKey class_instance_key,string field_instance_name, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_value", new object[] { class_instance_key, field_instance_name}, callback, asyncState); } public string Endget_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_values //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_values( LTConfigClassInstanceKey [] class_instance_keys, string [] [] field_instance_names ) { object [] results = this.Invoke("get_values", new object [] { class_instance_keys, field_instance_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_values(LTConfigClassInstanceKey [] class_instance_keys,string [] [] field_instance_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_values", new object[] { class_instance_keys, field_instance_names}, callback, asyncState); } public string [] [] Endget_values(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] public void set_value( bool create_instances_if_needed, LTConfigClassInstanceKey class_instance_key, string field_instance_name, string value ) { this.Invoke("set_value", new object [] { create_instances_if_needed, class_instance_key, field_instance_name, value}); } public System.IAsyncResult Beginset_value(bool create_instances_if_needed,LTConfigClassInstanceKey class_instance_key,string field_instance_name,string value, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_value", new object[] { create_instances_if_needed, class_instance_key, field_instance_name, value}, callback, asyncState); } public void Endset_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_values //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LTConfig/Field", RequestNamespace="urn:iControl:LTConfig/Field", ResponseNamespace="urn:iControl:LTConfig/Field")] public void set_values( bool create_instances_if_needed, LTConfigClassInstanceKey [] class_instance_keys, string [] [] field_instance_names, string [] [] values ) { this.Invoke("set_values", new object [] { create_instances_if_needed, class_instance_keys, field_instance_names, values}); } public System.IAsyncResult Beginset_values(bool create_instances_if_needed,LTConfigClassInstanceKey [] class_instance_keys,string [] [] field_instance_names,string [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_values", new object[] { create_instances_if_needed, class_instance_keys, field_instance_names, values}, callback, asyncState); } public void Endset_values(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. 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. */ using System; using System.Collections.Generic; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Router; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Router { public class URLConnection : HttpURLConnection { private Header resHeader; private bool sentRequest = false; private ByteArrayOutputStream os; private Body responseBody; private bool chunked = false; private Dictionary<string, IList<string>> requestProperties = new Dictionary<string , IList<string>>(); private const string Post = "POST"; private const string Get = "GET"; private const string Put = "PUT"; private const string Head = "HEAD"; private OutputStream responseOutputStream; private InputStream responseInputStream; private InputStream requestInputStream; public URLConnection(Uri url) : base(url) { responseInputStream = new PipedInputStream(); try { responseOutputStream = new PipedOutputStream((PipedInputStream)responseInputStream ); } catch (IOException e) { Log.E(Database.Tag, "Exception creating piped output stream", e); } } /// <exception cref="System.IO.IOException"></exception> public override void Connect() { } public override void Disconnect() { } // TODO Auto-generated method stub public override bool UsingProxy() { // TODO Auto-generated method stub return false; } public override IDictionary<string, IList<string>> GetRequestProperties() { Dictionary<string, IList<string>> map = new Dictionary<string, IList<string>>(); foreach (string key in requestProperties.Keys) { map.Put(key, Sharpen.Collections.UnmodifiableList(requestProperties.Get(key))); } return Sharpen.Collections.UnmodifiableMap(map); } public override string GetRequestProperty(string field) { IList<string> valuesList = requestProperties.Get(field); if (valuesList == null) { return null; } return valuesList[0]; } public override void SetRequestProperty(string field, string newValue) { IList<string> valuesList = new AList<string>(); valuesList.AddItem(newValue); requestProperties.Put(field, valuesList); } public override string GetHeaderField(int pos) { try { GetInputStream(); } catch (IOException) { } // ignore if (null == resHeader) { return null; } return resHeader.Get(pos); } public override string GetHeaderField(string key) { try { GetInputStream(); } catch (IOException) { } // ignore if (null == resHeader) { return null; } return resHeader.Get(key); } public override string GetHeaderFieldKey(int pos) { try { GetInputStream(); } catch (IOException) { } // ignore if (null == resHeader) { return null; } return resHeader.GetKey(pos); } public override IDictionary<string, IList<string>> GetHeaderFields() { try { // ensure that resHeader exists GetInputStream(); } catch (IOException) { } // ignore if (null == resHeader) { return null; } return resHeader.GetFieldMap(); } internal virtual Header GetResHeader() { if (resHeader == null) { resHeader = new Header(); } return resHeader; } public override int GetResponseCode() { return responseCode; } internal virtual void SetResponseCode(int responseCode) { this.responseCode = responseCode; } internal virtual void SetResponseBody(Body responseBody) { this.responseBody = responseBody; } public virtual Body GetResponseBody() { return this.responseBody; } internal virtual string GetBaseContentType() { string type = resHeader.Get("Content-Type"); if (type == null) { return null; } int delimeterPos = type.IndexOf(';'); if (delimeterPos > 0) { type = Sharpen.Runtime.Substring(type, delimeterPos); } return type; } /// <exception cref="System.IO.IOException"></exception> public override OutputStream GetOutputStream() { if (!doOutput) { throw new ProtocolException("Must set doOutput"); } // you can't write after you read if (sentRequest) { throw new ProtocolException("Can't write after you read"); } if (os != null) { return os; } // If the request method is neither PUT or POST, then you're not writing if (method != Put && method != Post) { throw new ProtocolException("Can only write to PUT or POST"); } if (!connected) { // connect and see if there is cache available. Connect(); } return os = new ByteArrayOutputStream(); } public virtual void SetChunked(bool chunked) { this.chunked = chunked; } public virtual bool IsChunked() { return chunked; } public virtual void SetResponseInputStream(InputStream responseInputStream) { this.responseInputStream = responseInputStream; } public virtual InputStream GetResponseInputStream() { return responseInputStream; } public virtual void SetResponseOutputStream(OutputStream responseOutputStream) { this.responseOutputStream = responseOutputStream; } public virtual OutputStream GetResponseOutputStream() { return responseOutputStream; } /// <exception cref="System.IO.IOException"></exception> public override InputStream GetInputStream() { return responseInputStream; } public virtual InputStream GetRequestInputStream() { return requestInputStream; } public virtual void SetRequestInputStream(InputStream requestInputStream) { this.requestInputStream = requestInputStream; } } /// <summary> /// Heavily borrowed from Apache Harmony /// https://github.com/apache/harmony/blob/trunk/classlib/modules/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/Header.java /// Under Apache License Version 2.0 /// </summary> internal class Header { private AList<string> props; private SortedDictionary<string, List<string>> keyTable; public Header() : base() { this.props = new AList<string>(20); this.keyTable = new SortedDictionary<string, List<string>>(string.CaseInsensitiveOrder ); } public Header(IDictionary<string, IList<string>> map) : this() { // initialize fields foreach (KeyValuePair<string, IList<string>> next in map.EntrySet()) { string key = next.Key; IList<string> value = next.Value; List<string> linkedList = new List<string>(); foreach (string element in value) { linkedList.AddItem(element); props.AddItem(key); props.AddItem(element); } keyTable.Put(key, linkedList); } } public virtual void Add(string key, string value) { if (key == null) { throw new ArgumentNullException(); } if (value == null) { return; } List<string> list = keyTable.Get(key); if (list == null) { list = new List<string>(); keyTable.Put(key, list); } list.AddItem(value); props.AddItem(key); props.AddItem(value); } public virtual void RemoveAll(string key) { Sharpen.Collections.Remove(keyTable, key); for (int i = 0; i < props.Count; i += 2) { if (key.Equals(props[i])) { props.Remove(i); // key props.Remove(i); } } } // value public virtual void AddAll(string key, IList<string> headers) { foreach (string header in headers) { Add(key, header); } } public virtual void AddIfAbsent(string key, string value) { if (Get(key) == null) { Add(key, value); } } public virtual void Set(string key, string value) { RemoveAll(key); Add(key, value); } public virtual IDictionary<string, IList<string>> GetFieldMap() { IDictionary<string, IList<string>> result = new SortedDictionary<string, IList<string >>(string.CaseInsensitiveOrder); // android-changed foreach (KeyValuePair<string, List<string>> next in keyTable.EntrySet()) { IList<string> v = next.Value; result.Put(next.Key, Sharpen.Collections.UnmodifiableList(v)); } return Sharpen.Collections.UnmodifiableMap(result); } public virtual string Get(int pos) { if (pos >= 0 && pos < props.Count / 2) { return props[pos * 2 + 1]; } return null; } public virtual string GetKey(int pos) { if (pos >= 0 && pos < props.Count / 2) { return props[pos * 2]; } return null; } public virtual string Get(string key) { List<string> result = keyTable.Get(key); if (result == null) { return null; } return result.GetLast(); } public virtual int Length() { return props.Count / 2; } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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. // ----------------------------------------------------------------------------- // The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects // ----------------------------------------------------------------------------- // Microsoft Public License (Ms-PL) // // This license governs use of the accompanying software. If you use the // software, you accept this license. If you do not accept the license, do not // use the software. // // 1. Definitions // The terms "reproduce," "reproduction," "derivative works," and // "distribution" have the same meaning here as under U.S. copyright law. // A "contribution" is the original software, or any additions or changes to // the software. // A "contributor" is any person that distributes its contribution under this // license. // "Licensed patents" are a contributor's patent claims that read directly on // its contribution. // // 2. Grant of Rights // (A) Copyright Grant- Subject to the terms of this license, including the // license conditions and limitations in section 3, each contributor grants // you a non-exclusive, worldwide, royalty-free copyright license to reproduce // its contribution, prepare derivative works of its contribution, and // distribute its contribution or any derivative works that you create. // (B) Patent Grant- Subject to the terms of this license, including the license // conditions and limitations in section 3, each contributor grants you a // non-exclusive, worldwide, royalty-free license under its licensed patents to // make, have made, use, sell, offer for sale, import, and/or otherwise dispose // of its contribution in the software or derivative works of the contribution // in the software. // // 3. Conditions and Limitations // (A) No Trademark License- This license does not grant you rights to use any // contributors' name, logo, or trademarks. // (B) If you bring a patent claim against any contributor over patents that // you claim are infringed by the software, your patent license from such // contributor to the software ends automatically. // (C) If you distribute any portion of the software, you must retain all // copyright, patent, trademark, and attribution notices that are present in the // software. // (D) If you distribute any portion of the software in source code form, you // may do so only under this license by including a complete copy of this // license with your distribution. If you distribute any portion of the software // in compiled or object code form, you may only do so under a license that // complies with this license. // (E) The software is licensed "as-is." You bear the risk of using it. The // contributors give no express warranties, guarantees or conditions. You may // have additional consumer rights under your local laws which this license // cannot change. To the extent permitted under your local laws, the // contributors exclude the implied warranties of merchantability, fitness for a // particular purpose and non-infringement. //----------------------------------------------------------------------------- // BasicEffect.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace SharpDX.Toolkit.Graphics { /// <summary> /// Built-in effect that supports optional texturing, vertex coloring, fog, and lighting. /// </summary> public partial class BasicEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog { #region Effect Parameters EffectParameter textureParam; EffectParameter samplerParam; EffectParameter diffuseColorParam; EffectParameter emissiveColorParam; EffectParameter specularColorParam; EffectParameter specularPowerParam; EffectParameter eyePositionParam; EffectParameter fogColorParam; EffectParameter fogVectorParam; EffectParameter worldParam; EffectParameter worldInverseTransposeParam; EffectParameter worldViewProjParam; EffectPass shaderPass; #endregion #region Fields bool lightingEnabled; bool preferPerPixelLighting; bool oneLight; bool fogEnabled; bool textureEnabled; bool vertexColorEnabled; Matrix world = Matrix.Identity; Matrix view = Matrix.Identity; Matrix projection = Matrix.Identity; Matrix worldView; Vector4 diffuseColor = Vector4.One; Vector3 emissiveColor = Vector3.Zero; Vector3 ambientLightColor = Vector3.Zero; float alpha = 1; DirectionalLight light0; DirectionalLight light1; DirectionalLight light2; float fogStart = 0; float fogEnd = 1; EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All; #endregion #region Public Properties /// <summary> /// Gets or sets the world matrix. /// </summary> public Matrix World { get { return world; } set { world = value; dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the view matrix. /// </summary> public Matrix View { get { return view; } set { view = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the projection matrix. /// </summary> public Matrix Projection { get { return projection; } set { projection = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj; } } /// <summary> /// Gets or sets the material diffuse color (range 0 to 1). /// </summary> public Vector4 DiffuseColor { get { return diffuseColor; } set { diffuseColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material emissive color (range 0 to 1). /// </summary> public Vector3 EmissiveColor { get { return emissiveColor; } set { emissiveColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material specular color (range 0 to 1). /// </summary> public Vector3 SpecularColor { get { return specularColorParam.GetValue<Vector3>(); } set { specularColorParam.SetValue(value); } } /// <summary> /// Gets or sets the material specular power. /// </summary> public float SpecularPower { get { return specularPowerParam.GetValue<float>(); } set { specularPowerParam.SetValue(value); } } /// <summary> /// Gets or sets the material alpha. /// </summary> public float Alpha { get { return alpha; } set { alpha = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the lighting enable flag. /// </summary> public bool LightingEnabled { get { return lightingEnabled; } set { if (lightingEnabled != value) { lightingEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.MaterialColor; } } } /// <summary> /// Gets or sets the per-pixel lighting prefer flag. /// </summary> public bool PreferPerPixelLighting { get { return preferPerPixelLighting; } set { if (preferPerPixelLighting != value) { preferPerPixelLighting = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the ambient light color (range 0 to 1). /// </summary> public Vector3 AmbientLightColor { get { return ambientLightColor; } set { ambientLightColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets the first directional light. /// </summary> public DirectionalLight DirectionalLight0 { get { return light0; } } /// <summary> /// Gets the second directional light. /// </summary> public DirectionalLight DirectionalLight1 { get { return light1; } } /// <summary> /// Gets the third directional light. /// </summary> public DirectionalLight DirectionalLight2 { get { return light2; } } /// <summary> /// Gets or sets the fog enable flag. /// </summary> public bool FogEnabled { get { return fogEnabled; } set { if (fogEnabled != value) { fogEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable; } } } /// <summary> /// Gets or sets the fog start distance. /// </summary> public float FogStart { get { return fogStart; } set { fogStart = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog end distance. /// </summary> public float FogEnd { get { return fogEnd; } set { fogEnd = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog color. /// </summary> public Vector3 FogColor { get { return fogColorParam.GetValue<Vector3>(); } set { fogColorParam.SetValue(value); } } /// <summary> /// Gets or sets whether texturing is enabled. /// </summary> public bool TextureEnabled { get { return textureEnabled; } set { if (textureEnabled != value) { textureEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the current texture. Either use this property or <see cref="TextureView"/> but not both at the same time. /// </summary> public Texture2DBase Texture { get { return textureParam.GetResource<Texture2DBase>(); } set { textureParam.SetResource(value); } } /// <summary> /// Gets or sets the current texture sampler. Default is <see cref="SamplerStateCollection.Default"/>. /// </summary> public SamplerState Sampler { get { return samplerParam.GetResource<SamplerState>(); } set { samplerParam.SetResource(value); } } /// <summary> /// Gets or sets the current texture view. Either use this property or <see cref="Texture"/> but not both at the same time. /// </summary> public Direct3D11.ShaderResourceView TextureView { get { return textureParam.GetResource<Direct3D11.ShaderResourceView>(); } set { textureParam.SetResource(value); } } /// <summary> /// Gets or sets whether vertex color is enabled. /// </summary> public bool VertexColorEnabled { get { return vertexColorEnabled; } set { if (vertexColorEnabled != value) { vertexColorEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } #endregion #region Methods /// <summary> /// Initializes a new instance of the <see cref="BasicEffect" /> class. /// </summary> /// <param name="device">The device.</param> public BasicEffect(GraphicsDevice device) : this(device, device.DefaultEffectPool) { } /// <summary> /// Initializes a new instance of the <see cref="BasicEffect" /> class from a specified <see cref="EffectPool"/>. /// </summary> /// <param name="device">The device.</param> /// <param name="pool">The pool.</param> public BasicEffect(GraphicsDevice device, EffectPool pool) : base(device, effectBytecode, pool) { DirectionalLight0.Enabled = true; SpecularColor = Vector3.One; SpecularPower = 16; } protected override void Initialize() { textureParam = Parameters["Texture"]; samplerParam = Parameters["TextureSampler"]; diffuseColorParam = Parameters["DiffuseColor"]; emissiveColorParam = Parameters["EmissiveColor"]; specularColorParam = Parameters["SpecularColor"]; specularPowerParam = Parameters["SpecularPower"]; eyePositionParam = Parameters["EyePosition"]; fogColorParam = Parameters["FogColor"]; fogVectorParam = Parameters["FogVector"]; worldParam = Parameters["World"]; worldInverseTransposeParam = Parameters["WorldInverseTranspose"]; worldViewProjParam = Parameters["WorldViewProj"]; light0 = new DirectionalLight(Parameters["DirLight0Direction"], Parameters["DirLight0DiffuseColor"], Parameters["DirLight0SpecularColor"], null); light1 = new DirectionalLight(Parameters["DirLight1Direction"], Parameters["DirLight1DiffuseColor"], Parameters["DirLight1SpecularColor"], null); light2 = new DirectionalLight(Parameters["DirLight2Direction"], Parameters["DirLight2DiffuseColor"], Parameters["DirLight2SpecularColor"], null); samplerParam.SetResource(GraphicsDevice.SamplerStates.Default); } ///// <summary> ///// Creates a new BasicEffect by cloning parameter settings from an existing instance. ///// </summary> //protected BasicEffect(BasicEffect cloneSource) // : base(cloneSource) //{ // CacheEffectParameters(cloneSource); // lightingEnabled = cloneSource.lightingEnabled; // preferPerPixelLighting = cloneSource.preferPerPixelLighting; // fogEnabled = cloneSource.fogEnabled; // textureEnabled = cloneSource.textureEnabled; // vertexColorEnabled = cloneSource.vertexColorEnabled; // world = cloneSource.world; // view = cloneSource.view; // projection = cloneSource.projection; // diffuseColor = cloneSource.diffuseColor; // emissiveColor = cloneSource.emissiveColor; // ambientLightColor = cloneSource.ambientLightColor; // alpha = cloneSource.alpha; // fogStart = cloneSource.fogStart; // fogEnd = cloneSource.fogEnd; //} /// <summary> /// Creates a clone of the current BasicEffect instance. /// </summary> //public override Effect Clone() //{ // return new BasicEffect(this); //} /// <summary> /// Sets up the standard key/fill/back lighting rig. /// </summary> public void EnableDefaultLighting() { LightingEnabled = true; AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2); } /// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override EffectPass OnApply(EffectPass pass) { // Make sure that domain, hull and geometry shaders are disable. GraphicsDevice.DomainShaderStage.Set(null); GraphicsDevice.HullShaderStage.Set(null); GraphicsDevice.GeometryShaderStage.Set(null); // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/emissive/alpha material color parameters? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { EffectHelpers.SetMaterialColor(lightingEnabled, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } if (lightingEnabled) { // Recompute the world inverse transpose and eye position? dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam); // Check if we can use the only-bother-with-the-first-light shader optimization. bool newOneLight = !light1.Enabled && !light2.Enabled; if (oneLight != newOneLight) { oneLight = newOneLight; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; if (textureEnabled) shaderIndex += 4; if (lightingEnabled) { if (preferPerPixelLighting) shaderIndex += 24; else if (oneLight) shaderIndex += 16; else shaderIndex += 8; } shaderPass = pass.SubPasses[shaderIndex]; dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } // Call the base class to process callbacks pass = base.OnApply(shaderPass); return pass; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================================= ** ** ** Purpose: An array implementation of a generic stack. ** ** =============================================================================*/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(StackDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class Stack<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; // Storage for stack elements private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in sync w/ collection. private Object _syncRoot; private const int DefaultCapacity = 4; /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack"]/*' /> public Stack() { _array = Array.Empty<T>(); } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack1"]/*' /> public Stack(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedNonNegNumRequired); _array = new T[capacity]; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack2"]/*' /> public Stack(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException("collection"); _array = EnumerableHelpers.ToArray(collection, out _size); } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Count"]/*' /> public int Count { get { return _size; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IsSynchronized"]/*' /> bool System.Collections.ICollection.IsSynchronized { get { return false; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.SyncRoot"]/*' /> Object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Clear"]/*' /> public void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Contains"]/*' /> public bool Contains(T item) { int count = _size; EqualityComparer<T> c = EqualityComparer<T>.Default; while (count-- > 0) { if (((Object)item) == null) { if (((Object)_array[count]) == null) return true; } else if (_array[count] != null && c.Equals(_array[count], item)) { return true; } } return false; } // Copies the stack into an array. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.CopyTo"]/*' /> public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (array != _array) { int srcIndex = 0; int dstIndex = arrayIndex + _size; for (int i = 0; i < _size; i++) array[--dstIndex] = _array[srcIndex++]; } else { // Legacy fallback in case we ever end up copying within the same array. Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } } void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } try { Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } // Returns an IEnumerator for this Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.GetEnumerator"]/*' /> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if (_size < threshold) { Array.Resize(ref _array, _size); _version++; } } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Peek"]/*' /> public T Peek() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); return _array[_size - 1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Pop"]/*' /> public T Pop() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); _version++; T item = _array[--_size]; _array[_size] = default(T); // Free memory quicker. return item; } // Pushes an item to the top of the stack. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Push"]/*' /> public void Push(T item) { if (_size == _array.Length) { Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length); } _array[_size++] = item; _version++; } // Copies the Stack to an array, in the same order Pop would return the items. public T[] ToArray() { T[] objArray = new T[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator"]/*' /> [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private Stack<T> _stack; private int _index; private int _version; private T _currentElement; internal Enumerator(Stack<T> stack) { _stack = stack; _version = _stack._version; _index = -2; _currentElement = default(T); } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Dispose"]/*' /> public void Dispose() { _index = -1; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.MoveNext"]/*' /> public bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size - 1; retval = (_index >= 0); if (retval) _currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) _currentElement = _stack._array[_index]; else _currentElement = default(T); return retval; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Current"]/*' /> public T Current { get { if (_index == -2) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return _currentElement; } } Object System.Collections.IEnumerator.Current { get { return Current; } } void System.Collections.IEnumerator.Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = default(T); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Tasks { /// <summary>CA2012: Use ValueTasks correctly.</summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class UseValueTasksCorrectlyAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2012"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UseValueTasksCorrectlyTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UseValueTasksCorrectlyDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static readonly DiagnosticDescriptor GeneralRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UseValueTasksCorrectlyMessage_General), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)), DiagnosticCategory.Reliability, RuleLevel.IdeSuggestion, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false); internal static readonly DiagnosticDescriptor UnconsumedRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UseValueTasksCorrectlyMessage_Unconsumed), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)), DiagnosticCategory.Reliability, RuleLevel.IdeSuggestion, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false); internal static readonly DiagnosticDescriptor DoubleConsumptionRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UseValueTasksCorrectlyMessage_DoubleConsumption), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)), DiagnosticCategory.Reliability, RuleLevel.IdeSuggestion, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false); internal static readonly DiagnosticDescriptor AccessingIncompleteResultRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UseValueTasksCorrectlyMessage_AccessingIncompleteResult), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)), DiagnosticCategory.Reliability, RuleLevel.IdeSuggestion, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(GeneralRule, UnconsumedRule, DoubleConsumptionRule, AccessingIncompleteResultRule); public sealed override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(compilationContext => { var typeProvider = WellKnownTypeProvider.GetOrCreate(compilationContext.Compilation); // Get the target ValueTask / ValueTask<T> types. If they don't exist, nothing more to do. if (!typeProvider.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask, out var valueTaskType) || !typeProvider.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask1, out var valueTaskOfTType)) { return; } // Get the type for System.Diagnostics.Debug. If we can't find it, that's ok, we just won't use it. var debugType = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsDebug); // Process all invocations. This analyzer works by finding all method invocations that return ValueTasks, // and then analyzing those invocations and their surroundings. compilationContext.RegisterOperationAction(operationContext => { var operation = operationContext.Operation; var invocation = (IInvocationOperation)operation; // Does the method return ValueTask? If not, we're done. if (!valueTaskType.Equals(invocation.TargetMethod.ReturnType) && !valueTaskOfTType.Equals(invocation.TargetMethod.ReturnType.OriginalDefinition)) { return; } // The only method that returns a ValueTask on which we allow unlimited later consumption // is ValueTask.Preserve. Use is rare, but special-case it. If this is Preserve, we're done. if (invocation.TargetMethod.Name == nameof(ValueTask.Preserve) && (valueTaskType.Equals(invocation.TargetMethod.ContainingType) || valueTaskOfTType.Equals(invocation.TargetMethod.ContainingType.OriginalDefinition))) { return; } // If this is a method call off of the ValueTask, then check to see if it's special. if (invocation.Parent is IInvocationOperation parentIo) { switch (parentIo.TargetMethod.Name) { case nameof(ValueTask.AsTask): case nameof(ValueTask.Preserve): // Using AsTask to convert to a Task is acceptable consumption. // Use Preserve to enable subsequent unlimited consumption is acceptable. return; case nameof(ValueTask.GetAwaiter) when parentIo.Parent is IInvocationOperation { TargetMethod: { Name: nameof(ValueTaskAwaiter.GetResult) } }: // Warn! Trying to block waiting for a value task isn't supported. operationContext.ReportDiagnostic(invocation.CreateDiagnostic(AccessingIncompleteResultRule)); return; case nameof(ValueTask.ConfigureAwait): // ConfigureAwait returns another awaitable. Use that one instead for subsequent analysis. operation = invocation = parentIo; break; } } else if (invocation.Parent is IPropertyReferenceOperation { Property: { Name: nameof(ValueTask<int>.Result) } }) { operationContext.ReportDiagnostic(invocation.CreateDiagnostic(AccessingIncompleteResultRule)); return; } // Just let any other direct member access fall through to be a general warning. while (operation.Parent != null) // for walking up the operation tree if necessary { switch (operation.Parent.Kind) { case OperationKind.Await: case OperationKind.Return: // The "99% case" is just awaiting the awaitable. Such usage is good. // The "0.9% case" is delegating to and returning another call's returned awaitable. Also good. return; case OperationKind.Argument: // The "0.09% case" is passing the result of a call directly as an argument to another method. // This could later result in a problem, as now there's a parameter inside the callee that's // holding on to the awaitable, and it could await it twice... but the caller is still correct, // and this analyzer does not perform inter-method analysis. var arg = (IArgumentOperation)operation.Parent; var originalType = arg.Parameter.Type.OriginalDefinition; if (originalType.Equals(valueTaskType) || originalType.Equals(valueTaskOfTType)) { // However, it's really only expected when the parameter type is explicitly a ValueTask{<T>}; // if it's just, say, a TValue, we're likely on a bad path, such as storing the instance into // a collection of some kind, e.g. Dictionary<string, ValueTask>.Add(..., vt). var originalParameter = arg.Parameter.OriginalDefinition; if (originalParameter.Type.Kind != SymbolKind.TypeParameter) { return; } } goto default; case OperationKind.ExpressionStatement: case OperationKind.Discard: case OperationKind.DiscardPattern: case OperationKind.SimpleAssignment when operation.Parent is ISimpleAssignmentOperation sao && sao.Target is IDiscardOperation: // Warn! This is a statement or discard. The result should have been used. operationContext.ReportDiagnostic(invocation.CreateDiagnostic(UnconsumedRule)); return; case OperationKind.Conversion: var conversion = (IConversionOperation)operation.Parent; if (conversion.Conversion.IsIdentity) { // Ignore identity conversions, which can pop in from time to time. operation = operation.Parent; continue; } goto default; // At this point, we're "in the weeds", but there are still some rare-but-used valid patterns to check for. case OperationKind.Coalesce: case OperationKind.Conditional: case OperationKind.ConditionalAccess: case OperationKind.SwitchExpression: case OperationKind.SwitchExpressionArm: // This is a ternary, null conditional, or switch expression, so consider the parent expression instead. operation = operation.Parent; continue; default: // Handle atypical / difficult cases that require more analysis. HandleAtypicalValueTaskUsage(operationContext, debugType, operation, invocation); return; } } }, OperationKind.Invocation); }); } /// <summary>Handles more complicated analysis to warn on more complicated erroneous usage patterns.</summary> private static void HandleAtypicalValueTaskUsage(OperationAnalysisContext operationContext, INamedTypeSymbol? debugType, IOperation operation, IInvocationOperation invocation) { if (TryGetLocalSymbolAssigned(operation.Parent, out var valueTypeSymbol, out var startingBlock)) { // At this point, it's very likely misuse and we could warn. However, there are a few advanced // patterns where the ValueTask might be stored into a local and very carefully used. As value // tasks are more likely to be used in more performance-sensitive code, we don't want a lot of // false positives from using such patterns in such code. So, we try to special-case these // advanced patterns by looking at the control flow graph and each block in it. Starting from // the entry block, we look to see if there's any "consumption" of the value task in a block. If // there are multiple consumptions in that block, it's an immediate error, as you can only consume // a value task once. If there's only one consumption, but we've already seen a consumption // on the path that got us here, then it's also erroneous. Otherwise, we keep following // the flow graph. If we try to jump to a block that's already had the awaiter consumed and // the current block did as well, that's also erroneous. Along the way, we further track // Debug.Assert(vt.Is*) calls, for cases where the developer wants to inform the reader/analyzer that // direct access to the result is known to be ok. This is a heuristic, and there are various things // that can thwart it, but it's relatively simple, handles most cases well, and minimizes both false // positives and false negatives (e.g. we're not tracking copying the local, but that's rare). This // part of the analysis is also expensive, but it should be executed only very rarely. // Dictionary to track blocks we've already seen. The TValue for each block is the merged // flow state for all paths we've followed into that block. var seen = new Dictionary<BasicBlock, FlowState>(); // Stack of blocks still left to investigate, starting with the entry block. Each entry // is the block and its flow state at the time we pushed it onto the stack. var stack = new Stack<(BasicBlock, FlowState)>(); stack.Push((startingBlock, default)); // Process all blocks until their aren't any remaining. while (stack.Count > 0) { // Get the next block to process. If we've already seen it, skip it. (var block, var blockState) = stack.Pop(); if (seen.ContainsKey(block)) { continue; } // Analyze the block. This involves: // - Checking if there are any asserts in the block that declare the ValueTask to have already completed. // - Counting how many "consumptions" of the ValueTask there are in the block. int assertsCompletionIndex = FindFirstAssertsCompletion(block, valueTypeSymbol, debugType); int consumptions = CountConsumptions(block, valueTypeSymbol); blockState.ThisConsumption = consumptions == 1; // Check if the analysis reveals a problem for this block. if (consumptions > 1 || (blockState.ThisConsumption && blockState.PreviousConsumption)) { // Warn! Either this block consumed it twice, or it consumed it after a previous // block in the flow to here also consumed it. operationContext.ReportDiagnostic(invocation.CreateDiagnostic(DoubleConsumptionRule)); return; } else if (!blockState.KnownCompletion && blockState.ThisConsumption) { // There weren't any assertions prior to this block, and this block does have a consumption, // but we don't know what kind. If it's an await, no problem, but if it's a direct result access // that requires knowing that the ValueTask completed, we need to get more specific and find the first // operation that tries such a direct access. int directAccessIndex = FindFirstDirectResultAccess(block, valueTypeSymbol); if (directAccessIndex >= 0 && (assertsCompletionIndex == -1 || assertsCompletionIndex > directAccessIndex)) { // Warn! We found a direct result access without any asserts before it to assert it was completed. operationContext.ReportDiagnostic(invocation.CreateDiagnostic(AccessingIncompleteResultRule)); return; } } // We've finished analyzing this block, so add it to our tracking dictionary. seen.Add(block, blockState); // We now to follow the successors. When we flow to them, we update their flow state to highlight // whether there were any asserts in this block, such that they can also consider completion asserted. bool setFallthroughKnownCompletion = assertsCompletionIndex != -1; bool setConditionalKnownCompletion = setFallthroughKnownCompletion; // If there's a conditional successor, we not only need to follow it, we need to evaluate the // condition. That condition might be something like "if (vt.IsCompleted)", in which case // we need to flow that completion knowledge (just as with asserts) into the relevant branch. if (block.ConditionalSuccessor?.Destination is BasicBlock conditional) { if (!(setFallthroughKnownCompletion | setConditionalKnownCompletion) || block.BranchValue != null) { bool? completionCondition = OperationImpliesCompletion(valueTypeSymbol, block.BranchValue); switch (block.ConditionKind) { case ControlFlowConditionKind.WhenTrue when completionCondition == true: case ControlFlowConditionKind.WhenFalse when completionCondition == false: setConditionalKnownCompletion = true; break; case ControlFlowConditionKind.WhenTrue when completionCondition == false: case ControlFlowConditionKind.WhenFalse when completionCondition == true: setFallthroughKnownCompletion = true; break; } } HandleSuccessor(conditional, setConditionalKnownCompletion); } // If there's a fallback successor, follow it as well. We computed any necessary completion // value previously, so just pass that along. if (block.FallThroughSuccessor?.Destination is BasicBlock fallthrough) { HandleSuccessor(fallthrough, setFallthroughKnownCompletion); } // Processes a successor, determining whether to push it onto the evaluation stack or update // the seen dictionary with the additional information we've gathered. void HandleSuccessor(BasicBlock successor, bool setKnownCompletion) { if (seen.TryGetValue(successor, out var successorConsumption)) { // We've previously seen the successor block. Check its state. if (blockState.ThisConsumption && !successorConsumption.PreviousConsumption) { if (successorConsumption.ThisConsumption) { // Warn! The ValueTask was consumed on another path into this block, and this block // also consumes it. operationContext.ReportDiagnostic(invocation.CreateDiagnostic(DoubleConsumptionRule)); return; } // Update its flow state accordingly; a previous path into it hadn't consumed the ValueTask, // but this one did. In contrast, we don't update the KnownCompletion state, because that // requires all paths into the block to have known completion. successorConsumption.PreviousConsumption = true; seen[successor] = successorConsumption; } } else { // Push the successor onto the evaluation stack. var successorState = blockState; successorState.PreviousConsumption |= blockState.ThisConsumption; successorState.KnownCompletion |= setKnownCompletion; stack.Push((successor, successorState)); } } } // Couldn't prove there was a problem, so err on the side of false negatives and don't warn. return; } // Warn! There was some very atypical consumption of the ValueTask. operationContext.ReportDiagnostic(invocation.CreateDiagnostic(GeneralRule)); } /// <summary>Represents the flow state for a basic block.</summary> #pragma warning disable CA1815 // Override equals and operator equals on value types private struct FlowState #pragma warning restore CA1815 { /// <summary>Gets or sets whether the ValueTask was known to have completed, either due to an assert or a condition proving it.</summary> public bool KnownCompletion { get; set; } /// <summary>Gets or sets whether a previous block in the flow consumed the ValueTask.</summary> public bool PreviousConsumption { get; set; } /// <summary>Gets or sets whether this block consumed the ValueTask.</summary> public bool ThisConsumption { get; set; } } private static bool TryGetLocalSymbolAssigned(IOperation? operation, [NotNullWhen(true)] out ISymbol? symbol, [NotNullWhen(true)] out BasicBlock? startingBlock) { ControlFlowGraph? cfg; switch (operation?.Kind) { case OperationKind.VariableInitializer when operation.Parent is IVariableDeclaratorOperation decl: if (decl.TryGetEnclosingControlFlowGraph(out cfg)) { symbol = decl.Symbol; startingBlock = cfg.GetEntry(); return true; } break; case OperationKind.SimpleAssignment: var assn = (ISimpleAssignmentOperation)operation; if (assn.TryGetEnclosingControlFlowGraph(out cfg)) { switch (assn.Target) { case ILocalReferenceOperation local: symbol = local.Local; startingBlock = cfg.GetEntry(); return true; case IParameterReferenceOperation parameter: symbol = parameter.Parameter; startingBlock = cfg.GetEntry(); return true; } } break; } symbol = null; startingBlock = null; return false; } /// <summary>Counts the number of operations in the block that represent a consumption of the ValueTask, such as awaiting it or calling GetAwaiter().GetResult().</summary> /// <param name="block">The block to be searched.</param> /// <param name="valueTaskSymbol">The ValueTask symbol for which we're searching.</param> /// <returns> /// The number of found consumption operations. This is generally 0 or 1, but could be greater than 1 in the case /// of bad usage; it stops counting at 2, as there's no need to differentiate any values greater than 1. /// </returns> private static int CountConsumptions(BasicBlock block, ISymbol valueTaskSymbol) { int count = 0; foreach (var op in block.DescendantOperations()) { if (IsLocalOrParameterSymbolReference(op, valueTaskSymbol) && op.Parent?.Kind switch { OperationKind.Await => true, OperationKind.Return => true, OperationKind.Argument => true, OperationKind.Invocation => true, // e.g. AsTask() OperationKind.PropertyReference when op.Parent is IPropertyReferenceOperation { Property: { Name: "Result" } } => true, _ => false }) { if (++count > 1) { // The only relevant values are 0 (no consumptions), 1 (valid consumption), and > 1 (too many consumptions in the same block). // As such, we can stop iterating when we hit > 1. break; } } } return count; } /// <summary>Finds the first expression statement in the block that does Debug.Assert(vt.Is*).</summary> /// <param name="block">The block to be searched.</param> /// <param name="valueTaskSymbol">The ValueTask symbol for which we're searching.</param> /// <param name="debugType">The type of System.Diagnostics.Debug.</param> /// <returns>The index of the first Debug.Assert(vt.Is*) statement, or -1 if none was found.</returns> private static int FindFirstAssertsCompletion(BasicBlock block, ISymbol valueTaskSymbol, INamedTypeSymbol? debugType) { if (debugType != null) { for (var i = 0; i < block.Operations.Length; i++) { if (block.Operations[i] is IExpressionStatementOperation stmt && stmt.Operation is IInvocationOperation assert && assert.TargetMethod?.Name == nameof(Debug.Assert) && assert.TargetMethod.ContainingType.Equals(debugType) && !assert.Arguments.IsEmpty && OperationImpliesCompletion(valueTaskSymbol, assert.Arguments[0].Value) == true) { return i; } } } return -1; } /// <summary>Finds the first operation in the block containing a direct access to a ValueTask's result, e.g. GetAwaiter().GetResult().</summary> /// <param name="block">The block to be searched.</param> /// <param name="valueTaskSymbol">The ValueTask symbol for which we're searching.</param> /// <returns>The index found, or -1 if none could be found.</returns> private static int FindFirstDirectResultAccess(BasicBlock block, ISymbol valueTaskSymbol) { // First search the body of the block. var operations = block.Operations; for (int i = 0; i < operations.Length; i++) { foreach (var op in operations[i].DescendantsAndSelf()) { if (HasDirectResultAccess(op)) { return i; } } } // Also search the branch value. if (block.BranchValue != null) { foreach (var op in block.BranchValue.DescendantsAndSelf()) { if (HasDirectResultAccess(op)) { return operations.Length; } } } return -1; // Determines if the operation itself is a direct access to the ValueTask's Result or GetAwaiter().GetResult(). bool HasDirectResultAccess(IOperation op) => IsLocalOrParameterSymbolReference(op, valueTaskSymbol) && op.Parent?.Kind switch { OperationKind.PropertyReference when op.Parent is IPropertyReferenceOperation { Property: { Name: nameof(ValueTask<int>.Result) } } => true, OperationKind.Invocation when op.Parent is IInvocationOperation { TargetMethod: { Name: nameof(ValueTask.GetAwaiter) } } => true, _ => false }; } /// <summary>Gets whether <paramref name="op"/> implies that the ValueTask has completed.</summary> /// <param name="valueTaskSymbol">The ValueTask symbol for which we're searching.</param> /// <param name="op">The operation to examine.</param> /// <returns>true if the operation implies the ValueTask has completed, false if the operation implies the ValueTask has not completed, and null if it's undetermined.</returns> private static bool? OperationImpliesCompletion(ISymbol valueTaskSymbol, IOperation? op) { if (op != null) { switch (op.Kind) { case OperationKind.PropertyReference when IsCompletedReference(op as IPropertyReferenceOperation): return true; case OperationKind.Unary when op is IUnaryOperation { OperatorKind: UnaryOperatorKind.Not } unary && IsCompletedReference(unary.Operand as IPropertyReferenceOperation): return false; } } return null; bool IsCompletedReference(IPropertyReferenceOperation? prop) => prop != null && IsLocalOrParameterSymbolReference(prop.Instance, valueTaskSymbol) && prop.Property.Name switch { nameof(ValueTask.IsCompleted) => true, nameof(ValueTask.IsCompletedSuccessfully) => true, nameof(ValueTask.IsFaulted) => true, nameof(ValueTask.IsCanceled) => true, _ => false }; } private static bool IsLocalOrParameterSymbolReference(IOperation op, ISymbol valueTaskSymbol) => op?.Kind switch { OperationKind.LocalReference => ((ILocalReferenceOperation)op).Local.Equals(valueTaskSymbol), OperationKind.ParameterReference => ((IParameterReferenceOperation)op).Parameter.Equals(valueTaskSymbol), _ => false, }; } }
// ScriptCompilerTask.cs // Script#/Core/Build // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Build; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using ScriptCruncher = Microsoft.Ajax.Utilities.Minifier; using ScriptCruncherSettings = Microsoft.Ajax.Utilities.CodeSettings; using ScriptSourceMap = Microsoft.Ajax.Utilities.ScriptSharpSourceMap; namespace ScriptSharp.Tasks { /// <summary> /// The Script# MSBuild task. /// </summary> public sealed class ScriptCompilerTask : Task, IErrorHandler, IStreamSourceResolver { private string _projectPath; private ITaskItem[] _references; private ITaskItem[] _sources; private ITaskItem[] _resources; private ITaskItem _assembly; private string _defines; private bool _minimize; private bool _copyReferences; private string _copyReferencesPath; private string _outputPath; private string _scriptName; private List<ITaskItem> _scripts; private bool _hasErrors; public ScriptCompilerTask() { _copyReferences = true; } [Required] public ITaskItem Assembly { get { return _assembly; } set { _assembly = value; } } public bool CopyReferences { get { return _copyReferences; } set { _copyReferences = value; } } public string CopyReferencesPath { get { if (_copyReferencesPath == null) { return String.Empty; } return _copyReferencesPath; } set { _copyReferencesPath = value; } } public string Defines { get { if (_defines == null) { return String.Empty; } return _defines; } set { _defines = value; } } public bool Minimize { get { return _minimize; } set { _minimize = value; } } [Required] public string OutputPath { get { if (_outputPath == null) { return String.Empty; } return _outputPath; } set { _outputPath = value; } } [Required] public string ProjectPath { get { return _projectPath; } set { _projectPath = value; } } [Required] public ITaskItem[] References { get { return _references; } set { _references = value; } } public ITaskItem[] Resources { get { return _resources; } set { _resources = value; } } public string ScriptName { get { return _scriptName; } set { _scriptName = value; } } [Output] public ITaskItem[] Scripts { get { if (_scripts == null) { return new ITaskItem[0]; } return _scripts.ToArray(); } } [Required] public ITaskItem[] Sources { get { return _sources; } set { _sources = value; } } private bool Compile(IEnumerable<ITaskItem> sourceItems, IEnumerable<ITaskItem> resourceItems, string locale) { ITaskItem scriptTaskItem; CompilerOptions options = CreateOptions(sourceItems, resourceItems, locale, /* includeTests */ false, /* minimize */ false, out scriptTaskItem); string errorMessage = String.Empty; if (options.Validate(out errorMessage) == false) { Log.LogError(errorMessage); return false; } ScriptCompiler compiler = new ScriptCompiler(this); compiler.Compile(options); if (_hasErrors == false) { // Only copy references once (when building language neutral scripts) bool copyReferences = String.IsNullOrEmpty(locale) && CopyReferences; OnScriptFileGenerated(scriptTaskItem, options, copyReferences); if (_hasErrors) { return false; } } else { return false; } if (options.HasTestTypes) { CompilerOptions testOptions = CreateOptions(sourceItems, resourceItems, locale, /* includeTests */ true, /* minimize */ false, out scriptTaskItem); ScriptCompiler testCompiler = new ScriptCompiler(this); testCompiler.Compile(testOptions); if (_hasErrors == false) { OnScriptFileGenerated(scriptTaskItem, testOptions, /* copyReferences */ false); } else { return false; } } if (_minimize) { CompilerOptions minimizeOptions = CreateOptions(sourceItems, resourceItems, locale, /* includeTests */ false, /* minimize */ true, out scriptTaskItem); ScriptCompiler minimizingCompiler = new ScriptCompiler(this); minimizingCompiler.Compile(minimizeOptions); if (_hasErrors == false) { ExecuteCruncher(scriptTaskItem); OnScriptFileGenerated(scriptTaskItem, minimizeOptions, /* copyReferences */ false); } else { return false; } } return true; } private CompilerOptions CreateOptions(IEnumerable<ITaskItem> sourceItems, IEnumerable<ITaskItem> resourceItems, string locale, bool includeTests, bool minimize, out ITaskItem outputScriptItem) { CompilerOptions options = new CompilerOptions(); options.IncludeTests = includeTests; options.Minimize = minimize; options.Defines = GetDefines(); options.References = GetReferences(); options.Sources = GetSources(sourceItems); options.Resources = GetResources(resourceItems, locale); options.IncludeResolver = this; string scriptFilePath = GetScriptFilePath(locale, minimize, includeTests); outputScriptItem = new TaskItem(scriptFilePath); options.ScriptFile = new TaskItemOutputStreamSource(outputScriptItem); return options; } public override bool Execute() { _scripts = new List<ITaskItem>(); bool success; try { success = ExecuteCore(_sources, _resources); } catch (Exception) { success = false; } return success; } private bool ExecuteCore(IEnumerable<ITaskItem> sources, IEnumerable<ITaskItem> resources) { // Create the neutral culture scripts first, and if that // succeeds, compile any localized variants that are supposed // to be generated. if (Compile(sources, resources, /* locale */ String.Empty)) { ICollection<string> locales = GetLocales(resources); foreach (string locale in locales) { if (Compile(sources, resources, locale) == false) { return false; } } GenerateDeploymentFile(); return true; } return false; } private void ExecuteCruncher(ITaskItem scriptItem) { string script = File.ReadAllText(scriptItem.ItemSpec); ScriptCruncher cruncher = new ScriptCruncher(); ScriptCruncherSettings cruncherSettings = new ScriptCruncherSettings() { StripDebugStatements = false, OutputMode = Microsoft.Ajax.Utilities.OutputMode.SingleLine, IgnorePreprocessorDefines = true, IgnoreConditionalCompilation = true }; cruncherSettings.AddNoAutoRename("$"); cruncherSettings.SetDebugNamespaces(null); string crunchedScript = cruncher.MinifyJavaScript(script, cruncherSettings); File.WriteAllText(scriptItem.ItemSpec, crunchedScript); } private void GenerateDeploymentFile() { try { string assemblyFile = Path.GetFileName(_assembly.ItemSpec); string scriptsFilePath = Path.Combine(OutputPath, Path.ChangeExtension(assemblyFile, "scripts")); Uri scriptsUri = new Uri(Path.GetFullPath(scriptsFilePath), UriKind.Absolute); IEnumerable<string> scripts = _scripts.Select(s => { Uri fileUri = new Uri(s.ItemSpec, UriKind.Absolute); return Uri.UnescapeDataString(scriptsUri.MakeRelativeUri(fileUri).ToString()); }); File.WriteAllLines(scriptsFilePath, scripts); } catch (Exception e) { Log.LogError(e.ToString()); } } private ICollection<string> GetDefines() { if (Defines.Length == 0) { return new string[0]; } return Defines.Split(';'); } private ICollection<string> GetLocales(IEnumerable<ITaskItem> resourceItems) { List<string> locales = new List<string>(); // Inspect the list of resources to create the list of unique locales if (resourceItems != null) { foreach (ITaskItem resourceItem in resourceItems) { string locale = ResourceFile.GetLocale(resourceItem.ItemSpec); if (locales.Contains(locale) == false) { locales.Add(locale); } } } return locales; } private ICollection<string> GetReferences() { if (_references == null) { return new string[0]; } List<string> references = new List<string>(_references.Length); foreach (ITaskItem reference in _references) { // TODO: This is a hack... something in the .net 4 build system causes // System.Core.dll to get included [sometimes]. // That shouldn't happen... so filter it out here. if (reference.ItemSpec.EndsWith("System.Core.dll", StringComparison.OrdinalIgnoreCase)) { continue; } references.Add(reference.ItemSpec); } return references; } private ICollection<IStreamSource> GetResources(IEnumerable<ITaskItem> allResources, string locale) { if (allResources == null) { return new TaskItemInputStreamSource[0]; } List<IStreamSource> resources = new List<IStreamSource>(); foreach (ITaskItem resource in allResources) { string itemLocale = ResourceFile.GetLocale(resource.ItemSpec); if (String.IsNullOrEmpty(locale) && String.IsNullOrEmpty(itemLocale)) { resources.Add(new TaskItemInputStreamSource(resource)); } else if ((String.Compare(locale, itemLocale, StringComparison.OrdinalIgnoreCase) == 0) || locale.StartsWith(itemLocale, StringComparison.OrdinalIgnoreCase)) { // Either the item locale matches, or the item locale is a prefix // of the locale (eg. we want to include "fr" if the locale specified // is fr-FR) resources.Add(new TaskItemInputStreamSource(resource)); } } return resources; } private string GetScriptFilePath(string locale, bool minimize, bool includeTests) { string scriptName = ScriptName; if (String.IsNullOrEmpty(scriptName)) { scriptName = Path.GetFileName(_assembly.ItemSpec); } string extension = includeTests ? "test.js" : (minimize ? "min.js" : "js"); if (String.IsNullOrEmpty(locale) == false) { extension = locale + "." + extension; } if (Directory.Exists(OutputPath) == false) { Directory.CreateDirectory(OutputPath); } return Path.GetFullPath(Path.Combine(OutputPath, Path.ChangeExtension(scriptName, extension))); } private ICollection<IStreamSource> GetSources(IEnumerable<ITaskItem> sourceItems) { if (sourceItems == null) { return new TaskItemInputStreamSource[0]; } List<IStreamSource> sources = new List<IStreamSource>(); foreach (ITaskItem sourceItem in sourceItems) { // TODO: This is a hack... something in the .net 4 build system causes // generation of an AssemblyAttributes.cs file with fully-qualified // type names, that we can't handle (this comes from multitargeting), // and there doesn't seem like a way to turn it off. if (sourceItem.ItemSpec.EndsWith(".AssemblyAttributes.cs", StringComparison.OrdinalIgnoreCase)) { continue; } sources.Add(new TaskItemInputStreamSource(sourceItem)); } return sources; } private void OnScriptFileGenerated(ITaskItem scriptItem, CompilerOptions options, bool copyReferences) { Func<string, bool, string> getScriptFile = delegate(string reference, bool minimized) { string scriptFile = Path.ChangeExtension(reference, minimized ? ".min.js" : ".js"); string fileName = Path.GetFileNameWithoutExtension(scriptFile); if (fileName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase)) { fileName = (minimized ? "ss.min" : "ss") + Path.GetExtension(scriptFile); scriptFile = Path.Combine(Path.GetDirectoryName(scriptFile), fileName); } if (File.Exists(scriptFile)) { return scriptFile; } fileName = Path.GetFileName(scriptFile); if ((fileName.Length > 7) && fileName.StartsWith("Script.", StringComparison.OrdinalIgnoreCase)) { fileName = fileName.Substring(7); scriptFile = Path.Combine(Path.GetDirectoryName(scriptFile), fileName); if (File.Exists(scriptFile)) { return scriptFile; } } return null; }; Action<string, string> safeCopyFile = delegate(string sourceFilePath, string targetFilePath) { try { string directory = Path.GetDirectoryName(targetFilePath); if (Directory.Exists(directory) == false) { Directory.CreateDirectory(directory); } if (File.Exists(targetFilePath)) { // If the file already exists, make sure it is not read-only, so // it can be overrwritten. File.SetAttributes(targetFilePath, FileAttributes.Normal); } File.Copy(sourceFilePath, targetFilePath, /* overwrite */ true); // Copy the file, and then make sure it is not read-only (for example, if the // source file for a referenced script is read-only). File.SetAttributes(targetFilePath, FileAttributes.Normal); _scripts.Add(new TaskItem(targetFilePath)); } catch (Exception e) { Log.LogError("Unable to copy referenced script '" + sourceFilePath + "' as '" + targetFilePath + "' (" + e.Message + ")"); _hasErrors = true; } }; string projectName = Path.GetFileNameWithoutExtension(_projectPath); string scriptFileName = Path.GetFileName(scriptItem.ItemSpec); string scriptPath = Path.GetFullPath(scriptItem.ItemSpec); string scriptFolder = Path.GetDirectoryName(scriptItem.ItemSpec); Log.LogMessage(MessageImportance.High, "{0} -> {1} ({2})", projectName, scriptFileName, scriptPath); if (copyReferences) { foreach (string reference in options.References) { string scriptFile = getScriptFile(reference, /* minimized */ false); if (scriptFile != null) { string path = Path.Combine(scriptFolder, CopyReferencesPath, Path.GetFileName(scriptFile)); safeCopyFile(scriptFile, path); } string minScriptFile = getScriptFile(reference, /* minimized */ true); if (minScriptFile != null) { string path = Path.Combine(scriptFolder, CopyReferencesPath, Path.GetFileName(minScriptFile)); safeCopyFile(minScriptFile, path); } } } _scripts.Add(scriptItem); } #region Implementation of IErrorHandler void IErrorHandler.ReportError(string errorMessage, string location) { _hasErrors = true; int line = 0; int column = 0; if (String.IsNullOrEmpty(location) == false) { if (location.EndsWith(")", StringComparison.Ordinal)) { int index = location.LastIndexOf("(", StringComparison.Ordinal); Debug.Assert(index > 0); string position = location.Substring(index + 1, location.Length - index - 2); string[] positionParts = position.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); Debug.Assert(positionParts.Length == 2); Int32.TryParse(positionParts[0], out line); Int32.TryParse(positionParts[1], out column); location = location.Substring(0, index); } } Log.LogError(String.Empty, String.Empty, String.Empty, location, line, column, 0, 0, errorMessage); } #endregion #region Implementation of IStreamSourceResolver IStreamSource IStreamSourceResolver.Resolve(string name) { string path = Path.Combine(Path.GetDirectoryName(_projectPath), name); if (File.Exists(path)) { return new FileInputStreamSource(path, name); } return null; } #endregion private sealed class TaskItemInputStreamSource : FileInputStreamSource { public TaskItemInputStreamSource(ITaskItem taskItem) : base(taskItem.ItemSpec) { } public TaskItemInputStreamSource(ITaskItem taskItem, string name) : base(taskItem.ItemSpec, name) { } } private sealed class TaskItemOutputStreamSource : FileOutputStreamSource { public TaskItemOutputStreamSource(ITaskItem taskItem) : base(taskItem.ItemSpec) { } public TaskItemOutputStreamSource(ITaskItem taskItem, string name) : base(taskItem.ItemSpec, name) { } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Threading; using System.Collections.Generic; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client; using Apache.Geode.Client.UnitTests; using Region = Apache.Geode.Client.IRegion<Object, Object>; using Apache.Geode.Client.Tests; #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* class CSTXListener<TKey, TVal> : TransactionListenerAdapter<TKey, TVal> { public CSTXListener(string cacheName) { m_cacheName = cacheName; } public override void AfterCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterCommitEvents++; afterCommitKeyEvents += te.Events.Length; } public override void AfterFailedCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterFailedCommitEvents++; afterFailedCommitKeyEvents += te.Events.Length; } public override void AfterRollback(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterRollbackEvents++; afterRollbackKeyEvents += te.Events.Length; } public override void Close() { closeEvent++; } public void ShowTallies() { Util.Log("CSTXListener state: (afterCommitEvents = {0}, afterRollbackEvents = {1}, afterFailedCommitEvents = {2}, afterCommitRegionEvents = {3}, afterRollbackRegionEvents = {4}, afterFailedCommitRegionEvents = {5}, closeEvent = {6})", afterCommitEvents, afterRollbackEvents, afterFailedCommitEvents, afterCommitKeyEvents, afterRollbackKeyEvents, afterFailedCommitKeyEvents, closeEvent); } public int AfterCommitEvents { get { return afterCommitEvents; } } public int AfterRollbackEvents { get { return afterRollbackEvents; } } public int AfterFailedCommitEvents { get { return afterFailedCommitEvents; } } public int AfterCommitKeyEvents { get { return afterCommitKeyEvents; } } public int AfterRollbackKeyEvents { get { return afterRollbackKeyEvents; } } public int AfterFailedCommitKeyEvents { get { return afterFailedCommitKeyEvents; } } public int CloseEvent { get { return closeEvent; } } public bool IncorrectCacheName { get { return incorrectCacheName; } } private int afterCommitEvents = 0; private int afterRollbackEvents = 0; private int afterFailedCommitEvents = 0; private int afterCommitKeyEvents = 0; private int afterRollbackKeyEvents = 0; private int afterFailedCommitKeyEvents = 0; private int closeEvent = 0; private string m_cacheName = null; private bool incorrectCacheName = false; } class CSTXWriter<TKey, TVal> : TransactionWriterAdapter<TKey, TVal> { public CSTXWriter(string cacheName, string instanceName) { m_instanceName = instanceName; m_cacheName = cacheName; } public override void BeforeCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; beforeCommitEvents++; beforeCommitKeyEvents += te.Events.Length; } public int BeforeCommitEvents { get { return beforeCommitEvents; } } public int BeforeCommitKeyEvents { get { return beforeCommitKeyEvents; } } public string InstanceName { get { return m_instanceName; } } public bool IncorrectCacheName { get { return incorrectCacheName; } } public void ShowTallies() { Util.Log("CSTXWriter state: (beforeCommitEvents = {0}, beforeCommitRegionEvents = {1}, instanceName = {2})", beforeCommitEvents, beforeCommitKeyEvents, m_instanceName); } private int beforeCommitEvents = 0; private int beforeCommitKeyEvents = 0; private string m_cacheName = null; private string m_instanceName; private bool incorrectCacheName = false; } */ #endregion [TestFixture] [Category("group1")] [Category("unicast_only")] public class ThinClientCSTX : ThinClientRegionSteps { #region CSTX_COMMENTED - transaction listener and writer are disabled for now /*private CSTXWriter<object, object> m_writer1; private CSTXWriter<object, object> m_writer2; private CSTXListener<object, object> m_listener1; private CSTXListener<object, object> m_listener2;*/ #endregion RegionOperation o_region1; RegionOperation o_region2; private TallyListener<object, object> m_listener; private static string[] cstxRegions = new string[] { "cstx1", "cstx2", "cstx3" }; private UnitProcess m_client1; protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); return new ClientBase[] { m_client1 }; } public void CreateRegion(string regionName, string locators, bool listener) { if (listener) m_listener = new TallyListener<object, object>(); else m_listener = null; Region region = null; region = CacheHelper.CreateTCRegion_Pool<object, object>(regionName, false, false, m_listener, locators, "__TESTPOOL1_", false); } #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* public void ValidateCSTXListenerWriter() { Util.Log("tallies for listener 1"); m_listener1.ShowTallies(); Util.Log("tallies for writer 1"); m_writer1.ShowTallies(); Util.Log("tallies for listener 2"); m_listener2.ShowTallies(); Util.Log("tallies for writer 2"); m_writer2.ShowTallies(); // listener 1 Assert.AreEqual(4, m_listener1.AfterCommitEvents, "Should be 4"); Assert.AreEqual(14, m_listener1.AfterCommitKeyEvents, "Should be 14"); Assert.AreEqual(0, m_listener1.AfterFailedCommitEvents, "Should be 0"); Assert.AreEqual(0, m_listener1.AfterFailedCommitKeyEvents, "Should be 0"); Assert.AreEqual(2, m_listener1.AfterRollbackEvents, "Should be 2"); Assert.AreEqual(6, m_listener1.AfterRollbackKeyEvents, "Should be 6"); Assert.AreEqual(1, m_listener1.CloseEvent, "Should be 1"); Assert.AreEqual(false, m_listener1.IncorrectCacheName, "Incorrect cache name in the events"); // listener 2 Assert.AreEqual(2, m_listener2.AfterCommitEvents, "Should be 2"); Assert.AreEqual(6, m_listener2.AfterCommitKeyEvents, "Should be 6"); Assert.AreEqual(0, m_listener2.AfterFailedCommitEvents, "Should be 0"); Assert.AreEqual(0, m_listener2.AfterFailedCommitKeyEvents, "Should be 0"); Assert.AreEqual(2, m_listener2.AfterRollbackEvents, "Should be 2"); Assert.AreEqual(6, m_listener2.AfterRollbackKeyEvents, "Should be 6"); Assert.AreEqual(1, m_listener2.CloseEvent, "Should be 1"); Assert.AreEqual(false, m_listener2.IncorrectCacheName, "Incorrect cache name in the events"); // writer 1 Assert.AreEqual(3, m_writer1.BeforeCommitEvents, "Should be 3"); Assert.AreEqual(10, m_writer1.BeforeCommitKeyEvents, "Should be 10"); Assert.AreEqual(false, m_writer1.IncorrectCacheName, "Incorrect cache name in the events"); // writer 2 Assert.AreEqual(1, m_writer2.BeforeCommitEvents, "Should be 1"); Assert.AreEqual(4, m_writer2.BeforeCommitKeyEvents, "Should be 4"); Assert.AreEqual(false, m_writer2.IncorrectCacheName, "Incorrect cache name in the events"); } */ #endregion public void ValidateListener() { o_region1 = new RegionOperation(cstxRegions[2]); CacheHelper.CSTXManager.Begin(); o_region1.Region.Put("key3", "value1", null); o_region1.Region.Put("key4", "value2", null); o_region1.Region.Remove("key4"); CacheHelper.CSTXManager.Commit(); // server is conflating the events on the same key hence only 1 create Assert.AreEqual(1, m_listener.Creates, "Should be 1 creates"); Assert.AreEqual(1, m_listener.Destroys, "Should be 1 destroys"); CacheHelper.CSTXManager.Begin(); o_region1.Region.Put("key1", "value1", null); o_region1.Region.Put("key2", "value2", null); o_region1.Region.Invalidate("key1"); o_region1.Region.Invalidate("key3"); CacheHelper.CSTXManager.Commit(); // server is conflating the events on the same key hence only 1 invalidate Assert.AreEqual(3, m_listener.Creates, "Should be 3 creates"); Assert.AreEqual(1, m_listener.Invalidates, "Should be 1 invalidates"); } public void SuspendResumeRollback() { o_region1 = new RegionOperation(cstxRegions[0]); o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(CacheHelper.CSTXManager.TransactionId), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(CacheHelper.CSTXManager.TransactionId), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); TransactionId tid = CacheHelper.CSTXManager.Suspend(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), true, "Transaction should be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend"); CacheHelper.CSTXManager.Resume(tid); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); o_region2.PutOp(2, null); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region before commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region before commit"); CacheHelper.CSTXManager.Rollback(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), false, "Transaction should NOT exist"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "Transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid, TimeSpan.FromMilliseconds(3000)), false, "Transaction should not be resumed"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after rollback"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after rollback"); bool resumeEx = false; try { CacheHelper.CSTXManager.Resume(tid); } catch (IllegalStateException) { resumeEx = true; } Assert.AreEqual(resumeEx, true, "The transaction should not be resumed"); } public void SuspendResumeInThread() { AutoResetEvent txEvent = new AutoResetEvent(false); AutoResetEvent txIdUpdated = new AutoResetEvent(false); SuspendTransactionThread susObj = new SuspendTransactionThread(false, txEvent, txIdUpdated); Thread susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); ResumeTransactionThread resObj = new ResumeTransactionThread(susObj.Tid, false, false, txEvent); Thread resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(false, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, true, false, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(true, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, false, true, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(true, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, true, true, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); } public void SuspendResumeCommit() { o_region1 = new RegionOperation(cstxRegions[0]); o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(CacheHelper.CSTXManager.TransactionId), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(CacheHelper.CSTXManager.TransactionId), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); TransactionId tid = CacheHelper.CSTXManager.Suspend(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), true, "Transaction should be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend"); CacheHelper.CSTXManager.Resume(tid); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "The transaction should not have been resumed again."); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); o_region2.PutOp(2, null); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region before commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region before commit"); CacheHelper.CSTXManager.Commit(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), false, "Transaction should NOT exist"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "Transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid, TimeSpan.FromMilliseconds(3000)), false, "Transaction should not be resumed"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region after commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region after commit"); o_region1.DestroyOpWithPdxValue(1, null); o_region2.DestroyOpWithPdxValue(2, null); bool resumeEx = false; try { CacheHelper.CSTXManager.Resume(tid); } catch (IllegalStateException) { resumeEx = true; } Assert.AreEqual(resumeEx, true, "The transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.Suspend(), null, "The transaction should not be suspended"); } public void CallOp() { #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* m_writer1 = new CSTXWriter<object, object>(CacheHelper.DCache.Name, "cstxWriter1"); m_writer2 = new CSTXWriter<object, object>(CacheHelper.DCache.Name, "cstxWriter2"); m_listener1 = new CSTXListener<object, object>(CacheHelper.DCache.Name); m_listener2 = new CSTXListener<object, object>(CacheHelper.DCache.Name); CacheHelper.CSTXManager.AddListener<object, object>(m_listener1); CacheHelper.CSTXManager.AddListener<object, object>(m_listener2); CacheHelper.CSTXManager.SetWriter<object, object>(m_writer1); // test two listener one writer for commit on two regions Util.Log(" test two listener one writer for commit on two regions"); */ #endregion CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); o_region1.PutOp(2, null); o_region2 = new RegionOperation(cstxRegions[1]); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); //two pdx put as well Assert.AreEqual(2 + 2, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); Assert.AreEqual(2 + 2, o_region2.Region.Keys.Count, "Commit didn't put two values in the region"); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* Util.Log(" test two listener one writer for commit on two regions - complete"); ////////////////////////////////// // region test two listener one writer for commit on one region Util.Log(" region test two listener one writer for commit on one region"); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log(" region test two listener one writer for commit on one region - complete"); ////////////////////////////////// // test two listener one writer for rollback on two regions Util.Log(" test two listener one writer for rollback on two regions"); */ #endregion CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Rollback(); //two pdx put as well Assert.AreEqual(2 + 2, o_region1.Region.Keys.Count, "Region has incorrect number of objects"); Assert.AreEqual(2 + 2, o_region2.Region.Keys.Count, "Region has incorrect number of objects"); o_region1.DestroyOpWithPdxValue(2, null); o_region2.DestroyOpWithPdxValue(2, null); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* Util.Log(" test two listener one writer for rollback on two regions - complete"); ////////////////////////////////// // test two listener one writer for rollback on on region Util.Log(" test two listener one writer for rollback on on region"); CacheHelper.CSTXManager.Begin(); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Rollback(); Util.Log(" test two listener one writer for rollback on on region - complete"); ////////////////////////////////// // test remove listener Util.Log(" test remove listener"); CacheHelper.CSTXManager.RemoveListener<object, object>(m_listener2); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log(" test remove listener - complete" ); ////////////////////////////////// // test GetWriter Util.Log("test GetWriter"); CSTXWriter<object, object> writer = (CSTXWriter<object, object>)CacheHelper.CSTXManager.GetWriter<object, object>(); Assert.AreEqual(writer.InstanceName, m_writer1.InstanceName, "GetWriter is not returning the object set by SetWriter"); Util.Log("test GetWriter - complete"); ////////////////////////////////// // set a different writer Util.Log("set a different writer"); CacheHelper.CSTXManager.SetWriter<object, object>(m_writer2); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log("set a different writer - complete"); ////////////////////////////////// */ #endregion } void runThinClientCSTXTest() { CacheHelper.SetupJavaServers(true, "client_server_transactions.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CacheHelper.InitClient); Util.Log("Creating two regions in client1"); m_client1.Call(CreateRegion, cstxRegions[0], CacheHelper.Locators, false); m_client1.Call(CreateRegion, cstxRegions[1], CacheHelper.Locators, false); m_client1.Call(CreateRegion, cstxRegions[2], CacheHelper.Locators, true); m_client1.Call(CallOp); m_client1.Call(SuspendResumeCommit); m_client1.Call(SuspendResumeRollback); m_client1.Call(SuspendResumeInThread); m_client1.Call(ValidateListener); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* m_client1.Call(ValidateCSTXListenerWriter); */ #endregion m_client1.Call(CacheHelper.Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearLocators(); CacheHelper.ClearEndpoints(); } void runThinClientPersistentTXTest() { CacheHelper.SetupJavaServers(true, "client_server_persistent_transactions.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, "--J=-Dgemfire.ALLOW_PERSISTENT_TRANSACTIONS=true"); Util.Log("Cacheserver 1 started."); m_client1.Call(CacheHelper.InitClient); Util.Log("Creating two regions in client1"); m_client1.Call(CreateRegion, cstxRegions[0], CacheHelper.Locators, false); m_client1.Call(initializePdxSerializer); m_client1.Call(doPutGetWithPdxSerializer); m_client1.Call(CacheHelper.Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearLocators(); CacheHelper.ClearEndpoints(); } [TearDown] public override void EndTest() { base.EndTest(); } //Successful [Test] public void ThinClientCSTXTest() { runThinClientCSTXTest(); } [Test] public void ThinClientPersistentTXTest() { runThinClientPersistentTXTest(); } public class SuspendTransactionThread { public SuspendTransactionThread(bool sleep, AutoResetEvent txevent, AutoResetEvent txIdUpdated) { m_sleep = sleep; m_txevent = txevent; m_txIdUpdated = txIdUpdated; } public void ThreadStart() { RegionOperation o_region1 = new RegionOperation(cstxRegions[0]); RegionOperation o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); m_tid = CacheHelper.CSTXManager.TransactionId; m_txIdUpdated.Set(); if (m_sleep) { m_txevent.WaitOne(); Thread.Sleep(5000); } m_tid = CacheHelper.CSTXManager.Suspend(); } public TransactionId Tid { get { return m_tid; } } private TransactionId m_tid = null; private bool m_sleep = false; private AutoResetEvent m_txevent = null; AutoResetEvent m_txIdUpdated = null; } public class ResumeTransactionThread { public ResumeTransactionThread(TransactionId tid, bool isCommit, bool tryResumeWithSleep, AutoResetEvent txevent) { m_tryResumeWithSleep = tryResumeWithSleep; m_txevent = txevent; m_tid = tid; m_isCommit = isCommit; } public void ThreadStart() { RegionOperation o_region1 = new RegionOperation(cstxRegions[0]); RegionOperation o_region2 = new RegionOperation(cstxRegions[1]); if (m_tryResumeWithSleep) { if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; } else { if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == true, "Transaction should be suspended")) return; } if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == true, "Transaction should exist")) return; if (AssertCheckFail(0 == o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend")) return; if (AssertCheckFail(0 == o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend")) return; if (m_tryResumeWithSleep) { m_txevent.Set(); CacheHelper.CSTXManager.TryResume(m_tid, TimeSpan.FromMilliseconds(30000)); } else CacheHelper.CSTXManager.Resume(m_tid); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == true, "Transaction should exist")) return; if (AssertCheckFail(o_region1.Region.Keys.Count == 2, "There should be two values in the region after suspend")) return; if (AssertCheckFail(o_region2.Region.Keys.Count == 2, "There should be two values in the region after suspend")) return; o_region2.PutOp(2, null); if (m_isCommit) { CacheHelper.CSTXManager.Commit(); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == false, "Transaction should NOT exist")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid, TimeSpan.FromMilliseconds(3000)) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(2 == o_region1.Region.Keys.Count, "There should be four values in the region after commit")) return; if (AssertCheckFail(4 == o_region2.Region.Keys.Count, "There should be four values in the region after commit")) return; o_region1.DestroyOpWithPdxValue(1, null); o_region2.DestroyOpWithPdxValue(2, null); } else { CacheHelper.CSTXManager.Rollback(); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == false, "Transaction should NOT exist")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid, TimeSpan.FromMilliseconds(3000)) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(0 == o_region1.Region.Keys.Count, "There should be 0 values in the region after rollback")) return; if (AssertCheckFail(0 == o_region2.Region.Keys.Count, "There should be 0 values in the region after rollback")) return; } } public bool AssertCheckFail(bool cond, String error) { if (!cond) { m_isFailed = true; m_error = error; return true; } return false; } public TransactionId Tid { get { return m_tid; } } public bool IsFailed { get { return m_isFailed; } } public String Error { get { return m_error; } } private TransactionId m_tid = null; private bool m_tryResumeWithSleep = false; private bool m_isFailed = false; private String m_error; private bool m_isCommit = false; private AutoResetEvent m_txevent = null; } public void initializePdxSerializer() { Serializable.RegisterPdxSerializer(new PdxSerializer()); } public void doPutGetWithPdxSerializer() { CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); for (int i = 0; i < 10; i++) { o_region1.Region[i] = i + 1; object ret = o_region1.Region[i]; o_region1.Region[i + 10] = i + 10; ret = o_region1.Region[i + 10]; o_region1.Region[i + 20] = i + 20; ret = o_region1.Region[i + 20]; } CacheHelper.CSTXManager.Commit(); Util.Log("Region keys count after commit for non-pdx keys = {0} ", o_region1.Region.Keys.Count); Assert.AreEqual(30, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); for (int i = 100; i < 110; i++) { object put = new SerializePdx1(true); o_region1.Region[i] = put; put = new SerializePdx2(true); o_region1.Region[i + 10] = put; put = new SerializePdx3(true, i % 2); o_region1.Region[i + 20] = put; } CacheHelper.CSTXManager.Commit(); for (int i = 100; i < 110; i++) { object put = new SerializePdx1(true); object ret = o_region1.Region[i]; Assert.AreEqual(put, ret); put = new SerializePdx2(true); ret = o_region1.Region[i + 10]; Assert.AreEqual(put, ret); put = new SerializePdx3(true, i % 2); ret = o_region1.Region[i + 20]; Assert.AreEqual(put, ret); } Util.Log("Region keys count after pdx-keys commit = {0} ", o_region1.Region.Keys.Count); Assert.AreEqual(60, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); } } }
namespace GitVersion { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using GitVersion.Helpers; using LibGit2Sharp; static class LibGitExtensions { public static DateTimeOffset When(this Commit commit) { return commit.Committer.When; } public static Branch FindBranch(this IRepository repository, string branchName) { var exact = repository.Branches.FirstOrDefault(x => x.Name == branchName); if (exact != null) { return exact; } return repository.Branches.FirstOrDefault(x => x.Name == "origin/" + branchName); } public static SemanticVersion LastVersionTagOnBranch(this Branch branch, IRepository repository, string tagPrefixRegex) { var tags = repository.Tags.Select(t => t).ToList(); return repository.Commits.QueryBy(new CommitFilter { Since = branch.Tip }) .SelectMany(c => tags.Where(t => c.Sha == t.Target.Sha).SelectMany(t => { SemanticVersion semver; if (SemanticVersion.TryParse(t.Name, tagPrefixRegex, out semver)) return new [] { semver }; return new SemanticVersion[0]; })) .FirstOrDefault(); } public static Commit FindCommitBranchWasBranchedFrom(this Branch branch, IRepository repository, params Branch[] excludedBranches) { using (Logger.IndentLog("Finding branch source")) { var otherBranches = repository.Branches.Except(excludedBranches).Where(b => IsSameBranch(branch, b)).ToList(); var mergeBases = otherBranches.Select(b => { var otherCommit = b.Tip; if (b.Tip.Parents.Contains(branch.Tip)) { otherCommit = b.Tip.Parents.First(); } var mergeBase = repository.Commits.FindMergeBase(otherCommit, branch.Tip); return mergeBase; }).Where(b => b != null).ToList(); return mergeBases.OrderByDescending(b => b.Committer.When).FirstOrDefault(); } } static bool IsSameBranch(Branch branch, Branch b) { return (b.IsRemote ? b.Name.Replace(b.Remote.Name + "/", string.Empty) : b.Name) != branch.Name; } public static IEnumerable<Branch> GetBranchesContainingCommit(this Commit commit, IRepository repository, bool onlyTrackedBranches) { var directBranchHasBeenFound = false; foreach (var branch in repository.Branches) { if (branch.Tip.Sha != commit.Sha || (onlyTrackedBranches && !branch.IsTracking)) { continue; } directBranchHasBeenFound = true; yield return branch; } if (directBranchHasBeenFound) { yield break; } foreach (var branch in repository.Branches.Where(b => (onlyTrackedBranches && !b.IsTracking))) { var commits = repository.Commits.QueryBy(new CommitFilter { Since = branch }).Where(c => c.Sha == commit.Sha); if (!commits.Any()) { continue; } yield return branch; } } public static GitObject PeeledTarget(this Tag tag) { var target = tag.Target; while (target is TagAnnotation) { target = ((TagAnnotation)(target)).Target; } return target; } public static IEnumerable<Commit> CommitsPriorToThan(this Branch branch, DateTimeOffset olderThan) { return branch.Commits.SkipWhile(c => c.When() > olderThan); } public static bool IsDetachedHead(this Branch branch) { return branch.CanonicalName.Equals("(no branch)", StringComparison.OrdinalIgnoreCase); } public static string GetRepositoryDirectory(this IRepository repository, bool omitGitPostFix = true) { var gitDirectory = repository.Info.Path; gitDirectory = gitDirectory.TrimEnd('\\'); if (omitGitPostFix && gitDirectory.EndsWith(".git")) { gitDirectory = gitDirectory.Substring(0, gitDirectory.Length - ".git".Length); gitDirectory = gitDirectory.TrimEnd('\\'); } return gitDirectory; } public static void CheckoutFilesIfExist(this IRepository repository, params string[] fileNames) { if (fileNames == null || fileNames.Length == 0) { return; } Logger.WriteInfo("Checking out files that might be needed later in dynamic repository"); foreach (var fileName in fileNames) { try { Logger.WriteInfo(string.Format(" Trying to check out '{0}'", fileName)); var headBranch = repository.Head; var tip = headBranch.Tip; var treeEntry = tip[fileName]; if (treeEntry == null) { continue; } var fullPath = Path.Combine(repository.GetRepositoryDirectory(), fileName); using (var stream = ((Blob) treeEntry.Target).GetContentStream()) { using (var streamReader = new BinaryReader(stream)) { File.WriteAllBytes(fullPath, streamReader.ReadBytes((int)stream.Length)); } } } catch (Exception ex) { Logger.WriteWarning(string.Format(" An error occurred while checking out '{0}': '{1}'", fileName, ex.Message)); } } } public static void DumpGraph(this IRepository repository, Action<string> writer = null, int? maxCommits = null) { DumpGraph(repository.Info.Path, writer, maxCommits); } public static void DumpGraph(string workingDirectory, Action<string> writer = null, int? maxCommits = null) { var output = new StringBuilder(); try { ProcessHelper.Run( o => output.AppendLine(o), e => output.AppendLineFormat("ERROR: {0}", e), null, "git", @"log --graph --format=""%h %cr %d"" --decorate --date=relative --all --remotes=*" + (maxCommits != null ? string.Format(" -n {0}", maxCommits) : null), //@"log --graph --abbrev-commit --decorate --date=relative --all --remotes=*", workingDirectory); } catch (FileNotFoundException exception) { if (exception.FileName != "git") { throw; } output.AppendLine("Could not execute 'git log' due to the following error:"); output.AppendLine(exception.ToString()); } if (writer != null) writer(output.ToString()); else Console.Write(output.ToString()); } } }
/* Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser. This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. 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.Drawing; using System.Drawing.Drawing2D; using PdfSharp.Drawing; namespace Trizbort { /// <summary> /// A palette of drawing tools such as brushes, pens and fonts. /// </summary> /// <remarks> /// Centralising such tools in one place avoids tedious management /// of their lifetimes and avoids creating them until necessary, /// and then only once. /// </remarks> internal class Palette : IDisposable { public void Dispose() { foreach (var item in m_items) { item.Dispose(); } } public Pen Pen(Color color) { return Pen(color, Settings.LineWidth); } public Pen Pen(Color color, float width) { var pen = new Pen(color, width) {StartCap = LineCap.Round, EndCap = LineCap.Round}; m_items.Add(pen); return pen; } public Brush Brush(Color color) { var brush = new SolidBrush(color); m_items.Add(brush); return brush; } public XBrush Gradient(Rect rect, Color color1, Color color2) { var brush = new XLinearGradientBrush(rect.ToRectangleF(), color1, color2, XLinearGradientMode.ForwardDiagonal); return brush; } public Font Font(string familyName, float emSize) { var font = new Font(familyName, emSize, FontStyle.Regular, GraphicsUnit.World); m_items.Add(font); return font; } public Font Font(Font prototype, FontStyle newStyle) { var font = new Font(prototype, newStyle); m_items.Add(font); return font; } public XGraphicsPath Path() { var path = new XGraphicsPath(); //m_items.Add(path); return path; } public Pen LinePen { get { return m_linePen ?? (m_linePen = Pen(Settings.Color[Colors.Line])); } } public Pen DashedLinePen { get { if (m_dashedLinePen == null) { m_dashedLinePen = Pen(Settings.Color[Colors.Line]); m_dashedLinePen.DashStyle = DashStyle.Dot; } return m_dashedLinePen; } } public Pen SelectedLinePen { get { if (m_selectedLinePen == null) { m_selectedLinePen = Pen(Settings.Color[Colors.SelectedLine]); } return m_selectedLinePen; } } public Pen SelectedDashedLinePen { get { if (m_selectedDashedLinePen == null) { m_selectedDashedLinePen = Pen(Settings.Color[Colors.SelectedLine]); m_selectedDashedLinePen.DashStyle = DashStyle.Dot; } return m_selectedDashedLinePen; } } public Pen HoverLinePen { get { return m_hoverLinePen ?? (m_hoverLinePen = Pen(Settings.Color[Colors.HoverLine])); } } public Pen HoverDashedLinePen { get { if (m_hoverDashedLinePen == null) { m_hoverDashedLinePen = Pen(Settings.Color[Colors.HoverLine]); m_hoverDashedLinePen.DashStyle = DashStyle.Dot; } return m_hoverDashedLinePen; } } public Pen GetLinePen(bool selected, bool hover, bool dashed) { if (selected) { return dashed ? SelectedDashedLinePen : SelectedLinePen; } else if (hover) { return dashed ? HoverDashedLinePen : HoverLinePen; } return dashed ? DashedLinePen : LinePen; } public Brush GetLineBrush(bool selected, bool hover) { if (selected) { return SelectedLineBrush; } else if (hover) { return HoverLineBrush; } return LineBrush; } public Brush LineBrush { get { return m_lineBrush ?? (m_lineBrush = Brush(Settings.Color[Colors.Line])); } } public Brush SelectedLineBrush { get { return m_selectedLineBrush ?? (m_selectedLineBrush = Brush(Settings.Color[Colors.SelectedLine])); } } public Brush HoverLineBrush { get { return m_hoverLineBrush ?? (m_hoverLineBrush = Brush(Settings.Color[Colors.HoverLine])); } } public Pen BorderPen { get { return m_borderPen ?? (m_borderPen = Pen(Settings.Color[Colors.Border])); } } public Pen LargeTextPen { get { return m_largeTextPen ?? (m_largeTextPen = Pen(Settings.Color[Colors.LargeText])); } } public Pen FillPen { get { return m_fillPen ?? (m_fillPen = Pen(Settings.Color[Colors.Fill])); } } public Pen GridPen { get { return m_gridPen ?? (m_gridPen = Pen(Settings.Color[Colors.Grid], 0)); } } public Brush CanvasBrush { get { return m_canvasBrush ?? (m_canvasBrush = Brush(Settings.Color[Colors.Canvas])); } } public Brush BorderBrush { get { return m_borderBrush ?? (m_borderBrush = Brush(Settings.Color[Colors.Border])); } } public Brush FillBrush { get { return m_fillBrush ?? (m_fillBrush = Brush(Settings.Color[Colors.Fill])); } } public Brush LargeTextBrush { get { return m_largeTextBrush ?? (m_largeTextBrush = Brush(Settings.Color[Colors.LargeText])); } } public Brush SmallTextBrush { get { return m_smallTextBrush ?? (m_smallTextBrush = Brush(Settings.Color[Colors.SmallText])); } } public Brush LineTextBrush { get { if (m_lineTextBrush == null) { m_lineTextBrush = Brush(Settings.Color[Colors.LineText]); } return m_lineTextBrush; } } public Brush MarqueeFillBrush { get { if (m_marqueeFillBrush == null) { m_marqueeFillBrush = Brush(Color.FromArgb(80, Settings.Color[Colors.Border])); } return m_marqueeFillBrush; } } public Pen MarqueeBorderPen { get { if (m_marqueeBorderPen == null) { m_marqueeBorderPen = Pen(Color.FromArgb(120, Settings.Color[Colors.Border]), 0); } return m_marqueeBorderPen; } } public Pen ResizeBorderPen { get { if (m_resizeBorderPen == null) { m_resizeBorderPen = Pen(Color.FromArgb(64, Color.SteelBlue), 6); //m_resizeBorderPen.DashStyle = DashStyle.Dot; } return m_resizeBorderPen; } } private List<IDisposable> m_items = new List<IDisposable>(); private Pen m_linePen; private Pen m_dashedLinePen; private Pen m_selectedLinePen; private Pen m_selectedDashedLinePen; private Pen m_hoverLinePen; private Pen m_hoverDashedLinePen; private Brush m_lineBrush; private Brush m_selectedLineBrush; private Brush m_hoverLineBrush; private Pen m_borderPen; private Pen m_largeTextPen; private Pen m_fillPen; private Pen m_gridPen; private Brush m_borderBrush; private Brush m_fillBrush; private Brush m_canvasBrush; private Brush m_largeTextBrush; private Brush m_smallTextBrush; private Brush m_lineTextBrush; private Brush m_marqueeFillBrush; private Pen m_marqueeBorderPen; private Pen m_resizeBorderPen; } }
/* * $Id: Rfc2812.cs 288 2008-07-28 21:56:47Z meebey $ * $URL: svn://svn.qnetp.net/smartirc/SmartIrc4net/trunk/src/IrcCommands/Rfc2812.cs $ * $Rev: 288 $ * $Author: meebey $ * $Date: 2008-07-28 17:56:47 -0400 (Mon, 28 Jul 2008) $ * * SmartIrc4net - the IRC library for .NET/C# <http://smartirc4net.sf.net> * * Copyright (c) 2003-2005 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net> * * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Text; using System.Globalization; using System.Text.RegularExpressions; namespace Meebey.SmartIrc4net { /// <summary> /// /// </summary> /// <threadsafety static="true" instance="true" /> public sealed class Rfc2812 { // nickname = ( letter / special ) *8( letter / digit / special / "-" ) // letter = %x41-5A / %x61-7A ; A-Z / a-z // digit = %x30-39 ; 0-9 // special = %x5B-60 / %x7B-7D // ; "[", "]", "\", "`", "_", "^", "{", "|", "}" private static Regex _NicknameRegex = new Regex(@"^[A-Za-z\[\]\\`_^{|}][A-Za-z0-9\[\]\\`_\-^{|}]+$", RegexOptions.Compiled); private Rfc2812() { } /// <summary> /// Checks if the passed nickname is valid according to the RFC /// /// Use with caution, many IRC servers are not conform with this! /// </summary> public static bool IsValidNickname(string nickname) { if ((nickname != null) && (nickname.Length > 0) && (_NicknameRegex.Match(nickname).Success)) { return true; } return false; } public static string Pass(string password) { return "PASS "+password; } public static string Nick(string nickname) { return "NICK "+nickname; } public static string User(string username, int usermode, string realname) { return "USER "+username+" "+usermode.ToString()+" * :"+realname; } public static string Oper(string name, string password) { return "OPER "+name+" "+password; } public static string Privmsg(string destination, string message) { return "PRIVMSG "+destination+" :"+message; } public static string Notice(string destination, string message) { return "NOTICE "+destination+" :"+message; } public static string Join(string channel) { return "JOIN "+channel; } public static string Join(string[] channels) { string channellist = String.Join(",", channels); return "JOIN "+channellist; } public static string Join(string channel, string key) { return "JOIN "+channel+" "+key; } public static string Join(string[] channels, string[] keys) { string channellist = String.Join(",", channels); string keylist = String.Join(",", keys); return "JOIN "+channellist+" "+keylist; } public static string Part(string channel) { return "PART "+channel; } public static string Part(string[] channels) { string channellist = String.Join(",", channels); return "PART "+channellist; } public static string Part(string channel, string partmessage) { return "PART "+channel+" :"+partmessage; } public static string Part(string[] channels, string partmessage) { string channellist = String.Join(",", channels); return "PART "+channellist+" :"+partmessage; } public static string Kick(string channel, string nickname) { return "KICK "+channel+" "+nickname; } public static string Kick(string channel, string nickname, string comment) { return "KICK "+channel+" "+nickname+" :"+comment; } public static string Kick(string[] channels, string nickname) { string channellist = String.Join(",", channels); return "KICK "+channellist+" "+nickname; } public static string Kick(string[] channels, string nickname, string comment) { string channellist = String.Join(",", channels); return "KICK "+channellist+" "+nickname+" :"+comment; } public static string Kick(string channel, string[] nicknames) { string nicknamelist = String.Join(",", nicknames); return "KICK "+channel+" "+nicknamelist; } public static string Kick(string channel, string[] nicknames, string comment) { string nicknamelist = String.Join(",", nicknames); return "KICK "+channel+" "+nicknamelist+" :"+comment; } public static string Kick(string[] channels, string[] nicknames) { string channellist = String.Join(",", channels); string nicknamelist = String.Join(",", nicknames); return "KICK "+channellist+" "+nicknamelist; } public static string Kick(string[] channels, string[] nicknames, string comment) { string channellist = String.Join(",", channels); string nicknamelist = String.Join(",", nicknames); return "KICK "+channellist+" "+nicknamelist+" :"+comment; } public static string Motd() { return "MOTD"; } public static string Motd(string target) { return "MOTD "+target; } [Obsolete("use Lusers() method instead")] public static string Luser() { return Lusers(); } public static string Lusers() { return "LUSERS"; } [Obsolete("use Lusers(string) method instead")] public static string Luser(string mask) { return Lusers(mask); } public static string Lusers(string mask) { return "LUSER "+mask; } [Obsolete("use Lusers(string, string) method instead")] public static string Luser(string mask, string target) { return Lusers(mask, target); } public static string Lusers(string mask, string target) { return "LUSER "+mask+" "+target; } public static string Version() { return "VERSION"; } public static string Version(string target) { return "VERSION "+target; } public static string Stats() { return "STATS"; } public static string Stats(string query) { return "STATS "+query; } public static string Stats(string query, string target) { return "STATS "+query+" "+target; } public static string Links() { return "LINKS"; } public static string Links(string servermask) { return "LINKS "+servermask; } public static string Links(string remoteserver, string servermask) { return "LINKS "+remoteserver+" "+servermask; } public static string Time() { return "TIME"; } public static string Time(string target) { return "TIME "+target; } public static string Connect(string targetserver, string port) { return "CONNECT "+targetserver+" "+port; } public static string Connect(string targetserver, string port, string remoteserver) { return "CONNECT "+targetserver+" "+port+" "+remoteserver; } public static string Trace() { return "TRACE"; } public static string Trace(string target) { return "TRACE "+target; } public static string Admin() { return "ADMIN"; } public static string Admin(string target) { return "ADMIN "+target; } public static string Info() { return "INFO"; } public static string Info(string target) { return "INFO "+target; } public static string Servlist() { return "SERVLIST"; } public static string Servlist(string mask) { return "SERVLIST "+mask; } public static string Servlist(string mask, string type) { return "SERVLIST "+mask+" "+type; } public static string Squery(string servicename, string servicetext) { return "SQUERY "+servicename+" :"+servicetext; } public static string List() { return "LIST"; } public static string List(string channel) { return "LIST "+channel; } public static string List(string[] channels) { string channellist = String.Join(",", channels); return "LIST "+channellist; } public static string List(string channel, string target) { return "LIST "+channel+" "+target; } public static string List(string[] channels, string target) { string channellist = String.Join(",", channels); return "LIST "+channellist+" "+target; } public static string Names() { return "NAMES"; } public static string Names(string channel) { return "NAMES "+channel; } public static string Names(string[] channels) { string channellist = String.Join(",", channels); return "NAMES "+channellist; } public static string Names(string channel, string target) { return "NAMES "+channel+" "+target; } public static string Names(string[] channels, string target) { string channellist = String.Join(",", channels); return "NAMES "+channellist+" "+target; } public static string Topic(string channel) { return "TOPIC "+channel; } public static string Topic(string channel, string newtopic) { return "TOPIC "+channel+" :"+newtopic; } public static string Mode(string target) { return "MODE "+target; } public static string Mode(string target, string newmode) { return "MODE "+target+" "+newmode; } /* public static string Mode(string target, string[] newModes, string[] newModeParameters) { if (newModes == null) { throw new ArgumentNullException("newModes"); } if (newModeParameters == null) { throw new ArgumentNullException("newModeParameters"); } if (newModes.Length != newModeParameters.Length) { throw new ArgumentException("newModes and modeParameters must have the same size."); } StringBuilder newMode = new StringBuilder(newModes.Length); StringBuilder newModeParameter = new StringBuilder(); // as per RFC 3.2.3, maximum is 3 modes changes at once int maxModeChanges = 3; if (newModes.Length > maxModeChanges) { throw new ArgumentOutOfRangeException( "newModes.Length", newModes.Length, String.Format("Mode change list is too large (> {0}).", maxModeChanges) ); } for (int i = 0; i < newModes.Length; i += maxModeChanges) { for (int j = 0; j < maxModeChanges; j++) { newMode.Append(newModes[i + j]); } for (int j = 0; j < maxModeChanges; j++) { newModeParameter.Append(newModeParameters[i + j]); } } newMode.Append(" "); newMode.Append(newModeParameter.ToString()); return Mode(target, newMode.ToString()); } */ public static string Service(string nickname, string distribution, string info) { return "SERVICE "+nickname+" * "+distribution+" * * :"+info; } public static string Invite(string nickname, string channel) { return "INVITE "+nickname+" "+channel; } public static string Who() { return "WHO"; } public static string Who(string mask) { return "WHO "+mask; } public static string Who(string mask, bool ircop) { if (ircop) { return "WHO "+mask+" o"; } else { return "WHO "+mask; } } public static string Whois(string mask) { return "WHOIS "+mask; } public static string Whois(string[] masks) { string masklist = String.Join(",", masks); return "WHOIS "+masklist; } public static string Whois(string target, string mask) { return "WHOIS "+target+" "+mask; } public static string Whois(string target, string[] masks) { string masklist = String.Join(",", masks); return "WHOIS "+target+" "+masklist; } public static string Whowas(string nickname) { return "WHOWAS "+nickname; } public static string Whowas(string[] nicknames) { string nicknamelist = String.Join(",", nicknames); return "WHOWAS "+nicknamelist; } public static string Whowas(string nickname, string count) { return "WHOWAS "+nickname+" "+count+" "; } public static string Whowas(string[] nicknames, string count) { string nicknamelist = String.Join(",", nicknames); return "WHOWAS "+nicknamelist+" "+count+" "; } public static string Whowas(string nickname, string count, string target) { return "WHOWAS "+nickname+" "+count+" "+target; } public static string Whowas(string[] nicknames, string count, string target) { string nicknamelist = String.Join(",", nicknames); return "WHOWAS "+nicknamelist+" "+count+" "+target; } public static string Kill(string nickname, string comment) { return "KILL "+nickname+" :"+comment; } public static string Ping(string server) { return "PING "+server; } public static string Ping(string server, string server2) { return "PING "+server+" "+server2; } public static string Pong(string server) { return "PONG "+server; } public static string Pong(string server, string server2) { return "PONG "+server+" "+server2; } public static string Error(string errormessage) { return "ERROR :"+errormessage; } public static string Away() { return "AWAY"; } public static string Away(string awaytext) { return "AWAY :"+awaytext; } public static string Rehash() { return "REHASH"; } public static string Die() { return "DIE"; } public static string Restart() { return "RESTART"; } public static string Summon(string user) { return "SUMMON "+user; } public static string Summon(string user, string target) { return "SUMMON "+user+" "+target; } public static string Summon(string user, string target, string channel) { return "SUMMON "+user+" "+target+" "+channel; } public static string Users() { return "USERS"; } public static string Users(string target) { return "USERS "+target; } public static string Wallops(string wallopstext) { return "WALLOPS :"+wallopstext; } public static string Userhost(string nickname) { return "USERHOST "+nickname; } public static string Userhost(string[] nicknames) { string nicknamelist = String.Join(" ", nicknames); return "USERHOST "+nicknamelist; } public static string Ison(string nickname) { return "ISON "+nickname; } public static string Ison(string[] nicknames) { string nicknamelist = String.Join(" ", nicknames); return "ISON "+nicknamelist; } public static string Quit() { return "QUIT"; } public static string Quit(string quitmessage) { return "QUIT :"+quitmessage; } public static string Squit(string server, string comment) { return "SQUIT "+server+" :"+comment; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using Debugging; using Microsoft.Zelig.Runtime.TypeSystem; using System; using System.Diagnostics; public sealed class InliningPathAnnotation : Annotation , IInliningPathAnnotation { // // State // // this is the original path used in the inlining heuristics unmodified for compatibility private MethodRepresentation[] m_path; // This contains the locations where the operator that this annotation is attached to was inlined into private DebugInfo[] m_InlinedAt; // // Constructor Methods // private InliningPathAnnotation( MethodRepresentation[] path, DebugInfo[] inlinedAt ) { Debug.Assert(path.Length == inlinedAt.Length); Debug.Assert(path.Length != 0); m_path = path; m_InlinedAt = inlinedAt; } public static InliningPathAnnotation Create( TypeSystemForIR ts , InliningPathAnnotation anOuter , MethodRepresentation md , DebugInfo debugInfo, InliningPathAnnotation anInner ) { Debug.Assert(anOuter == null || anOuter.DebugInfoPath.Length == anOuter.Path.Length); Debug.Assert(anInner == null || anInner.DebugInfoPath.Length == anInner.Path.Length); var pathOuter = anOuter != null ? anOuter.m_path : MethodRepresentation.SharedEmptyArray; var pathInner = anInner != null ? anInner.Path : MethodRepresentation.SharedEmptyArray; var path = ArrayUtility.AppendToNotNullArray( pathOuter, md ); path = ArrayUtility.AppendNotNullArrayToNotNullArray( path, pathInner ); // if the operator or varialbe didn't have debug info, then use the method itself if (debugInfo == null) debugInfo = md.DebugInfo; var debugInfoOuter = anOuter?.m_InlinedAt ?? DebugInfo.SharedEmptyArray; var debugInfoInner = anInner?.m_InlinedAt ?? DebugInfo.SharedEmptyArray; var debugInfoPath = ArrayUtility.AppendToNotNullArray( debugInfoOuter, debugInfo ); debugInfoPath = ArrayUtility.AppendNotNullArrayToNotNullArray( debugInfoPath, debugInfoInner ); return (InliningPathAnnotation)MakeUnique( ts, new InliningPathAnnotation( path, debugInfoPath ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is InliningPathAnnotation) { InliningPathAnnotation other = (InliningPathAnnotation)obj; return ArrayUtility.ArrayEqualsNotNull( this.m_path, other.m_path, 0 ); } return false; } public override int GetHashCode() { if(m_path.Length > 0) { return m_path[0].GetHashCode(); } return 0; } // // Helper Methods // public override Annotation Clone( CloningContext context ) { MethodRepresentation[] path = context.ConvertMethods( m_path ); if(Object.ReferenceEquals( path, m_path )) { return this; // Nothing to change. } return RegisterAndCloneState( context, MakeUnique( context.TypeSystem, new InliningPathAnnotation( path, m_InlinedAt ) ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); object origin = context.GetTransformInitiator(); if(origin is CompilationSteps.ComputeCallsClosure.Context) { // // Don't propagate the path, it might include methods that don't exist anymore. // } else if (context is TypeSystemForCodeTransformation.FlagProhibitedUses) { TypeSystemForCodeTransformation ts = (TypeSystemForCodeTransformation)context.GetTypeSystem(); for (int i = m_path.Length; --i >= 0;) { MethodRepresentation md = m_path[i]; if (ts.ReachabilitySet.IsProhibited(md)) { m_path = ArrayUtility.RemoveAtPositionFromNotNullArray(m_path, i); // REVIEW: // Consider implications of not removing the entry, but instead // setting the scope to null, this would keep the Source and line debug // info so the debug info code gneration could treat this like a // pre-processor macro substitution instead of an inlined call to // a function that doesn't exist anymore. m_InlinedAt = ArrayUtility.RemoveAtPositionFromNotNullArray(m_InlinedAt, i); IsSquashed = true; } } } else { context.Transform( ref m_path ); // TODO: Handle m_DebugInfo - there is no Transform method for DebugInfo[] so this info isn't serialized, etc... } context.Pop(); //Debug.Assert(m_path.Length == m_InlinedAt.Length); //Debug.Assert(m_path.Length != 0 || IsSquashed); } //--// // // Access Methods // public bool IsSquashed { get; private set; } /// <summary>Method path for an inlined operator</summary> /// <remarks> /// The last entry in the array contains the original source method for the operator this annotation is attached to. /// </remarks> public MethodRepresentation[] Path => m_path; /// <summary>Retrieves the source location information for the inlining chain</summary> /// <remarks> /// <para>It is possible for entries in this array to be null if there was no debug information /// for the call site the method is inlined into.</para> /// <para>It is worth noting that the debug info path does not "line up" with the <see cref="Path"/> /// array, it is in fact off by one index. This is due to the fact that the operator that this /// annotation applies to has its own DebugInfo indicating its source location. Thus, the last /// entry in DebugInfoPath contains the source location where the operator was inlined *into*.</para> /// </remarks> public Debugging.DebugInfo[] DebugInfoPath => m_InlinedAt; //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( "<Inlining Path:" ); bool fFirst = true; foreach(MethodRepresentation md in m_path) { if(!fFirst) { sb.AppendLine(); } else { fFirst = false; } sb.AppendFormat( " {0}", md.ToShortString() ); } sb.Append( ">" ); sb.Append("<DebugInfo Path:"); fFirst = true; if(m_InlinedAt != null) { foreach(var debugInfo in m_InlinedAt) { if(!fFirst) { sb.AppendLine( ); } else { fFirst = false; } sb.AppendFormat( " {0}", m_InlinedAt ); } } else { sb.AppendFormat( " {0}", "UNKNOWN" ); } sb.Append(">"); return sb.ToString(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; class r8NaNadd { //user-defined class that overloads operator + public class numHolder { double d_num; public numHolder(double d_num) { this.d_num = Convert.ToSingle(d_num); } public static double operator +(numHolder a, double b) { return a.d_num + b; } public static double operator +(numHolder a, numHolder b) { return a.d_num + b.d_num; } } static double d_s_test1_op1 = Double.NegativeInfinity; static double d_s_test1_op2 = Double.PositiveInfinity; static double d_s_test2_op1 = Double.PositiveInfinity; static double d_s_test2_op2 = Double.NaN; static double d_s_test3_op1 = Double.NaN; static double d_s_test3_op2 = Double.NaN; public static double d_test1_f(String s) { if (s == "test1_op1") return Double.NegativeInfinity; else return Double.PositiveInfinity; } public static double d_test2_f(String s) { if (s == "test2_op1") return Double.PositiveInfinity; else return Double.NaN; } public static double d_test3_f(String s) { if (s == "test3_op1") return Double.NaN; else return Double.NaN; } class CL { public double d_cl_test1_op1 = Double.NegativeInfinity; public double d_cl_test1_op2 = Double.PositiveInfinity; public double d_cl_test2_op1 = Double.PositiveInfinity; public double d_cl_test2_op2 = Double.NaN; public double d_cl_test3_op1 = Double.NaN; public double d_cl_test3_op2 = Double.NaN; } struct VT { public double d_vt_test1_op1; public double d_vt_test1_op2; public double d_vt_test2_op1; public double d_vt_test2_op2; public double d_vt_test3_op1; public double d_vt_test3_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.d_vt_test1_op1 = Double.NegativeInfinity; vt1.d_vt_test1_op2 = Double.PositiveInfinity; vt1.d_vt_test2_op1 = Double.PositiveInfinity; vt1.d_vt_test2_op2 = Double.NaN; vt1.d_vt_test3_op1 = Double.NaN; vt1.d_vt_test3_op2 = Double.NaN; double[] d_arr1d_test1_op1 = { 0, Double.NegativeInfinity }; double[,] d_arr2d_test1_op1 = { { 0, Double.NegativeInfinity }, { 1, 1 } }; double[, ,] d_arr3d_test1_op1 = { { { 0, Double.NegativeInfinity }, { 1, 1 } } }; double[] d_arr1d_test1_op2 = { Double.PositiveInfinity, 0, 1 }; double[,] d_arr2d_test1_op2 = { { 0, Double.PositiveInfinity }, { 1, 1 } }; double[, ,] d_arr3d_test1_op2 = { { { 0, Double.PositiveInfinity }, { 1, 1 } } }; double[] d_arr1d_test2_op1 = { 0, Double.PositiveInfinity }; double[,] d_arr2d_test2_op1 = { { 0, Double.PositiveInfinity }, { 1, 1 } }; double[, ,] d_arr3d_test2_op1 = { { { 0, Double.PositiveInfinity }, { 1, 1 } } }; double[] d_arr1d_test2_op2 = { Double.NaN, 0, 1 }; double[,] d_arr2d_test2_op2 = { { 0, Double.NaN }, { 1, 1 } }; double[, ,] d_arr3d_test2_op2 = { { { 0, Double.NaN }, { 1, 1 } } }; double[] d_arr1d_test3_op1 = { 0, Double.NaN }; double[,] d_arr2d_test3_op1 = { { 0, Double.NaN }, { 1, 1 } }; double[, ,] d_arr3d_test3_op1 = { { { 0, Double.NaN }, { 1, 1 } } }; double[] d_arr1d_test3_op2 = { Double.NaN, 0, 1 }; double[,] d_arr2d_test3_op2 = { { 0, Double.NaN }, { 1, 1 } }; double[, ,] d_arr3d_test3_op2 = { { { 0, Double.NaN }, { 1, 1 } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { double d_l_test1_op1 = Double.NegativeInfinity; double d_l_test1_op2 = Double.PositiveInfinity; if (!Double.IsNaN(d_l_test1_op1 + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_l_test1_op2)) { Console.WriteLine("Test1_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_s_test1_op2)) { Console.WriteLine("Test1_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] + d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 64 failed"); passed = false; } } { double d_l_test2_op1 = Double.PositiveInfinity; double d_l_test2_op2 = Double.NaN; if (!Double.IsNaN(d_l_test2_op1 + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_l_test2_op2)) { Console.WriteLine("Test2_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_s_test2_op2)) { Console.WriteLine("Test2_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] + d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 64 failed"); passed = false; } } { double d_l_test3_op1 = Double.NaN; double d_l_test3_op2 = Double.NaN; if (!Double.IsNaN(d_l_test3_op1 + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_l_test3_op2)) { Console.WriteLine("Test3_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_s_test3_op2)) { Console.WriteLine("Test3_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] + d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 64 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.Win32; namespace Microsoft.PythonTools.Profiling { sealed class ProfiledProcess : IDisposable { private readonly string _exe, _args, _dir; private readonly ProcessorArchitecture _arch; private readonly Process _process; private readonly PythonToolsService _pyService; public ProfiledProcess(PythonToolsService pyService, string exe, string args, string dir, Dictionary<string, string> envVars) { var arch = NativeMethods.GetBinaryType(exe); if (arch != ProcessorArchitecture.X86 && arch != ProcessorArchitecture.Amd64) { throw new InvalidOperationException(Strings.UnsupportedArchitecture.FormatUI(arch)); } dir = PathUtils.TrimEndSeparator(dir); if (string.IsNullOrEmpty(dir)) { dir = "."; } _pyService = pyService; _exe = exe; _args = args; _dir = dir; _arch = arch; ProcessStartInfo processInfo; string pythonInstallDir = Path.GetDirectoryName(PythonToolsInstallPath.GetFile("VsPyProf.dll", typeof(ProfiledProcess).Assembly)); string dll = _arch == ProcessorArchitecture.Amd64 ? "VsPyProf.dll" : "VsPyProfX86.dll"; string arguments = string.Join(" ", ProcessOutput.QuoteSingleArgument(Path.Combine(pythonInstallDir, "proflaun.py")), ProcessOutput.QuoteSingleArgument(Path.Combine(pythonInstallDir, dll)), ProcessOutput.QuoteSingleArgument(dir), _args ); processInfo = new ProcessStartInfo(_exe, arguments); if (_pyService.DebuggerOptions.WaitOnNormalExit) { processInfo.EnvironmentVariables["VSPYPROF_WAIT_ON_NORMAL_EXIT"] = "1"; } if (_pyService.DebuggerOptions.WaitOnAbnormalExit) { processInfo.EnvironmentVariables["VSPYPROF_WAIT_ON_ABNORMAL_EXIT"] = "1"; } processInfo.CreateNoWindow = false; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = false; processInfo.WorkingDirectory = _dir; if (envVars != null) { foreach (var keyValue in envVars) { processInfo.EnvironmentVariables[keyValue.Key] = keyValue.Value; } } _process = new Process(); _process.StartInfo = processInfo; } public void Dispose() { _process.Dispose(); } public void StartProfiling(string filename) { StartPerfMon(filename); _process.EnableRaisingEvents = true; _process.Exited += (sender, args) => { try { // Exited event is fired on a random thread pool thread, we need to handle exceptions. StopPerfMon(); } catch (InvalidOperationException e) { MessageBox.Show(Strings.UnableToStopPerfMon.FormatUI(e.Message), Strings.ProductTitle); } var procExited = ProcessExited; if (procExited != null) { procExited(this, EventArgs.Empty); } }; _process.Start(); } public event EventHandler ProcessExited; private void StartPerfMon(string filename) { string perfToolsPath = GetPerfToolsPath(); string perfMonPath = Path.Combine(perfToolsPath, "VSPerfMon.exe"); if (!File.Exists(perfMonPath)) { throw new InvalidOperationException(Strings.CannotLocatePerformanceTools); } var psi = new ProcessStartInfo(perfMonPath, "/trace /output:" + ProcessOutput.QuoteSingleArgument(filename)); psi.CreateNoWindow = true; psi.UseShellExecute = false; psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; Process.Start(psi).Dispose(); string perfCmdPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe"); using (var p = ProcessOutput.RunHiddenAndCapture(perfCmdPath, "/waitstart")) { p.Wait(); if (p.ExitCode != 0) { throw new InvalidOperationException(Strings.StartPerfCmdError.FormatUI( string.Join(Environment.NewLine, p.StandardOutputLines), string.Join(Environment.NewLine, p.StandardErrorLines) )); } } } private void StopPerfMon() { string perfToolsPath = GetPerfToolsPath(); string perfMonPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe"); using (var p = ProcessOutput.RunHiddenAndCapture(perfMonPath, "/shutdown")) { p.Wait(); if (p.ExitCode != 0) { throw new InvalidOperationException(Strings.StopPerfMonError.FormatUI( string.Join(Environment.NewLine, p.StandardOutputLines), string.Join(Environment.NewLine, p.StandardErrorLines) )); } } } private string GetPerfToolsPath() { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { if (baseKey == null) { throw new InvalidOperationException(Strings.CannotOpenSystemRegistry); } using (var key = baseKey.OpenSubKey(@"Software\Microsoft\VisualStudio\VSPerf")) { // ie. CollectionToolsDir2022 var path = key?.GetValue("CollectionToolsDir" + AssemblyVersionInfo.VSName) as string; if (!string.IsNullOrEmpty(path)) { if (_arch == ProcessorArchitecture.Amd64) { path = PathUtils.GetAbsoluteDirectoryPath(path, "x64"); } if (Directory.Exists(path)) { return path; } } } using (var key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\RemoteTools\{0}\DiagnosticsHub".FormatInvariant(AssemblyVersionInfo.VSVersion))) { var path = PathUtils.GetParent(key?.GetValue("VSPerfPath") as string); if (!string.IsNullOrEmpty(path)) { if (_arch == ProcessorArchitecture.Amd64) { path = PathUtils.GetAbsoluteDirectoryPath(path, "x64"); } if (Directory.Exists(path)) { return path; } } } } Debug.Fail("Registry search for Perfomance Tools failed - falling back on old path"); string shFolder; if (!_pyService.Site.TryGetShellProperty(__VSSPROPID.VSSPROPID_InstallDirectory, out shFolder)) { throw new InvalidOperationException(Strings.CannotFindShellFolder); } try { shFolder = Path.GetDirectoryName(Path.GetDirectoryName(shFolder)); } catch (ArgumentException) { throw new InvalidOperationException(Strings.CannotFindShellFolder); } string perfToolsPath; if (_arch == ProcessorArchitecture.Amd64) { perfToolsPath = @"Team Tools\Performance Tools\x64"; } else { perfToolsPath = @"Team Tools\Performance Tools\"; } perfToolsPath = Path.Combine(shFolder, perfToolsPath); return perfToolsPath; } internal void StopProfiling() { _process.Kill(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Security.Claims; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.TagHelpers.Cache; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.WebEncoders.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.TagHelpers { public class CacheTagKeyTest { [Fact] public void GenerateKey_ReturnsKeyBasedOnTagHelperUniqueId() { // Arrange var id = Guid.NewGuid().ToString(); var tagHelperContext = GetTagHelperContext(id); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; var expected = "CacheTagHelper||" + id; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] public void Equals_ReturnsTrueOnSameKey() { // Arrange var id = Guid.NewGuid().ToString(); var tagHelperContext1 = GetTagHelperContext(id); var cacheTagHelper1 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; var tagHelperContext2 = GetTagHelperContext(id); var cacheTagHelper2 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; // Act var cacheTagKey1 = new CacheTagKey(cacheTagHelper1, tagHelperContext1); var cacheTagKey2 = new CacheTagKey(cacheTagHelper2, tagHelperContext2); // Assert Assert.Equal(cacheTagKey1, cacheTagKey2); } [Fact] public void Equals_ReturnsFalseOnDifferentKey() { // Arrange var tagHelperContext1 = GetTagHelperContext("some-id"); var cacheTagHelper1 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; var tagHelperContext2 = GetTagHelperContext("some-other-id"); var cacheTagHelper2 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; // Act var cacheTagKey1 = new CacheTagKey(cacheTagHelper1, tagHelperContext1); var cacheTagKey2 = new CacheTagKey(cacheTagHelper2, tagHelperContext2); // Assert Assert.NotEqual(cacheTagKey1, cacheTagKey2); } [Fact] public void GetHashCode_IsSameForSimilarCacheTagHelper() { // Arrange var tagHelperContext1 = GetTagHelperContext("some-id"); var cacheTagHelper1 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; var tagHelperContext2 = GetTagHelperContext("some-id"); var cacheTagHelper2 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; var cacheKey1 = new CacheTagKey(cacheTagHelper1, tagHelperContext1); var cacheKey2 = new CacheTagKey(cacheTagHelper2, tagHelperContext2); // Act var hashcode1 = cacheKey1.GetHashCode(); var hashcode2 = cacheKey2.GetHashCode(); // Assert Assert.Equal(hashcode1, hashcode2); } [Fact] public void GetHashCode_VariesByUniqueId() { // Arrange var tagHelperContext1 = GetTagHelperContext("some-id"); var cacheTagHelper1 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; var tagHelperContext2 = GetTagHelperContext("some-other-id"); var cacheTagHelper2 = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext() }; var cacheKey1 = new CacheTagKey(cacheTagHelper1, tagHelperContext1); var cacheKey2 = new CacheTagKey(cacheTagHelper2, tagHelperContext2); // Act var hashcode1 = cacheKey1.GetHashCode(); var hashcode2 = cacheKey2.GetHashCode(); // Assert Assert.NotEqual(hashcode1, hashcode2); } [Fact] public void GenerateKey_ReturnsKeyBasedOnTagHelperName() { // Arrange var name = "some-name"; var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new DistributedCacheTagHelper( Mock.Of<IDistributedCacheTagHelperService>(), new HtmlTestEncoder()) { ViewContext = GetViewContext(), Name = name }; var expected = "DistributedCacheTagHelper||" + name; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Theory] [InlineData("Vary-By-Value")] [InlineData("Vary with spaces")] [InlineData(" Vary with more spaces ")] public void GenerateKey_UsesVaryByPropertyToGenerateKey(string varyBy) { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryBy = varyBy }; var expected = "CacheTagHelper||testid||VaryBy||" + varyBy; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Theory] [InlineData("Cookie0", "CacheTagHelper||testid||VaryByCookie(Cookie0||Cookie0Value)")] [InlineData("Cookie0,Cookie1", "CacheTagHelper||testid||VaryByCookie(Cookie0||Cookie0Value||Cookie1||Cookie1Value)")] [InlineData("Cookie0, Cookie1", "CacheTagHelper||testid||VaryByCookie(Cookie0||Cookie0Value||Cookie1||Cookie1Value)")] [InlineData(" Cookie0, , Cookie1 ", "CacheTagHelper||testid||VaryByCookie(Cookie0||Cookie0Value||Cookie1||Cookie1Value)")] [InlineData(",Cookie0,,Cookie1,", "CacheTagHelper||testid||VaryByCookie(Cookie0||Cookie0Value||Cookie1||Cookie1Value)")] public void GenerateKey_UsesVaryByCookieName(string varyByCookie, string expected) { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByCookie = varyByCookie }; cacheTagHelper.ViewContext.HttpContext.Request.Headers["Cookie"] = "Cookie0=Cookie0Value;Cookie1=Cookie1Value"; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Theory] [InlineData("Accept-Language", "CacheTagHelper||testid||VaryByHeader(Accept-Language||en-us;charset=utf8)")] [InlineData("X-CustomHeader,Accept-Encoding, NotAvailable", "CacheTagHelper||testid||VaryByHeader(X-CustomHeader||Header-Value||Accept-Encoding||utf8||NotAvailable||)")] [InlineData("X-CustomHeader, , Accept-Encoding, NotAvailable", "CacheTagHelper||testid||VaryByHeader(X-CustomHeader||Header-Value||Accept-Encoding||utf8||NotAvailable||)")] public void GenerateKey_UsesVaryByHeader(string varyByHeader, string expected) { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByHeader = varyByHeader }; var headers = cacheTagHelper.ViewContext.HttpContext.Request.Headers; headers["Accept-Language"] = "en-us;charset=utf8"; headers["Accept-Encoding"] = "utf8"; headers["X-CustomHeader"] = "Header-Value"; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Theory] [InlineData("category", "CacheTagHelper||testid||VaryByQuery(category||cats)")] [InlineData("Category,SortOrder,SortOption", "CacheTagHelper||testid||VaryByQuery(Category||cats||SortOrder||||SortOption||Adorability)")] [InlineData("Category, SortOrder, SortOption, ", "CacheTagHelper||testid||VaryByQuery(Category||cats||SortOrder||||SortOption||Adorability)")] public void GenerateKey_UsesVaryByQuery(string varyByQuery, string expected) { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByQuery = varyByQuery }; cacheTagHelper.ViewContext.HttpContext.Request.QueryString = new QueryString("?sortoption=Adorability&Category=cats&sortOrder="); // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Theory] [InlineData("id", "CacheTagHelper||testid||VaryByRoute(id||4)")] [InlineData("Category,,Id,OptionRouteValue", "CacheTagHelper||testid||VaryByRoute(Category||MyCategory||Id||4||OptionRouteValue||)")] [InlineData(" Category, , Id, OptionRouteValue, ", "CacheTagHelper||testid||VaryByRoute(Category||MyCategory||Id||4||OptionRouteValue||)")] public void GenerateKey_UsesVaryByRoute(string varyByRoute, string expected) { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByRoute = varyByRoute }; cacheTagHelper.ViewContext.RouteData.Values["id"] = 4; cacheTagHelper.ViewContext.RouteData.Values["category"] = "MyCategory"; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] [ReplaceCulture("de-CH", "de-CH")] public void GenerateKey_UsesVaryByRoute_UsesInvariantCulture() { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper( new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByRoute = "Category", }; cacheTagHelper.ViewContext.RouteData.Values["id"] = 4; cacheTagHelper.ViewContext.RouteData.Values["category"] = new DateTimeOffset(2018, 10, 31, 7, 37, 38, TimeSpan.FromHours(-7)); var expected = "CacheTagHelper||testid||VaryByRoute(Category||10/31/2018 07:37:38 -07:00)"; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] public void GenerateKey_UsesVaryByUser_WhenUserIsNotAuthenticated() { // Arrange var expected = "CacheTagHelper||testid||VaryByUser||"; var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByUser = true }; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] public void GenerateKey_UsesVaryByUserAndAuthenticatedUserName() { // Arrange var expected = "CacheTagHelper||testid||VaryByUser||test_name"; var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByUser = true }; var identity = new ClaimsIdentity(new[] { new Claim(ClaimsIdentity.DefaultNameClaimType, "test_name") }); cacheTagHelper.ViewContext.HttpContext.User = new ClaimsPrincipal(identity); // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] [ReplaceCulture("fr-FR", "es-ES")] public void GenerateKey_UsesCultureAndUICultureName_IfVaryByCulture_IsSet() { // Arrange var expected = "CacheTagHelper||testid||VaryByCulture||fr-FR||es-ES"; var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByCulture = true }; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] public void GenerateKey_WithMultipleVaryByOptions_CreatesCombinedKey() { // Arrange var expected = "CacheTagHelper||testid||VaryBy||custom-value||" + "VaryByHeader(content-type||text/html)||VaryByUser||someuser"; var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByUser = true, VaryByHeader = "content-type", VaryBy = "custom-value" }; cacheTagHelper.ViewContext.HttpContext.Request.Headers["Content-Type"] = "text/html"; var identity = new ClaimsIdentity(new[] { new Claim(ClaimsIdentity.DefaultNameClaimType, "someuser") }); cacheTagHelper.ViewContext.HttpContext.User = new ClaimsPrincipal(identity); // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] [ReplaceCulture("zh", "zh-Hans")] public void GenerateKey_WithVaryByCulture_ComposesWithOtherOptions() { // Arrange var expected = "CacheTagHelper||testid||VaryBy||custom-value||" + "VaryByHeader(content-type||text/html)||VaryByCulture||zh||zh-Hans"; var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByCulture = true, VaryByHeader = "content-type", VaryBy = "custom-value" }; cacheTagHelper.ViewContext.HttpContext.Request.Headers["Content-Type"] = "text/html"; // Act var cacheTagKey = new CacheTagKey(cacheTagHelper, tagHelperContext); var key = cacheTagKey.GenerateKey(); // Assert Assert.Equal(expected, key); } [Fact] public void Equality_ReturnsFalse_WhenVaryByCultureIsTrue_AndCultureIsDifferent() { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByCulture = true, }; // Act CacheTagKey key1; using (new CultureReplacer("fr-FR")) { key1 = new CacheTagKey(cacheTagHelper, tagHelperContext); } CacheTagKey key2; using (new CultureReplacer("es-ES")) { key2 = new CacheTagKey(cacheTagHelper, tagHelperContext); } var equals = key1.Equals(key2); var hashCode1 = key1.GetHashCode(); var hashCode2 = key2.GetHashCode(); // Assert Assert.False(equals, "CacheTagKeys must not be equal"); Assert.NotEqual(hashCode1, hashCode2); } [Fact] public void Equality_ReturnsFalse_WhenVaryByCultureIsTrue_AndUICultureIsDifferent() { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByCulture = true, }; // Act CacheTagKey key1; using (new CultureReplacer("fr", "fr-FR")) { key1 = new CacheTagKey(cacheTagHelper, tagHelperContext); } CacheTagKey key2; using (new CultureReplacer("fr", "fr-CA")) { key2 = new CacheTagKey(cacheTagHelper, tagHelperContext); } var equals = key1.Equals(key2); var hashCode1 = key1.GetHashCode(); var hashCode2 = key2.GetHashCode(); // Assert Assert.False(equals, "CacheTagKeys must not be equal"); Assert.NotEqual(hashCode1, hashCode2); } [Fact] public void Equality_ReturnsTrue_WhenVaryByCultureIsTrue_AndCultureIsSame() { // Arrange var tagHelperContext = GetTagHelperContext(); var cacheTagHelper = new CacheTagHelper(new CacheTagHelperMemoryCacheFactory(Mock.Of<IMemoryCache>()), new HtmlTestEncoder()) { ViewContext = GetViewContext(), VaryByCulture = true, }; // Act CacheTagKey key1; CacheTagKey key2; using (new CultureReplacer("fr-FR", "fr-FR")) { key1 = new CacheTagKey(cacheTagHelper, tagHelperContext); } using (new CultureReplacer("fr-fr", "fr-fr")) { key2 = new CacheTagKey(cacheTagHelper, tagHelperContext); } var equals = key1.Equals(key2); var hashCode1 = key1.GetHashCode(); var hashCode2 = key2.GetHashCode(); // Assert Assert.True(equals, "CacheTagKeys must be equal"); Assert.Equal(hashCode1, hashCode2); } private static ViewContext GetViewContext() { var actionContext = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()); return new ViewContext(actionContext, Mock.Of<IView>(), new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()), Mock.Of<ITempDataDictionary>(), TextWriter.Null, new HtmlHelperOptions()); } private static TagHelperContext GetTagHelperContext(string id = "testid") { return new TagHelperContext( tagName: "test", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>(), uniqueId: id); } } }
//----------------------------------------------------------------------- // <copyright file="FlowBufferSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class FlowBufferSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowBufferSpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(1, 1); Materializer = ActorMaterializer.Create(Sys, settings); } [Fact] public void Buffer_must_pass_elements_through_normally_in_backpressured_mode() { var future = Source.From(Enumerable.Range(1, 1000)) .Buffer(100, OverflowStrategy.Backpressure) .Grouped(1001) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); future.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); future.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1,1000)); } [Fact] public void Buffer_must_pass_elements_through_normally_in_backpressured_mode_with_buffer_size_one() { var future = Source.From(Enumerable.Range(1, 1000)) .Buffer(1, OverflowStrategy.Backpressure) .Grouped(1001) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); future.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); future.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 1000)); } [Fact] public void Buffer_must_pass_elements_through_a_chain_of_backpressured_buffers_of_different_size() { this.AssertAllStagesStopped(() => { var future = Source.From(Enumerable.Range(1, 1000)) .Buffer(1, OverflowStrategy.Backpressure) .Buffer(10, OverflowStrategy.Backpressure) .Buffer(256, OverflowStrategy.Backpressure) .Buffer(1, OverflowStrategy.Backpressure) .Buffer(5, OverflowStrategy.Backpressure) .Buffer(128, OverflowStrategy.Backpressure) .Grouped(1001) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); future.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); future.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 1000)); }, Materializer); } [Fact] public void Buffer_must_accept_elements_that_fit_in_the_buffer_while_downstream_is_silent() { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<int>(); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.Backpressure) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 100).ForEach(i => publisher.SendNext(i)); // drain Enumerable.Range(1, 100).ForEach(i => { sub.Request(1); subscriber.ExpectNext(i); }); sub.Cancel(); } [Fact] public void Buffer_must_drop_head_elements_if_buffer_is_full_and_configured_so() { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<int>(); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.DropHead) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 200).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 101; i <= 200; i++) { sub.Request(1); subscriber.ExpectNext(i); } sub.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } [Fact] public void Buffer_must_drop_tail_elements_if_buffer_is_full_and_configured_so() { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<int>(); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.DropTail) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 200).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 1; i <= 99; i++) { sub.Request(1); subscriber.ExpectNext(i); } sub.Request(1); subscriber.ExpectNext(200); sub.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } [Fact] public void Buffer_must_drop_all_elements_if_buffer_is_full_and_configured_so() { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<int>(); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.DropBuffer) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 150).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 101; i <= 150; i++) { sub.Request(1); subscriber.ExpectNext(i); } sub.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } [Fact] public void Buffer_must_drop_new_elements_if_buffer_is_full_and_configured_so() { var t = this.SourceProbe<int>() .Buffer(100, OverflowStrategy.DropNew) .ToMaterialized(this.SinkProbe<int>(), Keep.Both) .Run(Materializer); var publisher = t.Item1; var subscriber = t.Item2; subscriber.EnsureSubscription(); // Fill up buffer Enumerable.Range(1, 150).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 1; i <= 100; i++) subscriber.RequestNext(i); subscriber.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); subscriber.RequestNext(-1); subscriber.Cancel(); } [Fact] public void Buffer_must_fail_upstream_if_buffer_is_full_and_configured_so() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<int>(); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.Fail) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 100).ForEach(i => publisher.SendNext(i)); // drain for (var i = 1; i <= 10; i++) { sub.Request(1); subscriber.ExpectNext(i); } // overflow the buffer for (var i = 101; i <= 111; i++) publisher.SendNext(i); publisher.ExpectCancellation(); var actualError = subscriber.ExpectError(); actualError.Should().BeOfType<BufferOverflowException>(); actualError.Message.Should().Be("Buffer overflow (max capacity was 100)"); }, Materializer); } [Theory] [InlineData(OverflowStrategy.DropHead)] [InlineData(OverflowStrategy.DropTail)] [InlineData(OverflowStrategy.DropBuffer)] public void Buffer_must_work_with_strategy_if_bugger_size_of_one(OverflowStrategy strategy) { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<int>(); Source.FromPublisher(publisher) .Buffer(1, strategy) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 200).ForEach(i => publisher.SendNext(i)); // The request below is in race otherwise with the onNext(200) above subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); sub.Request(1); subscriber.ExpectNext(200); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using IdentityModel; using IdentityServer4.Extensions; using IdentityServer4.Models; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace IdentityServer4.Validation { /// <summary> /// Validates JWT requwest objects /// </summary> public class JwtRequestValidator { private readonly string _audienceUri; private readonly IHttpContextAccessor _httpContextAccessor; /// <summary> /// The audience URI to use /// </summary> protected string AudienceUri { get { if (_audienceUri.IsPresent()) { return _audienceUri; } else { return _httpContextAccessor.HttpContext.GetIdentityServerIssuerUri(); } } } /// <summary> /// The logger /// </summary> protected readonly ILogger Logger; /// <summary> /// Instantiates an instance of private_key_jwt secret validator /// </summary> public JwtRequestValidator(IHttpContextAccessor contextAccessor, ILogger<JwtRequestValidator> logger) { _httpContextAccessor = contextAccessor; Logger = logger; } /// <summary> /// Instantiates an instance of private_key_jwt secret validator (used for testing) /// </summary> internal JwtRequestValidator(string audience, ILogger<JwtRequestValidator> logger) { _audienceUri = audience; Logger = logger; } /// <summary> /// Validates a JWT request object /// </summary> /// <param name="client">The client</param> /// <param name="jwtTokenString">The JWT</param> /// <returns></returns> public virtual async Task<JwtRequestValidationResult> ValidateAsync(Client client, string jwtTokenString) { if (client == null) throw new ArgumentNullException(nameof(client)); if (String.IsNullOrWhiteSpace(jwtTokenString)) throw new ArgumentNullException(nameof(jwtTokenString)); var fail = new JwtRequestValidationResult { IsError = true }; List<SecurityKey> trustedKeys; try { trustedKeys = await GetKeysAsync(client); } catch (Exception e) { Logger.LogError(e, "Could not parse client secrets"); return fail; } if (!trustedKeys.Any()) { Logger.LogError("There are no keys available to validate JWT."); return fail; } JwtSecurityToken jwtSecurityToken; try { jwtSecurityToken = await ValidateJwtAsync(jwtTokenString, trustedKeys, client); } catch (Exception e) { Logger.LogError(e, "JWT token validation error"); return fail; } if (jwtSecurityToken.Payload.ContainsKey(OidcConstants.AuthorizeRequest.Request) || jwtSecurityToken.Payload.ContainsKey(OidcConstants.AuthorizeRequest.RequestUri)) { Logger.LogError("JWT payload must not contain request or request_uri"); return fail; } var payload = await ProcessPayloadAsync(jwtSecurityToken); var result = new JwtRequestValidationResult { IsError = false, Payload = payload }; Logger.LogDebug("JWT request object validation success."); return result; } /// <summary> /// Retrieves keys for a given client /// </summary> /// <param name="client">The client</param> /// <returns></returns> protected virtual Task<List<SecurityKey>> GetKeysAsync(Client client) { return client.ClientSecrets.GetKeysAsync(); } /// <summary> /// Validates the JWT token /// </summary> /// <param name="jwtTokenString">JWT as a string</param> /// <param name="keys">The keys</param> /// <param name="client">The client</param> /// <returns></returns> protected virtual Task<JwtSecurityToken> ValidateJwtAsync(string jwtTokenString, IEnumerable<SecurityKey> keys, Client client) { var tokenValidationParameters = new TokenValidationParameters { IssuerSigningKeys = keys, ValidateIssuerSigningKey = true, ValidIssuer = client.ClientId, ValidateIssuer = true, ValidAudience = AudienceUri, ValidateAudience = true, RequireSignedTokens = true, RequireExpirationTime = true }; var handler = new JwtSecurityTokenHandler(); handler.ValidateToken(jwtTokenString, tokenValidationParameters, out var token); return Task.FromResult((JwtSecurityToken)token); } /// <summary> /// Processes the JWT contents /// </summary> /// <param name="token">The JWT token</param> /// <returns></returns> protected virtual Task<Dictionary<string, string>> ProcessPayloadAsync(JwtSecurityToken token) { // filter JWT validation values var payload = new Dictionary<string, string>(); foreach (var key in token.Payload.Keys) { if (!Constants.Filters.JwtRequestClaimTypesFilter.Contains(key)) { var value = token.Payload[key]; if (value is string s) { payload.Add(key, s); } else if (value is JObject jobj) { payload.Add(key, jobj.ToString(Formatting.None)); } else if (value is JArray jarr) { payload.Add(key, jarr.ToString(Formatting.None)); } } } return Task.FromResult(payload); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Threading; using log4net; using Nini.Config; using Nwc.XmlRpc; using BclExtras; using OpenMetaverse; using OpenMetaverse.StructuredData; using Amib.Threading; namespace OpenSim.Framework { /// <summary> /// The method used by Util.FireAndForget for asynchronously firing events /// </summary> public enum FireAndForgetMethod { UnsafeQueueUserWorkItem, QueueUserWorkItem, BeginInvoke, SmartThreadPool, Thread, } /// <summary> /// Miscellaneous utility functions /// </summary> public class Util { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static uint nextXferID = 5000; private static Random randomClass = new Random(); // Get a list of invalid file characters (OS dependent) private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]"; private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]"; private static object XferLock = new object(); /// <summary>Thread pool used for Util.FireAndForget if /// FireAndForgetMethod.SmartThreadPool is used</summary> private static SmartThreadPool m_ThreadPool; // Unix-epoch starts at January 1st 1970, 00:00:00 UTC. And all our times in the server are (or at least should be) in UTC. private static readonly DateTime unixEpoch = DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime(); public static readonly Regex UUIDPattern = new Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); public static FireAndForgetMethod FireAndForgetMethod = FireAndForgetMethod.SmartThreadPool; /// <summary> /// Linear interpolates B<->C using percent A /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <returns></returns> public static double lerp(double a, double b, double c) { return (b*a) + (c*(1 - a)); } /// <summary> /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y. /// Layout: /// A B /// C D /// A<->C = Y /// C<->D = X /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <param name="d"></param> /// <returns></returns> public static double lerp2D(double x, double y, double a, double b, double c, double d) { return lerp(y, lerp(x, a, b), lerp(x, c, d)); } public static Encoding UTF8 = Encoding.UTF8; /// <value> /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards) /// </value> public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f"); #region Vector Equations /// <summary> /// Get the distance between two 3d vectors /// </summary> /// <param name="a">A 3d vector</param> /// <param name="b">A 3d vector</param> /// <returns>The distance between the two vectors</returns> public static double GetDistanceTo(Vector3 a, Vector3 b) { float dx = a.X - b.X; float dy = a.Y - b.Y; float dz = a.Z - b.Z; return Math.Sqrt(dx * dx + dy * dy + dz * dz); } /// <summary> /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="amount"></param> /// <returns></returns> public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount) { float dx = a.X - b.X; float dy = a.Y - b.Y; float dz = a.Z - b.Z; return (dx*dx + dy*dy + dz*dz) < (amount*amount); } /// <summary> /// Get the magnitude of a 3d vector /// </summary> /// <param name="a">A 3d vector</param> /// <returns>The magnitude of the vector</returns> public static double GetMagnitude(Vector3 a) { return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z)); } /// <summary> /// Get a normalized form of a 3d vector /// </summary> /// <param name="a">A 3d vector</param> /// <returns>A new vector which is normalized form of the vector</returns> /// <remarks>The vector paramater cannot be <0,0,0></remarks> public static Vector3 GetNormalizedVector(Vector3 a) { if (IsZeroVector(a)) throw new ArgumentException("Vector paramater cannot be a zero vector."); float Mag = (float) GetMagnitude(a); return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag); } /// <summary> /// Returns if a vector is a zero vector (has all zero components) /// </summary> /// <returns></returns> public static bool IsZeroVector(Vector3 v) { if (v.X == 0 && v.Y == 0 && v.Z == 0) { return true; } return false; } # endregion public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up) { float s; float tr = (float) (fwd.X + left.Y + up.Z + 1.0); if (tr >= 1.0) { s = (float) (0.5 / Math.Sqrt(tr)); return new Quaternion( (left.Z - up.Y) * s, (up.X - fwd.Z) * s, (fwd.Y - left.X) * s, (float) 0.25 / s); } else { float max = (left.Y > up.Z) ? left.Y : up.Z; if (max < fwd.X) { s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0)); float x = (float) (s * 0.5); s = (float) (0.5 / s); return new Quaternion( x, (fwd.Y + left.X) * s, (up.X + fwd.Z) * s, (left.Z - up.Y) * s); } else if (max == left.Y) { s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0)); float y = (float) (s * 0.5); s = (float) (0.5 / s); return new Quaternion( (fwd.Y + left.X) * s, y, (left.Z + up.Y) * s, (up.X - fwd.Z) * s); } else { s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0)); float z = (float) (s * 0.5); s = (float) (0.5 / s); return new Quaternion( (up.X + fwd.Z) * s, (left.Z + up.Y) * s, z, (fwd.Y - left.X) * s); } } } public static Random RandomClass { get { return randomClass; } } public static ulong UIntsToLong(uint X, uint Y) { return Utils.UIntsToLong(X, Y); } public static T Clamp<T>(T x, T min, T max) where T : IComparable<T> { return x.CompareTo(max) > 0 ? max : x.CompareTo(min) < 0 ? min : x; } public static uint GetNextXferID() { uint id = 0; lock (XferLock) { id = nextXferID; nextXferID++; } return id; } public static string GetFileName(string file) { // Return just the filename on UNIX platforms // TODO: this should be customisable with a prefix, but that's something to do later. if (Environment.OSVersion.Platform == PlatformID.Unix) { return file; } // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData if (Environment.OSVersion.Platform == PlatformID.Win32NT) { if (!Directory.Exists("%APPDATA%\\OpenSim\\")) { Directory.CreateDirectory("%APPDATA%\\OpenSim"); } return "%APPDATA%\\OpenSim\\" + file; } // Catch all - covers older windows versions // (but those probably wont work anyway) return file; } /// <summary> /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes. /// /// Please don't delete me even if I appear currently unused! /// </summary> /// <param name="rawXml"></param> /// <returns></returns> public static string GetFormattedXml(string rawXml) { XmlDocument xd = new XmlDocument(); xd.LoadXml(rawXml); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; try { xd.WriteTo(xtw); } finally { xtw.Close(); } return sb.ToString(); } public static bool IsEnvironmentSupported(ref string reason) { // Must have .NET 2.0 (Generics / libsl) if (Environment.Version.Major < 2) { reason = ".NET 1.0/1.1 lacks components that is used by OpenSim"; return false; } // Windows 95/98/ME are unsupported if (Environment.OSVersion.Platform == PlatformID.Win32Windows && Environment.OSVersion.Platform != PlatformID.Win32NT) { reason = "Windows 95/98/ME will not run OpenSim"; return false; } // Windows 2000 / Pre-SP2 XP if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 0) { reason = "Please update to Windows XP Service Pack 2 or Server2003"; return false; } return true; } public static int UnixTimeSinceEpoch() { return ToUnixTime(DateTime.UtcNow); } public static int ToUnixTime(DateTime stamp) { TimeSpan t = stamp.ToUniversalTime() - unixEpoch; return (int) t.TotalSeconds; } public static DateTime ToDateTime(ulong seconds) { DateTime epoch = unixEpoch; return epoch.AddSeconds(seconds); } public static DateTime ToDateTime(int seconds) { DateTime epoch = unixEpoch; return epoch.AddSeconds(seconds); } /// <summary> /// Return an md5 hash of the given string /// </summary> /// <param name="data"></param> /// <returns></returns> public static string Md5Hash(string data) { byte[] dataMd5 = ComputeMD5Hash(data); StringBuilder sb = new StringBuilder(); for (int i = 0; i < dataMd5.Length; i++) sb.AppendFormat("{0:x2}", dataMd5[i]); return sb.ToString(); } private static byte[] ComputeMD5Hash(string data) { MD5 md5 = MD5.Create(); return md5.ComputeHash(Encoding.Default.GetBytes(data)); } /// <summary> /// Return an SHA1 hash of the given string /// </summary> /// <param name="data"></param> /// <returns></returns> public static string SHA1Hash(string data) { byte[] hash = ComputeSHA1Hash(data); return BitConverter.ToString(hash).Replace("-", String.Empty); } private static byte[] ComputeSHA1Hash(string src) { SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider(); return SHA1.ComputeHash(Encoding.Default.GetBytes(src)); } public static int fast_distance2d(int x, int y) { x = Math.Abs(x); y = Math.Abs(y); int min = Math.Min(x, y); return (x + y - (min >> 1) - (min >> 2) + (min >> 4)); } public static bool IsOutsideView(uint oldx, uint newx, uint oldy, uint newy) { // Eventually this will be a function of the draw distance / camera position too. return (((int)Math.Abs((int)(oldx - newx)) > 1) || ((int)Math.Abs((int)(oldy - newy)) > 1)); } public static string FieldToString(byte[] bytes) { return FieldToString(bytes, String.Empty); } /// <summary> /// Convert a variable length field (byte array) to a string, with a /// field name prepended to each line of the output /// </summary> /// <remarks>If the byte array has unprintable characters in it, a /// hex dump will be put in the string instead</remarks> /// <param name="bytes">The byte array to convert to a string</param> /// <param name="fieldName">A field name to prepend to each line of output</param> /// <returns>An ASCII string or a string containing a hex dump, minus /// the null terminator</returns> public static string FieldToString(byte[] bytes, string fieldName) { // Check for a common case if (bytes.Length == 0) return String.Empty; StringBuilder output = new StringBuilder(); bool printable = true; for (int i = 0; i < bytes.Length; ++i) { // Check if there are any unprintable characters in the array if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09 && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00) { printable = false; break; } } if (printable) { if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1))); } else { for (int i = 0; i < bytes.Length; i += 16) { if (i != 0) output.Append(Environment.NewLine); if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } for (int j = 0; j < 16; j++) { if ((i + j) < bytes.Length) output.Append(String.Format("{0:X2} ", bytes[i + j])); else output.Append(" "); } for (int j = 0; j < 16 && (i + j) < bytes.Length; j++) { if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E) output.Append((char) bytes[i + j]); else output.Append("."); } } } return output.ToString(); } /// <summary> /// Converts a URL to a IPAddress /// </summary> /// <param name="url">URL Standard Format</param> /// <returns>A resolved IP Address</returns> public static IPAddress GetHostFromURL(string url) { return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]); } /// <summary> /// Returns a IP address from a specified DNS, favouring IPv4 addresses. /// </summary> /// <param name="dnsAddress">DNS Hostname</param> /// <returns>An IP address, or null</returns> public static IPAddress GetHostFromDNS(string dnsAddress) { // Is it already a valid IP? No need to look it up. IPAddress ipa; if (IPAddress.TryParse(dnsAddress, out ipa)) return ipa; IPAddress[] hosts = null; // Not an IP, lookup required try { hosts = Dns.GetHostEntry(dnsAddress).AddressList; } catch (Exception e) { m_log.ErrorFormat("[UTIL]: An error occurred while resolving {0}, {1}", dnsAddress, e); // Still going to throw the exception on for now, since this was what was happening in the first place throw e; } foreach (IPAddress host in hosts) { if (host.AddressFamily == AddressFamily.InterNetwork) { return host; } } if (hosts.Length > 0) return hosts[0]; return null; } public static Uri GetURI(string protocol, string hostname, int port, string path) { return new UriBuilder(protocol, hostname, port, path).Uri; } /// <summary> /// Gets a list of all local system IP addresses /// </summary> /// <returns></returns> public static IPAddress[] GetLocalHosts() { return Dns.GetHostAddresses(Dns.GetHostName()); } public static IPAddress GetLocalHost() { string dnsAddress = "localhost"; IPAddress[] hosts = Dns.GetHostEntry(dnsAddress).AddressList; foreach (IPAddress host in hosts) { if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork) { return host; } } if (hosts.Length > 0) { foreach (IPAddress host in hosts) { if (host.AddressFamily == AddressFamily.InterNetwork) return host; } // Well all else failed... return hosts[0]; } return null; } /// <summary> /// Removes all invalid path chars (OS dependent) /// </summary> /// <param name="path">path</param> /// <returns>safe path</returns> public static string safePath(string path) { return Regex.Replace(path, regexInvalidPathChars, String.Empty); } /// <summary> /// Removes all invalid filename chars (OS dependent) /// </summary> /// <param name="path">filename</param> /// <returns>safe filename</returns> public static string safeFileName(string filename) { return Regex.Replace(filename, regexInvalidFileChars, String.Empty); ; } // // directory locations // public static string homeDir() { string temp; // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal)); // temp = Path.Combine(personal,".OpenSim"); temp = "."; return temp; } public static string assetsDir() { return Path.Combine(configDir(), "assets"); } public static string inventoryDir() { return Path.Combine(configDir(), "inventory"); } public static string configDir() { return "."; } public static string dataDir() { return "."; } public static string logDir() { return "."; } // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html public static string GetUniqueFilename(string FileName) { int count = 0; string Name; if (File.Exists(FileName)) { FileInfo f = new FileInfo(FileName); if (!String.IsNullOrEmpty(f.Extension)) { Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.')); } else { Name = f.FullName; } while (File.Exists(FileName)) { count++; FileName = Name + count + f.Extension; } } return FileName; } // Nini (config) related Methods public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName) { if (!File.Exists(fileName)) { //create new file } XmlConfigSource config = new XmlConfigSource(fileName); AddDataRowToConfig(config, row); config.Save(); return config; } public static void AddDataRowToConfig(IConfigSource config, DataRow row) { config.Configs.Add((string) row[0]); for (int i = 0; i < row.Table.Columns.Count; i++) { config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]); } } public static float Clip(float x, float min, float max) { return Math.Min(Math.Max(x, min), max); } public static int Clip(int x, int min, int max) { return Math.Min(Math.Max(x, min), max); } /// <summary> /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens. /// </summary> /// <param name="UUID"></param> /// <returns></returns> public static String ToRawUuidString(UUID UUID) { return UUID.Guid.ToString("n"); } public static string CleanString(string input) { if (input.Length == 0) return input; int clip = input.Length; // Test for ++ string terminator int pos = input.IndexOf("\0"); if (pos != -1 && pos < clip) clip = pos; // Test for CR pos = input.IndexOf("\r"); if (pos != -1 && pos < clip) clip = pos; // Test for LF pos = input.IndexOf("\n"); if (pos != -1 && pos < clip) clip = pos; // Truncate string before first end-of-line character found return input.Substring(0, clip); } /// <summary> /// returns the contents of /etc/issue on Unix Systems /// Use this for where it's absolutely necessary to implement platform specific stuff /// </summary> /// <returns></returns> public static string ReadEtcIssue() { try { StreamReader sr = new StreamReader("/etc/issue.net"); string issue = sr.ReadToEnd(); sr.Close(); return issue; } catch (Exception) { return ""; } } public static void SerializeToFile(string filename, Object obj) { IFormatter formatter = new BinaryFormatter(); Stream stream = null; try { stream = new FileStream( filename, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, obj); } catch (Exception e) { m_log.Error(e.ToString()); } finally { if (stream != null) { stream.Close(); } } } public static Object DeserializeFromFile(string filename) { IFormatter formatter = new BinaryFormatter(); Stream stream = null; Object ret = null; try { stream = new FileStream( filename, FileMode.Open, FileAccess.Read, FileShare.None); ret = formatter.Deserialize(stream); } catch (Exception e) { m_log.Error(e.ToString()); } finally { if (stream != null) { stream.Close(); } } return ret; } public static string Compress(string text) { byte[] buffer = Util.UTF8.GetBytes(text); MemoryStream memory = new MemoryStream(); using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true)) { compressor.Write(buffer, 0, buffer.Length); } memory.Position = 0; byte[] compressed = new byte[memory.Length]; memory.Read(compressed, 0, compressed.Length); byte[] compressedBuffer = new byte[compressed.Length + 4]; Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length); Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4); return Convert.ToBase64String(compressedBuffer); } public static string Decompress(string compressedText) { byte[] compressedBuffer = Convert.FromBase64String(compressedText); using (MemoryStream memory = new MemoryStream()) { int msgLength = BitConverter.ToInt32(compressedBuffer, 0); memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4); byte[] buffer = new byte[msgLength]; memory.Position = 0; using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress)) { decompressor.Read(buffer, 0, buffer.Length); } return Util.UTF8.GetString(buffer); } } public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args) { return SendXmlRpcCommand(url, methodName, args); } public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args) { XmlRpcRequest client = new XmlRpcRequest(methodName, args); return client.Send(url, 6000); } /// <summary> /// Returns an error message that the user could not be found in the database /// </summary> /// <returns>XML string consisting of a error element containing individual error(s)</returns> public static XmlRpcResponse CreateUnknownUserErrorResponse() { XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); responseData["error_type"] = "unknown_user"; responseData["error_desc"] = "The user requested is not in the database"; response.Value = responseData; return response; } /// <summary> /// Converts a byte array in big endian order into an ulong. /// </summary> /// <param name="bytes"> /// The array of bytes /// </param> /// <returns> /// The extracted ulong /// </returns> public static ulong BytesToUInt64Big(byte[] bytes) { if (bytes.Length < 8) return 0; return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) | ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7]; } // used for RemoteParcelRequest (for "About Landmark") public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y) { byte[] bytes = { (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24), (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56), (byte)x, (byte)(x >> 8), 0, 0, (byte)y, (byte)(y >> 8), 0, 0 }; return new UUID(bytes, 0); } public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z) { byte[] bytes = { (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24), (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56), (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8), (byte)y, (byte)(y >> 8), 0, 0 }; return new UUID(bytes, 0); } public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y) { byte[] bytes = parcelID.GetBytes(); regionHandle = Utils.BytesToUInt64(bytes); x = Utils.BytesToUInt(bytes, 8) & 0xffff; y = Utils.BytesToUInt(bytes, 12) & 0xffff; } public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z) { byte[] bytes = parcelID.GetBytes(); regionHandle = Utils.BytesToUInt64(bytes); x = Utils.BytesToUInt(bytes, 8) & 0xffff; z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16; y = Utils.BytesToUInt(bytes, 12) & 0xffff; } public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y) { ulong regionHandle; uint rx, ry; ParseFakeParcelID(parcelID, out regionHandle, out x, out y); Utils.LongToUInts(regionHandle, out rx, out ry); x += rx; y += ry; } /// <summary> /// Get operating system information if available. Returns only the first 45 characters of information /// </summary> /// <returns> /// Operating system information. Returns an empty string if none was available. /// </returns> public static string GetOperatingSystemInformation() { string os = String.Empty; if (Environment.OSVersion.Platform != PlatformID.Unix) { os = Environment.OSVersion.ToString(); } else { os = ReadEtcIssue(); } if (os.Length > 45) { os = os.Substring(0, 45); } return os; } /// <summary> /// Is the given string a UUID? /// </summary> /// <param name="s"></param> /// <returns></returns> public static bool isUUID(string s) { return UUIDPattern.IsMatch(s); } public static string GetDisplayConnectionString(string connectionString) { int passPosition = 0; int passEndPosition = 0; string displayConnectionString = null; // hide the password in the connection string passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase); passPosition = connectionString.IndexOf("=", passPosition); if (passPosition < connectionString.Length) passPosition += 1; passEndPosition = connectionString.IndexOf(";", passPosition); displayConnectionString = connectionString.Substring(0, passPosition); displayConnectionString += "***"; displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition); return displayConnectionString; } public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass) { Type settingsType = settingsClass.GetType(); FieldInfo[] fieldInfos = settingsType.GetFields(); foreach (FieldInfo fieldInfo in fieldInfos) { if (!fieldInfo.IsStatic) { if (fieldInfo.FieldType == typeof(System.String)) { fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass))); } else if (fieldInfo.FieldType == typeof(System.Boolean)) { fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass))); } else if (fieldInfo.FieldType == typeof(System.Int32)) { fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass))); } else if (fieldInfo.FieldType == typeof(System.Single)) { fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass))); } else if (fieldInfo.FieldType == typeof(System.UInt32)) { fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString()))); } } } PropertyInfo[] propertyInfos = settingsType.GetProperties(); foreach (PropertyInfo propInfo in propertyInfos) { if ((propInfo.CanRead) && (propInfo.CanWrite)) { if (propInfo.PropertyType == typeof(System.String)) { propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null); } else if (propInfo.PropertyType == typeof(System.Boolean)) { propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null); } else if (propInfo.PropertyType == typeof(System.Int32)) { propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null); } else if (propInfo.PropertyType == typeof(System.Single)) { propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null); } if (propInfo.PropertyType == typeof(System.UInt32)) { propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null); } } } return settingsClass; } public static string Base64ToString(string str) { UTF8Encoding encoder = new UTF8Encoding(); Decoder utf8Decode = encoder.GetDecoder(); byte[] todecode_byte = Convert.FromBase64String(str); int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length); char[] decoded_char = new char[charCount]; utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0); string result = new String(decoded_char); return result; } public static Guid GetHashGuid(string data, string salt) { byte[] hash = ComputeMD5Hash(data + salt); //string s = BitConverter.ToString(hash); Guid guid = new Guid(hash); return guid; } public static byte ConvertMaturityToAccessLevel(uint maturity) { byte retVal = 0; switch (maturity) { case 0: //PG retVal = 13; break; case 1: //Mature retVal = 21; break; case 2: // Adult retVal = 42; break; } return retVal; } /// <summary> /// Produces an OSDMap from its string representation on a stream /// </summary> /// <param name="data">The stream</param> /// <param name="length">The size of the data on the stream</param> /// <returns>The OSDMap or an exception</returns> public static OSDMap GetOSDMap(Stream stream, int length) { byte[] data = new byte[length]; stream.Read(data, 0, length); string strdata = Util.UTF8.GetString(data); OSDMap args = null; OSD buffer; buffer = OSDParser.DeserializeJson(strdata); if (buffer.Type == OSDType.Map) { args = (OSDMap)buffer; return args; } return null; } public static string[] Glob(string path) { string vol=String.Empty; if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar) { string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries); if (vcomps.Length > 1) { path = vcomps[1]; vol = vcomps[0]; } } string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries); // Glob path = vol; if (vol != String.Empty) path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar}); else path = new String(new char[] {Path.DirectorySeparatorChar}); List<string> paths = new List<string>(); List<string> found = new List<string>(); paths.Add(path); int compIndex = -1; foreach (string c in comps) { compIndex++; List<string> addpaths = new List<string>(); foreach (string p in paths) { string[] dirs = Directory.GetDirectories(p, c); if (dirs.Length != 0) { foreach (string dir in dirs) addpaths.Add(Path.Combine(path, dir)); } // Only add files if that is the last path component if (compIndex == comps.Length - 1) { string[] files = Directory.GetFiles(p, c); foreach (string f in files) found.Add(f); } } paths = addpaths; } return found.ToArray(); } public static string ServerURI(string uri) { if (uri == string.Empty) return string.Empty; // Get rid of eventual slashes at the end uri = uri.TrimEnd('/'); IPAddress ipaddr1 = null; string port1 = ""; try { ipaddr1 = Util.GetHostFromURL(uri); } catch { } try { port1 = uri.Split(new char[] { ':' })[2]; } catch { } // We tried our best to convert the domain names to IP addresses return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri; } public static byte[] StringToBytes256(string str) { if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; } if (str.Length > 254) str = str.Remove(254); if (!str.EndsWith("\0")) { str += "\0"; } // Because this is UTF-8 encoding and not ASCII, it's possible we // might have gotten an oversized array even after the string trim byte[] data = UTF8.GetBytes(str); if (data.Length > 256) { Array.Resize<byte>(ref data, 256); data[255] = 0; } return data; } public static byte[] StringToBytes1024(string str) { if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; } if (str.Length > 1023) str = str.Remove(1023); if (!str.EndsWith("\0")) { str += "\0"; } // Because this is UTF-8 encoding and not ASCII, it's possible we // might have gotten an oversized array even after the string trim byte[] data = UTF8.GetBytes(str); if (data.Length > 1024) { Array.Resize<byte>(ref data, 1024); data[1023] = 0; } return data; } #region FireAndForget Threading Pattern /// <summary> /// Created to work around a limitation in Mono with nested delegates /// </summary> private class FireAndForgetWrapper { public void FireAndForget(System.Threading.WaitCallback callback) { callback.BeginInvoke(null, EndFireAndForget, callback); } public void FireAndForget(System.Threading.WaitCallback callback, object obj) { callback.BeginInvoke(obj, EndFireAndForget, callback); } private static void EndFireAndForget(IAsyncResult ar) { System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState; try { callback.EndInvoke(ar); } catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); } ar.AsyncWaitHandle.Close(); } } public static void FireAndForget(System.Threading.WaitCallback callback) { FireAndForget(callback, null); } public static void InitThreadPool(int maxThreads) { if (maxThreads < 2) throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2"); if (m_ThreadPool != null) throw new InvalidOperationException("SmartThreadPool is already initialized"); m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2); } public static int FireAndForgetCount() { const int MAX_SYSTEM_THREADS = 200; switch (FireAndForgetMethod) { case FireAndForgetMethod.UnsafeQueueUserWorkItem: case FireAndForgetMethod.QueueUserWorkItem: case FireAndForgetMethod.BeginInvoke: int workerThreads, iocpThreads; ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads); return workerThreads; case FireAndForgetMethod.SmartThreadPool: return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads; case FireAndForgetMethod.Thread: return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count; default: throw new NotImplementedException(); } } public static void FireAndForget(System.Threading.WaitCallback callback, object obj) { switch (FireAndForgetMethod) { case FireAndForgetMethod.UnsafeQueueUserWorkItem: ThreadPool.UnsafeQueueUserWorkItem(callback, obj); break; case FireAndForgetMethod.QueueUserWorkItem: ThreadPool.QueueUserWorkItem(callback, obj); break; case FireAndForgetMethod.BeginInvoke: FireAndForgetWrapper wrapper = Singleton.GetInstance<FireAndForgetWrapper>(); wrapper.FireAndForget(callback, obj); break; case FireAndForgetMethod.SmartThreadPool: if (m_ThreadPool == null) m_ThreadPool = new SmartThreadPool(2000, 15, 2); m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { callback, obj }); break; case FireAndForgetMethod.Thread: Thread thread = new Thread(delegate(object o) { callback(o); }); thread.Start(obj); break; default: throw new NotImplementedException(); } } private static object SmartThreadPoolCallback(object o) { object[] array = (object[])o; WaitCallback callback = (WaitCallback)array[0]; object obj = array[1]; callback(obj); return null; } #endregion FireAndForget Threading Pattern } }
using System; using System.Collections; using Alachisoft.NGroups.Util; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common.Logger; namespace Alachisoft.NGroups.Stack { /// <summary> ACK-based sliding window for a sender. Messages are added to the window keyed by seqno /// When an ACK is received, the corresponding message is removed. The Retransmitter /// continously iterates over the entries in the hashmap, retransmitting messages based on their /// creation time and an (increasing) timeout. When there are no more messages in the retransmission /// table left, the thread terminates. It will be re-activated when a new entry is added to the /// retransmission table. /// </summary> /// <author> Bela Ban /// </author> internal class AckSenderWindow : Retransmitter.RetransmitCommand { private void InitBlock() { retransmitter = new Retransmitter(null, this); } internal AckSenderWindow.RetransmitCommand retransmit_command = null; // called to request XMIT of msg internal System.Collections.Hashtable msgs = new System.Collections.Hashtable(); // keys: seqnos (Long), values: Messages internal long[] interval = new long[]{1000, 2000, 3000, 4000}; internal Retransmitter retransmitter; internal Alachisoft.NCache.Common.DataStructures.Queue msg_queue = new Alachisoft.NCache.Common.DataStructures.Queue(); // for storing messages if msgs is full internal int window_size = - 1; // the max size of msgs, when exceeded messages will be queued /// <summary>when queueing, after msgs size falls below this value, msgs are added again (queueing stops) </summary> internal int min_threshold = - 1; internal bool use_sliding_window = false, queueing = false; internal Protocol transport = null; // used to send messages private ILogger _ncacheLog; private ILogger NCacheLog { get { return _ncacheLog; } } internal interface RetransmitCommand { void retransmit(long seqno, Message msg); } /// <summary> Creates a new instance. Thre retransmission thread has to be started separately with /// <code>start()</code>. /// </summary> /// <param name="com">If not null, its method <code>retransmit()</code> will be called when a message /// needs to be retransmitted (called by the Retransmitter). /// </param> public AckSenderWindow(AckSenderWindow.RetransmitCommand com, ILogger NCacheLog) { _ncacheLog = NCacheLog; InitBlock(); retransmit_command = com; retransmitter.RetransmitTimeouts = interval; } public AckSenderWindow(AckSenderWindow.RetransmitCommand com, long[] interval, ILogger NCacheLog) { _ncacheLog = NCacheLog; InitBlock(); retransmit_command = com; this.interval = interval; retransmitter.RetransmitTimeouts = interval; } /// <summary> This constructor whould be used when we want AckSenderWindow to send the message added /// by add(), rather then ourselves. /// </summary> public AckSenderWindow(AckSenderWindow.RetransmitCommand com, long[] interval, Protocol transport, ILogger NCacheLog) { _ncacheLog = NCacheLog; InitBlock(); retransmit_command = com; this.interval = interval; this.transport = transport; retransmitter.RetransmitTimeouts = interval; } public virtual void setWindowSize(int window_size, int min_threshold) { this.window_size = window_size; this.min_threshold = min_threshold; // sanity tests for the 2 values: if (min_threshold > window_size) { this.min_threshold = window_size; this.window_size = min_threshold; NCacheLog.Warn("min_threshold (" + min_threshold + ") has to be less than window_size ( " + window_size + "). Values are swapped"); } if (this.window_size <= 0) { this.window_size = this.min_threshold > 0?(int) (this.min_threshold * 1.5):500; NCacheLog.Warn("window_size is <= 0, setting it to " + this.window_size); } if (this.min_threshold <= 0) { this.min_threshold = this.window_size > 0?(int) (this.window_size * 0.5):250; NCacheLog.Warn("min_threshold is <= 0, setting it to " + this.min_threshold); } NCacheLog.Debug("window_size=" + this.window_size + ", min_threshold=" + this.min_threshold); use_sliding_window = true; } public virtual void reset() { lock (msgs.SyncRoot) { msgs.Clear(); } // moved out of sync scope: Retransmitter.reset()/add()/remove() are sync'ed anyway // Bela Jan 15 2003 retransmitter.reset(); } /// <summary> Adds a new message to the retransmission table. If the message won't have received an ack within /// a certain time frame, the retransmission thread will retransmit the message to the receiver. If /// a sliding window protocol is used, we only add up to <code>window_size</code> messages. If the table is /// full, we add all new messages to a queue. Those will only be added once the table drains below a certain /// threshold (<code>min_threshold</code>) /// </summary> public virtual void add(long seqno, Message msg) { lock (msgs.SyncRoot) { if (msgs.ContainsKey(seqno)) return ; if (!use_sliding_window) { addMessage(seqno, msg); } else { // we use a sliding window if (queueing) addToQueue(seqno, msg); else { if (msgs.Count + 1 > window_size) { queueing = true; addToQueue(seqno, msg); if (NCacheLog.IsInfoEnabled) NCacheLog.Info("window_size (" + window_size + ") was exceeded, " + "starting to queue messages until window size falls under " + min_threshold); } else { addMessage(seqno, msg); } } } } } /// <summary> Removes the message from <code>msgs</code>, removing them also from retransmission. If /// sliding window protocol is used, and was queueing, check whether we can resume adding elements. /// Add all elements. If this goes above window_size, stop adding and back to queueing. Else /// set queueing to false. /// </summary> public virtual void ack(long seqno) { Entry entry; lock (msgs.SyncRoot) { msgs.Remove(seqno); retransmitter.remove(seqno); if (use_sliding_window && queueing) { if (msgs.Count < min_threshold) { // we fell below threshold, now we can resume adding msgs if (NCacheLog.IsInfoEnabled) NCacheLog.Info("number of messages in table fell under min_threshold (" + min_threshold + "): adding " + msg_queue.Count + " messages on queue"); while (msgs.Count < window_size) { if ((entry = removeFromQueue()) != null) { addMessage(entry.seqno, entry.msg); } else break; } if (msgs.Count + 1 > window_size) { if (NCacheLog.IsInfoEnabled) NCacheLog.Info("exceeded window_size (" + window_size + ") again, will still queue"); return ; // still queueing } else queueing = false; // allows add() to add messages again if (NCacheLog.IsInfoEnabled) NCacheLog.Info("set queueing to false (table size=" + msgs.Count + ')'); } } } } public override string ToString() { return Global.CollectionToString(msgs.Keys) + " (retransmitter: " + retransmitter.ToString() + ')'; } /* -------------------------------- Retransmitter.RetransmitCommand interface ------------------- */ public virtual void retransmit(long first_seqno, long last_seqno, Address sender) { Message msg; if (retransmit_command != null) { for (long i = first_seqno; i <= last_seqno; i++) { if ((msg = (Message) msgs[(long) i]) != null) { // find the message to retransmit retransmit_command.retransmit(i, msg); //System.out.println("### retr(" + first_seqno + "): tstamp=" + System.currentTimeMillis()); } } } } /* ----------------------------- End of Retransmitter.RetransmitCommand interface ---------------- */ /* ---------------------------------- Private methods --------------------------------------- */ internal virtual void addMessage(long seqno, Message msg) { if (transport != null) transport.passDown(new Event(Event.MSG, msg)); msgs[seqno] = msg; retransmitter.add(seqno, seqno); } internal virtual void addToQueue(long seqno, Message msg) { try { msg_queue.add(new Entry(this, seqno, msg)); } catch (System.Exception ex) { NCacheLog.Error("AckSenderWindow.add()", ex.ToString()); } } internal virtual Entry removeFromQueue() { try { return msg_queue.Count == 0?null:(Entry) msg_queue.remove(); } catch (System.Exception ex) { NCacheLog.Error("AckSenderWindow.removeFromQueue()", ex.ToString()); return null; } } /* ------------------------------ End of Private methods ------------------------------------ */ /// <summary>Struct used to store message alongside with its seqno in the message queue </summary> internal class Entry { private void InitBlock(AckSenderWindow enclosingInstance) { this.enclosingInstance = enclosingInstance; } private AckSenderWindow enclosingInstance; public AckSenderWindow Enclosing_Instance { get { return enclosingInstance; } } internal long seqno; internal Message msg; internal Entry(AckSenderWindow enclosingInstance, long seqno, Message msg) { InitBlock(enclosingInstance); this.seqno = seqno; this.msg = msg; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Amib.Threading.Internal { #region PriorityQueue class /// <summary> /// PriorityQueue class /// This class is not thread safe because we use external lock /// </summary> public sealed class PriorityQueue : IEnumerable { #region Private members /// <summary> /// The number of queues, there is one for each type of priority /// </summary> private const int _queuesCount = WorkItemPriority.Highest - WorkItemPriority.Lowest + 1; /// <summary> /// Work items queues. There is one for each type of priority /// </summary> private readonly LinkedList<IHasWorkItemPriority>[] _queues = new LinkedList<IHasWorkItemPriority>[_queuesCount]; /// <summary> /// Use with IEnumerable interface /// </summary> private int _version; /// <summary> /// The total number of work items within the queues /// </summary> private int _workItemsCount; #endregion Private members #region Contructor public PriorityQueue() { for (int i = 0; i < _queues.Length; ++i) { _queues[i] = new LinkedList<IHasWorkItemPriority>(); } } #endregion Contructor #region Methods /// <summary> /// The number of work items /// </summary> public int Count { get { return _workItemsCount; } } /// <summary> /// Clear all the work items /// </summary> public void Clear() { if (_workItemsCount > 0) { foreach (LinkedList<IHasWorkItemPriority> queue in _queues) { queue.Clear(); } _workItemsCount = 0; ++_version; } } /// <summary> /// Dequeque a work item. /// </summary> /// <returns>Returns the next work item</returns> public IHasWorkItemPriority Dequeue() { IHasWorkItemPriority workItem = null; if (_workItemsCount > 0) { int queueIndex = GetNextNonEmptyQueue(-1); Debug.Assert(queueIndex >= 0); workItem = _queues[queueIndex].First.Value; _queues[queueIndex].RemoveFirst(); Debug.Assert(null != workItem); --_workItemsCount; ++_version; } return workItem; } /// <summary> /// Enqueue a work item. /// </summary> /// <param name="workItem">A work item</param> public void Enqueue(IHasWorkItemPriority workItem) { Debug.Assert(null != workItem); int queueIndex = _queuesCount - (int)workItem.WorkItemPriority - 1; Debug.Assert(queueIndex >= 0); Debug.Assert(queueIndex < _queuesCount); _queues[queueIndex].AddLast(workItem); ++_workItemsCount; ++_version; } /// <summary> /// Find the next non empty queue starting at queue queueIndex+1 /// </summary> /// <param name="queueIndex">The index-1 to start from</param> /// <returns> /// The index of the next non empty queue or -1 if all the queues are empty /// </returns> private int GetNextNonEmptyQueue(int queueIndex) { for (int i = queueIndex + 1; i < _queuesCount; ++i) { if (_queues[i].Count > 0) { return i; } } return -1; } #endregion Methods #region IEnumerable Members /// <summary> /// Returns an enumerator to iterate over the work items /// </summary> /// <returns>Returns an enumerator</returns> public IEnumerator GetEnumerator() { return new PriorityQueueEnumerator(this); } #endregion IEnumerable Members #region PriorityQueueEnumerator /// <summary> /// The class the implements the enumerator /// </summary> private class PriorityQueueEnumerator : IEnumerator { private readonly PriorityQueue _priorityQueue; private IEnumerator _enumerator; private int _queueIndex; private int _version; public PriorityQueueEnumerator(PriorityQueue priorityQueue) { _priorityQueue = priorityQueue; _version = _priorityQueue._version; _queueIndex = _priorityQueue.GetNextNonEmptyQueue(-1); if (_queueIndex >= 0) { _enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator(); } else { _enumerator = null; } } #region IEnumerator Members public object Current { get { Debug.Assert(null != _enumerator); return _enumerator.Current; } } public bool MoveNext() { if (null == _enumerator) { return false; } if (_version != _priorityQueue._version) { throw new InvalidOperationException("The collection has been modified"); } if (!_enumerator.MoveNext()) { _queueIndex = _priorityQueue.GetNextNonEmptyQueue(_queueIndex); if (-1 == _queueIndex) { return false; } _enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator(); _enumerator.MoveNext(); return true; } return true; } public void Reset() { _version = _priorityQueue._version; _queueIndex = _priorityQueue.GetNextNonEmptyQueue(-1); if (_queueIndex >= 0) { _enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator(); } else { _enumerator = null; } } #endregion IEnumerator Members } #endregion PriorityQueueEnumerator } #endregion PriorityQueue class }
// // TextEntryBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // 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 Xwt.Drawing; namespace Xwt.GtkBackend { public partial class TextEntryBackend : WidgetBackend, ITextEntryBackend { public override void Initialize () { Widget = new Gtk.Entry (); Widget.Show (); } protected virtual Gtk.Entry TextEntry { get { return (Gtk.Entry)base.Widget; } } protected new Gtk.Entry Widget { get { return TextEntry; } set { base.Widget = value; } } protected new ITextEntryEventSink EventSink { get { return (ITextEntryEventSink)base.EventSink; } } public string Text { get { return Widget.Text; } set { Widget.Text = value ?? ""; } // null value causes GTK error } public Alignment TextAlignment { get { if (Widget.Xalign == 0) return Alignment.Start; else if (Widget.Xalign == 1) return Alignment.End; else return Alignment.Center; } set { switch (value) { case Alignment.Start: Widget.Xalign = 0; break; case Alignment.End: Widget.Xalign = 1; break; case Alignment.Center: Widget.Xalign = 0.5f; break; } } } public override Color BackgroundColor { get { return base.BackgroundColor; } set { base.BackgroundColor = value; Widget.ModifyBase (Gtk.StateType.Normal, value.ToGtkValue ()); } } public bool ReadOnly { get { return !Widget.IsEditable; } set { Widget.IsEditable = !value; } } public bool ShowFrame { get { return Widget.HasFrame; } set { Widget.HasFrame = value; } } public int CursorPosition { get { return Widget.Position; } set { Widget.Position = value; } } public int SelectionStart { get { int start, end; Widget.GetSelectionBounds (out start, out end); return start; } set { int cacheStart = SelectionStart; int cacheLength = SelectionLength; Widget.GrabFocus (); if (String.IsNullOrEmpty (Text)) return; Widget.SelectRegion (value, value + cacheLength); if (cacheStart != value) HandleSelectionChanged (); } } public int SelectionLength { get { int start, end; Widget.GetSelectionBounds (out start, out end); return end - start; } set { int cacheStart = SelectionStart; int cacheLength = SelectionLength; Widget.GrabFocus (); if (String.IsNullOrEmpty (Text)) return; Widget.SelectRegion (cacheStart, cacheStart + value); if (cacheLength != value) HandleSelectionChanged (); } } public string SelectedText { get { int start = SelectionStart; int end = start + SelectionLength; if (start == end) return String.Empty; try { return Text.Substring (start, end - start); } catch { return String.Empty; } } set { int cacheSelStart = SelectionStart; int pos = cacheSelStart; if (SelectionLength > 0) { Widget.DeleteSelection (); } Widget.InsertText (value, ref pos); Widget.GrabFocus (); Widget.SelectRegion (cacheSelStart, pos); HandleSelectionChanged (); } } public bool MultiLine { get; set; } public void SetCompletions (string[] completions) { if (completions == null || completions.Length == 0) { Widget.Completion = null; return; } var model = new Gtk.ListStore (typeof(string)); foreach (var c in completions) model.SetValue (model.Append (), 0, c); Widget.Completion = new Gtk.EntryCompletion () { Model = model, PopupCompletion = true, TextColumn = 0 }; } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is TextEntryEvent) { switch ((TextEntryEvent)eventId) { case TextEntryEvent.Changed: Widget.Changed += HandleChanged; break; case TextEntryEvent.Activated: Widget.Activated += HandleActivated; break; case TextEntryEvent.SelectionChanged: enableSelectionChangedEvent = true; Widget.MoveCursor += HandleMoveCursor; Widget.ButtonPressEvent += HandleButtonPressEvent; Widget.ButtonReleaseEvent += HandleButtonReleaseEvent; Widget.MotionNotifyEvent += HandleMotionNotifyEvent; break; } } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is TextEntryEvent) { switch ((TextEntryEvent)eventId) { case TextEntryEvent.Changed: Widget.Changed -= HandleChanged; break; case TextEntryEvent.Activated: Widget.Activated -= HandleActivated; break; case TextEntryEvent.SelectionChanged: enableSelectionChangedEvent = false; Widget.MoveCursor -= HandleMoveCursor; Widget.ButtonPressEvent -= HandleButtonPressEvent; Widget.ButtonReleaseEvent -= HandleButtonReleaseEvent; Widget.MotionNotifyEvent -= HandleMotionNotifyEvent; break; } } } void HandleChanged (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnChanged (); EventSink.OnSelectionChanged (); }); } void HandleActivated (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnActivated (); }); } bool enableSelectionChangedEvent; void HandleSelectionChanged () { if (enableSelectionChangedEvent) ApplicationContext.InvokeUserCode (delegate { EventSink.OnSelectionChanged (); }); } void HandleMoveCursor (object sender, EventArgs e) { HandleSelectionChanged (); } int cacheSelectionStart, cacheSelectionLength; bool isMouseSelection; [GLib.ConnectBefore] void HandleButtonPressEvent (object o, Gtk.ButtonPressEventArgs args) { if (args.Event.Button == 1) { HandleSelectionChanged (); cacheSelectionStart = SelectionStart; cacheSelectionLength = SelectionLength; isMouseSelection = true; } } [GLib.ConnectBefore] void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args) { if (isMouseSelection) if (cacheSelectionStart != SelectionStart || cacheSelectionLength != SelectionLength) HandleSelectionChanged (); cacheSelectionStart = SelectionStart; cacheSelectionLength = SelectionLength; } [GLib.ConnectBefore] void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args) { if (args.Event.Button == 1) { isMouseSelection = false; HandleSelectionChanged (); } } } }