context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. 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 */ #endregion using System; using System.IO; using System.Windows.Forms; using System.Diagnostics; using System.Threading; using log4net; using Axiom.Core; using Axiom.Graphics; using Axiom.Media; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using D3D = Microsoft.DirectX.Direct3D; namespace Axiom.RenderSystems.DirectX9 { /// <summary> /// The Direct3D implementation of the RenderWindow class. /// </summary> public class D3DRenderWindow : RenderWindow { #region Fields private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(D3DRenderWindow)); protected Driver driver; Control windowHandle; bool isExternal; // private D3D.Device device; protected bool isSwapChain; protected D3D.SwapChain swapChain; protected PresentParameters presentParams = new PresentParameters(); /// <summary>Used to provide support for multiple RenderWindows per device.</summary> protected D3D.Surface renderSurface; /// <summary>Stencil buffer (or zbuffer)</summary> protected D3D.Surface renderZBuffer; protected MultiSampleType fsaaType; protected int fsaaQuality; protected int displayFrequency; protected bool isVSync; protected bool useNVPerfHUD; protected bool multiThreaded; protected string initialLoadBitmap; protected DefaultForm form = null; #endregion Fields public D3D.Surface RenderSurface { get { return renderSurface; } } public PresentParameters PresentationParameters { get { return presentParams; } } #region Constructor public D3DRenderWindow(Driver driver, bool isSwapChain) { this.driver = driver; this.isSwapChain = isSwapChain; fsaaType = MultiSampleType.None; fsaaQuality = 0; isFullScreen = false; isSwapChain = false; isExternal = false; windowHandle = null; isActive = false; displayFrequency = 0; } #endregion #region RenderWindow implementation /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="colorDepth"></param> /// <param name="isFullScreen"></param> /// <param name="left"></param> /// <param name="top"></param> /// <param name="depthBuffer"></param>height /// <param name="miscParams"></param> public override void Create(string name, int width, int height, bool isFullScreen, params object[] miscParams) { Control parentWindow = null; Control externalWindow = null; fsaaType = MultiSampleType.None; fsaaQuality = 0; isVSync = false; string title = name; int colorDepth = 32; int left = -1; int top = -1; bool depthBuffer = true; // Parameters that would have been set in the params list, but are not used // border, outerSize useNVPerfHUD = false; multiThreaded = false; Debug.Assert(miscParams.Length % 2 == 0); int index = 0; while (index < miscParams.Length) { string key = (string)miscParams[index++]; object value = miscParams[index++]; switch (key) { case "left": left = (int)value; break; case "top": top = (int)value; break; case "title": title = (string)value; break; case "parentWindow": parentWindow = (Control)value; break; case "externalWindow": externalWindow = (Control)value; break; case "vsync": isVSync = (bool)value; break; case "displayFrequency": displayFrequency = (int)value; break; case "colorDepth": case "colourDepth": colorDepth = (int)value; break; case "depthBuffer": depthBuffer = (bool)value; break; case "FSAA": fsaaType = (MultiSampleType)value; break; case "FSAAQuality": fsaaQuality = (int)value; break; case "useNVPerfHUD": useNVPerfHUD = (bool)value; break; case "multiThreaded": multiThreaded = (bool)value; break; case "initialLoadBitmap": initialLoadBitmap = (string)value; break; case "border": case "outerDimensions": default: log.Warn("Option not yet implemented"); break; } } if (windowHandle != null) Destroy(); if (externalWindow == null) { this.width = width; this.height = height; this.top = top; this.left = left; FormBorderStyle borderStyle = FormBorderStyle.None; FormWindowState windowState = FormWindowState.Normal; if (!isFullScreen) { // If RenderSystem.AllowResize is true, put a // resize border on the window. borderStyle = (Root.Instance.RenderSystem.AllowResize ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle); windowState = FormWindowState.Normal; } else { borderStyle = FormBorderStyle.None; windowState = FormWindowState.Maximized; this.top = 0; this.left = 0; } isExternal = false; form = new DefaultForm(!isFullScreen, initialLoadBitmap); // Set these two to false, or else windows get created // with different dimensions that requesting in Width // and Height! log.InfoFormat("Initial form settings: AutoSize: {0}; AutoScale: {1}", form.AutoSize, form.AutoScaleMode); form.AutoSize = false; form.AutoScaleMode = AutoScaleMode.None; form.ClientSize = new System.Drawing.Size(width, height); // TODO: I should support the maximize box once I get resize working // form.MaximizeBox = true; form.MaximizeBox = false; form.MinimizeBox = true; form.Top = this.top; form.Left = this.left; form.FormBorderStyle = borderStyle; form.WindowState = windowState; form.Text = title; form.StartPosition = FormStartPosition.CenterScreen; form.BringToFront(); if (isFullScreen) { form.TopMost = true; form.TopLevel = true; form.Width = width; form.Height = height; } // form.Target.Visible = false; form.Show(); // set the default form's renderwindow so it can access it internally form.RenderWindow = this; form.Activate(); windowHandle = form.Target; } else { windowHandle = externalWindow; isExternal = true; this.top = windowHandle.Top; this.left = windowHandle.Left; System.Drawing.Rectangle rect = windowHandle.ClientRectangle; this.width = rect.Width; this.height = rect.Height; } windowHandle.Resize += this.OnExternalWindowEvent; windowHandle.Move += this.OnExternalWindowEvent; this.name = name; this.isDepthBuffered = depthBuffer; this.isFullScreen = isFullScreen; this.colorDepth = colorDepth; CreateD3DResources(); isActive = true; // FIXME: These lines were not in Ogre, but are in Axiom. //D3D.Device device = driver.Device; // device.DeviceReset += new EventHandler(OnResetDevice); //this.OnResetDevice(device, null); } /// <summary> /// Specifies the custom attribute by converting this to a string and passing to GetCustomAttribute() /// </summary> // public enum CustomAttribute { D3DDEVICE, D3DZBUFFER, D3DBACKBUFFER } public void CreateD3DResources() { // access device via driver Device device = driver.Device; if (isSwapChain && device == null) { throw new Exception("Secondary window has not been given the device from the primary!"); } DeviceType devType = DeviceType.Hardware; presentParams = new PresentParameters(); presentParams.Windowed = !isFullScreen; presentParams.SwapEffect = SwapEffect.Discard; // triple buffer if VSync is on presentParams.BackBufferCount = isVSync ? 2 : 1; presentParams.EnableAutoDepthStencil = isDepthBuffered; presentParams.DeviceWindow = windowHandle; presentParams.BackBufferWidth = width; presentParams.BackBufferHeight = height; presentParams.FullScreenRefreshRateInHz = isFullScreen ? displayFrequency : 0; if (isVSync) { presentParams.PresentationInterval = PresentInterval.One; } else { // NB not using vsync in windowed mode in D3D9 can cause jerking at low // frame rates no matter what buffering modes are used (odd - perhaps a // timer issue in D3D9 since GL doesn't suffer from this) // low is < 200fps in this context if (!isFullScreen) log.Debug("Disabling VSync in windowed mode can cause timing issues at lower " + "frame rates, turn VSync on if you observe this problem."); presentParams.PresentationInterval = PresentInterval.Immediate; } presentParams.BackBufferFormat = Format.R5G6B5; if (colorDepth > 16) presentParams.BackBufferFormat = Format.X8R8G8B8; if (colorDepth > 16) { // Try to create a 32-bit depth, 8-bit stencil if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType, presentParams.BackBufferFormat, Usage.DepthStencil, ResourceType.Surface, DepthFormat.D24S8)) { // Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType, presentParams.BackBufferFormat, Usage.DepthStencil, ResourceType.Surface, DepthFormat.D32)) { // Jeez, what a naff card. Fall back on 16-bit depth buffering presentParams.AutoDepthStencilFormat = DepthFormat.D16; } else presentParams.AutoDepthStencilFormat = DepthFormat.D32; } else { // Woohoo! if (D3D.Manager.CheckDepthStencilMatch(driver.AdapterNumber, devType, presentParams.BackBufferFormat, presentParams.BackBufferFormat, DepthFormat.D24S8)) { presentParams.AutoDepthStencilFormat = DepthFormat.D24S8; } else presentParams.AutoDepthStencilFormat = DepthFormat.D24X8; } } else { // 16-bit depth, software stencil presentParams.AutoDepthStencilFormat = DepthFormat.D16; } presentParams.MultiSample = fsaaType; presentParams.MultiSampleQuality = fsaaQuality; if (isSwapChain) { swapChain = new SwapChain(device, presentParams); if (swapChain == null) { // Try a second time, may fail the first time due to back buffer count, // which will be corrected by the runtime swapChain = new SwapChain(device, presentParams); } // Store references to buffers for convenience renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono); // Additional swap chains need their own depth buffer // to support resizing them if (isDepthBuffered) { renderZBuffer = device.CreateDepthStencilSurface(width, height, presentParams.AutoDepthStencilFormat, presentParams.MultiSample, presentParams.MultiSampleQuality, false); } else { renderZBuffer = null; } // Ogre releases the mpRenderSurface here (but not the mpRenderZBuffer) // release immediately so we don't hog them // mpRenderSurface->Release(); // We'll need the depth buffer for rendering the swap chain // //mpRenderZBuffer->Release(); } else { if (device == null) { #if !USE_D3D_EVENTS // Turn off default event handlers, since Managed DirectX seems confused. Device.IsUsingEventHandlers = false; #endif // We haven't created the device yet, this must be the first time // Do we want to preserve the FPU mode? Might be useful for scientific apps CreateFlags extraFlags = 0; if (multiThreaded) { extraFlags |= CreateFlags.MultiThreaded; } // TODO: query and preserve the fpu mode // Set default settings (use the one Ogre discovered as a default) int adapterToUse = driver.AdapterNumber; if (useNVPerfHUD) { // Look for 'NVIDIA NVPerfHUD' adapter // If it is present, override default settings foreach (AdapterInformation identifier in D3D.Manager.Adapters) { log.Info("Device found: " + identifier.Information.Description); if (identifier.Information.Description.Contains("PerfHUD")) { log.Info("Attempting to use PerfHUD"); adapterToUse = identifier.Adapter; devType = DeviceType.Reference; break; } } } try { device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.HardwareVertexProcessing | extraFlags, presentParams); } catch (Exception) { log.Info("First device creation failed"); try { // Try a second time, may fail the first time due to back buffer count, // which will be corrected down to 1 by the runtime device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.HardwareVertexProcessing | extraFlags, presentParams); } catch (Exception) { try { // Looks like we can't use HardwareVertexProcessing, so try Mixed device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.MixedVertexProcessing | extraFlags, presentParams); } catch (Exception) { // Ok, one last try. Try software. If this fails, just throw up. device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.SoftwareVertexProcessing | extraFlags, presentParams); } } } // TODO: For a full screen app, I'm supposed to do this to prevent alt-tab // from messing things up. //device.DeviceResizing += new // System.ComponentModel.CancelEventHandler(this.CancelResize); } log.InfoFormat("Device constructed with presentation parameters: {0}", presentParams.ToString()); // update device in driver driver.Device = device; // Store references to buffers for convenience renderSurface = device.GetRenderTarget(0); renderZBuffer = device.DepthStencilSurface; // Ogre releases these here // release immediately so we don't hog them // mpRenderSurface->Release(); // mpRenderZBuffer->Release(); } } private void CancelResize(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = true; } /// <summary> /// /// </summary> public override void Dispose() { base.Dispose(); Destroy(); } public void DestroyD3DResources() { // FIXME: Ogre doesn't do this Dispose call here (just sets to null). if (renderSurface != null) { renderSurface.Dispose(); renderSurface = null; } // renderSurface = null; if (isSwapChain) { if (renderZBuffer != null) { renderZBuffer.Dispose(); renderZBuffer = null; } if (swapChain != null) { swapChain.Dispose(); swapChain = null; } } else { // FIXME: Ogre doesn't do this Dispose call here (just sets to null). if (renderZBuffer != null) { renderZBuffer.Dispose(); renderZBuffer = null; } // renderZBuffer = null; } } protected void Destroy() { DestroyD3DResources(); if (windowHandle != null && !isExternal) { // if the control is a form, then close it Form form = windowHandle.FindForm(); form.Close(); form.Dispose(); } windowHandle = null; // make sure this window is no longer active isActive = false; } public override void Reposition(int top, int left) { if (windowHandle != null && !isFullScreen) { Form form = windowHandle.FindForm(); form.SetDesktopLocation(left, top); } } /// <summary> /// /// </summary> /// <param name="width"></param> /// <param name="height"></param> public override void Resize(int width, int height) { if (windowHandle != null && !isFullScreen) { windowHandle.Size = new System.Drawing.Size(width, height); } } public void OnExternalWindowEvent(object sender, EventArgs e) { WindowMovedOrResized(); } public void WindowMovedOrResized() { log.Info("D3DRenderWindow.WindowMovedOrResized called."); if (windowHandle == null) return; Form form = windowHandle.FindForm(); if (form != null) { if (form.WindowState == FormWindowState.Minimized) return; this.top = form.DesktopLocation.Y; this.left = form.DesktopLocation.X; } if ((width == windowHandle.Size.Width) && (height == windowHandle.Size.Height)) return; if (isSwapChain) { PresentParameters pp = new PresentParameters(presentParams); width = windowHandle.Size.Width > 0 ? windowHandle.Size.Width : 1; height = windowHandle.Size.Height > 0 ? windowHandle.Size.Height : 1; if (presentParams.Windowed) { pp.BackBufferWidth = width; pp.BackBufferHeight = height; } if (renderZBuffer != null) { renderZBuffer.Dispose(); renderZBuffer = null; } if (swapChain != null) { swapChain.Dispose(); swapChain = null; } if (renderSurface != null) { renderSurface.Dispose(); renderSurface = null; } swapChain = new SwapChain(driver.Device, pp); presentParams = pp; renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono); renderZBuffer = driver.Device.CreateDepthStencilSurface(presentParams.BackBufferWidth, presentParams.BackBufferHeight, presentParams.AutoDepthStencilFormat, presentParams.MultiSample, presentParams.MultiSampleQuality, false); // TODO: Ogre releases here // renderSurface.Release(); } else { // primary windows must reset the device width = windowHandle.Size.Width > 0 ? windowHandle.Size.Width : 1; height = windowHandle.Size.Height > 0 ? windowHandle.Size.Height : 1; if (presentParams.Windowed) { presentParams.BackBufferWidth = width; presentParams.BackBufferHeight = height; } D3D9RenderSystem renderSystem = (D3D9RenderSystem)Root.Instance.RenderSystem; renderSystem.NotifyDeviceLost(); } // Notify viewports of resize foreach (Axiom.Core.Viewport viewport in viewportList) viewport.UpdateDimensions(); } /// <summary> /// /// </summary> /// <param name="waitForVSync"></param> public override void SwapBuffers(bool waitForVSync) { D3D.Device device = driver.Device; if (device != null) { int status; // tests coop level to make sure we are ok to render device.CheckCooperativeLevel(out status); if (status == (int)Microsoft.DirectX.Direct3D.ResultCode.Success) { // swap back buffer to the front if (isSwapChain) { swapChain.Present(); } else { device.Present(); } } else if (status == (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceLost) { // Device is lost, and is not available for reset now log.Warn("Device State: DeviceLost"); D3D9RenderSystem renderSystem = (D3D9RenderSystem)Root.Instance.RenderSystem; renderSystem.NotifyDeviceLost(); } else if (status == (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceNotReset) { // The device needs to be reset, and has not yet been reset. log.Warn("Device State: DeviceNotReset"); device.Reset(device.PresentationParameters); } else { throw new Exception(string.Format("Unknown status code from CheckCooperativeLevel: {0}", status)); } } } public override object GetCustomAttribute(string attribute) { switch(attribute) { case "D3DDEVICE": return driver.Device; case "HWND": return windowHandle; case "isTexture": return false; case "D3DZBUFFER": return renderZBuffer; case "DDBACKBUFFER": return renderSurface; case "DDFRONTBUFFER": return renderSurface; } log.WarnFormat("There is no D3DRenderWindow custom attribute named {0}", attribute); return null; } /// <summary> /// /// </summary> public override bool IsActive { get { return isActive; } set { isActive = value; } } /// <summary> /// /// </summary> public override bool IsFullScreen { get { return base.IsFullScreen; } } /// <summary> /// Saves the window contents to a stream. /// </summary> /// <param name="stream">Stream to write the window contents to.</param> public override void Save(Stream stream, PixelFormat requestedFormat) { D3D.Device device = driver.Device; DisplayMode mode = device.DisplayMode; SurfaceDescription desc = new SurfaceDescription(); desc.Width = mode.Width; desc.Height = mode.Height; desc.Format = Format.A8R8G8B8; // create a temp surface which will hold the screen image Surface surface = device.CreateOffscreenPlainSurface( mode.Width, mode.Height, Format.A8R8G8B8, Pool.SystemMemory); // get the entire front buffer. This is SLOW!! device.GetFrontBufferData(0, surface); // if not fullscreen, the front buffer contains the entire desktop image. we need to grab only the portion // that contains our render window if (!IsFullScreen) { // whatever our target control is, we need to walk up the chain and find the parent form Form form = windowHandle.FindForm(); // get the actual screen location of the form System.Drawing.Rectangle rect = form.RectangleToScreen(form.ClientRectangle); desc.Width = width; desc.Height = height; desc.Format = Format.A8R8G8B8; // create a temp surface that is sized the same as our target control Surface tmpSurface = device.CreateOffscreenPlainSurface(rect.Width, rect.Height, Format.A8R8G8B8, Pool.Default); // copy the data from the front buffer to the window sized surface device.UpdateSurface(surface, rect, tmpSurface); // dispose of the prior surface surface.Dispose(); surface = tmpSurface; } int pitch; // lock the surface to grab the data GraphicsStream graphStream = surface.LockRectangle(LockFlags.ReadOnly | LockFlags.NoSystemLock, out pitch); // create an RGB buffer byte[] buffer = new byte[width * height * 3]; int offset = 0, line = 0, count = 0; // gotta copy that data manually since it is in another format (sheesh!) unsafe { byte* data = (byte*)graphStream.InternalData; for (int y = 0; y < desc.Height; y++) { line = y * pitch; for (int x = 0; x < desc.Width; x++) { offset = x * 4; int pixel = line + offset; // Actual format is BRGA for some reason buffer[count++] = data[pixel + 2]; buffer[count++] = data[pixel + 1]; buffer[count++] = data[pixel + 0]; } } } surface.UnlockRectangle(); // dispose of the surface surface.Dispose(); // gotta flip the image real fast Image image = Image.FromDynamicImage(buffer, width, height, PixelFormat.R8G8B8); image.FlipAroundX(); // write the data to the stream provided stream.Write(image.Data, 0, image.Data.Length); } public override void Update() { D3D9RenderSystem rs = (D3D9RenderSystem)Root.Instance.RenderSystem; // access device through driver D3D.Device device = driver.Device; if (rs.DeviceLost) { log.Info("In D3DRenderWindow.Update, rs.DeviceLost is true"); // Test the cooperative mode first int status; device.CheckCooperativeLevel(out status); if (status == (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceLost) { // device lost, and we can't reset // can't do anything about it here, wait until we get // D3DERR_DEVICENOTRESET; rendering calls will silently fail until // then (except Present, but we ignore device lost there too) // FIXME: Ogre doesn't do these two Dispose calls here. #if NOT // This code is what Ogre does for this clause, but since // Ogre gets to immediately call release on the renderSurface // and renderZBuffer, this assign of null will end up leaving // the reference count at 0 for them, and will cause them to // be freed. For the Axiom code, I'm just going to leave them // alone, and do the proper dispose calls in the devicenotreset // clause. renderSurface = null; // need to release if swap chain if (!isSwapChain) { renderZBuffer = null; } else { // Do I need to dispose of the ZBuffer here? // SAFE_RELEASE (mpRenderZBuffer); if (renderZBuffer != null) { renderZBuffer.Dispose(); renderZBuffer = null; } } #endif Thread.Sleep(50); return; } else { if (status != (int)Microsoft.DirectX.Direct3D.ResultCode.Success && status != (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceNotReset) { // I've encountered some unexpected device state // Ogre would just continue, but I want to make sure I notice this. throw new Exception(string.Format("Unknown Device State: {0}", status)); } // FIXME: Ogre doesn't do these two Dispose calls here. if (renderSurface != null) { log.Info("Disposing of render surface"); renderSurface.Dispose(); renderSurface = null; } if (renderZBuffer != null) { log.Info("Disposing of render zbuffer"); renderZBuffer.Dispose(); renderZBuffer = null; } log.InfoFormat("In D3DRenderWindow.Update, calling rs.RestoreLostDevice(); status = {0}", status); // device lost, and we can reset rs.RestoreLostDevice(); // Still lost? if (rs.DeviceLost) { // Wait a while Thread.Sleep(50); return; } if (!isSwapChain) { log.Info("In D3DRenderWindow.Update, re-querying buffers"); // re-qeuery buffers renderSurface = device.GetRenderTarget(0); renderZBuffer = device.DepthStencilSurface; // release immediately so we don't hog them // mpRenderSurface->Release(); // mpRenderZBuffer->Release(); } else { log.Info("In D3DRenderWindow.Update, isSwapChain is true, changing viewport dimensions"); // Update dimensions incase changed foreach (Axiom.Core.Viewport vp in viewportList) vp.UpdateDimensions(); // Actual restoration of surfaces will happen in // D3D9RenderSystem.RestoreLostDevice when it calls // CreateD3DResources for each secondary window } } } base.Update(); } private void OnResetDevice(object sender, EventArgs e) { Device resetDevice = (Device)sender; // Turn off culling, so we see the front and back of the triangle resetDevice.RenderState.CullMode = Cull.None; // Turn on the ZBuffer resetDevice.RenderState.ZBufferEnable = true; resetDevice.RenderState.Lighting = true; //make sure lighting is enabled } public override object Handle { get { return windowHandle; } } public override bool PictureBoxVisible { get { if (form != null && form.PictureBox != null) return form.PictureBox.Visible; else return false; } set { if (form != null && form.PictureBox != null) form.PictureBox.Visible = value; } } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using Lucene.Net.Documents; namespace Lucene.Net.Index { using Lucene.Net.Support; using NUnit.Framework; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using TermQuery = Lucene.Net.Search.TermQuery; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; [TestFixture] public class TestDirectoryReaderReopen : LuceneTestCase { [Test] public virtual void TestReopen_Mem() { Directory dir1 = NewDirectory(); CreateIndex(Random(), dir1, false); PerformDefaultTests(new TestReopenAnonymousInnerClassHelper(this, dir1)); dir1.Dispose(); Directory dir2 = NewDirectory(); CreateIndex(Random(), dir2, true); PerformDefaultTests(new TestReopenAnonymousInnerClassHelper2(this, dir2)); dir2.Dispose(); } private class TestReopenAnonymousInnerClassHelper : TestReopen { private readonly TestDirectoryReaderReopen OuterInstance; private Directory Dir1; public TestReopenAnonymousInnerClassHelper(TestDirectoryReaderReopen outerInstance, Directory dir1) { this.OuterInstance = outerInstance; this.Dir1 = dir1; } protected internal override void ModifyIndex(int i) { TestDirectoryReaderReopen.ModifyIndex(i, Dir1); } protected internal override DirectoryReader OpenReader() { return DirectoryReader.Open(Dir1); } } private class TestReopenAnonymousInnerClassHelper2 : TestReopen { private readonly TestDirectoryReaderReopen OuterInstance; private Directory Dir2; public TestReopenAnonymousInnerClassHelper2(TestDirectoryReaderReopen outerInstance, Directory dir2) { this.OuterInstance = outerInstance; this.Dir2 = dir2; } protected internal override void ModifyIndex(int i) { TestDirectoryReaderReopen.ModifyIndex(i, Dir2); } protected internal override DirectoryReader OpenReader() { return DirectoryReader.Open(Dir2); } } // LUCENE-1228: IndexWriter.Commit() does not update the index version // populate an index in iterations. // at the end of every iteration, commit the index and reopen/recreate the reader. // in each iteration verify the work of previous iteration. // try this once with reopen once recreate, on both RAMDir and FSDir. [Test] public virtual void TestCommitReopen() { Directory dir = NewDirectory(); DoTestReopenWithCommit(Random(), dir, true); dir.Dispose(); } [Test] public virtual void TestCommitRecreate() { Directory dir = NewDirectory(); DoTestReopenWithCommit(Random(), dir, false); dir.Dispose(); } private void DoTestReopenWithCommit(Random random, Directory dir, bool withReopen) { IndexWriter iwriter = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode_e.CREATE).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(NewLogMergePolicy())); iwriter.Commit(); DirectoryReader reader = DirectoryReader.Open(dir); try { int M = 3; FieldType customType = new FieldType(TextField.TYPE_STORED); customType.Tokenized = false; FieldType customType2 = new FieldType(TextField.TYPE_STORED); customType2.Tokenized = false; customType2.OmitNorms = true; FieldType customType3 = new FieldType(); customType3.Stored = true; for (int i = 0; i < 4; i++) { for (int j = 0; j < M; j++) { Document doc = new Document(); doc.Add(NewField("id", i + "_" + j, customType)); doc.Add(NewField("id2", i + "_" + j, customType2)); doc.Add(NewField("id3", i + "_" + j, customType3)); iwriter.AddDocument(doc); if (i > 0) { int k = i - 1; int n = j + k * M; Document prevItereationDoc = reader.Document(n); Assert.IsNotNull(prevItereationDoc); string id = prevItereationDoc.Get("id"); Assert.AreEqual(k + "_" + j, id); } } iwriter.Commit(); if (withReopen) { // reopen DirectoryReader r2 = DirectoryReader.OpenIfChanged(reader); if (r2 != null) { reader.Dispose(); reader = r2; } } else { // recreate reader.Dispose(); reader = DirectoryReader.Open(dir); } } } finally { iwriter.Dispose(); reader.Dispose(); } } private void PerformDefaultTests(TestReopen test) { DirectoryReader index1 = test.OpenReader(); DirectoryReader index2 = test.OpenReader(); TestDirectoryReader.AssertIndexEquals(index1, index2); // verify that reopen() does not return a new reader instance // in case the index has no changes ReaderCouple couple = RefreshReader(index2, false); Assert.IsTrue(couple.RefreshedReader == index2); couple = RefreshReader(index2, test, 0, true); index1.Dispose(); index1 = couple.NewReader; DirectoryReader index2_refreshed = couple.RefreshedReader; index2.Dispose(); // test if refreshed reader and newly opened reader return equal results TestDirectoryReader.AssertIndexEquals(index1, index2_refreshed); index2_refreshed.Dispose(); AssertReaderClosed(index2, true); AssertReaderClosed(index2_refreshed, true); index2 = test.OpenReader(); for (int i = 1; i < 4; i++) { index1.Dispose(); couple = RefreshReader(index2, test, i, true); // refresh DirectoryReader index2.Dispose(); index2 = couple.RefreshedReader; index1 = couple.NewReader; TestDirectoryReader.AssertIndexEquals(index1, index2); } index1.Dispose(); index2.Dispose(); AssertReaderClosed(index1, true); AssertReaderClosed(index2, true); } [Test] public virtual void TestThreadSafety() { Directory dir = NewDirectory(); // NOTE: this also controls the number of threads! int n = TestUtil.NextInt(Random(), 20, 40); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); for (int i = 0; i < n; i++) { writer.AddDocument(CreateDocument(i, 3)); } writer.ForceMerge(1); writer.Dispose(); TestReopen test = new TestReopenAnonymousInnerClassHelper3(this, dir, n); IList<ReaderCouple> readers = new SynchronizedCollection<ReaderCouple>(); DirectoryReader firstReader = DirectoryReader.Open(dir); DirectoryReader reader = firstReader; ReaderThread[] threads = new ReaderThread[n]; ISet<DirectoryReader> readersToClose = new ConcurrentHashSet<DirectoryReader>(new HashSet<DirectoryReader>()); for (int i = 0; i < n; i++) { if (i % 2 == 0) { DirectoryReader refreshed = DirectoryReader.OpenIfChanged(reader); if (refreshed != null) { readersToClose.Add(reader); reader = refreshed; } } DirectoryReader r = reader; int index = i; ReaderThreadTask task; if (i < 4 || (i >= 10 && i < 14) || i > 18) { task = new ReaderThreadTaskAnonymousInnerClassHelper(this, test, readers, readersToClose, r, index); } else { task = new ReaderThreadTaskAnonymousInnerClassHelper2(this, readers); } threads[i] = new ReaderThread(task); threads[i].Start(); } lock (this) { Monitor.Wait(this, TimeSpan.FromMilliseconds(1000)); } for (int i = 0; i < n; i++) { if (threads[i] != null) { threads[i].StopThread(); } } for (int i = 0; i < n; i++) { if (threads[i] != null) { threads[i].Join(); if (threads[i].Error != null) { string msg = "Error occurred in thread " + threads[i].Name + ":\n" + threads[i].Error.Message; Assert.Fail(msg); } } } foreach (DirectoryReader readerToClose in readersToClose) { readerToClose.Dispose(); } firstReader.Dispose(); reader.Dispose(); foreach (DirectoryReader readerToClose in readersToClose) { AssertReaderClosed(readerToClose, true); } AssertReaderClosed(reader, true); AssertReaderClosed(firstReader, true); dir.Dispose(); } private class TestReopenAnonymousInnerClassHelper3 : TestReopen { private readonly TestDirectoryReaderReopen OuterInstance; private Directory Dir; private int n; public TestReopenAnonymousInnerClassHelper3(TestDirectoryReaderReopen outerInstance, Directory dir, int n) { this.OuterInstance = outerInstance; this.Dir = dir; this.n = n; } protected internal override void ModifyIndex(int i) { IndexWriter modifier = new IndexWriter(Dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); modifier.AddDocument(CreateDocument(n + i, 6)); modifier.Dispose(); } protected internal override DirectoryReader OpenReader() { return DirectoryReader.Open(Dir); } } private class ReaderThreadTaskAnonymousInnerClassHelper : ReaderThreadTask { private readonly TestDirectoryReaderReopen OuterInstance; private Lucene.Net.Index.TestDirectoryReaderReopen.TestReopen Test; private IList<ReaderCouple> Readers; private ISet<DirectoryReader> ReadersToClose; private DirectoryReader r; private int Index; public ReaderThreadTaskAnonymousInnerClassHelper(TestDirectoryReaderReopen outerInstance, Lucene.Net.Index.TestDirectoryReaderReopen.TestReopen test, IList<ReaderCouple> readers, ISet<DirectoryReader> readersToClose, DirectoryReader r, int index) { this.OuterInstance = outerInstance; this.Test = test; this.Readers = readers; this.ReadersToClose = readersToClose; this.r = r; this.Index = index; } public override void Run() { Random rnd = LuceneTestCase.Random(); while (!Stopped) { if (Index % 2 == 0) { // refresh reader synchronized ReaderCouple c = (OuterInstance.RefreshReader(r, Test, Index, true)); ReadersToClose.Add(c.NewReader); ReadersToClose.Add(c.RefreshedReader); Readers.Add(c); // prevent too many readers break; } else { // not synchronized DirectoryReader refreshed = DirectoryReader.OpenIfChanged(r); if (refreshed == null) { refreshed = r; } IndexSearcher searcher = NewSearcher(refreshed); ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("field1", "a" + rnd.Next(refreshed.MaxDoc))), null, 1000).ScoreDocs; if (hits.Length > 0) { searcher.Doc(hits[0].Doc); } if (refreshed != r) { refreshed.Dispose(); } } lock (this) { Monitor.Wait(this, TimeSpan.FromMilliseconds(TestUtil.NextInt(Random(), 1, 100))); } } } } private class ReaderThreadTaskAnonymousInnerClassHelper2 : ReaderThreadTask { private readonly TestDirectoryReaderReopen OuterInstance; private IList<ReaderCouple> Readers; public ReaderThreadTaskAnonymousInnerClassHelper2(TestDirectoryReaderReopen outerInstance, IList<ReaderCouple> readers) { this.OuterInstance = outerInstance; this.Readers = readers; } public override void Run() { Random rnd = LuceneTestCase.Random(); while (!Stopped) { int numReaders = Readers.Count; if (numReaders > 0) { ReaderCouple c = Readers[rnd.Next(numReaders)]; TestDirectoryReader.AssertIndexEquals(c.NewReader, c.RefreshedReader); } lock (this) { Monitor.Wait(this, TimeSpan.FromMilliseconds(TestUtil.NextInt(Random(), 1, 100))); } } } } internal class ReaderCouple { internal ReaderCouple(DirectoryReader r1, DirectoryReader r2) { NewReader = r1; RefreshedReader = r2; } internal DirectoryReader NewReader; internal DirectoryReader RefreshedReader; } internal abstract class ReaderThreadTask { protected internal volatile bool Stopped; public virtual void Stop() { this.Stopped = true; } public abstract void Run(); } private class ReaderThread : ThreadClass { internal ReaderThreadTask Task; internal Exception Error; internal ReaderThread(ReaderThreadTask task) { this.Task = task; } public virtual void StopThread() { this.Task.Stop(); } public override void Run() { try { this.Task.Run(); } catch (Exception r) { Console.WriteLine(r.StackTrace); this.Error = r; } } } private object CreateReaderMutex = new object(); private ReaderCouple RefreshReader(DirectoryReader reader, bool hasChanges) { return RefreshReader(reader, null, -1, hasChanges); } internal virtual ReaderCouple RefreshReader(DirectoryReader reader, TestReopen test, int modify, bool hasChanges) { lock (CreateReaderMutex) { DirectoryReader r = null; if (test != null) { test.ModifyIndex(modify); r = test.OpenReader(); } DirectoryReader refreshed = null; try { refreshed = DirectoryReader.OpenIfChanged(reader); if (refreshed == null) { refreshed = reader; } } finally { if (refreshed == null && r != null) { // Hit exception -- close opened reader r.Dispose(); } } if (hasChanges) { if (refreshed == reader) { Assert.Fail("No new DirectoryReader instance created during refresh."); } } else { if (refreshed != reader) { Assert.Fail("New DirectoryReader instance created during refresh even though index had no changes."); } } return new ReaderCouple(r, refreshed); } } public static void CreateIndex(Random random, Directory dir, bool multiSegment) { IndexWriter.Unlock(dir); IndexWriter w = new IndexWriter(dir, LuceneTestCase.NewIndexWriterConfig(random, TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(new LogDocMergePolicy())); for (int i = 0; i < 100; i++) { w.AddDocument(CreateDocument(i, 4)); if (multiSegment && (i % 10) == 0) { w.Commit(); } } if (!multiSegment) { w.ForceMerge(1); } w.Dispose(); DirectoryReader r = DirectoryReader.Open(dir); if (multiSegment) { Assert.IsTrue(r.Leaves.Count > 1); } else { Assert.IsTrue(r.Leaves.Count == 1); } r.Dispose(); } public static Document CreateDocument(int n, int numFields) { StringBuilder sb = new StringBuilder(); Document doc = new Document(); sb.Append("a"); sb.Append(n); FieldType customType2 = new FieldType(TextField.TYPE_STORED); customType2.Tokenized = false; customType2.OmitNorms = true; FieldType customType3 = new FieldType(); customType3.Stored = true; doc.Add(new TextField("field1", sb.ToString(), Field.Store.YES)); doc.Add(new Field("fielda", sb.ToString(), customType2)); doc.Add(new Field("fieldb", sb.ToString(), customType3)); sb.Append(" b"); sb.Append(n); for (int i = 1; i < numFields; i++) { doc.Add(new TextField("field" + (i + 1), sb.ToString(), Field.Store.YES)); } return doc; } internal static void ModifyIndex(int i, Directory dir) { switch (i) { case 0: { if (VERBOSE) { Console.WriteLine("TEST: modify index"); } IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); w.DeleteDocuments(new Term("field2", "a11")); w.DeleteDocuments(new Term("field2", "b30")); w.Dispose(); break; } case 1: { IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); w.ForceMerge(1); w.Dispose(); break; } case 2: { IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); w.AddDocument(CreateDocument(101, 4)); w.ForceMerge(1); w.AddDocument(CreateDocument(102, 4)); w.AddDocument(CreateDocument(103, 4)); w.Dispose(); break; } case 3: { IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); w.AddDocument(CreateDocument(101, 4)); w.Dispose(); break; } } } internal static void AssertReaderClosed(IndexReader reader, bool checkSubReaders) { Assert.AreEqual(0, reader.RefCount); if (checkSubReaders && reader is CompositeReader) { // we cannot use reader context here, as reader is // already closed and calling getTopReaderContext() throws AlreadyClosed! IList<IndexReader> subReaders = ((CompositeReader)reader).GetSequentialSubReaders(); foreach (IndexReader r in subReaders) { AssertReaderClosed(r, checkSubReaders); } } } internal abstract class TestReopen { protected internal abstract DirectoryReader OpenReader(); protected internal abstract void ModifyIndex(int i); } internal class KeepAllCommits<T> : IndexDeletionPolicy where T : IndexCommit { public override void OnInit<T>(IList<T> commits) { } public override void OnCommit<T>(IList<T> commits) { } } [Test] public virtual void TestReopenOnCommit() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(new KeepAllCommits<IndexCommit>()).SetMaxBufferedDocs(-1).SetMergePolicy(NewLogMergePolicy(10))); for (int i = 0; i < 4; i++) { Document doc = new Document(); doc.Add(NewStringField("id", "" + i, Field.Store.NO)); writer.AddDocument(doc); IDictionary<string, string> data = new Dictionary<string, string>(); data["index"] = i + ""; writer.CommitData = data; writer.Commit(); } for (int i = 0; i < 4; i++) { writer.DeleteDocuments(new Term("id", "" + i)); IDictionary<string, string> data = new Dictionary<string, string>(); data["index"] = (4 + i) + ""; writer.CommitData = data; writer.Commit(); } writer.Dispose(); DirectoryReader r = DirectoryReader.Open(dir); Assert.AreEqual(0, r.NumDocs); ICollection<IndexCommit> commits = DirectoryReader.ListCommits(dir); foreach (IndexCommit commit in commits) { DirectoryReader r2 = DirectoryReader.OpenIfChanged(r, commit); Assert.IsNotNull(r2); Assert.IsTrue(r2 != r); IDictionary<string, string> s = commit.UserData; int v; if (s.Count == 0) { // First commit created by IW v = -1; } else { v = Convert.ToInt32(s["index"]); } if (v < 4) { Assert.AreEqual(1 + v, r2.NumDocs); } else { Assert.AreEqual(7 - v, r2.NumDocs); } r.Dispose(); r = r2; } r.Dispose(); dir.Dispose(); } [Test] public virtual void TestOpenIfChangedNRTToCommit() { Directory dir = NewDirectory(); // Can't use RIW because it randomly commits: IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document doc = new Document(); doc.Add(NewStringField("field", "value", Field.Store.NO)); w.AddDocument(doc); w.Commit(); IList<IndexCommit> commits = DirectoryReader.ListCommits(dir); Assert.AreEqual(1, commits.Count); w.AddDocument(doc); DirectoryReader r = DirectoryReader.Open(w, true); Assert.AreEqual(2, r.NumDocs); IndexReader r2 = DirectoryReader.OpenIfChanged(r, commits[0]); Assert.IsNotNull(r2); r.Dispose(); Assert.AreEqual(1, r2.NumDocs); w.Dispose(); r2.Dispose(); dir.Dispose(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.MachineLearning.WebServices { using Microsoft.Rest.Azure; using Models; /// <summary> /// WebServicesOperations operations. /// </summary> public partial interface IWebServicesOperations { /// <summary> /// Create or update a web service. This call will overwrite an /// existing web service. Note that there is no warning or /// confirmation. This is a nonrecoverable operation. If your intent /// is to create a new web service, call the Get operation first to /// verify that it does not exist. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='createOrUpdatePayload'> /// The payload that is used to create or update the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string webServiceName, WebService createOrUpdatePayload, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Create or update a web service. This call will overwrite an /// existing web service. Note that there is no warning or /// confirmation. This is a nonrecoverable operation. If your intent /// is to create a new web service, call the Get operation first to /// verify that it does not exist. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='createOrUpdatePayload'> /// The payload that is used to create or update the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string webServiceName, WebService createOrUpdatePayload, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the Web Service Definiton as specified by a subscription, /// resource group, and name. Note that the storage credentials and /// web service keys are not returned by this call. To get the web /// service access keys, call List Keys. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> GetWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Modifies an existing web service resource. The PATCH API call is /// an asynchronous operation. To determine whether it has completed /// successfully, you must perform a Get operation. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='patchPayload'> /// The payload to use to patch the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> PatchWithHttpMessagesAsync(string resourceGroupName, string webServiceName, WebService patchPayload, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Modifies an existing web service resource. The PATCH API call is /// an asynchronous operation. To determine whether it has completed /// successfully, you must perform a Get operation. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='patchPayload'> /// The payload to use to patch the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebService>> BeginPatchWithHttpMessagesAsync(string resourceGroupName, string webServiceName, WebService patchPayload, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes the specified web service. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RemoveWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes the specified web service. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginRemoveWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the access keys for the specified web service. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<WebServiceKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string webServiceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the web services in the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<WebService>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, string skiptoken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the web services in the specified subscription. /// </summary> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<WebService>>> ListWithHttpMessagesAsync(string skiptoken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the web services in the specified resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<WebService>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the web services in the specified subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<WebService>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using System; using System.Collections.Generic; using System.Text; using EspacioInfinitoDotNet.Graphics; using EspacioInfinitoDotNet.Maths; using System.Drawing; using Tao.OpenGl; namespace EspacioInfinitoDotNet.GUI { public class GUIGraphicEngine { #region Atributos Stack<Rectangle> boundsStack = new Stack<Rectangle>(); Size size; Rectangle bounds; GraphicEngine graphicEngine; Color foreColor = Color.White; Color backColor = Color.Black; Color textColor = Color.White; Size[] tamaniosLetras; private IntPtr bitmapFont = Tao.FreeGlut.Glut.GLUT_BITMAP_HELVETICA_12; int altoLetra; int altoLetraConEspacioAbajo; public Size Size { get { return size; } set { this.size = value; } } public Rectangle Bounds { get { return bounds; } } public Color ForeColor { get { return foreColor; } set { this.foreColor = value; } } public Color BackColor { get { return backColor; } set { this.backColor = value; } } public Color TextColor { get { return textColor; } set { this.textColor = value; } } #endregion public GUIGraphicEngine(GraphicEngine graphicEngine) { this.graphicEngine = graphicEngine; } public bool Init() { size = GraphicEngine.Instance.Size; bounds.Size = size; InicialiarFonts(); return (true); } private void InicialiarFonts() { tamaniosLetras = new Size[256]; altoLetra = Tao.FreeGlut.Glut.glutBitmapHeight(bitmapFont); altoLetraConEspacioAbajo = altoLetra * 12 / 10; //Compenso por los caracteres que van por debajo de la linea for (int i = 0; i < 256; i++) tamaniosLetras[i] = new Size(Tao.FreeGlut.Glut.glutBitmapWidth(bitmapFont, (char) i), altoLetra); } #region Metodos internos private void SetClipRectangle(Rectangle rectangle) { Gl.glScissor(rectangle.X, Size.Height - (rectangle.Y + rectangle.Height), rectangle.Width, rectangle.Height); } internal void PushBounds(Rectangle bounds) { boundsStack.Push(this.bounds); this.bounds = new Rectangle( this.bounds.X + bounds.X, this.bounds.Y + bounds.Y, bounds.Width, bounds.Height); SetClipRectangle(this.bounds); } internal void PopBounds() { this.bounds = boundsStack.Pop(); SetClipRectangle(this.bounds); } private Point TranslatePoint(Point point) { return new Point(point.X + bounds.X, point.Y + bounds.Y); } private Rectangle TranslateRectangle(Rectangle rectangle) { return new Rectangle(TranslatePoint(rectangle.Location), rectangle.Size); } #endregion public void DrawRectangle(Rectangle rectangle) { DrawRectangle(rectangle, backColor); } public void DrawRectangle(Rectangle rectangle, Color color) { rectangle = TranslateRectangle(rectangle); Gl.glBegin(Gl.GL_QUADS); Gl.glColor4ub(color.R, color.G, color.B, color.A); Gl.glVertex3i(rectangle.X, rectangle.Y, 0); Gl.glVertex3i(rectangle.X, rectangle.Y + rectangle.Height, 0); Gl.glVertex3i(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height, 0); Gl.glVertex3i(rectangle.X + rectangle.Width, rectangle.Y, 0); Gl.glColor4ub(255, 255, 255, 255); Gl.glEnd(); } public void DrawRectangleFrame(Rectangle rectangle, int width) { DrawRectangleFrame(rectangle, foreColor, width); } public void DrawRectangleFrame(Rectangle rectangle, Color color, int width) { Rectangle rectTemp = new Rectangle(); //Dibujo las barras horizonaltes rectTemp.Location = rectangle.Location; rectTemp.X += width; rectTemp.Width = rectangle.Size.Width - width * 2; rectTemp.Height = width; DrawRectangle(rectTemp, color); rectTemp.Y = rectangle.Y + rectangle.Height - width; DrawRectangle(rectTemp, color); //Dibujo las barras verticales rectTemp.Location = rectangle.Location; rectTemp.Width = width; rectTemp.Height = rectangle.Height; DrawRectangle(rectTemp, color); rectTemp.X = rectangle.X + rectangle.Width - width; DrawRectangle(rectTemp, color); } public void DrawText(Point position, string text) { DrawText(position, text, textColor); } public void DrawText(Point position, string text, Color color) { position = TranslatePoint(position); Gl.glColor4ub(color.R, color.G, color.B, color.A); Gl.glRasterPos2i(position.X, position.Y + altoLetra); Tao.FreeGlut.Glut.glutBitmapString(bitmapFont, text); Gl.glColor4ub(255, 255, 255, 255); } public class DrawTextInfo { internal List<Point> location = new List<Point>(); internal List<String> text = new List<string>(); } public DrawTextInfo CalculateDrawTextInfo(Rectangle rectangle, string text) { DrawTextInfo dtInfo = new DrawTextInfo(); Point position = new Point(0, 0); int altoLetra = tamaniosLetras[(int)' '].Height; if (position.Y + altoLetra <= rectangle.Height) { int ancho = 0; text = text.Replace("\n", " \n "); String[] palabras = text.Split(' '); int nPalabra = 0; StringBuilder sb = new StringBuilder(text.Length); string texto = ""; bool imprimir = false; while (nPalabra < palabras.Length) { String palabra = palabras[nPalabra]; int anchoPalabra = 0; if (palabra != "\n") { foreach (Char c in palabra) { if (c >= 256) anchoPalabra += tamaniosLetras[' '].Width; else anchoPalabra += tamaniosLetras[c].Width; } if (anchoPalabra + ancho > rectangle.Width) { if (ancho == 0) { texto = palabra; nPalabra++; } else { texto = sb.ToString(); } imprimir = true; } else { sb.Append(palabra); sb.Append(' '); ancho += anchoPalabra + tamaniosLetras[' '].Width; nPalabra++; } } else { imprimir = true; texto = sb.ToString(); nPalabra++; } if (!imprimir && nPalabra == palabras.Length) { texto = sb.ToString(); imprimir = true; } if (imprimir) { dtInfo.location.Add(new Point(position.X + rectangle.X, position.Y + rectangle.Y)); dtInfo.text.Add(texto); position.Y += altoLetra; if (position.Y + altoLetra > rectangle.Height) break; ancho = 0; sb.Length = 0; imprimir = false; } } } return dtInfo; } public void DrawText(Rectangle rectangle, string text, Color color) { DrawText(CalculateDrawTextInfo(rectangle, text), color); } public void DrawText(DrawTextInfo dtInfo, Color color) { for (int i = 0; i < dtInfo.location.Count; i++) DrawText(dtInfo.location[i], dtInfo.text[i], color); } /*public Size GetTextSizePixels(string text, int maxWidth) { int altoLetra = tamaniosLetras[(int) ' '].Height; int sizeX = 0; int sizeY = altoLetra; foreach (Char c in text.ToCharArray()) { if (c < 256) { if (c == '\n' || c == '\r') { sizeX = 0; sizeY += altoLetra; } else { int anchoLetra = tamaniosLetras[(int)c].Width; if (sizeX + anchoLetra > maxWidth) { sizeY += altoLetra; sizeX = anchoLetra; } else { sizeX += anchoLetra; } } } } return new Size(maxWidth, sizeY); }*/ public Size GetTextSizePixels(string text) { int alto = altoLetra; int ancho = Tao.FreeGlut.Glut.glutBitmapLength(bitmapFont, text); return new Size(ancho, alto); } } }
using System; using System.Web; using umbraco.presentation.LiveEditing; using umbraco.BasePages; using umbraco.cms.businesslogic.web; using System.Xml.Linq; using umbraco.IO; using umbraco.presentation.preview; using umbraco.BusinessLogic; using System.Xml; namespace umbraco.presentation { /// <summary> /// A custom HttpServerUtilityBase object which exposes some additional methods and also overrides /// some such as MapPath to use the IOHelper. /// </summary> /// <remarks> /// Unforunately when this class was created it /// inherited from HttpServerUtilityWrapper intead of HttpServerUtilityBase which meant that this is not unit testable /// and still has a dependency on a real HttpRequest. So now it inherits from HttpRequestBase which /// means we need to override all of the methods and just wrap them with the _server object passed in. /// /// This now needs to exist only because of backwards compatibility /// </remarks> [Obsolete("This class is no longer used, for the overridden MapPath methods and custom methods use IOHelper")] public class UmbracoServerUtility : HttpServerUtilityBase { private readonly HttpServerUtilityBase _server; #region Constructor public UmbracoServerUtility(HttpServerUtilityBase server) { _server = server; } [Obsolete("Use the alternate constructor which accepts a HttpServerUtilityBase object instead")] public UmbracoServerUtility(HttpServerUtility server) { _server = new HttpServerUtilityWrapper(server); } #endregion #region Wrapped methods public override object CreateObject(string progID) { return _server.CreateObject(progID); } public override object CreateObject(Type type) { return _server.CreateObject(type); } public override object CreateObjectFromClsid(string clsid) { return _server.CreateObjectFromClsid(clsid); } public override bool Equals(object obj) { return _server.Equals(obj); } public override void Execute(IHttpHandler handler, System.IO.TextWriter writer, bool preserveForm) { _server.Execute(handler, writer, preserveForm); } public override void Execute(string path) { _server.Execute(path); } public override void Execute(string path, bool preserveForm) { _server.Execute(path, preserveForm); } public override void Execute(string path, System.IO.TextWriter writer) { _server.Execute(path, writer); } public override void Execute(string path, System.IO.TextWriter writer, bool preserveForm) { _server.Execute(path, writer, preserveForm); } public override int GetHashCode() { return _server.GetHashCode(); } public override Exception GetLastError() { return _server.GetLastError(); } public override string HtmlDecode(string s) { return _server.HtmlDecode(s); } public override void HtmlDecode(string s, System.IO.TextWriter output) { _server.HtmlDecode(s, output); } public override string HtmlEncode(string s) { return _server.HtmlEncode(s); } public override void ClearError() { _server.ClearError(); } public override void HtmlEncode(string s, System.IO.TextWriter output) { _server.HtmlEncode(s, output); } public override string MachineName { get { return _server.MachineName; } } public override int ScriptTimeout { get { return _server.ScriptTimeout; } set { _server.ScriptTimeout = value; } } public override string ToString() { return _server.ToString(); } public override void Transfer(IHttpHandler handler, bool preserveForm) { _server.Transfer(handler, preserveForm); } public override void Transfer(string path) { _server.Transfer(path); } public override void Transfer(string path, bool preserveForm) { _server.Transfer(path, preserveForm); } public override void TransferRequest(string path) { _server.TransferRequest(path); } public override void TransferRequest(string path, bool preserveForm) { _server.TransferRequest(path, preserveForm); } public override void TransferRequest(string path, bool preserveForm, string method, System.Collections.Specialized.NameValueCollection headers) { _server.TransferRequest(path, preserveForm, method, headers); } public override string UrlDecode(string s) { return _server.UrlDecode(s); } public override void UrlDecode(string s, System.IO.TextWriter output) { _server.UrlDecode(s, output); } public override string UrlEncode(string s) { return _server.UrlEncode(s); } public override void UrlEncode(string s, System.IO.TextWriter output) { _server.UrlEncode(s, output); } public override string UrlPathEncode(string s) { return _server.UrlPathEncode(s); } public override byte[] UrlTokenDecode(string input) { return _server.UrlTokenDecode(input); } public override string UrlTokenEncode(byte[] input) { return _server.UrlTokenEncode(input); } #endregion #region Overridden methods /// <summary> /// Returns the physical file path that corresponds to the specified virtual path on the Web server. /// </summary> /// <param name="path">The virtual path of the Web server.</param> /// <returns> /// The physical file path that corresponds to <paramref name="path"/>. /// </returns> /// <exception cref="T:System.Web.HttpException"> /// The current <see cref="T:System.Web.HttpContext"/> is null. /// </exception> public override string MapPath(string path) { return IOHelper.MapPath(path); } #endregion public string UmbracoPath { get { return IOHelper.ResolveUrl( SystemDirectories.Umbraco ); } } public string ContentXmlPath { get { return IOHelper.ResolveUrl( SystemFiles.ContentCacheXml ); } } [Obsolete("This is no longer used in the codebase and will be removed. ")] private const string XDocumentCacheKey = "XDocumentCache"; /// <summary> /// Gets the Umbraco XML cache /// </summary> /// <value>The content XML.</value> [Obsolete("This is no longer used in the codebase and will be removed. If you need to access the current XML cache document you can use the Umbraco.Web.Umbraco.Context.GetXml() method.")] public XDocument ContentXml { get { if (UmbracoContext.Current.InPreviewMode) { var pc = new PreviewContent(new Guid(StateHelper.Cookies.Preview.GetValue())); pc.LoadPreviewset(); return XmlDocumentToXDocument(pc.XmlContent); } else { if (HttpContext.Current == null) return XDocument.Load(ContentXmlPath); var xml = HttpContext.Current.Items[XDocumentCacheKey] as XDocument; if (xml == null) { xml = XmlDocumentToXDocument(content.Instance.XmlContent); HttpContext.Current.Items[XDocumentCacheKey] = xml; } return xml; } } } private XDocument XmlDocumentToXDocument(XmlDocument xml) { using (var nodeReader = new XmlNodeReader(xml)) { nodeReader.MoveToContent(); return XDocument.Load(nodeReader); } } public string DataFolder { get { return IOHelper.ResolveUrl( SystemDirectories.Data ); } } } }
using System; namespace Raksha.Asn1.Cms { public class AuthEnvelopedData : Asn1Encodable { private DerInteger version; private OriginatorInfo originatorInfo; private Asn1Set recipientInfos; private EncryptedContentInfo authEncryptedContentInfo; private Asn1Set authAttrs; private Asn1OctetString mac; private Asn1Set unauthAttrs; public AuthEnvelopedData( OriginatorInfo originatorInfo, Asn1Set recipientInfos, EncryptedContentInfo authEncryptedContentInfo, Asn1Set authAttrs, Asn1OctetString mac, Asn1Set unauthAttrs) { // "It MUST be set to 0." this.version = new DerInteger(0); this.originatorInfo = originatorInfo; // TODO // "There MUST be at least one element in the collection." this.recipientInfos = recipientInfos; this.authEncryptedContentInfo = authEncryptedContentInfo; // TODO // "The authAttrs MUST be present if the content type carried in // EncryptedContentInfo is not id-data." this.authAttrs = authAttrs; this.mac = mac; this.unauthAttrs = unauthAttrs; } private AuthEnvelopedData( Asn1Sequence seq) { int index = 0; // TODO // "It MUST be set to 0." Asn1Object tmp = seq[index++].ToAsn1Object(); version = (DerInteger)tmp; tmp = seq[index++].ToAsn1Object(); if (tmp is Asn1TaggedObject) { originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++].ToAsn1Object(); } // TODO // "There MUST be at least one element in the collection." recipientInfos = Asn1Set.GetInstance(tmp); tmp = seq[index++].ToAsn1Object(); authEncryptedContentInfo = EncryptedContentInfo.GetInstance(tmp); tmp = seq[index++].ToAsn1Object(); if (tmp is Asn1TaggedObject) { authAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++].ToAsn1Object(); } else { // TODO // "The authAttrs MUST be present if the content type carried in // EncryptedContentInfo is not id-data." } mac = Asn1OctetString.GetInstance(tmp); if (seq.Count > index) { tmp = seq[index++].ToAsn1Object(); unauthAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); } } /** * return an AuthEnvelopedData object from a tagged object. * * @param obj the tagged object holding the object we want. * @param isExplicit true if the object is meant to be explicitly * tagged false otherwise. * @throws ArgumentException if the object held by the * tagged object cannot be converted. */ public static AuthEnvelopedData GetInstance( Asn1TaggedObject obj, bool isExplicit) { return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit)); } /** * return an AuthEnvelopedData object from the given object. * * @param obj the object we want converted. * @throws ArgumentException if the object cannot be converted. */ public static AuthEnvelopedData GetInstance( object obj) { if (obj == null || obj is AuthEnvelopedData) return (AuthEnvelopedData)obj; if (obj is Asn1Sequence) return new AuthEnvelopedData((Asn1Sequence)obj); throw new ArgumentException("Invalid AuthEnvelopedData: " + obj.GetType().Name); } public DerInteger Version { get { return version; } } public OriginatorInfo OriginatorInfo { get { return originatorInfo; } } public Asn1Set RecipientInfos { get { return recipientInfos; } } public EncryptedContentInfo AuthEncryptedContentInfo { get { return authEncryptedContentInfo; } } public Asn1Set AuthAttrs { get { return authAttrs; } } public Asn1OctetString Mac { get { return mac; } } public Asn1Set UnauthAttrs { get { return unauthAttrs; } } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * AuthEnvelopedData ::= SEQUENCE { * version CMSVersion, * originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL, * recipientInfos RecipientInfos, * authEncryptedContentInfo EncryptedContentInfo, * authAttrs [1] IMPLICIT AuthAttributes OPTIONAL, * mac MessageAuthenticationCode, * unauthAttrs [2] IMPLICIT UnauthAttributes OPTIONAL } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(version); if (originatorInfo != null) { v.Add(new DerTaggedObject(false, 0, originatorInfo)); } v.Add(recipientInfos, authEncryptedContentInfo); // "authAttrs optionally contains the authenticated attributes." if (authAttrs != null) { // "AuthAttributes MUST be DER encoded, even if the rest of the // AuthEnvelopedData structure is BER encoded." v.Add(new DerTaggedObject(false, 1, authAttrs)); } v.Add(mac); // "unauthAttrs optionally contains the unauthenticated attributes." if (unauthAttrs != null) { v.Add(new DerTaggedObject(false, 2, unauthAttrs)); } return new BerSequence(v); } } }
using System; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; namespace netduino.helpers.Hardware { /// <summary> /// This class implements a complete driver for the Dallas Semiconductors / Maxim DS1307 I2C real-time clock: http://pdfserv.maxim-ic.com/en/ds/DS1307.pdf /// </summary> public class DS1307 : IDisposable { [Flags] // Defines the frequency of the signal on the SQW interrupt pin on the clock when enabled public enum SQWFreq { SQW_1Hz, SQW_4kHz, SQW_8kHz, SQW_32kHz, SQW_OFF }; [Flags] // Defines the logic level on the SQW pin when the frequency is disabled public enum SQWDisabledOutputControl { Zero, One }; // Real time clock I2C address public const int DS1307_I2C_ADDRESS = 0x68; // Start / End addresses of the date/time registers public const byte DS1307_RTC_START_ADDRESS = 0x00; public const byte DS1307_RTC_END_ADDRESS = 0x06; // Square wave frequency generator register address public const byte DS1307_SQUARE_WAVE_CTRL_REGISTER_ADDRESS = 0x07; // Start / End addresses of the user RAM registers public const byte DS1307_RAM_START_ADDRESS = 0x08; public const byte DS1307_RAM_END_ADDRESS = 0x3f; // Total size of the user RAM block public const byte DS1307_RAM_SIZE = 56; // Instance of the I2C clock protected I2CDevice Clock; // I2C bus frequency for the clock public int ClockRateKHz { get; private set; } // I2C transactions timeout value in milliseconds public int TimeOutMs { get; private set; } public DS1307(int timeoutMs = 30, int clockRateKHz = 50) { TimeOutMs = timeoutMs; ClockRateKHz = clockRateKHz; Clock = new I2CDevice(new I2CDevice.Configuration(DS1307_I2C_ADDRESS, ClockRateKHz)); } /// <summary> /// Gets the date / time in 24 hour format. /// </summary> /// <returns>A DateTime object</returns> public DateTime Get() { byte[] clockData = new byte [7]; // Read time registers (7 bytes from DS1307_RTC_START_ADDRESS) var transaction = new I2CDevice.I2CTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] {DS1307_RTC_START_ADDRESS}), I2CDevice.CreateReadTransaction(clockData) }; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C transaction failed"); } return new DateTime( BcdToDec(clockData[6]) + 2000, // year BcdToDec(clockData[5]), // month BcdToDec(clockData[4]), // day BcdToDec(clockData[2] & 0x3f), // hours over 24 hours BcdToDec(clockData[1]), // minutes BcdToDec(clockData[0] & 0x7f) // seconds ); } /// <summary> /// Sets the time on the clock using the datetime object. Milliseconds are not used. /// </summary> /// <param name="dt">A DateTime object used to set the clock</param> public void Set(DateTime dt) { var transaction = new I2CDevice.I2CWriteTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] { DS1307_RTC_START_ADDRESS, DecToBcd(dt.Second), DecToBcd(dt.Minute), DecToBcd(dt.Hour), DecToBcd((int)dt.DayOfWeek), DecToBcd(dt.Day), DecToBcd(dt.Month), DecToBcd(dt.Year - 2000)} ) }; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C write transaction failed"); } } /// <summary> /// Enables / Disables the square wave generation function of the clock. /// Requires a pull-up resistor on the clock's SQW pin. /// </summary> /// <param name="Freq">Desired frequency or disabled</param> /// <param name="OutCtrl">Logical level of output pin when the frequency is disabled (zero by default)</param> public void SetSquareWave(SQWFreq Freq, SQWDisabledOutputControl OutCtrl = SQWDisabledOutputControl.Zero) { byte SqwCtrlReg = (byte) OutCtrl; SqwCtrlReg <<= 3; // bit 7 defines the square wave output level when disabled // bit 6 & 5 are unused if (Freq != SQWFreq.SQW_OFF) { SqwCtrlReg |= 1; } SqwCtrlReg <<= 4; // bit 4 defines if the oscillator generating the square wave frequency is on or off. // bit 3 & 2 are unused SqwCtrlReg |= (byte) Freq; // bit 1 & 0 define the frequency of the square wave WriteRegister(DS1307_SQUARE_WAVE_CTRL_REGISTER_ADDRESS, SqwCtrlReg); } /// <summary> /// Halts / Resumes the time-keeping function on the clock. /// Calling this function preserves the value of the seconds register. /// </summary> /// <param name="halt">True: halt, False: resume</param> public void Halt(bool halt) { var seconds = this[DS1307_RTC_START_ADDRESS]; if (halt) { seconds |= 0x80; // Set bit 7 } else { seconds &= 0x7f; // Reset bit 7 } WriteRegister(DS1307_RTC_START_ADDRESS, seconds); } /// <summary> /// Writes to the clock's user RAM registers as a block /// </summary> /// <param name="buffer">A byte buffer of size DS1307_RAM_SIZE</param> public void SetRAM(byte[] buffer) { if (buffer.Length != DS1307_RAM_SIZE) { throw new ArgumentOutOfRangeException("Invalid buffer length"); } // Allocate a new buffer large enough to include the RAM start address byte and the payload var TrxBuffer = new byte[sizeof(byte) /*Address byte*/ + DS1307_RAM_SIZE]; // Set the RAM start address TrxBuffer[0] = DS1307_RAM_START_ADDRESS; // Copy the user buffer after the address buffer.CopyTo(TrxBuffer, 1); // Write to the clock's RAM var transaction = new I2CDevice.I2CWriteTransaction[] {I2CDevice.CreateWriteTransaction(TrxBuffer)}; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C write transaction failed"); } } /// <summary> /// Reads the clock's user RAM registers as a block. /// </summary> /// <returns>A byte array of size DS1307_RAM_SIZE containing the user RAM data</returns> public byte[] GetRAM() { var ram = new byte[DS1307_RAM_SIZE]; var transaction = new I2CDevice.I2CTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] {DS1307_RAM_START_ADDRESS}), I2CDevice.CreateReadTransaction(ram) }; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C transaction failed"); } return ram; } /// <summary> /// Reads an arbitrary RTC or RAM register /// </summary> /// <param name="address">Register address between 0x00 and 0x3f</param> /// <returns>The value of the byte read at the address</returns> public byte this[byte address] { get { if (address > DS1307_RAM_END_ADDRESS) { throw new ArgumentOutOfRangeException("Invalid register address"); } var value = new byte[1]; // Read the RAM register @ the address var transaction = new I2CDevice.I2CTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] {address}), I2CDevice.CreateReadTransaction(value) }; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C transaction failed"); } return value[0]; } } /// <summary> /// Writes an arbitrary RTC or RAM register /// </summary> /// <param name="address">Register address between 0x00 and 0x3f</param> /// <param name="val">The value of the byte to write at that address</param> public void WriteRegister(byte address, byte val) { if (address > DS1307_RAM_END_ADDRESS) { throw new ArgumentOutOfRangeException("Invalid register address"); } var transaction = new I2CDevice.I2CWriteTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] {address, (byte) val}) }; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C write transaction failed"); } } /// <summary> /// Takes a Binary-Coded-Decimal value and returns it as an integer value /// </summary> /// <param name="val">BCD encoded value</param> /// <returns>An integer value</returns> protected int BcdToDec(int val) { return ((val / 16 * 10) + (val % 16)); } /// <summary> /// Takes a Decimal value and converts it into a Binary-Coded-Decimal value /// </summary> /// <param name="val">Value to be converted</param> /// <returns>A BCD-encoded value</returns> protected byte DecToBcd(int val) { return (byte)((val / 10 * 16) + (val % 10)); } /// <summary> /// Releases clock resources /// </summary> public void Dispose() { Clock.Dispose(); Clock = null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class LoopHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override IHighlighter CreateHighlighter() { return new LoopHighlighter(); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { {|Cursor:[|while|]|} (true) { if (x) { [|break|]; } else { [|continue|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { void M() { [|while|] (true) { if (x) { {|Cursor:[|break|]|}; } else { [|continue|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_3() { await TestAsync( @"class C { void M() { [|while|] (true) { if (x) { [|break|]; } else { {|Cursor:[|continue|]|}; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_1() { await TestAsync( @"class C { void M() { {|Cursor:[|do|]|} { if (x) { [|break|]; } else { [|continue|]; } } [|while|] (true); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_2() { await TestAsync( @"class C { void M() { [|do|] { if (x) { {|Cursor:[|break|]|}; } else { [|continue|]; } } [|while|] (true); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_3() { await TestAsync( @"class C { void M() { [|do|] { if (x) { [|break|]; } else { {|Cursor:[|continue|]|}; } } [|while|] (true); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_4() { await TestAsync( @"class C { void M() { [|do|] { if (x) { [|break|]; } else { [|continue|]; } } {|Cursor:[|while|]|} (true); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_5() { await TestAsync( @"class C { void M() { do { if (x) { break; } else { continue; } } while {|Cursor:(true)|}; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_6() { await TestAsync( @"class C { void M() { [|do|] { if (x) { [|break|]; } else { [|continue|]; } } [|while|] (true);{|Cursor:|} } }"); } private const string SpecExample3 = @"for (int i = 0; i < 10; i++) { if (x) { break; } else { continue; } }"; [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample3_1() { await TestAsync( @"class C { void M() { {|Cursor:[|for|]|} (int i = 0; i < 10; i++) { if (x) { [|break|]; } else { [|continue|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample3_2() { await TestAsync( @"class C { void M() { [|for|] (int i = 0; i < 10; i++) { if (x) { {|Cursor:[|break|];|} } else { [|continue|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample3_3() { await TestAsync( @"class C { void M() { [|for|] (int i = 0; i < 10; i++) { if (x) { [|break|]; } else { {|Cursor:[|continue|];|} } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_1() { await TestAsync( @"class C { void M() { {|Cursor:[|foreach|]|} (var a in x) { if (x) { [|break|]; } else { [|continue|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_2() { await TestAsync( @"class C { void M() { [|foreach|] (var a in x) { if (x) { {|Cursor:[|break|];|} } else { [|continue|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_3() { await TestAsync( @"class C { void M() { [|foreach|] (var a in x) { if (x) { [|break|]; } else { {|Cursor:[|continue|];|} } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_1() { await TestAsync( @"class C { void M() { {|Cursor:[|foreach|]|} (var a in x) { if (a) { [|break|]; } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_2() { await TestAsync( @"class C { void M() { [|foreach|] (var a in x) { if (a) { {|Cursor:[|break|];|} } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_3() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { {|Cursor:[|do|]|} { [|break|]; } [|while|] (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_4() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { [|do|] { {|Cursor:[|break|];|} } [|while|] (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_5() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { [|do|] { [|break|]; } {|Cursor:[|while|]|} (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_6() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { [|do|] { [|break|]; } [|while|] (false);{|Cursor:|} break; } break; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_7() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: {|Cursor:[|while|]|} (true) { do { break; } while (false); [|break|]; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_8() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: [|while|] (true) { do { break; } while (false); {|Cursor:[|break|];|} } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } // TestNestedExample1 9-13 are in SwitchStatementHighlighterTests.cs [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_14() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } {|Cursor:[|for|]|} (int i = 0; i < 10; i++) { [|break|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_15() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } [|for|] (int i = 0; i < 10; i++) { {|Cursor:[|break|];|} } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_1() { await TestAsync( @"class C { void M() { {|Cursor:[|foreach|]|} (var a in x) { if (a) { [|continue|]; } else { while (true) { do { continue; } while (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_2() { await TestAsync( @"class C { void M() { [|foreach|] (var a in x) { if (a) { {|Cursor:[|continue|];|} } else { while (true) { do { continue; } while (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_3() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { {|Cursor:[|do|]|} { [|continue|]; } [|while|] (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_4() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { [|do|] { {|Cursor:[|continue|];|} } [|while|] (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_5() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { [|do|] { [|continue|]; } {|Cursor:[|while|]|} (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_6() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { do { continue; } while {|Cursor:(false)|}; continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_7() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { [|do|] { [|continue|]; } [|while|] (false);{|Cursor:|} continue; } } for (int i = 0; i < 10; i++) { continue; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_8() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { {|Cursor:[|while|]|} (true) { do { continue; } while (false); [|continue|]; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_9() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { [|while|] (true) { do { continue; } while (false); {|Cursor:[|continue|];|} } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_10() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { do { continue; } while (false); continue; } } {|Cursor:[|for|]|} (int i = 0; i < 10; i++) { [|continue|]; } } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample2_11() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { do { continue; } while (false); continue; } } [|for|] (int i = 0; i < 10; i++) { {|Cursor:[|continue|];|} } } } } "); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\PointLightComponent.h:18 namespace UnrealEngine { [ManageType("ManagePointLightComponent")] public partial class ManagePointLightComponent : UPointLightComponent, IManageWrapper { public ManagePointLightComponent(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_UpdateLightGUIDs(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnAttachmentChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnHiddenInGameChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnVisibilityChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PropagateLightingScenarioChange(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_UpdateBounds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_Activate(IntPtr self, bool bReset); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_BeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_CreateRenderState_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_Deactivate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_DestroyComponent(IntPtr self, bool bPromoteChildren); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_DestroyRenderState_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_InitializeComponent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnActorEnableCollisionChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnComponentCreated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnCreatePhysicsState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnDestroyPhysicsState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnRegister(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnRep_IsActive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnUnregister(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_SendRenderDynamicData_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_SendRenderTransform_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_SetActive(IntPtr self, bool bNewActive, bool bReset); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_ToggleActive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_UninitializeComponent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPointLightComponent_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods /// <summary> /// Update/reset light GUIDs. /// </summary> public override void UpdateLightGUIDs() => E__Supper__UPointLightComponent_UpdateLightGUIDs(this); /// <summary> /// DEPRECATED - Use DetachFromComponent() instead /// </summary> public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify) => E__Supper__UPointLightComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify); /// <summary> /// Called when AttachParent changes, to allow the scene to update its attachment state. /// </summary> public override void OnAttachmentChanged() => E__Supper__UPointLightComponent_OnAttachmentChanged(this); /// <summary> /// Overridable internal function to respond to changes in the hidden in game value of the component. /// </summary> protected override void OnHiddenInGameChanged() => E__Supper__UPointLightComponent_OnHiddenInGameChanged(this); /// <summary> /// Overridable internal function to respond to changes in the visibility of the component. /// </summary> protected override void OnVisibilityChanged() => E__Supper__UPointLightComponent_OnVisibilityChanged(this); /// <summary> /// Updates any visuals after the lighting has changed /// </summary> public override void PropagateLightingScenarioChange() => E__Supper__UPointLightComponent_PropagateLightingScenarioChange(this); /// <summary> /// Update the Bounds of the component. /// </summary> public override void UpdateBounds() => E__Supper__UPointLightComponent_UpdateBounds(this); /// <summary> /// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true. /// </summary> /// <param name="bTriggerNotifiers">if true, send zone/volume change events</param> public override void UpdatePhysicsVolume(bool bTriggerNotifiers) => E__Supper__UPointLightComponent_UpdatePhysicsVolume(this, bTriggerNotifiers); /// <summary> /// Activates the SceneComponent, should be overridden by native child classes. /// </summary> /// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param> public override void Activate(bool bReset) => E__Supper__UPointLightComponent_Activate(this, bReset); /// <summary> /// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component). /// <para>All Components (that want initialization) in the level will be Initialized on load before any </para> /// Actor/Component gets BeginPlay. /// <para>Requires component to be registered and initialized. </para> /// </summary> public override void BeginPlay() => E__Supper__UPointLightComponent_BeginPlay(this); /// <summary> /// Used to create any rendering thread information for this component /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void CreateRenderState_Concurrent() => E__Supper__UPointLightComponent_CreateRenderState_Concurrent(this); /// <summary> /// Deactivates the SceneComponent. /// </summary> public override void Deactivate() => E__Supper__UPointLightComponent_Deactivate(this); /// <summary> /// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill. /// </summary> public override void DestroyComponent(bool bPromoteChildren) => E__Supper__UPointLightComponent_DestroyComponent(this, bPromoteChildren); /// <summary> /// Used to shut down any rendering thread structure for this component /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void DestroyRenderState_Concurrent() => E__Supper__UPointLightComponent_DestroyRenderState_Concurrent(this); /// <summary> /// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component). /// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para> /// Requires component to be registered, and bWantsInitializeComponent to be true. /// </summary> public override void InitializeComponent() => E__Supper__UPointLightComponent_InitializeComponent(this); /// <summary> /// Called when this actor component has moved, allowing it to discard statically cached lighting information. /// </summary> public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly) => E__Supper__UPointLightComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly); /// <summary> /// Called on each component when the Actor's bEnableCollisionChanged flag changes /// </summary> public override void OnActorEnableCollisionChanged() => E__Supper__UPointLightComponent_OnActorEnableCollisionChanged(this); /// <summary> /// Called when a component is created (not loaded). This can happen in the editor or during gameplay /// </summary> public override void OnComponentCreated() => E__Supper__UPointLightComponent_OnComponentCreated(this); /// <summary> /// Called when a component is destroyed /// </summary> /// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param> public override void OnComponentDestroyed(bool bDestroyingHierarchy) => E__Supper__UPointLightComponent_OnComponentDestroyed(this, bDestroyingHierarchy); /// <summary> /// Used to create any physics engine information for this component /// </summary> protected override void OnCreatePhysicsState() => E__Supper__UPointLightComponent_OnCreatePhysicsState(this); /// <summary> /// Used to shut down and physics engine structure for this component /// </summary> protected override void OnDestroyPhysicsState() => E__Supper__UPointLightComponent_OnDestroyPhysicsState(this); /// <summary> /// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called. /// </summary> protected override void OnRegister() => E__Supper__UPointLightComponent_OnRegister(this); public override void OnRep_IsActive() => E__Supper__UPointLightComponent_OnRep_IsActive(this); /// <summary> /// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called. /// </summary> protected override void OnUnregister() => E__Supper__UPointLightComponent_OnUnregister(this); /// <summary> /// Virtual call chain to register all tick functions /// </summary> /// <param name="bRegister">true to register, false, to unregister</param> protected override void RegisterComponentTickFunctions(bool bRegister) => E__Supper__UPointLightComponent_RegisterComponentTickFunctions(this, bRegister); /// <summary> /// Called to send dynamic data for this component to the rendering thread /// </summary> protected override void SendRenderDynamicData_Concurrent() => E__Supper__UPointLightComponent_SendRenderDynamicData_Concurrent(this); /// <summary> /// Called to send a transform update for this component to the rendering thread /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void SendRenderTransform_Concurrent() => E__Supper__UPointLightComponent_SendRenderTransform_Concurrent(this); /// <summary> /// Sets whether the component is active or not /// </summary> /// <param name="bNewActive">The new active state of the component</param> /// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param> public override void SetActive(bool bNewActive, bool bReset) => E__Supper__UPointLightComponent_SetActive(this, bNewActive, bReset); /// <summary> /// Sets whether the component should be auto activate or not. Only safe during construction scripts. /// </summary> /// <param name="bNewAutoActivate">The new auto activate state of the component</param> public override void SetAutoActivate(bool bNewAutoActivate) => E__Supper__UPointLightComponent_SetAutoActivate(this, bNewAutoActivate); /// <summary> /// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered /// </summary> /// <param name="bEnabled">Whether it should be enabled or not</param> public override void SetComponentTickEnabled(bool bEnabled) => E__Supper__UPointLightComponent_SetComponentTickEnabled(this, bEnabled); /// <summary> /// Spawns a task on GameThread that will call SetComponentTickEnabled /// </summary> /// <param name="bEnabled">Whether it should be enabled or not</param> public override void SetComponentTickEnabledAsync(bool bEnabled) => E__Supper__UPointLightComponent_SetComponentTickEnabledAsync(this, bEnabled); /// <summary> /// Toggles the active state of the component /// </summary> public override void ToggleActive() => E__Supper__UPointLightComponent_ToggleActive(this); /// <summary> /// Handle this component being Uninitialized. /// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para> /// </summary> public override void UninitializeComponent() => E__Supper__UPointLightComponent_UninitializeComponent(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UPointLightComponent_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UPointLightComponent_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UPointLightComponent_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UPointLightComponent_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UPointLightComponent_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UPointLightComponent_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UPointLightComponent_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UPointLightComponent_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UPointLightComponent_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UPointLightComponent_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UPointLightComponent_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UPointLightComponent_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UPointLightComponent_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UPointLightComponent_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UPointLightComponent_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManagePointLightComponent self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManagePointLightComponent(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManagePointLightComponent>(PtrDesc); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Mstc.Web.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime { using ConditionalAttribute = System.Diagnostics.ConditionalAttribute; using Console = System.Console; using IDebugEventListener = Antlr.Runtime.Debug.IDebugEventListener; public delegate int SpecialStateTransitionHandler(DFA dfa, int s, IIntStream input); /** <summary>A DFA implemented as a set of transition tables.</summary> * * <remarks> * Any state that has a semantic predicate edge is special; those states * are generated with if-then-else structures in a specialStateTransition() * which is generated by cyclicDFA template. * * There are at most 32767 states (16-bit signed short). * Could get away with byte sometimes but would have to generate different * types and the simulation code too. For a point of reference, the Java * lexer's Tokens rule DFA has 326 states roughly. * </remarks> */ public class DFA { public DFA() : this(new SpecialStateTransitionHandler(SpecialStateTransitionDefault)) { } public DFA(SpecialStateTransitionHandler specialStateTransition) { this.SpecialStateTransition = specialStateTransition ?? new SpecialStateTransitionHandler(SpecialStateTransitionDefault); } protected short[] eot; protected short[] eof; protected char[] min; protected char[] max; protected short[] accept; protected short[] special; protected short[][] transition; protected int decisionNumber; /** <summary>Which recognizer encloses this DFA? Needed to check backtracking</summary> */ protected BaseRecognizer recognizer; public readonly bool debug = false; /** <summary> * From the input stream, predict what alternative will succeed * using this DFA (representing the covering regular approximation * to the underlying CFL). Return an alternative number 1..n. Throw * an exception upon error. * </summary> */ public virtual int Predict(IIntStream input) { if (debug) { Console.Error.WriteLine("Enter DFA.predict for decision " + decisionNumber); } int mark = input.Mark(); // remember where decision started in input int s = 0; // we always start at s0 try { for (; ; ) { if (debug) Console.Error.WriteLine("DFA " + decisionNumber + " state " + s + " LA(1)=" + (char)input.LA(1) + "(" + input.LA(1) + "), index=" + input.Index); int specialState = special[s]; if (specialState >= 0) { if (debug) { Console.Error.WriteLine("DFA " + decisionNumber + " state " + s + " is special state " + specialState); } s = SpecialStateTransition(this, specialState, input); if (debug) { Console.Error.WriteLine("DFA " + decisionNumber + " returns from special state " + specialState + " to " + s); } if (s == -1) { NoViableAlt(s, input); return 0; } input.Consume(); continue; } if (accept[s] >= 1) { if (debug) Console.Error.WriteLine("accept; predict " + accept[s] + " from state " + s); return accept[s]; } // look for a normal char transition char c = (char)input.LA(1); // -1 == \uFFFF, all tokens fit in 65000 space if (c >= min[s] && c <= max[s]) { int snext = transition[s][c - min[s]]; // move to next state if (snext < 0) { // was in range but not a normal transition // must check EOT, which is like the else clause. // eot[s]>=0 indicates that an EOT edge goes to another // state. if (eot[s] >= 0) { // EOT Transition to accept state? if (debug) Console.Error.WriteLine("EOT transition"); s = eot[s]; input.Consume(); // TODO: I had this as return accept[eot[s]] // which assumed here that the EOT edge always // went to an accept...faster to do this, but // what about predicated edges coming from EOT // target? continue; } NoViableAlt(s, input); return 0; } s = snext; input.Consume(); continue; } if (eot[s] >= 0) { // EOT Transition? if (debug) Console.Error.WriteLine("EOT transition"); s = eot[s]; input.Consume(); continue; } if (c == unchecked((char)TokenTypes.EndOfFile) && eof[s] >= 0) { // EOF Transition to accept state? if (debug) Console.Error.WriteLine("accept via EOF; predict " + accept[eof[s]] + " from " + eof[s]); return accept[eof[s]]; } // not in range and not EOF/EOT, must be invalid symbol if (debug) { Console.Error.WriteLine("min[" + s + "]=" + min[s]); Console.Error.WriteLine("max[" + s + "]=" + max[s]); Console.Error.WriteLine("eot[" + s + "]=" + eot[s]); Console.Error.WriteLine("eof[" + s + "]=" + eof[s]); for (int p = 0; p < transition[s].Length; p++) { Console.Error.Write(transition[s][p] + " "); } Console.Error.WriteLine(); } NoViableAlt(s, input); return 0; } } finally { input.Rewind(mark); } } protected virtual void NoViableAlt(int s, IIntStream input) { if (recognizer.state.backtracking > 0) { recognizer.state.failed = true; return; } NoViableAltException nvae = new NoViableAltException(Description, decisionNumber, s, input); Error(nvae); throw nvae; } /** <summary>A hook for debugging interface</summary> */ public virtual void Error(NoViableAltException nvae) { } public SpecialStateTransitionHandler SpecialStateTransition { get; private set; } //public virtual int specialStateTransition( int s, IntStream input ) //{ // return -1; //} static int SpecialStateTransitionDefault(DFA dfa, int s, IIntStream input) { return -1; } public virtual string Description { get { return "n/a"; } } /** <summary> * Given a String that has a run-length-encoding of some unsigned shorts * like "\1\2\3\9", convert to short[] {2,9,9,9}. We do this to avoid * static short[] which generates so much init code that the class won't * compile. :( * </summary> */ public static short[] UnpackEncodedString(string encodedString) { // walk first to find how big it is. int size = 0; for (int i = 0; i < encodedString.Length; i += 2) { size += encodedString[i]; } short[] data = new short[size]; int di = 0; for (int i = 0; i < encodedString.Length; i += 2) { char n = encodedString[i]; char v = encodedString[i + 1]; // add v n times to data for (int j = 1; j <= n; j++) { data[di++] = (short)v; } } return data; } /** <summary>Hideous duplication of code, but I need different typed arrays out :(</summary> */ public static char[] UnpackEncodedStringToUnsignedChars(string encodedString) { // walk first to find how big it is. int size = 0; for (int i = 0; i < encodedString.Length; i += 2) { size += encodedString[i]; } char[] data = new char[size]; int di = 0; for (int i = 0; i < encodedString.Length; i += 2) { char n = encodedString[i]; char v = encodedString[i + 1]; // add v n times to data for (int j = 1; j <= n; j++) { data[di++] = v; } } return data; } [Conditional("ANTLR_DEBUG")] protected virtual void DebugRecognitionException(RecognitionException ex) { IDebugEventListener dbg = recognizer.DebugListener; if (dbg != null) dbg.RecognitionException(ex); } } }
using FluentAssertions; using Meziantou.Framework.Collections; using Xunit; namespace Meziantou.Framework.Tests.Collections; public class LimitListTests { [Fact] public void AddFirst_01() { // Arrange var list = new LimitList<int>(3); // Act list.AddFirst(1); list.AddFirst(2); // Assert list.ToList().Should().Equal(new int[] { 2, 1 }); } [Fact] public void AddFirst_02() { // Arrange var list = new LimitList<int>(3); // Act list.AddFirst(1); list.AddFirst(2); list.AddFirst(3); list.AddFirst(4); // Assert list.ToList().Should().Equal(new int[] { 4, 3, 2 }); } [Fact] public void AddLast_01() { // Arrange var list = new LimitList<int>(3); // Act list.AddLast(1); list.AddLast(2); // Assert list.ToList().Should().Equal(new int[] { 1, 2 }); } [Fact] public void AddLast_02() { // Arrange var list = new LimitList<int>(3); // Act list.AddLast(1); list.AddLast(2); list.AddLast(3); list.AddLast(4); // Assert list.ToList().Should().Equal(new int[] { 2, 3, 4 }); } [Fact] public void IndexOf_01() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); list.AddLast(3); // Act var index = list.IndexOf(2); // Assert index.Should().Be(1); } [Fact] public void IndexOf_02() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); list.AddLast(3); list.AddLast(4); // Act var index = list.IndexOf(1); // Assert index.Should().Be(-1); } [Fact] public void Count_01() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); // Act var count = list.Count; // Assert count.Should().Be(2); } [Fact] public void Contains_01() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); // Act var result = list.Contains(2); // Assert result.Should().BeTrue(); } [Fact] public void Contains_02() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); // Act var result = list.Contains(3); // Assert result.Should().BeFalse(); } [Fact] public void Remove_01() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); // Act var result = list.Remove(1); // Assert result.Should().BeTrue(); list.Should().Equal(2); } [Fact] public void Remove_02() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); list.AddLast(3); // Act var result = list.Remove(2); // Assert result.Should().BeTrue(); list.Should().Equal(1, 3); } [Fact] public void Remove_03() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); // Act var result = list.Remove(4); // Assert result.Should().BeFalse(); list.Should().Equal(1); } [Fact] public void Indexer_01() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); // Act list[0] = 10; // Assert list.Should().Equal(10); } [Fact] public void Indexer_02() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); // Act list[1] = 10; // Assert list.Should().Equal(1, 10); } [Fact] public void Indexer_03() { // Arrange var list = new LimitList<int>(3); // Act/Assert new Func<object>(() => list[1] = 10).Should().ThrowExactly<ArgumentOutOfRangeException>(); } [Fact] public void RemoveAt() { // Arrange var list = new LimitList<int>(3); list.AddLast(1); list.AddLast(2); list.AddLast(3); // Act list.RemoveAt(1); // Assert list.Should().Equal(1, 3); } }
// 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.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryLogicalTests { //TODO: Need tests on the short-circuit and non-short-circuit nature of the two forms. #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckBoolAndTest(bool useInterpreter) { bool[] array = new bool[] { true, false }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyBoolAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckBoolAndAlsoTest(bool useInterpreter) { bool[] array = new bool[] { true, false }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyBoolAndAlso(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckBoolOrTest(bool useInterpreter) { bool[] array = new bool[] { true, false }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyBoolOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckBoolOrElseTest(bool useInterpreter) { bool[] array = new bool[] { true, false }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyBoolOrElse(array[i], array[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyBoolAnd(bool a, bool b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.And( Expression.Constant(a, typeof(bool)), Expression.Constant(b, typeof(bool))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBoolAndAlso(bool a, bool b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.AndAlso( Expression.Constant(a, typeof(bool)), Expression.Constant(b, typeof(bool))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a && b, f()); } private static void VerifyBoolOr(bool a, bool b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Or( Expression.Constant(a, typeof(bool)), Expression.Constant(b, typeof(bool))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } private static void VerifyBoolOrElse(bool a, bool b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.OrElse( Expression.Constant(a, typeof(bool)), Expression.Constant(b, typeof(bool))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a || b, f()); } #endregion public static IEnumerable<object[]> AndAlso_TestData() { yield return new object[] { 5, 3, 1, true }; yield return new object[] { 0, 3, 0, false }; yield return new object[] { 5, 0, 0, true }; } [Theory] [PerCompilationType(nameof(AndAlso_TestData))] public static void AndAlso_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter) { TrueFalseClass left = new TrueFalseClass(leftValue); TrueFalseClass right = new TrueFalseClass(rightValue); BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right)); Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter); Assert.Equal(expectedValue, lambda().Value); // AndAlso only evaluates the false operator of left Assert.Equal(0, left.TrueCallCount); Assert.Equal(1, left.FalseCallCount); Assert.Equal(0, right.TrueCallCount); Assert.Equal(0, right.FalseCallCount); // AndAlso only evaluates the operator if left is not false Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount); } [Theory] [ClassData(typeof(CompilationTypes))] public static void AndAlso_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter) { BinaryExpression expression = Expression.AndAlso(Expression.Constant(new NamedMethods(5)), Expression.Constant(new NamedMethods(3))); Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter); Assert.Equal(1, lambda().Value); } [Theory] [PerCompilationType(nameof(AndAlso_TestData))] public static void AndAlso_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter) { MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.AndMethod)); TrueFalseClass left = new TrueFalseClass(leftValue); TrueFalseClass right = new TrueFalseClass(rightValue); BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right), method); Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter); Assert.Equal(expectedValue, lambda().Value); // AndAlso only evaluates the false operator of left Assert.Equal(0, left.TrueCallCount); Assert.Equal(1, left.FalseCallCount); Assert.Equal(0, right.TrueCallCount); Assert.Equal(0, right.FalseCallCount); // AndAlso only evaluates the method if left is not false Assert.Equal(0, left.OperatorCallCount); Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount); } public static IEnumerable<object[]> OrElse_TestData() { yield return new object[] { 5, 3, 5, false }; yield return new object[] { 0, 3, 3, true }; yield return new object[] { 5, 0, 5, false }; } [Theory] [PerCompilationType(nameof(OrElse_TestData))] public static void OrElse_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter) { TrueFalseClass left = new TrueFalseClass(leftValue); TrueFalseClass right = new TrueFalseClass(rightValue); BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right)); Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter); Assert.Equal(expectedValue, lambda().Value); // OrElse only evaluates the true operator of left Assert.Equal(1, left.TrueCallCount); Assert.Equal(0, left.FalseCallCount); Assert.Equal(0, right.TrueCallCount); Assert.Equal(0, right.FalseCallCount); // OrElse only evaluates the operator if left is not true Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount); } [Theory] [ClassData(typeof(CompilationTypes))] public static void OrElse_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter) { BinaryExpression expression = Expression.OrElse(Expression.Constant(new NamedMethods(0)), Expression.Constant(new NamedMethods(3))); Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter); Assert.Equal(3, lambda().Value); } [Theory] [PerCompilationType(nameof(OrElse_TestData))] public static void OrElse_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter) { MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.OrMethod)); TrueFalseClass left = new TrueFalseClass(leftValue); TrueFalseClass right = new TrueFalseClass(rightValue); BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right), method); Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter); Assert.Equal(expectedValue, lambda().Value); // OrElse only evaluates the true operator of left Assert.Equal(1, left.TrueCallCount); Assert.Equal(0, left.FalseCallCount); Assert.Equal(0, right.TrueCallCount); Assert.Equal(0, right.FalseCallCount); // OrElse only evaluates the method if left is not true Assert.Equal(0, left.OperatorCallCount); Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount); } [Fact] public static void AndAlso_CannotReduce() { Expression exp = Expression.AndAlso(Expression.Constant(true), Expression.Constant(false)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void OrElse_CannotReduce() { Expression exp = Expression.OrElse(Expression.Constant(true), Expression.Constant(false)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void AndAlso_LeftNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true))); Assert.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true), null)); } [Fact] public static void OrElse_LeftNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true))); Assert.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true), null)); } [Fact] public static void AndAlso_RightNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null)); Assert.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null, null)); } [Fact] public static void OrElse_RightNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null)); Assert.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null, null)); } [Fact] public static void AndAlso_BinaryOperatorNotDefined_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello"))); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello"), null)); } [Fact] public static void OrElse_BinaryOperatorNotDefined_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello"))); Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello"), null)); } public static IEnumerable<object[]> InvalidMethod_TestData() { yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod)) }; yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticVoidMethod)) }; } [Theory] [ClassData(typeof(OpenGenericMethodsData))] [MemberData(nameof(InvalidMethod_TestData))] public static void InvalidMethod_ThrowsArgumentException(MethodInfo method) { Assert.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method)); Assert.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method)); } [Fact] public static void AndAlso_NoMethod_NotStatic_ThrowsInvalidOperationException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public, type.AsType(), new Type[] { type.AsType(), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void OrElse_NoMethod_NotStatic_ThrowsInvalidOperationException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public, type.AsType(), new Type[] { type.AsType(), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void AndAlso_NoMethod_VoidReturnType_ThrowsArgumentException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type.AsType(), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void OrElse_NoMethod_VoidReturnType_ThrowsArgumentException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type.AsType(), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj))); } [Theory] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod0))] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod1))] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod3))] public static void Method_DoesntHaveTwoParameters_ThrowsArgumentException(Type type, string methodName) { MethodInfo method = type.GetMethod(methodName); Assert.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method)); Assert.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(3)] public static void AndAlso_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount) { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type.AsType(), Enumerable.Repeat(type.AsType(), parameterCount).ToArray()); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj))); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(3)] public static void OrElse_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount) { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type.AsType(), Enumerable.Repeat(type.AsType(), parameterCount).ToArray()); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void AndAlso_Method_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException() { MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid)); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method)); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method)); } [Fact] public static void AndAlso_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type.AsType(), new Type[] { typeof(int), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void OrElse_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException() { MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid)); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method)); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method)); } [Fact] public static void OrElse_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type.AsType(), new Type[] { typeof(int), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void MethodParametersNotEqual_ThrowsArgumentException() { MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid1)); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method)); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant("abc"), method)); } [Fact] public static void Method_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException() { MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid2)); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method)); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method)); } [Fact] public static void AndAlso_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type.AsType(), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void OrElse_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException() { TypeBuilder type = GetTypeBuilder(); MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type.AsType(), type.AsType() }); andOperator.GetILGenerator().Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); object obj = Activator.CreateInstance(createdType); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void MethodDeclaringTypeHasNoTrueFalseOperator_ThrowsArgumentException() { MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid)); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method)); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method)); } public static IEnumerable<object[]> Operator_IncorrectMethod_TestData() { // Does not return bool TypeBuilder typeBuilder1 = GetTypeBuilder(); yield return new object[] { typeBuilder1, typeof(void), new Type[] { typeBuilder1.AsType() } }; // Parameter is not assignable from left yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[] { typeof(int) } }; // Has two parameters TypeBuilder typeBuilder2 = GetTypeBuilder(); yield return new object[] { typeBuilder2, typeof(bool), new Type[] { typeBuilder2.AsType(), typeBuilder2.AsType() } }; // Has no parameters yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[0] }; } [Theory] [MemberData(nameof(Operator_IncorrectMethod_TestData))] public static void Method_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes) { MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opFalse.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder.AsType(), new Type[] { builder.AsType(), builder.AsType() }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); object obj = Activator.CreateInstance(createdType.AsType()); MethodInfo createdMethod = createdType.GetMethod("Method"); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod)); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod)); } [Theory] [MemberData(nameof(Operator_IncorrectMethod_TestData))] public static void Method_FalseOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[]parameterTypes) { MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes); opFalse.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder.AsType(), new Type[] { builder.AsType(), builder.AsType() }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); object obj = Activator.CreateInstance(createdType.AsType()); MethodInfo createdMethod = createdType.GetMethod("Method"); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod)); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod)); } [Theory] [MemberData(nameof(Operator_IncorrectMethod_TestData))] public static void AndAlso_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes) { MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opFalse.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder.AsType(), new Type[] { builder.AsType(), builder.AsType() }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); object obj = Activator.CreateInstance(createdType.AsType()); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj))); } [Theory] [MemberData(nameof(Operator_IncorrectMethod_TestData))] public static void OrElse_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes) { MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opFalse.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder.AsType(), new Type[] { builder.AsType(), builder.AsType() }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); object obj = Activator.CreateInstance(createdType.AsType()); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj))); } [Theory] [InlineData("op_True")] [InlineData("op_False")] public static void Method_NoTrueFalseOperator_ThrowsArgumentException(string name) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); TypeBuilder builder = module.DefineType("Type"); MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder.AsType(), new Type[] { builder.AsType(), builder.AsType() }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); object obj = Activator.CreateInstance(createdType.AsType()); MethodInfo createdMethod = createdType.GetMethod("Method"); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod)); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod)); } [Theory] [InlineData("op_True")] [InlineData("op_False")] public static void AndAlso_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); TypeBuilder builder = module.DefineType("Type"); MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder.AsType(), new Type[] { builder.AsType(), builder.AsType() }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); object obj = Activator.CreateInstance(createdType.AsType()); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj))); } [Theory] [InlineData("op_True")] [InlineData("op_False")] public static void OrElse_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); TypeBuilder builder = module.DefineType("Type"); MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder.AsType(), new Type[] { builder.AsType(), builder.AsType() }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); object obj = Activator.CreateInstance(createdType.AsType()); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj))); } [Fact] public static void Method_ParamsDontMatchOperator_ThrowsInvalidOperationException() { TypeBuilder builder = GetTypeBuilder(); MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opFalse.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); MethodInfo createdMethod = createdType.GetMethod("Method"); Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), createdMethod)); Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), createdMethod)); } [Fact] public static void AndAlso_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException() { TypeBuilder builder = GetTypeBuilder(); MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opFalse.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5))); } [Fact] public static void OrElse_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException() { TypeBuilder builder = GetTypeBuilder(); MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opTrue.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder.AsType() }); opFalse.GetILGenerator().Emit(OpCodes.Ret); MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) }); method.GetILGenerator().Emit(OpCodes.Ret); TypeInfo createdType = builder.CreateTypeInfo(); Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5))); } [Fact] public static void ImplicitConversionToBool_ThrowsArgumentException() { MethodInfo method = typeof(ClassWithImplicitBoolOperator).GetMethod(nameof(ClassWithImplicitBoolOperator.ConversionMethod)); Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method)); Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method)); } [Theory] [ClassData(typeof(UnreadableExpressionsData))] public static void AndAlso_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression) { Assert.Throws<ArgumentException>("left", () => Expression.AndAlso(unreadableExpression, Expression.Constant(true))); } [Theory] [ClassData(typeof(UnreadableExpressionsData))] public static void AndAlso_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression) { Assert.Throws<ArgumentException>("right", () => Expression.AndAlso(Expression.Constant(true), unreadableExpression)); } [Theory] [ClassData(typeof(UnreadableExpressionsData))] public static void OrElse_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression) { Assert.Throws<ArgumentException>("left", () => Expression.OrElse(unreadableExpression, Expression.Constant(true))); } [Theory] [ClassData(typeof(UnreadableExpressionsData))] public static void OrElse_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression) { Assert.Throws<ArgumentException>("right", () => Expression.OrElse(Expression.Constant(false), unreadableExpression)); } [Fact] public static void ToStringTest() { // NB: These were && and || in .NET 3.5 but shipped as AndAlso and OrElse in .NET 4.0; we kept the latter. BinaryExpression e1 = Expression.AndAlso(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b")); Assert.Equal("(a AndAlso b)", e1.ToString()); BinaryExpression e2 = Expression.OrElse(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b")); Assert.Equal("(a OrElse b)", e2.ToString()); } [Fact] public static void AndAlsoGlobalMethod() { MethodInfo method = GlobalMethod(typeof(int), new[] { typeof(int), typeof(int) }); Assert.Throws<ArgumentException>(() => Expression.AndAlso(Expression.Constant(1), Expression.Constant(2), method)); } [Fact] public static void OrElseGlobalMethod() { MethodInfo method = GlobalMethod(typeof(int), new [] { typeof(int), typeof(int) }); Assert.Throws<ArgumentException>(() => Expression.OrElse(Expression.Constant(1), Expression.Constant(2), method)); } private static TypeBuilder GetTypeBuilder() { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); return module.DefineType("Type"); } private static MethodInfo GlobalMethod(Type returnType, Type[] parameterTypes) { ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module"); MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, returnType, parameterTypes); globalMethod.GetILGenerator().Emit(OpCodes.Ret); module.CreateGlobalFunctions(); return module.GetMethod(globalMethod.Name); } public class NonGenericClass { public void InstanceMethod() { } public static void StaticVoidMethod() { } public static int StaticIntMethod0() => 0; public static int StaticIntMethod1(int i) => 0; public static int StaticIntMethod3(int i1, int i2, int i3) => 0; public static int StaticIntMethod2Valid(int i1, int i2) => 0; public static int StaticIntMethod2Invalid1(int i1, string i2) => 0; public static string StaticIntMethod2Invalid2(int i1, int i2) => "abc"; } public class TrueFalseClass { public int TrueCallCount { get; set; } public int FalseCallCount { get; set; } public int OperatorCallCount { get; set; } public int MethodCallCount { get; set; } public TrueFalseClass(int value) { Value = value; } public int Value { get; } public static bool operator true(TrueFalseClass c) { c.TrueCallCount++; return c.Value != 0; } public static bool operator false(TrueFalseClass c) { c.FalseCallCount++; return c.Value == 0; } public static TrueFalseClass operator &(TrueFalseClass c1, TrueFalseClass c2) { c1.OperatorCallCount++; return new TrueFalseClass(c1.Value & c2.Value); } public static TrueFalseClass AndMethod(TrueFalseClass c1, TrueFalseClass c2) { c1.MethodCallCount++; return new TrueFalseClass(c1.Value & c2.Value); } public static TrueFalseClass operator |(TrueFalseClass c1, TrueFalseClass c2) { c1.OperatorCallCount++; return new TrueFalseClass(c1.Value | c2.Value); } public static TrueFalseClass OrMethod(TrueFalseClass c1, TrueFalseClass c2) { c1.MethodCallCount++; return new TrueFalseClass(c1.Value | c2.Value); } } public class NamedMethods { public NamedMethods(int value) { Value = value; } public int Value { get; } public static bool operator true(NamedMethods c) => c.Value != 0; public static bool operator false(NamedMethods c) => c.Value == 0; public static NamedMethods op_BitwiseAnd(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value & c2.Value); public static NamedMethods op_BitwiseOr(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value | c2.Value); } public class ClassWithImplicitBoolOperator { public static ClassWithImplicitBoolOperator ConversionMethod(ClassWithImplicitBoolOperator bool1, ClassWithImplicitBoolOperator bool2) { return bool1; } public static implicit operator bool(ClassWithImplicitBoolOperator boolClass) => true; } } }
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 #define UNITY_4 #endif using UnityEngine; using UnityEditor; using System.Collections; using Pathfinding; namespace Pathfinding { [CustomGraphEditor (typeof(RecastGraph),"RecastGraph")] /** \astarpro */ public class RecastGraphEditor : GraphEditor { #if UNITY_3_5 public GameObject meshRenderer; public MeshFilter meshFilter; #endif public Mesh navmeshRender; public Renderer navmeshRenderer; /** Material to use for navmeshes in the editor */ public static Material navmeshMaterial; public static bool tagMaskFoldout = false; public override void OnEnable () { #if UNITY_3_5 CreateDebugMesh (); #else UpdateDebugMesh (editor.script); #endif //Get a callback when scanning has finished AstarPath.OnLatePostScan += UpdateDebugMesh; } public override void OnDestroy () { #if UNITY_3_5 if (meshRenderer != null) { GameObject.DestroyImmediate (meshRenderer); } #else //Avoid memory leak Mesh.DestroyImmediate (navmeshRender); #endif } public override void OnDisable () { AstarPath.OnLatePostScan -= UpdateDebugMesh; #if UNITY_3_5 if (meshRenderer != null) { //GameObject.DestroyImmediate (meshRenderer); } #endif } #if UNITY_3_5 public void CreateDebugMesh () { RecastGraph graph = target as RecastGraph; meshRenderer = GameObject.Find ("RecastGraph_"+graph.guid.ToString ()); if (meshRenderer == null || meshFilter == null || navmeshRender == null || navmeshRenderer == null) { if (meshRenderer == null) { meshRenderer = new GameObject ("RecastGraph_"+graph.guid.ToString ()); meshRenderer.hideFlags = /*HideFlags.NotEditable |*/ HideFlags.DontSave; } if (meshRenderer.GetComponent<NavMeshRenderer>() == null) { meshRenderer.AddComponent<NavMeshRenderer>(); } MeshFilter filter; if ((filter = meshRenderer.GetComponent<MeshFilter>()) == null) { filter = meshRenderer.AddComponent<MeshFilter>(); } navmeshRenderer = meshRenderer.GetComponent<MeshRenderer>(); if (navmeshRenderer == null) { navmeshRenderer = meshRenderer.AddComponent<MeshRenderer>(); navmeshRenderer.castShadows = false; navmeshRenderer.receiveShadows = false; } if (filter.sharedMesh == null) { navmeshRender = new Mesh (); filter.sharedMesh = navmeshRender; } else { navmeshRender = filter.sharedMesh; } navmeshRender.name = "Navmesh_"+graph.guid.ToString (); } if (navmeshMaterial == null) { navmeshMaterial = AssetDatabase.LoadAssetAtPath (AstarPathEditor.editorAssets + "/Materials/Navmesh.mat",typeof(Material)) as Material; if (navmeshMaterial == null) { Debug.LogWarning ("Could not find navmesh material at path "+AstarPathEditor.editorAssets + "/Materials/Navmesh.mat"); } navmeshRenderer.material = navmeshMaterial; } } #endif public void UpdateDebugMesh (AstarPath astar) { #if UNITY_3_5 CreateDebugMesh (); meshRenderer.transform.position = Vector3.zero; meshRenderer.transform.localScale = Vector3.one; #endif /* RecastGraph graph = target as RecastGraph; if (graph != null && graph.nodes != null && graph.vectorVertices != null) { if (navmeshRender == null) navmeshRender = new Mesh(); navmeshRender.Clear (); navmeshRender.vertices = graph.vectorVertices; int[] tris = new int[graph.nodes.Length*3]; Color[] vColors = new Color[graph.vectorVertices.Length]; for (int i=0;i<graph.nodes.Length;i++) { TriangleMeshNode node = graph.nodes[i] as TriangleMeshNode; tris[i*3] = node.v0; tris[i*3+1] = node.v1; tris[i*3+2] = node.v2; Color col = Mathfx.IntToColor ((int)node.Region,1F); vColors[node.v0] = col; vColors[node.v1] = col; vColors[node.v2] = col; } navmeshRender.triangles = tris; navmeshRender.colors = vColors; //meshRenderer.transform.position = graph.forcedBoundsCenter-graph.forcedBoundsSize*0.5F; //meshRenderer.transform.localScale = Int3.Precision*Voxelize.CellScale; navmeshRender.RecalculateNormals (); navmeshRender.RecalculateBounds (); if (navmeshMaterial == null) { navmeshMaterial = AssetDatabase.LoadAssetAtPath (AstarPathEditor.editorAssets + "/Materials/Navmesh.mat",typeof(Material)) as Material; } navmeshRender.hideFlags = HideFlags.HideAndDontSave; #if UNITY_3_5 navmeshRenderer.material = navmeshMaterial; #endif }*/ } public override void OnSceneGUI (NavGraph target) { #if UNITY_3_5 if (navmeshRenderer != null) { navmeshRenderer.enabled = editor.script.showNavGraphs; } #else /*if (editor.script.showNavGraphs) { //navmeshMaterial, 0 if (navmeshRender != null && navmeshMaterial != null) { //Render the navmesh-mesh. The shader has three passes if (navmeshMaterial.SetPass (0)) Graphics.DrawMeshNow (navmeshRender, Matrix4x4.identity); if (navmeshMaterial.SetPass (1)) Graphics.DrawMeshNow (navmeshRender, Matrix4x4.identity); if (navmeshMaterial.SetPass (2)) Graphics.DrawMeshNow (navmeshRender, Matrix4x4.identity); } }*/ #endif } public enum UseTiles { UseTiles = 0, DontUseTiles = 1 } public override void OnDrawGizmos () { } public override void OnInspectorGUI (NavGraph target) { RecastGraph graph = target as RecastGraph; bool preEnabled = GUI.enabled; //if (graph.forceBounds) { System.Int64 estWidth = Mathf.RoundToInt (Mathf.Ceil (graph.forcedBoundsSize.x / graph.cellSize)); System.Int64 estDepth = Mathf.RoundToInt (Mathf.Ceil (graph.forcedBoundsSize.z / graph.cellSize)); if (estWidth*estDepth >= 1024*1024 || estDepth >= 1024*1024 || estWidth >= 1024*1024) { GUIStyle helpBox = GUI.skin.FindStyle ("HelpBox"); if (helpBox == null) helpBox = GUI.skin.FindStyle ("Box"); Color preColor = GUI.color; if (estWidth*estDepth >= 2048*2048 || estDepth >= 2048*2048 || estWidth >= 2048*2048) { GUI.color = Color.red; } else { GUI.color = Color.yellow; } GUILayout.Label ("Warning : Might take some time to calculate",helpBox); GUI.color = preColor; } GUI.enabled = false; EditorGUILayout.LabelField ("Width (samples)",estWidth.ToString ()); EditorGUILayout.LabelField ("Depth (samples)",estDepth.ToString ()); /*} else { GUI.enabled = false; EditorGUILayout.LabelField ("Width (samples)","undetermined"); EditorGUILayout.LabelField ("Depth (samples)","undetermined"); }*/ GUI.enabled = preEnabled; graph.cellSize = EditorGUILayout.FloatField (new GUIContent ("Cell Size","Size of one voxel in world units"),graph.cellSize); if (graph.cellSize < 0.001F) graph.cellSize = 0.001F; graph.cellHeight = EditorGUILayout.FloatField (new GUIContent ("Cell Height","Height of one voxel in world units"),graph.cellHeight); if (graph.cellHeight < 0.001F) graph.cellHeight = 0.001F; graph.useTiles = (UseTiles)EditorGUILayout.EnumPopup ("Use Tiled Graph", graph.useTiles?UseTiles.UseTiles:UseTiles.DontUseTiles) == UseTiles.UseTiles; EditorGUI.BeginDisabledGroup (!graph.useTiles); graph.editorTileSize = EditorGUILayout.IntField (new GUIContent ("Tile Size", "Size in voxels of a single tile.\n" + "This is the width of the tile.\n" + "\n" + "A large tile size can be faster to initially scan (but beware of out of memory issues if you try with a too large tile size in a large world)\n" + "smaller tile sizes are (much) faster to update.\n" + "\n" + "Different tile sizes can affect the quality of paths. It is often good to split up huge open areas into several tiles for\n" + "better quality paths, but too small tiles can lead to effects looking like invisible obstacles."), graph.editorTileSize); EditorGUI.EndDisabledGroup (); graph.minRegionSize = EditorGUILayout.FloatField (new GUIContent ("Min Region Size", "Small regions will be removed. In square world units"), graph.minRegionSize); graph.walkableHeight = EditorGUILayout.FloatField (new GUIContent ("Walkable Height","Minimum distance to the roof for an area to be walkable"),graph.walkableHeight); graph.walkableClimb = EditorGUILayout.FloatField (new GUIContent ("Walkable Climb","How high can the character climb"),graph.walkableClimb); graph.characterRadius = EditorGUILayout.FloatField (new GUIContent ("Character Radius","Radius of the character, it's good to add some margin though"),graph.characterRadius); graph.maxSlope = EditorGUILayout.Slider (new GUIContent ("Max Slope","Approximate maximum slope"),graph.maxSlope,0F,90F); graph.maxEdgeLength = EditorGUILayout.FloatField (new GUIContent ("Max Edge Length","Maximum length of one edge in the completed navmesh before it is split. A lower value can often yield better quality graphs"),graph.maxEdgeLength); graph.maxEdgeLength = graph.maxEdgeLength < graph.cellSize ? graph.cellSize : graph.maxEdgeLength; graph.contourMaxError = EditorGUILayout.FloatField (new GUIContent ("Max Edge Error","Amount of simplification to apply to edges"),graph.contourMaxError); graph.rasterizeTerrain = EditorGUILayout.Toggle (new GUIContent ("Rasterize Terrain","Should a rasterized terrain be included"), graph.rasterizeTerrain); if (graph.rasterizeTerrain) { EditorGUI.indentLevel++; graph.rasterizeTrees = EditorGUILayout.Toggle (new GUIContent ("Rasterize Trees", "Rasterize tree colliders on terrains. " + "If the tree prefab has a collider, that collider will be rasterized. " + "Otherwise a simple box collider will be used and the script will " + "try to adjust it to the tree's scale, it might not do a very good job though so " + "an attached collider is preferable."), graph.rasterizeTrees); if (graph.rasterizeTrees) { EditorGUI.indentLevel++; graph.colliderRasterizeDetail = EditorGUILayout.FloatField (new GUIContent ("Collider Detail", "Controls the detail of the generated collider meshes. Increasing does not necessarily yield better navmeshes, but lowering will speed up scan"), graph.colliderRasterizeDetail); EditorGUI.indentLevel--; } graph.terrainSampleSize = EditorGUILayout.IntField (new GUIContent ("Terrain Sample Size","Size of terrain samples. A lower value is better, but slower"), graph.terrainSampleSize); graph.terrainSampleSize = graph.terrainSampleSize < 1 ? 1 : graph.terrainSampleSize;//Clamp to at least 1 EditorGUI.indentLevel--; } graph.rasterizeMeshes = EditorGUILayout.Toggle (new GUIContent ("Rasterize Meshes", "Should meshes be rasterized and used for building the navmesh"), graph.rasterizeMeshes); graph.rasterizeColliders = EditorGUILayout.Toggle (new GUIContent ("Rasterize Colliders", "Should colliders be rasterized and used for building the navmesh"), graph.rasterizeColliders); if (graph.rasterizeColliders) { EditorGUI.indentLevel++; graph.colliderRasterizeDetail = EditorGUILayout.FloatField (new GUIContent ("Collider Detail", "Controls the detail of the generated collider meshes. Increasing does not necessarily yield better navmeshes, but lowering will speed up scan"), graph.colliderRasterizeDetail); EditorGUI.indentLevel--; } Separator (); graph.forcedBoundsCenter = EditorGUILayout.Vector3Field ("Center",graph.forcedBoundsCenter); graph.forcedBoundsSize = EditorGUILayout.Vector3Field ("Size",graph.forcedBoundsSize); if (GUILayout.Button (new GUIContent ("Snap bounds to scene","Will snap the bounds of the graph to exactly contain all active meshes in the scene"))) { graph.SnapForceBoundsToScene (); GUI.changed = true; } Separator (); #if UNITY_4 EditorGUILayout.HelpBox ("Objects contained in any of these masks will be taken into account.",MessageType.None); #endif graph.mask = EditorGUILayoutx.LayerMaskField ("Layer Mask",graph.mask); tagMaskFoldout = EditorGUILayoutx.UnityTagMaskList (new GUIContent("Tag Mask"), tagMaskFoldout, graph.tagMask); Separator (); graph.showMeshOutline = EditorGUILayout.Toggle (new GUIContent ("Show mesh outline","Toggles gizmos for drawing an outline of the mesh"),graph.showMeshOutline); graph.showNodeConnections = EditorGUILayout.Toggle (new GUIContent ("Show node connections","Toggles gizmos for drawing node connections"),graph.showNodeConnections); if (GUILayout.Button ("Export to .obj file")) { ExportToFile (graph); } Separator (); GUILayout.Label (new GUIContent ("Advanced"), EditorStyles.boldLabel); graph.relevantGraphSurfaceMode = (RecastGraph.RelevantGraphSurfaceMode)EditorGUILayout.EnumPopup (new GUIContent ("Relevant Graph Surface Mode", "Require every region to have a RelevantGraphSurface component inside it.\n" + "A RelevantGraphSurface component placed in the scene specifies that\n" + "the navmesh region it is inside should be included in the navmesh.\n\n" + "If this is set to OnlyForCompletelyInsideTile\n" + "a navmesh region is included in the navmesh if it\n" + "has a RelevantGraphSurface inside it, or if it\n" + "is adjacent to a tile border. This can leave some small regions\n" + "which you didn't want to have included because they are adjacent\n" + "to tile borders, but it removes the need to place a component\n" + "in every single tile, which can be tedious (see below).\n\n" + "If this is set to RequireForAll\n" + "a navmesh region is included only if it has a RelevantGraphSurface\n" + "inside it. Note that even though the navmesh\n" + "looks continous between tiles, the tiles are computed individually\n" + "and therefore you need a RelevantGraphSurface component for each\n" + "region and for each tile."), graph.relevantGraphSurfaceMode); graph.nearestSearchOnlyXZ = EditorGUILayout.Toggle (new GUIContent ("Nearest node queries in XZ space", "Recomended for single-layered environments.\nFaster but can be inacurate esp. in multilayered contexts."), graph.nearestSearchOnlyXZ); //graph.mask = 1 << EditorGUILayout.LayerField ("Mask",(int)Mathf.Log (graph.mask,2)); } /** Exports the INavmesh graph to a file */ public void ExportToFile (RecastGraph target) { //INavmesh graph = (INavmesh)target; if (target == null) return; RecastGraph.NavmeshTile[] tiles = target.GetTiles(); if (tiles == null) { if (EditorUtility.DisplayDialog ("Scan graph before exporting?","The graph does not contain any mesh data. Do you want to scan it?","Ok","Cancel")) { AstarPathEditor.MenuScan (); tiles = target.GetTiles(); if (tiles == null) return; } else { return; } } string path = EditorUtility.SaveFilePanel ("Export .obj","","navmesh.obj","obj"); if (path == "") return; //Generate .obj System.Text.StringBuilder sb = new System.Text.StringBuilder(); string name = System.IO.Path.GetFileNameWithoutExtension (path); sb.Append ("g ").Append(name).AppendLine(); //Vertices start from 1 int vCount = 1; //Define single texture coordinate to zero sb.Append ("vt 0 0\n"); for (int t=0;t<tiles.Length;t++) { RecastGraph.NavmeshTile tile = tiles[t]; if (tile == null) continue; Int3[] vertices = tile.verts; //Write vertices for (int i=0;i<vertices.Length;i++) { Vector3 v = (Vector3)vertices[i]; sb.Append(string.Format("v {0} {1} {2}\n",-v.x,v.y,v.z)); } //Write triangles TriangleMeshNode[] nodes = tile.nodes; for (int i=0;i<nodes.Length;i++) { TriangleMeshNode node = nodes[i]; if (node == null) { Debug.LogError ("Node was null or no TriangleMeshNode. Critical error. Graph type " + target.GetType().Name); return; } if (node.GetVertexArrayIndex(0) < 0 || node.GetVertexArrayIndex(0) >= vertices.Length) throw new System.Exception ("ERR"); sb.Append(string.Format("f {0}/1 {1}/1 {2}/1\n", (node.GetVertexArrayIndex(0) + vCount),(node.GetVertexArrayIndex(1) + vCount),(node.GetVertexArrayIndex(2) + vCount))); } vCount += vertices.Length; } string obj = sb.ToString(); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path)) { sw.Write(obj); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FluentAssertions.Common; using FluentAssertions.Execution; namespace FluentAssertions.Equivalency { /// <remarks> /// I think (but did not try) this would have been easier using 'dynamic' but that is /// precluded by some of the PCL targets. /// </remarks> public class GenericDictionaryEquivalencyStep : IEquivalencyStep { public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); return ((context.Subject != null) && GetIDictionaryInterfaces(subjectType).Any()); } private static Type[] GetIDictionaryInterfaces(Type type) { return Common.TypeExtensions.GetClosedGenericInterfaces( type, typeof(IDictionary<,>)); } public bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { if (PreconditionsAreMet(context, config)) { AssertDictionaryEquivalence(context, parent, config); } return true; } private static bool PreconditionsAreMet(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); return (AssertImplementsOnlyOneDictionaryInterface(context.Subject) && AssertIsCompatiblyTypedDictionary(subjectType, context.Expectation) && AssertSameLength(context.Subject, subjectType, context.Expectation)); } private static bool AssertImplementsOnlyOneDictionaryInterface(object subject) { Type[] interfaces = GetIDictionaryInterfaces(subject.GetType()); bool multipleInterfaces = (interfaces.Count() > 1); if (multipleInterfaces) { AssertionScope.Current.FailWith( string.Format( "{{context:Subject}} implements multiple dictionary types. " + "It is not known which type should be use for equivalence.{0}" + "The following IDictionary interfaces are implemented: {1}", Environment.NewLine, String.Join(", ", (IEnumerable<Type>)interfaces))); return false; } return true; } private static bool AssertIsCompatiblyTypedDictionary(Type subjectType, object expectation) { Type subjectDictionaryType = GetIDictionaryInterface(subjectType); Type subjectKeyType = GetDictionaryKeyType(subjectDictionaryType); Type[] expectationDictionaryInterfaces = GetIDictionaryInterfaces(expectation.GetType()); if (!expectationDictionaryInterfaces.Any()) { AssertionScope.Current.FailWith( "{context:subject} is a dictionary and cannot be compared with a non-dictionary type."); return false; } Type[] suitableDictionaryInterfaces = expectationDictionaryInterfaces.Where( @interface => GetDictionaryKeyType(@interface).IsAssignableFrom(subjectKeyType)).ToArray(); if (suitableDictionaryInterfaces.Count() > 1) { // Code could be written to handle this better, but is it really worth the effort? AssertionScope.Current.FailWith( "The expected object implements multiple IDictionary interfaces. " + "If you need to use ShouldBeEquivalentTo in this case please file " + "a bug with the FluentAssertions devlopment team"); return false; } if (!suitableDictionaryInterfaces.Any()) { AssertionScope.Current.FailWith( string.Format( "The {{context:subject}} dictionary has keys of type {0}; " + "however, the expected dictionary is not keyed with any compatible types.{1}" + "The expected dictionary implements: {2}", subjectKeyType, Environment.NewLine, string.Join(",", (IEnumerable<Type>)expectationDictionaryInterfaces))); return false; } return true; } private static Type GetDictionaryKeyType(Type subjectType) { return subjectType.GetGenericArguments()[0]; } private static bool AssertSameLength(object subject, Type subjectType, object expectation) { string methodName = ExpressionExtensions.GetMethodName(() => AssertSameLength<object, object, object, object>(null, null)); MethodCallExpression assertSameLength = Expression.Call( typeof(GenericDictionaryEquivalencyStep), methodName, GetDictionaryTypeArguments(subjectType) .Concat(GetDictionaryTypeArguments(expectation.GetType())) .ToArray(), Expression.Constant(subject, GetIDictionaryInterface(subjectType)), Expression.Constant(expectation, GetIDictionaryInterface(expectation.GetType()))); return (bool)Expression.Lambda(assertSameLength).Compile().DynamicInvoke(); } private static IEnumerable<Type> GetDictionaryTypeArguments(Type subjectType) { var dictionaryType = GetIDictionaryInterface(subjectType); return dictionaryType.GetGenericArguments(); } private static Type GetIDictionaryInterface(Type subjectType) { return GetIDictionaryInterfaces(subjectType).Single(); } private static bool AssertSameLength<TSubjectKey, TSubjectValue, TExpectKey, TExpectedValue>( IDictionary<TSubjectKey, TSubjectValue> subject, IDictionary<TExpectKey, TExpectedValue> expectation) { return AssertionScope.Current.ForCondition(subject.Count == expectation.Count) .FailWith( "Expected {context:subject} to be a dictionary with {0} item(s), but found {1} item(s).", expectation.Count, subject.Count); } private static void AssertDictionaryEquivalence( IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); string methodName = ExpressionExtensions.GetMethodName( () => AssertDictionaryEquivalence<object, object, object, object>(null, null, null, null, null)); var assertDictionaryEquivalence = Expression.Call( typeof(GenericDictionaryEquivalencyStep), methodName, GetDictionaryTypeArguments(subjectType) .Concat(GetDictionaryTypeArguments(context.Expectation.GetType())) .ToArray(), Expression.Constant(context), Expression.Constant(parent), Expression.Constant(config), Expression.Constant(context.Subject, GetIDictionaryInterface(subjectType)), Expression.Constant(context.Expectation, GetIDictionaryInterface(context.Expectation.GetType()))); Expression.Lambda(assertDictionaryEquivalence).Compile().DynamicInvoke(); } private static void AssertDictionaryEquivalence<TSubjectKey, TSubjectValue, TExpectKey, TExpectedValue>( EquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config, IDictionary<TSubjectKey, TSubjectValue> subject, IDictionary<TExpectKey, TExpectedValue> expectation) where TSubjectKey : TExpectKey { foreach (TSubjectKey key in subject.Keys) { TExpectedValue expectedValue; if (expectation.TryGetValue(key, out expectedValue)) { if (config.IsRecursive) { parent.AssertEqualityUsing(context.CreateForDictionaryItem(key, subject[key], expectation[key])); } else { subject[key].Should().Be(expectation[key], context.Reason, context.ReasonArgs); } } else { AssertionScope.Current.FailWith("{context:subject} contains unexpected key {0}", key); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using Xunit; using SortedDictionaryTests.SortedDictionary_SortedDictionary_ValueCollection; using SortedDictionary_SortedDictionaryUtils; namespace SortedDictionaryTests { public class SortedDictionary_ValueCollectionTests { public class IntGenerator { private int _index; public IntGenerator() { _index = 0; } public int NextValue() { return _index++; } public Object NextValueObject() { return (Object)NextValue(); } } public class StringGenerator { private int _index; public StringGenerator() { _index = 0; } public String NextValue() { return (_index++).ToString(); } public Object NextValueObject() { return (Object)NextValue(); } } [Fact] public static void ValueCollectionTest1() { IntGenerator intGenerator = new IntGenerator(); StringGenerator stringGenerator = new StringGenerator(); intGenerator.NextValue(); stringGenerator.NextValue(); //Scenario 1: Vanilla - fill in SortedDictionary with 10 keys and check this property Driver<int, int> IntDriver = new Driver<int, int>(); Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>(); Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>(); int count = 100; SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count); SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count); int[] ints = new int[count]; for (int i = 0; i < count; i++) ints[i] = i; IntDriver.TestVanilla(ints, ints); simpleRef.TestVanilla(simpleStrings, simpleStrings); simpleVal.TestVanilla(simpleInts, simpleInts); IntDriver.NonGenericIDictionaryTestVanilla(ints, ints); simpleRef.NonGenericIDictionaryTestVanilla(simpleStrings, simpleStrings); simpleVal.NonGenericIDictionaryTestVanilla(simpleInts, simpleInts); //Scenario 2: Check for an empty SortedDictionary IntDriver.TestVanilla(new int[0], new int[0]); simpleRef.TestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]); simpleVal.TestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]); IntDriver.NonGenericIDictionaryTestVanilla(new int[0], new int[0]); simpleRef.NonGenericIDictionaryTestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]); simpleVal.NonGenericIDictionaryTestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]); //Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the //change is reflected int half = count / 2; SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half]; SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half]; SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half]; SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half]; int[] ints_1 = new int[half]; int[] ints_2 = new int[half]; for (int i = 0; i < half; i++) { simpleInts_1[i] = simpleInts[i]; simpleStrings_1[i] = simpleStrings[i]; ints_1[i] = ints[i]; simpleInts_2[i] = simpleInts[i + half]; simpleStrings_2[i] = simpleStrings[i + half]; ints_2[i] = ints[i + half]; } IntDriver.TestModify(ints_1, ints_1, ints_2); simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2); simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2); IntDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2); simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2); simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2); } [Fact] public static void SortedDictionary_ValueCollectionTest_Negative() { IntGenerator intGenerator = new IntGenerator(); StringGenerator stringGenerator = new StringGenerator(); intGenerator.NextValue(); stringGenerator.NextValue(); //Scenario 1: Vanilla - fill in SortedDictionary with 10 keys and check this property Driver<int, int> IntDriver = new Driver<int, int>(); Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>(); Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>(); int count = 100; SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count); SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count); int[] ints = new int[count]; for (int i = 0; i < count; i++) ints[i] = i; IntDriver.TestVanilla_Negative(ints, ints); simpleRef.TestVanilla_Negative(simpleStrings, simpleStrings); simpleVal.TestVanilla_Negative(simpleInts, simpleInts); IntDriver.NonGenericIDictionaryTestVanilla_Negative(ints, ints); simpleRef.NonGenericIDictionaryTestVanilla_Negative(simpleStrings, simpleStrings); simpleVal.NonGenericIDictionaryTestVanilla_Negative(simpleInts, simpleInts); //Scenario 2: Check for an empty SortedDictionary IntDriver.TestVanilla_Negative(new int[0], new int[0]); simpleRef.TestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]); simpleVal.TestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]); IntDriver.NonGenericIDictionaryTestVanilla_Negative(new int[0], new int[0]); simpleRef.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]); simpleVal.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]); } [Fact] public static void SortedDictionary_ValueCollectionTest2() { IntGenerator intGenerator = new IntGenerator(); StringGenerator stringGenerator = new StringGenerator(); intGenerator.NextValue(); stringGenerator.NextValue(); Driver<int, int> intDriver = new Driver<int, int>(); Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>(); Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>(); //Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the //change is reflected int count = 100; SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count); SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count); int[] ints = new int[count]; int half = count / 2; SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half]; SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half]; SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half]; SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half]; for (int i = 0; i < count; i++) ints[i] = i; int[] ints_1 = new int[half]; int[] ints_2 = new int[half]; for (int i = 0; i < half; i++) { simpleInts_1[i] = simpleInts[i]; simpleStrings_1[i] = simpleStrings[i]; ints_1[i] = ints[i]; simpleInts_2[i] = simpleInts[i + half]; simpleStrings_2[i] = simpleStrings[i + half]; ints_2[i] = ints[i + half]; } intDriver.TestModify(ints_1, ints_1, ints_2); simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2); simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2); intDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2); simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2); simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2); } } namespace SortedDictionary_SortedDictionary_ValueCollection { public class Driver<KeyType, ValueType> { public void TestVanilla(KeyType[] keys, ValueType[] values) { SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(); for (int i = 0; i < keys.Length - 1; i++) _dic.Add(keys[i], values[i]); SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic); Assert.Equal(_col.Count, _dic.Count); //"Err_1! Count not equal" IEnumerator<ValueType> _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { Assert.True(_dic.ContainsValue(_enum.Current)); //"Err_2! Expected key to be present" count++; } Assert.Equal(count, _dic.Count); //"Err_3! Count not equal" ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < values.Length - 1; i++) Assert.True(_dic.ContainsValue(_values[i])); //"Err_4! Expected key to be present" count = 0; foreach (ValueType currValue in _dic.Values) { Assert.True(_dic.ContainsValue(currValue)); //"Err_5! Expected key to be present" count++; } Assert.Equal(count, _dic.Count); //"Err_! Count not equal" try { //The behavior here is undefined as long as we don't AV we're fine ValueType item = _enum.Current; } catch (Exception) { } } // verify we get InvalidOperationException when we call MoveNext() after adding a key public void TestVanilla_Negative(KeyType[] keys, ValueType[] values) { SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(); for (int i = 0; i < keys.Length - 1; i++) _dic.Add(keys[i], values[i]); SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic); IEnumerator<ValueType> _enum = _col.GetEnumerator(); if (keys.Length > 0) { _dic.Add(keys[keys.Length - 1], values[values.Length - 1]); Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_6! Expected InvalidOperationException." } } public void TestModify(KeyType[] keys, ValueType[] values, ValueType[] newValues) { SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(); for (int i = 0; i < keys.Length; i++) { _dic.Add(keys[i], values[i]); } SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic); for (int i = 0; i < keys.Length; i++) _dic.Remove(keys[i]); Assert.Equal(_col.Count, 0); //"Err_7! Count not equal" IEnumerator<ValueType> _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { Assert.True(_dic.ContainsValue(_enum.Current)); //"Err_8! Expected key to be present" count++; } Assert.Equal(count, 0); //"Err_9! Count not equal" for (int i = 0; i < keys.Length; i++) _dic[keys[i]] = newValues[i]; Assert.Equal(_col.Count, _dic.Count); //"Err_10! Count not equal" _enum = _col.GetEnumerator(); count = 0; while (_enum.MoveNext()) { Assert.True(_dic.ContainsValue(_enum.Current)); //"Err_11! Expected key to be present" count++; } Assert.Equal(count, _dic.Count); //"Err_12! Count not equal" ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length; i++) Assert.True(_dic.ContainsValue(_values[i])); //"Err_13! Expected key to be present" } public void NonGenericIDictionaryTestVanilla(KeyType[] keys, ValueType[] values) { SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(); IDictionary _idic = _dic; for (int i = 0; i < keys.Length - 1; i++) _dic.Add(keys[i], values[i]); SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic); Assert.Equal(_col.Count, _dic.Count); //"Err_14! Count not equal" IEnumerator _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_15! Expected key to be present" count++; } Assert.Equal(count, _dic.Count); //"Err_16! Count not equal" ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length - 1; i++) Assert.True(_dic.ContainsValue(_values[i])); //"Err_17! Expected key to be present" _enum.Reset(); count = 0; while (_enum.MoveNext()) { Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_18! Expected key to be present" count++; } Assert.Equal(count, _dic.Count); //"Err_19! Count not equal" _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length - 1; i++) Assert.True(_dic.ContainsValue(_values[i])); //"Err_20! Expected key to be present" } public void NonGenericIDictionaryTestVanilla_Negative(KeyType[] keys, ValueType[] values) { SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(); IDictionary _idic = _dic; for (int i = 0; i < keys.Length - 1; i++) _dic.Add(keys[i], values[i]); SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic); IEnumerator _enum = _col.GetEnumerator(); // get to the end while (_enum.MoveNext()) { } Assert.Throws<InvalidOperationException>((() => _dic.ContainsValue((ValueType)_enum.Current))); //"Err_21! Expected InvalidOperationException." if (keys.Length > 0) { _dic.Add(keys[keys.Length - 1], values[values.Length - 1]); Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_22! Expected InvalidOperationException." Assert.Throws<InvalidOperationException>((() => _enum.Reset())); //"Err_23! Expected InvalidOperationException." } } public void NonGenericIDictionaryTestModify(KeyType[] keys, ValueType[] values, ValueType[] newValues) { SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(); IDictionary _idic = _dic; for (int i = 0; i < keys.Length; i++) _dic.Add(keys[i], values[i]); SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic); for (int i = 0; i < keys.Length; i++) _dic.Remove(keys[i]); Assert.Equal(_col.Count, 0); //"Err_24! Expected count to be zero" IEnumerator _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_! Expected key to be present" count++; } Assert.Equal(count, 0); //"Err_25! Expected count to be zero" for (int i = 0; i < keys.Length; i++) _dic[keys[i]] = newValues[i]; Assert.Equal(_col.Count, _dic.Count); //"Err_26! Count not equal" _enum = _col.GetEnumerator(); count = 0; while (_enum.MoveNext()) { Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_27! Expected key to be present" count++; } Assert.Equal(count, _dic.Count); //"Err_28! Count not equal" ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length; i++) Assert.True(_dic.ContainsValue(_values[i])); //"Err_29! Expected key to be present" } } } }
using System; using System.Collections.Generic; using System.Linq; using MonoMac.Foundation; using MonoMac.AppKit; using System.IO; using ICSharpCode.SharpZipLib.Zip; using dex.net; using MonoMac.CoreText; using System.Text.RegularExpressions; using MonoMac.CoreGraphics; namespace DexMac { public partial class MainWindowController : MonoMac.AppKit.NSWindowController { private string _tempFile = null; private Dex _dex; private WritersFactory _factory = new WritersFactory (); private IDexWriter _writer; private CTStringAttributes _codeFont; private List<CodeHighlight> _codeHighlight = new List<CodeHighlight> (); private ClassDisplayOptions _classDisplayOptions = ClassDisplayOptions.ClassAnnotations | ClassDisplayOptions.ClassName | ClassDisplayOptions.ClassDetails | ClassDisplayOptions.Fields; #region Constructors // Called when created from unmanaged code public MainWindowController (IntPtr handle) : base (handle) { Initialize (); } // Called when created directly from a XIB file [Export ("initWithCoder:")] public MainWindowController (NSCoder coder) : base (coder) { Initialize (); } // Call to load from the XIB/NIB file public MainWindowController () : base ("MainWindow") { Initialize (); } // Shared initialization code void Initialize () { } #endregion //strongly typed window accessor public new MainWindow Window { get { return (MainWindow)base.Window; } } internal void OpenDex(string filename) { string dexFile = filename; _tempFile = null; if (System.IO.Path.GetExtension(dexFile).EndsWith("apk")) { var apkFile = new FileInfo (dexFile); if (apkFile.Exists) { var zip = new ZipFile (dexFile); var entry = zip.GetEntry ("classes.dex"); if (entry != null) { var zipStream = zip.GetInputStream (entry); var tempFileName = System.IO.Path.GetTempFileName (); var buffer = new byte[4096]; using (var writer = File.Create(tempFileName)) { int bytesRead; while ((bytesRead = zipStream.Read(buffer, 0, 4096)) > 0) { writer.Write (buffer, 0, bytesRead); } } dexFile = tempFileName; _tempFile = dexFile; } } } _dex = new Dex(new FileStream (dexFile, FileMode.Open)); this.Window.Title = "DexMac - " + System.IO.Path.GetFileName (filename); this.Window.Delegate = new DexWindowDelegate (this); _codeFont = new CTStringAttributes () { Font = new CTFont("Menlo-Regular", 12f) }; codeTextView.TextContainer.WidthTracksTextView = false; codeTextView.TextContainer.ContainerSize = new System.Drawing.SizeF (float.MaxValue, float.MaxValue); searchField.Changed += ApplySearchFilter; var dexDataSource = new DexDataSource(); dexDataSource.SetData (_dex); dexOutlineView.DataSource = dexDataSource; //dexOutlineView.SelectionDidChange += OnSelectionChanged; dexOutlineView.Delegate = new OutlineViewWorkaroundDelegate (this); // Supported Languages languagePopUpButton.RemoveAllItems (); languagePopUpButton.AddItems (_factory.GetWriters()); UpdateSelectedLanguage (); _writer.dex = _dex; } partial void languagePopUpButtonClicked (MonoMac.Foundation.NSObject sender) { UpdateSelectedLanguage(); UpdateCodeWindow(); } private void UpdateSelectedLanguage() { var lang = languagePopUpButton.ItemTitle (languagePopUpButton.IndexOfSelectedItem); _writer = _factory.GetWriter (lang); _writer.dex = _dex; _codeHighlight.Clear (); foreach (var highlight in _writer.GetCodeHightlight()) { _codeHighlight.Add (new CodeHighlight (highlight)); } } private void PopulateClasses() { var datasource = (DexDataSource)dexOutlineView.DataSource; datasource.SetData (_dex); dexOutlineView.ReloadData (); } private void UpdateCodeWindow() { var value = dexOutlineView.ItemAtRow (dexOutlineView.SelectedRow); var writer = new StringWriter (); if (value is ClassModel) { var dexClass = value as ClassModel; _writer.WriteOutClass (dexClass._class, _classDisplayOptions, writer); } else if (value is MethodModel) { var dexMethod = (MethodModel)value; _writer.WriteOutMethod (dexMethod._class, dexMethod._method, writer, new Indentation(), true); } codeTextView.TextStorage.SetString(HighlightCode(writer.ToString ())); } private NSAttributedString HighlightCode(String code) { var highlightedCode = new NSMutableAttributedString (new NSAttributedString ((NSString)code, _codeFont)); foreach (var highlight in _codeHighlight) { foreach (Match match in highlight.Expression.Matches(code)) { highlightedCode.AddAttribute(NSAttributedString.ForegroundColorAttributeName, highlight.Color, new NSRange(match.Groups[1].Index, match.Groups[1].Length)); } } return (NSAttributedString)highlightedCode.Copy(); } void ApplySearchFilter (object sender, EventArgs e) { var datasource = (DexDataSource)dexOutlineView.DataSource; if (string.IsNullOrEmpty (searchField.StringValue)) { datasource.ResetFilter (); } else { datasource.SetFilter (searchField.StringValue); } dexOutlineView.ReloadData (); } class OutlineViewWorkaroundDelegate : NSOutlineViewDelegate { MainWindowController _controller; public OutlineViewWorkaroundDelegate (MainWindowController controller) { _controller = controller; } public override void SelectionDidChange (NSNotification notification) { _controller.UpdateCodeWindow (); } } class DexWindowDelegate : NSWindowDelegate { MainWindowController _controller; public DexWindowDelegate(MainWindowController controller) { _controller = controller; } public override void WillClose (NSNotification notification) { _controller._dex.Dispose (); if (_controller._tempFile != null) { try { new FileInfo (_controller._tempFile).Delete(); } catch { } } } } class CodeHighlight { internal Regex Expression; internal NSColor Color; internal CodeHighlight(HightlightInfo info) { Expression = info.Expression; Color = NSColor.FromDeviceRgba(info.Color.Red/255f, info.Color.Green/255f, info.Color.Blue/255f, 1); } } } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // David Stephensen (mailto:David.Stephensen@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Reflection; using System.Collections; using MigraDoc.DocumentObjectModel.Internals; using MigraDoc.DocumentObjectModel.Visitors; using MigraDoc.DocumentObjectModel.IO; using MigraDoc.DocumentObjectModel.Fields; using MigraDoc.DocumentObjectModel.Shapes; namespace MigraDoc.DocumentObjectModel { /// <summary> /// Represents a paragraph which is used to build up a document with text. /// </summary> public class Paragraph : DocumentObject, IVisitable { /// <summary> /// Initializes a new instance of the Paragraph class. /// </summary> public Paragraph() { } /// <summary> /// Initializes a new instance of the Paragraph class with the specified parent. /// </summary> internal Paragraph(DocumentObject parent) : base(parent) { } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new Paragraph Clone() { return (Paragraph)DeepCopy(); } /// <summary> /// Implements the deep copy of the object. /// </summary> protected override object DeepCopy() { Paragraph paragraph = (Paragraph)base.DeepCopy(); if (paragraph.format != null) { paragraph.format = paragraph.format.Clone(); paragraph.format.parent = paragraph; } if (paragraph.elements != null) { paragraph.elements = paragraph.elements.Clone(); paragraph.elements.parent = paragraph; } return paragraph; } /// <summary> /// Adds a text phrase to the paragraph. /// </summary> public Text AddText(String text) { return this.Elements.AddText(text); } /// <summary> /// Adds a single character repeated the specified number of times to the paragraph. /// </summary> public Text AddChar(char ch, int count) { return this.Elements.AddChar(ch, count); } /// <summary> /// Adds a single character to the paragraph. /// </summary> public Text AddChar(char ch) { return this.Elements.AddChar(ch); } /// <summary> /// Adds one or more Symbol objects. /// </summary> public Character AddCharacter(SymbolName symbolType, int count) { return this.Elements.AddCharacter(symbolType, count); } /// <summary> /// Adds a Symbol object. /// </summary> public Character AddCharacter(SymbolName symbolType) { return this.Elements.AddCharacter(symbolType); } /// <summary> /// Adds one or more Symbol objects defined by a character. /// </summary> public Character AddCharacter(char ch, int count) { return this.Elements.AddCharacter(ch, count); } /// <summary> /// Adds a Symbol object defined by a character. /// </summary> public Character AddCharacter(char ch) { return this.Elements.AddCharacter(ch); } /// <summary> /// Adds a space character as many as count. /// </summary> public Character AddSpace(int count) { return this.Elements.AddSpace(count); } /// <summary> /// Adds a horizontal tab. /// </summary> public void AddTab() { this.Elements.AddTab(); } /// <summary> /// Adds a line break. /// </summary> public void AddLineBreak() { this.Elements.AddLineBreak(); } /// <summary> /// Adds a new FormattedText. /// </summary> public FormattedText AddFormattedText() { return this.Elements.AddFormattedText(); } /// <summary> /// Adds a new FormattedText object with the given format. /// </summary> public FormattedText AddFormattedText(TextFormat textFormat) { return this.Elements.AddFormattedText(textFormat); } /// <summary> /// Adds a new FormattedText with the given Font. /// </summary> public FormattedText AddFormattedText(Font font) { return this.Elements.AddFormattedText(font); } /// <summary> /// Adds a new FormattedText with the given text. /// </summary> public FormattedText AddFormattedText(string text) { return this.Elements.AddFormattedText(text); } /// <summary> /// Adds a new FormattedText object with the given text and format. /// </summary> public FormattedText AddFormattedText(string text, TextFormat textFormat) { return this.Elements.AddFormattedText(text, textFormat); } /// <summary> /// Adds a new FormattedText object with the given text and font. /// </summary> public FormattedText AddFormattedText(string text, Font font) { return this.Elements.AddFormattedText(text, font); } /// <summary> /// Adds a new FormattedText object with the given text and style. /// </summary> public FormattedText AddFormattedText(string text, string style) { return this.Elements.AddFormattedText(text, style); } /// <summary> /// Adds a new Hyperlink of Type "Local", /// i.e. the Target is a Bookmark within the Document /// </summary> public Hyperlink AddHyperlink(string name) { return this.Elements.AddHyperlink(name); } /// <summary> /// Adds a new Hyperlink /// </summary> public Hyperlink AddHyperlink(string name, HyperlinkType type) { return this.Elements.AddHyperlink(name, type); } /// <summary> /// Adds a new Bookmark. /// </summary> public BookmarkField AddBookmark(string name) { return this.Elements.AddBookmark(name); } /// <summary> /// Adds a new PageField. /// </summary> public PageField AddPageField() { return this.Elements.AddPageField(); } /// <summary> /// Adds a new PageRefField. /// </summary> public PageRefField AddPageRefField(string name) { return this.Elements.AddPageRefField(name); } /// <summary> /// Adds a new NumPagesField. /// </summary> public NumPagesField AddNumPagesField() { return this.Elements.AddNumPagesField(); } /// <summary> /// Adds a new SectionField. /// </summary> public SectionField AddSectionField() { return this.Elements.AddSectionField(); } /// <summary> /// Adds a new SectionPagesField. /// </summary> public SectionPagesField AddSectionPagesField() { return this.Elements.AddSectionPagesField(); } /// <summary> /// Adds a new DateField. /// </summary> public DateField AddDateField() { return this.Elements.AddDateField(); } /// <summary> /// Adds a new DateField. /// </summary> public DateField AddDateField(string format) { return this.Elements.AddDateField(format); } /// <summary> /// Adds a new InfoField. /// </summary> public InfoField AddInfoField(InfoFieldType iType) { return this.Elements.AddInfoField(iType); } /// <summary> /// Adds a new Footnote with the specified text. /// </summary> public Footnote AddFootnote(string text) { return this.Elements.AddFootnote(text); } /// <summary> /// Adds a new Footnote. /// </summary> public Footnote AddFootnote() { return this.Elements.AddFootnote(); } /// <summary> /// Adds a new Image object /// </summary> public Image AddImage(string fileName) { return this.Elements.AddImage(fileName); } /// <summary> /// Adds a new Bookmark /// </summary> public void Add(BookmarkField bookmark) { this.Elements.Add(bookmark); } /// <summary> /// Adds a new PageField /// </summary> public void Add(PageField pageField) { this.Elements.Add(pageField); } /// <summary> /// Adds a new PageRefField /// </summary> public void Add(PageRefField pageRefField) { this.Elements.Add(pageRefField); } /// <summary> /// Adds a new NumPagesField /// </summary> public void Add(NumPagesField numPagesField) { this.Elements.Add(numPagesField); } /// <summary> /// Adds a new SectionField /// </summary> public void Add(SectionField sectionField) { this.Elements.Add(sectionField); } /// <summary> /// Adds a new SectionPagesField /// </summary> public void Add(SectionPagesField sectionPagesField) { this.Elements.Add(sectionPagesField); } /// <summary> /// Adds a new DateField /// </summary> public void Add(DateField dateField) { this.Elements.Add(dateField); } /// <summary> /// Adds a new InfoField /// </summary> public void Add(InfoField infoField) { this.Elements.Add(infoField); } /// <summary> /// Adds a new Footnote /// </summary> public void Add(Footnote footnote) { this.Elements.Add(footnote); } /// <summary> /// Adds a new Text /// </summary> public void Add(Text text) { this.Elements.Add(text); } /// <summary> /// Adds a new FormattedText /// </summary> public void Add(FormattedText formattedText) { this.Elements.Add(formattedText); } /// <summary> /// Adds a new Hyperlink /// </summary> public void Add(Hyperlink hyperlink) { this.Elements.Add(hyperlink); } /// <summary> /// Adds a new Image /// </summary> public void Add(Image image) { this.Elements.Add(image); } /// <summary> /// Adds a new Character /// </summary> public void Add(Character character) { this.Elements.Add(character); } #endregion #region Properties /// <summary> /// Gets or sets the style name. /// </summary> public string Style { get { return this.style.Value; } set { this.style.Value = value; } } [DV] internal NString style = NString.NullValue; /// <summary> /// Gets or sets the ParagraphFormat object of the paragraph. /// </summary> public ParagraphFormat Format { get { if (this.format == null) this.format = new ParagraphFormat(this); return this.format; } set { SetParent(value); this.format = value; } } [DV] internal ParagraphFormat format; /// <summary> /// Gets the collection of document objects that defines the paragraph. /// </summary> public ParagraphElements Elements { get { if (this.elements == null) this.elements = new ParagraphElements(this); return this.elements; } set { SetParent(value); this.elements = value; } } [DV] internal ParagraphElements elements; /// <summary> /// Gets or sets a comment associated with this object. /// </summary> public string Comment { get { return this.comment.Value; } set { this.comment.Value = value; } } [DV] internal NString comment = NString.NullValue; #endregion #region Internal /// <summary> /// Allows the visitor object to visit the document object and it's child objects. /// </summary> void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren) { visitor.VisitParagraph(this); if (visitChildren && this.elements != null) ((IVisitable)this.elements).AcceptVisitor(visitor, visitChildren); } /// <summary> /// For internal use only. /// </summary> internal bool SerializeContentOnly { get { return serializeContentOnly; } set { serializeContentOnly = value; } } bool serializeContentOnly = false; /// <summary> /// Converts Paragraph into DDL. /// </summary> internal override void Serialize(Serializer serializer) { if (!serializeContentOnly) { serializer.WriteComment(this.comment.Value); serializer.WriteLine("\\paragraph"); int pos = serializer.BeginAttributes(); if (this.style.Value != "") serializer.WriteLine("Style = \"" + this.style.Value + "\""); if (!this.IsNull("Format")) this.format.Serialize(serializer, "Format", null); serializer.EndAttributes(pos); serializer.BeginContent(); if (!this.IsNull("Elements")) this.Elements.Serialize(serializer); serializer.CloseUpLine(); serializer.EndContent(); } else { this.Elements.Serialize(serializer); serializer.CloseUpLine(); } } /// <summary> /// Returns the meta object of this instance. /// </summary> internal override Meta Meta { get { if (meta == null) meta = new Meta(typeof(Paragraph)); return meta; } } /// <summary> /// Returns an array of Paragraphs that are separated by parabreaks. Null if no parabreak is found. /// </summary> internal Paragraph[] SplitOnParaBreak() { if (this.elements == null) return null; int startIdx = 0; ArrayList paragraphs = new ArrayList(); for (int idx = 0; idx < this.Elements.Count; ++idx) { DocumentObject element = this.Elements[idx]; if (element is Character) { Character character = (Character)element; if (character.SymbolName == SymbolName.ParaBreak) { Paragraph paragraph = new Paragraph(); paragraph.Format = this.Format.Clone(); paragraph.Style = this.Style; paragraph.Elements = SubsetElements(startIdx, idx - 1); startIdx = idx + 1; paragraphs.Add(paragraph); } } } if (startIdx == 0) //No paragraph breaks given. return null; else { Paragraph paragraph = new Paragraph(); paragraph.Format = this.Format.Clone(); paragraph.Style = this.Style; paragraph.Elements = SubsetElements(startIdx, this.elements.Count - 1); paragraphs.Add(paragraph); return (Paragraph[])paragraphs.ToArray(typeof(Paragraph)); } } /// <summary> /// Gets a subset of the paragraphs elements. /// </summary> /// <param name="startIdx">Start index of the required subset.</param> /// <param name="endIdx">End index of the required subset.</param> /// <returns>A ParagraphElements object with cloned elements.</returns> private ParagraphElements SubsetElements(int startIdx, int endIdx) { ParagraphElements paragraphElements = new ParagraphElements(); for (int idx = startIdx; idx <= endIdx; ++idx) { paragraphElements.Add((DocumentObject)this.elements[idx].Clone()); } return paragraphElements; } static Meta meta; #endregion } }
// Copyright 2007-2011 The Apache Software Foundation. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.FileSystem { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using Internal; using Logging; using Magnum.Extensions; using Magnum.FileSystem.Events; using Magnum.FileSystem.Internal; using Stact; public class PollingFileSystemEventProducer : IDisposable { readonly UntypedChannel _channel; readonly TimeSpan _checkInterval; readonly ChannelConnection _connection; readonly string _directory; readonly Fiber _fiber; readonly FileSystemEventProducer _fileSystemEventProducer; readonly Dictionary<string, Guid> _hashes; readonly Scheduler _scheduler; bool _disposed; ScheduledOperation _scheduledAction; static readonly ILog _logger = Logger.Get(typeof(PollingFileSystemEventProducer)); /// <summary> /// Creates a PollingFileSystemEventProducer /// </summary> /// <param name="directory">The directory to watch</param> /// <param name="channel">The channel where events should be sent</param> /// <param name="scheduler">Event scheduler</param> /// <param name="fiber">Fiber to schedule on</param> /// <param name="checkInterval">The maximal time between events or polls on a given file</param> public PollingFileSystemEventProducer(string directory, UntypedChannel channel, Scheduler scheduler, Fiber fiber, TimeSpan checkInterval) : this(directory, channel, scheduler, fiber, checkInterval, true) { } /// <summary> /// Creates a PollingFileSystemEventProducer /// </summary> /// <param name="directory">The directory to watch</param> /// <param name="channel">The channel where events should be sent</param> /// <param name="scheduler">Event scheduler</param> /// <param name="fiber">Fiber to schedule on</param> /// <param name="checkInterval">The maximal time between events or polls on a given file</param> /// <param name="checkSubDirectory">Indicates if subdirectorys will be checked or ignored</param> public PollingFileSystemEventProducer(string directory, UntypedChannel channel, [NotNull] Scheduler scheduler, Fiber fiber, TimeSpan checkInterval, bool checkSubDirectory) { if (scheduler == null) throw new ArgumentNullException("scheduler"); _directory = directory; _channel = channel; _fiber = fiber; _hashes = new Dictionary<string, Guid>(); _scheduler = scheduler; _checkInterval = checkInterval; _scheduledAction = scheduler.Schedule(3.Seconds(), _fiber, HashFileSystem); var myChannel = new ChannelAdapter(); _connection = myChannel.Connect(connectionConfigurator => { connectionConfigurator.AddConsumerOf<FileSystemChanged>().UsingConsumer(HandleFileSystemChangedAndCreated); connectionConfigurator.AddConsumerOf<FileSystemCreated>().UsingConsumer(HandleFileSystemChangedAndCreated); connectionConfigurator.AddConsumerOf<FileSystemRenamed>().UsingConsumer(HandleFileSystemRenamed); connectionConfigurator.AddConsumerOf<FileSystemDeleted>().UsingConsumer(HandleFileSystemDeleted); }); _fileSystemEventProducer = new FileSystemEventProducer(directory, myChannel, checkSubDirectory); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void HandleFileSystemChangedAndCreated(FileSystemEvent fileEvent) { HandleHash(fileEvent.Path, GenerateHashForFile(fileEvent.Path)); } void HandleFileSystemRenamed(FileSystemRenamed fileEvent) { HandleFileSystemChangedAndCreated(fileEvent); HandleFileSystemDeleted(new FileSystemDeletedImpl(fileEvent.OldName, fileEvent.OldPath)); } void HandleFileSystemDeleted(FileSystemEvent fileEvent) { RemoveHash(fileEvent.Path); } void HandleHash(string key, Guid newHash) { if (string.IsNullOrEmpty(key)) return; if (_hashes.ContainsKey(key)) { if (_hashes[key] != newHash) { _hashes[key] = newHash; _channel.Send(new FileChangedImpl(Path.GetFileName(key), key)); } } else { _hashes.Add(key, newHash); _channel.Send(new FileCreatedImpl(Path.GetFileName(key), key)); } } void RemoveHash(string key) { _hashes.Remove(key); _channel.Send(new FileSystemDeletedImpl(Path.GetFileName(key), key)); } void HashFileSystem() { try { var newHashes = new Dictionary<string, Guid>(); ProcessDirectory(newHashes, _directory); // process all the new hashes found newHashes.ToList().ForEach(x => HandleHash(x.Key, x.Value)); // remove any hashes we couldn't process _hashes.Where(x => !newHashes.ContainsKey(x.Key)).ToList().ConvertAll(x => x.Key).ForEach(RemoveHash); } finally { _scheduledAction = _scheduler.Schedule(_checkInterval, _fiber, HashFileSystem); } } void ProcessDirectory(Dictionary<string, Guid> hashes, string baseDirectory) { string[] files = Directory.GetFiles(baseDirectory); foreach (string file in files) { string fullFileName = Path.Combine(baseDirectory, file); hashes.Add(fullFileName, GenerateHashForFile(fullFileName)); } Directory.GetDirectories(baseDirectory).ToList().Each(dir => ProcessDirectory(hashes, dir)); } static Guid GenerateHashForFile(string file) { try { string hashValue; using (FileStream f = File.OpenRead(file)) using (var md5 = new MD5CryptoServiceProvider()) { byte[] fileHash = md5.ComputeHash(f); hashValue = BitConverter.ToString(fileHash).Replace("-", ""); } return new Guid(hashValue); } catch (Exception e) { _logger.ErrorFormat("Problem hashing file '{0}'. See the next log message for details.", file); // chew up exception and say empty hash // can we do something more interesting than this? // Henrik: perhaps log it so that we can abduce a better exception handling policy in the future? _logger.Error("Problem creating MD5 hash of file '{0}'. See inner exception details (have a look at the " + "piece of code generating this to have a look at whether we can do something better).", e); return Guid.Empty; } } void Dispose(bool disposing) { if (_disposed) return; if (disposing) { _scheduledAction.Cancel(); _connection.Dispose(); _fileSystemEventProducer.Dispose(); } _disposed = true; } } }
/* ==================================================================== 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. ==================================================================== */ /* * TestCellStyle.java * * Created on December 11, 2001, 5:51 PM */ namespace TestCases.HSSF.UserModel { using System; using System.IO; using NPOI.Util; using NPOI.HSSF.UserModel; using NUnit.Framework; using TestCases.HSSF; using NPOI.SS.UserModel; /** * Class to Test cell styling functionality * * @author Andrew C. Oliver */ [TestFixture] public class TestCellStyle { private static HSSFWorkbook OpenSample(String sampleFileName) { return HSSFTestDataSamples.OpenSampleWorkbook(sampleFileName); } /** Creates a new instance of TestCellStyle */ public TestCellStyle() { } /** * TEST NAME: Test Write Sheet Font <P> * OBJECTIVE: Test that HSSF can Create a simple spreadsheet with numeric and string values and styled with fonts.<P> * SUCCESS: HSSF Creates a sheet. Filesize Matches a known good. NPOI.SS.UserModel.Sheet objects * Last row, first row is Tested against the correct values (99,0).<P> * FAILURE: HSSF does not Create a sheet or excepts. Filesize does not Match the known good. * NPOI.SS.UserModel.Sheet last row or first row is incorrect. <P> * */ [Test] public void TestWriteSheetFont() { string filepath = TempFile.GetTempFilePath("TestWriteSheetFont", ".xls"); FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate); HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); IRow r = null; ICell c = null; IFont fnt = wb.CreateFont(); NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle(); fnt.Color=(NPOI.HSSF.Util.HSSFColor.Red.Index); fnt.Boldweight= (short)FontBoldWeight.Bold; cs.SetFont(fnt); for (short rownum = ( short ) 0; rownum < 100; rownum++) { r = s.CreateRow(rownum); // r.SetRowNum(( short ) rownum); for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2) { c = r.CreateCell(cellnum); c.SetCellValue(rownum * 10000 + cellnum + ((( double ) rownum / 1000) + (( double ) cellnum / 10000))); c = r.CreateCell(cellnum + 1); c.SetCellValue("TEST"); c.CellStyle = (cs); } } wb.Write(out1); out1.Close(); SanityChecker sanityChecker = new SanityChecker(); sanityChecker.CheckHSSFWorkbook(wb); Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99"); Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0"); // assert((s.LastRowNum == 99)); } /** * Tests that is creating a file with a date or an calendar works correctly. */ [Test] public void TestDataStyle() { string filepath = TempFile.GetTempFilePath("TestWriteSheetStyleDate", ".xls"); FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate); HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle(); IRow row = s.CreateRow(0); // with Date: ICell cell = row.CreateCell(1); cs.DataFormat=(HSSFDataFormat.GetBuiltinFormat("m/d/yy")); cell.CellStyle = (cs); cell.SetCellValue(DateTime.Now); // with Calendar: cell = row.CreateCell(2); cs.DataFormat=(HSSFDataFormat.GetBuiltinFormat("m/d/yy")); cell.CellStyle = (cs); cell.SetCellValue(DateTime.Now); wb.Write(out1); out1.Close(); SanityChecker sanityChecker = new SanityChecker(); sanityChecker.CheckHSSFWorkbook(wb); Assert.AreEqual(0, s.LastRowNum, "LAST ROW "); Assert.AreEqual(0, s.FirstRowNum,"FIRST ROW "); } [Test] public void TestHashEquals() { HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle(); NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle(); IRow row = s.CreateRow(0); ICell cell1 = row.CreateCell(1); ICell cell2 = row.CreateCell(2); cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy")); cs2.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy")); cell1.CellStyle = (cs1); cell1.SetCellValue(DateTime.Now); cell2.CellStyle = (cs2); cell2.SetCellValue(DateTime.Now); Assert.AreEqual(cs1.GetHashCode(), cs1.GetHashCode()); Assert.AreEqual(cs2.GetHashCode(), cs2.GetHashCode()); Assert.IsTrue(cs1.Equals(cs1)); Assert.IsTrue(cs2.Equals(cs2)); // Change cs1, hash will alter int hash1 = cs1.GetHashCode(); cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy")); Assert.IsFalse(hash1 == cs1.GetHashCode()); } /** * TEST NAME: Test Write Sheet Style <P> * OBJECTIVE: Test that HSSF can Create a simple spreadsheet with numeric and string values and styled with colors * and borders.<P> * SUCCESS: HSSF Creates a sheet. Filesize Matches a known good. NPOI.SS.UserModel.Sheet objects * Last row, first row is Tested against the correct values (99,0).<P> * FAILURE: HSSF does not Create a sheet or excepts. Filesize does not Match the known good. * NPOI.SS.UserModel.Sheet last row or first row is incorrect. <P> * */ [Test] public void TestWriteSheetStyle() { string filepath = TempFile.GetTempFilePath("TestWriteSheetStyle", ".xls"); FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate); HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); IRow r = null; ICell c = null; IFont fnt = wb.CreateFont(); NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle(); NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle(); cs.BorderBottom= (BorderStyle.Thin); cs.BorderLeft= (BorderStyle.Thin); cs.BorderRight= (BorderStyle.Thin); cs.BorderTop= (BorderStyle.Thin); cs.FillForegroundColor= ( short ) 0xA; cs.FillPattern = FillPattern.SolidForeground; fnt.Color= ( short ) 0xf; fnt.IsItalic= (true); cs2.FillForegroundColor= ( short ) 0x0; cs2.FillPattern= FillPattern.SolidForeground; cs2.SetFont(fnt); for (short rownum = ( short ) 0; rownum < 100; rownum++) { r = s.CreateRow(rownum); // r.SetRowNum(( short ) rownum); for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2) { c = r.CreateCell(cellnum); c.SetCellValue(rownum * 10000 + cellnum + ((( double ) rownum / 1000) + (( double ) cellnum / 10000))); c.CellStyle = (cs); c = r.CreateCell(cellnum + 1); c.SetCellValue("TEST"); c.CellStyle = (cs2); } } wb.Write(out1); out1.Close(); SanityChecker sanityChecker = new SanityChecker(); sanityChecker.CheckHSSFWorkbook(wb); Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99"); Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0"); // assert((s.LastRowNum == 99)); } /** * Cloning one NPOI.SS.UserModel.CellType onto Another, same * HSSFWorkbook */ [Test] public void TestCloneStyleSameWB() { HSSFWorkbook wb = new HSSFWorkbook(); IFont fnt = wb.CreateFont(); fnt.FontName=("TestingFont"); Assert.AreEqual(5, wb.NumberOfFonts); NPOI.SS.UserModel.ICellStyle orig = wb.CreateCellStyle(); orig.Alignment=(HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat=((short)18); Assert.AreEqual(HorizontalAlignment.Right,orig.Alignment); Assert.AreEqual(fnt,orig.GetFont(wb)); Assert.AreEqual(18,orig.DataFormat); NPOI.SS.UserModel.ICellStyle clone = wb.CreateCellStyle(); Assert.AreNotEqual(HorizontalAlignment.Right , clone.Alignment); Assert.AreNotEqual(fnt, clone.GetFont(wb)); Assert.AreNotEqual(18, clone.DataFormat); clone.CloneStyleFrom(orig); Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(fnt, clone.GetFont(wb)); Assert.AreEqual(18, clone.DataFormat); Assert.AreEqual(5, wb.NumberOfFonts); orig.Alignment = HorizontalAlignment.Left; Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); } /** * Cloning one NPOI.SS.UserModel.CellType onto Another, across * two different HSSFWorkbooks */ [Test] public void TestCloneStyleDiffWB() { HSSFWorkbook wbOrig = new HSSFWorkbook(); IFont fnt = wbOrig.CreateFont(); fnt.FontName=("TestingFont"); Assert.AreEqual(5, wbOrig.NumberOfFonts); IDataFormat fmt = wbOrig.CreateDataFormat(); fmt.GetFormat("MadeUpOne"); fmt.GetFormat("MadeUpTwo"); NPOI.SS.UserModel.ICellStyle orig = wbOrig.CreateCellStyle(); orig.Alignment = (HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat=(fmt.GetFormat("Test##")); Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(fnt,orig.GetFont(wbOrig)); Assert.AreEqual(fmt.GetFormat("Test##") , orig.DataFormat); // Now a style on another workbook HSSFWorkbook wbClone = new HSSFWorkbook(); Assert.AreEqual(4, wbClone.NumberOfFonts); IDataFormat fmtClone = wbClone.CreateDataFormat(); NPOI.SS.UserModel.ICellStyle clone = wbClone.CreateCellStyle(); Assert.AreEqual(4, wbClone.NumberOfFonts); Assert.AreNotEqual(HorizontalAlignment.Right,clone.Alignment); Assert.AreNotEqual("TestingFont", clone.GetFont(wbClone).FontName); clone.CloneStyleFrom(orig); Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreEqual("TestingFont" ,clone.GetFont(wbClone).FontName); Assert.AreEqual(fmtClone.GetFormat("Test##"),clone.DataFormat); Assert.AreNotEqual(fmtClone.GetFormat("Test##") , fmt.GetFormat("Test##")); Assert.AreEqual(5, wbClone.NumberOfFonts); } [Test] public void TestStyleNames() { HSSFWorkbook wb = OpenSample("WithExtendedStyles.xls"); NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0); ICell c1 = s.GetRow(0).GetCell(0); ICell c2 = s.GetRow(1).GetCell(0); ICell c3 = s.GetRow(2).GetCell(0); HSSFCellStyle cs1 = (HSSFCellStyle)c1.CellStyle; HSSFCellStyle cs2 = (HSSFCellStyle)c2.CellStyle; HSSFCellStyle cs3 = (HSSFCellStyle)c3.CellStyle; Assert.IsNotNull(cs1); Assert.IsNotNull(cs2); Assert.IsNotNull(cs3); // Check we got the styles we'd expect Assert.AreEqual(10, cs1.GetFont(wb).FontHeightInPoints); Assert.AreEqual(9, cs2.GetFont(wb).FontHeightInPoints); Assert.AreEqual(12, cs3.GetFont(wb).FontHeightInPoints); Assert.AreEqual(15, cs1.Index); Assert.AreEqual(23, cs2.Index); Assert.AreEqual(24, cs3.Index); Assert.IsNull(cs1.ParentStyle); Assert.IsNotNull(cs2.ParentStyle); Assert.IsNotNull(cs3.ParentStyle); Assert.AreEqual(21, cs2.ParentStyle.Index); Assert.AreEqual(22, cs3.ParentStyle.Index); // Now Check we can get style records for // the parent ones Assert.IsNull(wb.Workbook.GetStyleRecord(15)); Assert.IsNull(wb.Workbook.GetStyleRecord(23)); Assert.IsNull(wb.Workbook.GetStyleRecord(24)); Assert.IsNotNull(wb.Workbook.GetStyleRecord(21)); Assert.IsNotNull(wb.Workbook.GetStyleRecord(22)); // Now Check the style names Assert.AreEqual(null, cs1.UserStyleName); Assert.AreEqual(null, cs2.UserStyleName); Assert.AreEqual(null, cs3.UserStyleName); Assert.AreEqual("style1", cs2.ParentStyle.UserStyleName); Assert.AreEqual("style2", cs3.ParentStyle.UserStyleName); // now apply a named style to a new cell ICell c4 = s.GetRow(0).CreateCell(1); c4.CellStyle = (cs2); Assert.AreEqual("style1", ((HSSFCellStyle)c4.CellStyle).ParentStyle.UserStyleName); } [Test] public void TestGetSetBorderHair() { HSSFWorkbook wb = OpenSample("55341_CellStyleBorder.xls"); ISheet s = wb.GetSheetAt(0); ICellStyle cs; cs = s.GetRow(0).GetCell(0).CellStyle; Assert.AreEqual(BorderStyle.Hair, cs.BorderRight); cs = s.GetRow(1).GetCell(1).CellStyle; Assert.AreEqual(BorderStyle.Dotted, cs.BorderRight); cs = s.GetRow(2).GetCell(2).CellStyle; Assert.AreEqual(BorderStyle.DashDotDot, cs.BorderRight); cs = s.GetRow(3).GetCell(3).CellStyle; Assert.AreEqual(BorderStyle.Dashed, cs.BorderRight); cs = s.GetRow(4).GetCell(4).CellStyle; Assert.AreEqual(BorderStyle.Thin, cs.BorderRight); cs = s.GetRow(5).GetCell(5).CellStyle; Assert.AreEqual(BorderStyle.MediumDashDotDot, cs.BorderRight); cs = s.GetRow(6).GetCell(6).CellStyle; Assert.AreEqual(BorderStyle.SlantedDashDot, cs.BorderRight); cs = s.GetRow(7).GetCell(7).CellStyle; Assert.AreEqual(BorderStyle.MediumDashDot, cs.BorderRight); cs = s.GetRow(8).GetCell(8).CellStyle; Assert.AreEqual(BorderStyle.MediumDashed, cs.BorderRight); cs = s.GetRow(9).GetCell(9).CellStyle; Assert.AreEqual(BorderStyle.Medium, cs.BorderRight); cs = s.GetRow(10).GetCell(10).CellStyle; Assert.AreEqual(BorderStyle.Thick, cs.BorderRight); cs = s.GetRow(11).GetCell(11).CellStyle; Assert.AreEqual(BorderStyle.Double, cs.BorderRight); } [Test] public void TestShrinkToFit() { // Existing file IWorkbook wb = OpenSample("ShrinkToFit.xls"); ISheet s = wb.GetSheetAt(0); IRow r = s.GetRow(0); ICellStyle cs = r.GetCell(0).CellStyle; Assert.AreEqual(true, cs.ShrinkToFit); // New file IWorkbook wbOrig = new HSSFWorkbook(); s = wbOrig.CreateSheet(); r = s.CreateRow(0); cs = wbOrig.CreateCellStyle(); cs.ShrinkToFit = (/*setter*/false); r.CreateCell(0).CellStyle = (/*setter*/cs); cs = wbOrig.CreateCellStyle(); cs.ShrinkToFit = (/*setter*/true); r.CreateCell(1).CellStyle = (/*setter*/cs); // Write out1, Read, and check wb = HSSFTestDataSamples.WriteOutAndReadBack(wbOrig as HSSFWorkbook); s = wb.GetSheetAt(0); r = s.GetRow(0); Assert.AreEqual(false, r.GetCell(0).CellStyle.ShrinkToFit); Assert.AreEqual(true, r.GetCell(1).CellStyle.ShrinkToFit); } } }
/* * Copyright (c) 2006-2014, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.InteropServices; using System.Globalization; namespace OpenMetaverse { /// <summary> /// A two-dimensional vector with floating-point values /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector2 : IComparable<Vector2>, IEquatable<Vector2> { /// <summary>X value</summary> public float X; /// <summary>Y value</summary> public float Y; #region Constructors public Vector2(float x, float y) { X = x; Y = y; } public Vector2(float value) { X = value; Y = value; } public Vector2(Vector2 vector) { X = vector.X; Y = vector.Y; } #endregion Constructors #region Public Methods /// <summary> /// Test if this vector is equal to another vector, within a given /// tolerance range /// </summary> /// <param name="vec">Vector to test against</param> /// <param name="tolerance">The acceptable magnitude of difference /// between the two vectors</param> /// <returns>True if the magnitude of difference between the two vectors /// is less than the given tolerance, otherwise false</returns> public bool ApproxEquals(Vector2 vec, float tolerance) { Vector2 diff = this - vec; return (diff.LengthSquared() <= tolerance * tolerance); } /// <summary> /// Test if this vector is composed of all finite numbers /// </summary> public bool IsFinite() { return Utils.IsFinite(X) && Utils.IsFinite(Y); } /// <summary> /// IComparable.CompareTo implementation /// </summary> public int CompareTo(Vector2 vector) { return Length().CompareTo(vector.Length()); } /// <summary> /// Builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing two four-byte floats</param> /// <param name="pos">Beginning position in the byte array</param> public void FromBytes(byte[] byteArray, int pos) { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[8]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 8); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); } } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <returns>An eight-byte array containing X and Y</returns> public byte[] GetBytes() { byte[] byteArray = new byte[8]; ToBytes(byteArray, 0); return byteArray; } /// <summary> /// Writes the raw bytes for this vector to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 8 bytes before the end of the array</param> public void ToBytes(byte[] dest, int pos) { Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4); if (!BitConverter.IsLittleEndian) { Array.Reverse(dest, pos + 0, 4); Array.Reverse(dest, pos + 4, 4); } } public float Length() { return (float)Math.Sqrt(DistanceSquared(this, Zero)); } public float LengthSquared() { return DistanceSquared(this, Zero); } public void Normalize() { this = Normalize(this); } #endregion Public Methods #region Static Methods public static Vector2 Add(Vector2 value1, Vector2 value2) { value1.X += value2.X; value1.Y += value2.Y; return value1; } public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { return new Vector2( Utils.Clamp(value1.X, min.X, max.X), Utils.Clamp(value1.Y, min.Y, max.Y)); } public static float Distance(Vector2 value1, Vector2 value2) { return (float)Math.Sqrt(DistanceSquared(value1, value2)); } public static float DistanceSquared(Vector2 value1, Vector2 value2) { return (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y); } public static Vector2 Divide(Vector2 value1, Vector2 value2) { value1.X /= value2.X; value1.Y /= value2.Y; return value1; } public static Vector2 Divide(Vector2 value1, float divider) { float factor = 1 / divider; value1.X *= factor; value1.Y *= factor; return value1; } public static float Dot(Vector2 value1, Vector2 value2) { return value1.X * value2.X + value1.Y * value2.Y; } public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return new Vector2( Utils.Lerp(value1.X, value2.X, amount), Utils.Lerp(value1.Y, value2.Y, amount)); } public static Vector2 Max(Vector2 value1, Vector2 value2) { return new Vector2( Math.Max(value1.X, value2.X), Math.Max(value1.Y, value2.Y)); } public static Vector2 Min(Vector2 value1, Vector2 value2) { return new Vector2( Math.Min(value1.X, value2.X), Math.Min(value1.Y, value2.Y)); } public static Vector2 Multiply(Vector2 value1, Vector2 value2) { value1.X *= value2.X; value1.Y *= value2.Y; return value1; } public static Vector2 Multiply(Vector2 value1, float scaleFactor) { value1.X *= scaleFactor; value1.Y *= scaleFactor; return value1; } public static Vector2 Negate(Vector2 value) { value.X = -value.X; value.Y = -value.Y; return value; } public static Vector2 Normalize(Vector2 value) { const float MAG_THRESHOLD = 0.0000001f; float factor = DistanceSquared(value, Zero); if (factor > MAG_THRESHOLD) { factor = 1f / (float)Math.Sqrt(factor); value.X *= factor; value.Y *= factor; } else { value.X = 0f; value.Y = 0f; } return value; } /// <summary> /// Parse a vector from a string /// </summary> /// <param name="val">A string representation of a 2D vector, enclosed /// in arrow brackets and separated by commas</param> public static Vector3 Parse(string val) { char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector3( float.Parse(split[0].Trim(), Utils.EnUsCulture), float.Parse(split[1].Trim(), Utils.EnUsCulture), float.Parse(split[2].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector3 result) { try { result = Parse(val); return true; } catch (Exception) { result = Vector3.Zero; return false; } } /// <summary> /// Interpolates between two vectors using a cubic equation /// </summary> public static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount) { return new Vector2( Utils.SmoothStep(value1.X, value2.X, amount), Utils.SmoothStep(value1.Y, value2.Y, amount)); } public static Vector2 Subtract(Vector2 value1, Vector2 value2) { value1.X -= value2.X; value1.Y -= value2.Y; return value1; } public static Vector2 Transform(Vector2 position, Matrix4 matrix) { position.X = (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41; position.Y = (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42; return position; } public static Vector2 TransformNormal(Vector2 position, Matrix4 matrix) { position.X = (position.X * matrix.M11) + (position.Y * matrix.M21); position.Y = (position.X * matrix.M12) + (position.Y * matrix.M22); return position; } #endregion Static Methods #region Overrides public override bool Equals(object obj) { return (obj is Vector2) ? this == ((Vector2)obj) : false; } public bool Equals(Vector2 other) { return this == other; } public override int GetHashCode() { int hash = X.GetHashCode(); hash = hash * 31 + Y.GetHashCode(); return hash; } /// <summary> /// Get a formatted string representation of the vector /// </summary> /// <returns>A string representation of the vector</returns> public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}>", X, Y); } /// <summary> /// Get a string representation of the vector elements with up to three /// decimal digits and separated by spaces only /// </summary> /// <returns>Raw string representation of the vector</returns> public string ToRawString() { CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; return String.Format(enUs, "{0} {1}", X, Y); } #endregion Overrides #region Operators public static bool operator ==(Vector2 value1, Vector2 value2) { return value1.X == value2.X && value1.Y == value2.Y; } public static bool operator !=(Vector2 value1, Vector2 value2) { return value1.X != value2.X || value1.Y != value2.Y; } public static Vector2 operator +(Vector2 value1, Vector2 value2) { value1.X += value2.X; value1.Y += value2.Y; return value1; } public static Vector2 operator -(Vector2 value) { value.X = -value.X; value.Y = -value.Y; return value; } public static Vector2 operator -(Vector2 value1, Vector2 value2) { value1.X -= value2.X; value1.Y -= value2.Y; return value1; } public static Vector2 operator *(Vector2 value1, Vector2 value2) { value1.X *= value2.X; value1.Y *= value2.Y; return value1; } public static Vector2 operator *(Vector2 value, float scaleFactor) { value.X *= scaleFactor; value.Y *= scaleFactor; return value; } public static Vector2 operator /(Vector2 value1, Vector2 value2) { value1.X /= value2.X; value1.Y /= value2.Y; return value1; } public static Vector2 operator /(Vector2 value1, float divider) { float factor = 1 / divider; value1.X *= factor; value1.Y *= factor; return value1; } #endregion Operators /// <summary>A vector with a value of 0,0</summary> public readonly static Vector2 Zero = new Vector2(); /// <summary>A vector with a value of 1,1</summary> public readonly static Vector2 One = new Vector2(1f, 1f); /// <summary>A vector with a value of 1,0</summary> public readonly static Vector2 UnitX = new Vector2(1f, 0f); /// <summary>A vector with a value of 0,1</summary> public readonly static Vector2 UnitY = new Vector2(0f, 1f); } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Collections.Generic; using NUnit.Framework; using Quartz.Impl.Calendar; using Quartz.Impl.Matchers; using Quartz.Impl.Triggers; using Quartz.Job; using Quartz.Simpl; using Quartz.Spi; using System.Collections.Specialized; using System.Globalization; using System.Threading; namespace Quartz.Impl.RavenDB.Tests { /// <summary> /// Unit tests for RavenJobStore, based on the RAMJobStore tests with minor changes /// (originally submitted by Johannes Zillmann) /// </summary> [TestFixture] public class RavenJobStoreUnitTests { private IJobStore fJobStore; private JobDetailImpl fJobDetail; private SampleSignaler fSignaler; [SetUp] public void SetUp() { fJobStore = new RavenJobStore(); fJobStore.ClearAllSchedulingData(); Thread.Sleep(1000); } private void InitJobStore() { fJobStore = new RavenJobStore(); fJobStore.ClearAllSchedulingData(); fSignaler = new SampleSignaler(); fJobStore.Initialize(null, fSignaler); fJobStore.SchedulerStarted(); fJobDetail = new JobDetailImpl("job1", "jobGroup1", typeof(NoOpJob)); fJobDetail.Durable = true; fJobStore.StoreJob(fJobDetail, true); } [Test] public void TestAcquireNextTrigger() { InitJobStore(); DateTimeOffset d = DateBuilder.EvenMinuteDateAfterNow(); IOperableTrigger trigger1 = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(200), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger2 = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(50), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger3 = new SimpleTriggerImpl("trigger1", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(100), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger1.ComputeFirstFireTimeUtc(null); trigger2.ComputeFirstFireTimeUtc(null); trigger3.ComputeFirstFireTimeUtc(null); fJobStore.StoreTrigger(trigger1, false); fJobStore.StoreTrigger(trigger2, false); fJobStore.StoreTrigger(trigger3, false); DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value; Assert.AreEqual(0, fJobStore.AcquireNextTriggers(d.AddMilliseconds(10), 1, TimeSpan.Zero).Count); Assert.AreEqual(trigger2, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(trigger1, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(0, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero).Count); // release trigger3 fJobStore.ReleaseAcquiredTrigger(trigger3); Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]); } [Test] public void TestAcquireNextTriggerBatch() { InitJobStore(); DateTimeOffset d = DateBuilder.EvenMinuteDateAfterNow(); IOperableTrigger early = new SimpleTriggerImpl("early", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d, d.AddMilliseconds(5), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger1 = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200000), d.AddMilliseconds(200005), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger2 = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200100), d.AddMilliseconds(200105), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger3 = new SimpleTriggerImpl("trigger3", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200200), d.AddMilliseconds(200205), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger4 = new SimpleTriggerImpl("trigger4", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200300), d.AddMilliseconds(200305), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger10 = new SimpleTriggerImpl("trigger10", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(500000), d.AddMilliseconds(700000), 2, TimeSpan.FromSeconds(2)); early.ComputeFirstFireTimeUtc(null); trigger1.ComputeFirstFireTimeUtc(null); trigger2.ComputeFirstFireTimeUtc(null); trigger3.ComputeFirstFireTimeUtc(null); trigger4.ComputeFirstFireTimeUtc(null); trigger10.ComputeFirstFireTimeUtc(null); fJobStore.StoreTrigger(early, false); fJobStore.StoreTrigger(trigger1, false); fJobStore.StoreTrigger(trigger2, false); fJobStore.StoreTrigger(trigger3, false); fJobStore.StoreTrigger(trigger4, false); fJobStore.StoreTrigger(trigger10, false); DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value; IList<IOperableTrigger> acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 4, TimeSpan.FromSeconds(1)); Assert.AreEqual(4, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); acquiredTriggers = this.fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 5, TimeSpan.FromMilliseconds(1000)); Assert.AreEqual(5, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); Assert.AreEqual(trigger4.Key, acquiredTriggers[4].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 6, TimeSpan.FromSeconds(1)); Assert.AreEqual(5, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); Assert.AreEqual(trigger4.Key, acquiredTriggers[4].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(1), 5, TimeSpan.Zero); Assert.AreEqual(2, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(250), 5, TimeSpan.FromMilliseconds(199)); Assert.AreEqual(5, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(150), 5, TimeSpan.FromMilliseconds(50L)); Assert.AreEqual(4, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); } [Test] public void TestTriggerStates() { InitJobStore(); IOperableTrigger trigger = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, DateTimeOffset.Now.AddSeconds(100), DateTimeOffset.Now.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(TriggerState.None, fJobStore.GetTriggerState(trigger.Key)); fJobStore.StoreTrigger(trigger, false); Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(trigger.Key)); fJobStore.PauseTrigger(trigger.Key); Assert.AreEqual(TriggerState.Paused, fJobStore.GetTriggerState(trigger.Key)); fJobStore.ResumeTrigger(trigger.Key); Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(trigger.Key)); trigger = fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]; Assert.IsNotNull(trigger); fJobStore.ReleaseAcquiredTrigger(trigger); trigger = fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]; Assert.IsNotNull(trigger); Assert.AreEqual(0, fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1)).Count); } [Test] public void TestRemoveCalendarWhenTriggersPresent() { InitJobStore(); // QRTZNET-29 IOperableTrigger trigger = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, DateTimeOffset.Now.AddSeconds(100), DateTimeOffset.Now.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger.ComputeFirstFireTimeUtc(null); ICalendar cal = new MonthlyCalendar(); fJobStore.StoreTrigger(trigger, false); fJobStore.StoreCalendar("cal", cal, false, true); fJobStore.RemoveCalendar("cal"); } [Test] public void TestStoreTriggerReplacesTrigger() { InitJobStore(); string jobName = "StoreJobReplacesJob"; string jobGroup = "StoreJobReplacesJobGroup"; JobDetailImpl detail = new JobDetailImpl(jobName, jobGroup, typeof (NoOpJob)); fJobStore.StoreJob(detail, false); string trName = "StoreTriggerReplacesTrigger"; string trGroup = "StoreTriggerReplacesTriggerGroup"; IOperableTrigger tr = new SimpleTriggerImpl(trName, trGroup, DateTimeOffset.Now); tr.JobKey = new JobKey(jobName, jobGroup); tr.CalendarName = null; fJobStore.StoreTrigger(tr, false); Assert.AreEqual(tr, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup))); tr.CalendarName = "NonExistingCalendar"; fJobStore.StoreTrigger(tr, true); Assert.AreEqual(tr, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup))); Assert.AreEqual(tr.CalendarName, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup)).CalendarName, "StoreJob doesn't replace triggers"); bool exceptionRaised = false; try { fJobStore.StoreTrigger(tr, false); } catch (ObjectAlreadyExistsException) { exceptionRaised = true; } Assert.IsTrue(exceptionRaised, "an attempt to store duplicate trigger succeeded"); } [Test] public void PauseJobGroupPausesNewJob() { InitJobStore(); string jobName1 = "PauseJobGroupPausesNewJob"; string jobName2 = "PauseJobGroupPausesNewJob2"; string jobGroup = "PauseJobGroupPausesNewJobGroup"; JobDetailImpl detail = new JobDetailImpl(jobName1, jobGroup, typeof (NoOpJob)); detail.Durable = true; fJobStore.StoreJob(detail, false); fJobStore.PauseJobs(GroupMatcher<JobKey>.GroupEquals(jobGroup)); detail = new JobDetailImpl(jobName2, jobGroup, typeof (NoOpJob)); detail.Durable = true; fJobStore.StoreJob(detail, false); string trName = "PauseJobGroupPausesNewJobTrigger"; string trGroup = "PauseJobGroupPausesNewJobTriggerGroup"; IOperableTrigger tr = new SimpleTriggerImpl(trName, trGroup, DateTimeOffset.UtcNow); tr.JobKey = new JobKey(jobName2, jobGroup); fJobStore.StoreTrigger(tr, false); Assert.AreEqual(TriggerState.Paused, fJobStore.GetTriggerState(tr.Key)); } [Test] public void TestRetrieveJob_NoJobFound() { InitJobStore(); var store = new RavenJobStore(); IJobDetail job = store.RetrieveJob(new JobKey("not", "existing")); Assert.IsNull(job); } [Test] public void TestRetrieveTrigger_NoTriggerFound() { InitJobStore(); var store = new RavenJobStore(); IOperableTrigger trigger = store.RetrieveTrigger(new TriggerKey("not", "existing")); Assert.IsNull(trigger); } [Test] public void testStoreAndRetrieveJobs() { InitJobStore(); var store = new RavenJobStore(); // Store jobs. for (int i = 0; i < 10; i++) { IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); store.StoreJob(job, false); } // Retrieve jobs. for (int i = 0; i < 10; i++) { JobKey jobKey = JobKey.Create("job" + i); IJobDetail storedJob = store.RetrieveJob(jobKey); Assert.AreEqual(jobKey, storedJob.Key); } } [Test] public void TestStoreAndRetrieveTriggers() { InitJobStore(); var store = new RavenJobStore(); store.SchedulerStarted(); // Store jobs and triggers. for (int i = 0; i < 10; i++) { IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); store.StoreJob(job, true); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.Create(); ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger" + i).WithSchedule(schedule).ForJob(job).Build(); store.StoreTrigger((IOperableTrigger) trigger, true); } // Retrieve job and trigger. for (int i = 0; i < 10; i++) { JobKey jobKey = JobKey.Create("job" + i); IJobDetail storedJob = store.RetrieveJob(jobKey); Assert.AreEqual(jobKey, storedJob.Key); TriggerKey triggerKey = new TriggerKey("trigger" + i); ITrigger storedTrigger = store.RetrieveTrigger(triggerKey); Assert.AreEqual(triggerKey, storedTrigger.Key); } } [Test] public void TestAcquireTriggers() { InitJobStore(); ISchedulerSignaler schedSignaler = new SampleSignaler(); ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); var store = new RavenJobStore(); store.Initialize(loadHelper, schedSignaler); store.SchedulerStarted(); // Setup: Store jobs and triggers. DateTime startTime0 = DateTime.UtcNow.AddMinutes(1).ToUniversalTime(); // a min from now. for (int i = 0; i < 10; i++) { DateTime startTime = startTime0.AddMinutes(i*1); // a min apart IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.RepeatMinutelyForever(2); IOperableTrigger trigger = (IOperableTrigger) TriggerBuilder.Create().WithIdentity("trigger" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build(); // Manually trigger the first fire time computation that scheduler would do. Otherwise // the store.acquireNextTriggers() will not work properly. DateTimeOffset? fireTime = trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(true, fireTime != null); store.StoreJobAndTrigger(job, trigger); } // Test acquire one trigger at a time for (int i = 0; i < 10; i++) { DateTimeOffset noLaterThan = startTime0.AddMinutes(i); int maxCount = 1; TimeSpan timeWindow = TimeSpan.Zero; IList<IOperableTrigger> triggers = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow); Assert.AreEqual(1, triggers.Count); Assert.AreEqual("trigger" + i, triggers[0].Key.Name); // Let's remove the trigger now. store.RemoveJob(triggers[0].JobKey); } } [Test] public void TestAcquireTriggersInBatch() { InitJobStore(); ISchedulerSignaler schedSignaler = new SampleSignaler(); ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); var store = new RavenJobStore(); store.Initialize(loadHelper, schedSignaler); // Setup: Store jobs and triggers. DateTimeOffset startTime0 = DateTimeOffset.UtcNow.AddMinutes(1); // a min from now. for (int i = 0; i < 10; i++) { DateTimeOffset startTime = startTime0.AddMinutes(i); // a min apart IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.RepeatMinutelyForever(2); IOperableTrigger trigger = (IOperableTrigger) TriggerBuilder.Create().WithIdentity("trigger" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build(); // Manually trigger the first fire time computation that scheduler would do. Otherwise // the store.acquireNextTriggers() will not work properly. DateTimeOffset? fireTime = trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(true, fireTime != null); store.StoreJobAndTrigger(job, trigger); } // Test acquire batch of triggers at a time DateTimeOffset noLaterThan = startTime0.AddMinutes(10); int maxCount = 7; TimeSpan timeWindow = TimeSpan.FromMinutes(8); IList<IOperableTrigger> triggers = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow); Assert.AreEqual(7, triggers.Count); for (int i = 0; i < 7; i++) { Assert.AreEqual("trigger" + i, triggers[i].Key.Name); } } [Test] public void TestBasicStorageFunctions() { var sched = CreateScheduler("TestBasicStorageFunctions", 2); sched.Start(); // test basic storage functions of scheduler... IJobDetail job = JobBuilder.Create() .OfType<TestJob>() .WithIdentity("j1") .StoreDurably() .Build(); Assert.IsFalse(sched.CheckExists(new JobKey("j1")), "Unexpected existence of job named 'j1'."); sched.AddJob(job, false); Assert.IsTrue(sched.CheckExists(new JobKey("j1")), "Expected existence of job named 'j1' but checkExists return false."); job = sched.GetJobDetail(new JobKey("j1")); Assert.IsNotNull(job, "Stored job not found!"); sched.DeleteJob(new JobKey("j1")); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("t1") .ForJob(job) .StartNow() .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5)) .Build(); Assert.IsFalse(sched.CheckExists(new TriggerKey("t1")), "Unexpected existence of trigger named '11'."); sched.ScheduleJob(job, trigger); Assert.IsTrue(sched.CheckExists(new TriggerKey("t1")), "Expected existence of trigger named 't1' but checkExists return false."); job = sched.GetJobDetail(new JobKey("j1")); Assert.IsNotNull(job, "Stored job not found!"); trigger = sched.GetTrigger(new TriggerKey("t1")); Assert.IsNotNull(trigger, "Stored trigger not found!"); job = JobBuilder.Create() .OfType<TestJob>() .WithIdentity("j2", "g1") .Build(); trigger = TriggerBuilder.Create() .WithIdentity("t2", "g1") .ForJob(job) .StartNow() .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5)) .Build(); sched.ScheduleJob(job, trigger); job = JobBuilder.Create() .OfType<TestJob>() .WithIdentity("j3", "g1") .Build(); trigger = TriggerBuilder.Create() .WithIdentity("t3", "g1") .ForJob(job) .StartNow() .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5)) .Build(); sched.ScheduleJob(job, trigger); IList<string> jobGroups = sched.GetJobGroupNames(); IList<string> triggerGroups = sched.GetTriggerGroupNames(); Assert.AreEqual(2, jobGroups.Count, "Job group list size expected to be = 2 "); Assert.AreEqual(2, triggerGroups.Count, "Trigger group list size expected to be = 2 "); Collection.ISet<JobKey> jobKeys = sched.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(JobKey.DefaultGroup)); Collection.ISet<TriggerKey> triggerKeys = sched.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(TriggerKey.DefaultGroup)); Assert.AreEqual(1, jobKeys.Count, "Number of jobs expected in default group was 1 "); Assert.AreEqual(1, triggerKeys.Count, "Number of triggers expected in default group was 1 "); jobKeys = sched.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("g1")); triggerKeys = sched.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("g1")); Assert.AreEqual(2, jobKeys.Count, "Number of jobs expected in 'g1' group was 2 "); Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 2 "); TriggerState s = sched.GetTriggerState(new TriggerKey("t2", "g1")); Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL "); sched.PauseTrigger(new TriggerKey("t2", "g1")); s = sched.GetTriggerState(new TriggerKey("t2", "g1")); Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED "); sched.ResumeTrigger(new TriggerKey("t2", "g1")); s = sched.GetTriggerState(new TriggerKey("t2", "g1")); Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL "); Collection.ISet<string> pausedGroups = sched.GetPausedTriggerGroups(); Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 "); sched.PauseTriggers(GroupMatcher<TriggerKey>.GroupEquals("g1")); // test that adding a trigger to a paused group causes the new trigger to be paused also... job = JobBuilder.Create() .OfType<TestJob>() .WithIdentity("j4", "g1") .Build(); trigger = TriggerBuilder.Create() .WithIdentity("t4", "g1") .ForJob(job) .StartNow() .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5)) .Build(); sched.ScheduleJob(job, trigger); pausedGroups = sched.GetPausedTriggerGroups(); Assert.AreEqual(1, pausedGroups.Count, "Size of paused trigger groups list expected to be 1 "); s = sched.GetTriggerState(new TriggerKey("t2", "g1")); Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED "); s = sched.GetTriggerState(new TriggerKey("t4", "g1")); Assert.AreEqual(TriggerState.Paused, s, "State of trigger t4 expected to be PAUSED"); sched.ResumeTriggers(GroupMatcher<TriggerKey>.GroupEquals("g1")); s = sched.GetTriggerState(new TriggerKey("t2", "g1")); Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL "); s = sched.GetTriggerState(new TriggerKey("t4", "g1")); Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL "); pausedGroups = sched.GetPausedTriggerGroups(); Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 "); Assert.IsFalse(sched.UnscheduleJob(new TriggerKey("foasldfksajdflk")), "Scheduler should have returned 'false' from attempt to unschedule non-existing trigger. "); Assert.IsTrue(sched.UnscheduleJob(new TriggerKey("t3", "g1")), "Scheduler should have returned 'true' from attempt to unschedule existing trigger. "); jobKeys = sched.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("g1")); triggerKeys = sched.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("g1")); Assert.AreEqual(2, jobKeys.Count, "Number of jobs expected in 'g1' group was 2 "); // job should have been deleted also, because it is non-durable Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 2 "); Assert.IsTrue(sched.UnscheduleJob(new TriggerKey("t1")), "Scheduler should have returned 'true' from attempt to unschedule existing trigger. "); jobKeys = sched.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(JobKey.DefaultGroup)); triggerKeys = sched.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(TriggerKey.DefaultGroup)); Assert.AreEqual(1, jobKeys.Count, "Number of jobs expected in default group was 1 "); // job should have been left in place, because it is non-durable Assert.AreEqual(0, triggerKeys.Count, "Number of triggers expected in default group was 0 "); sched.Shutdown(); } private IScheduler CreateScheduler(string name, int threadCount) { NameValueCollection properties = new NameValueCollection { // Setting some scheduler properties ["quartz.scheduler.instanceName"] = name + "Scheduler", ["quartz.scheduler.instanceId"] = "AUTO", ["quartz.threadPool.threadCount"] = threadCount.ToString(CultureInfo.InvariantCulture), ["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz", // Setting RavenDB as the persisted JobStore ["quartz.jobStore.type"] = "Quartz.Impl.RavenDB.RavenJobStore, Quartz.Impl.RavenDB", }; IScheduler sched = new StdSchedulerFactory(properties).GetScheduler(); return sched; } private const string Barrier = "BARRIER"; private const string DateStamps = "DATE_STAMPS"; [DisallowConcurrentExecution] [PersistJobDataAfterExecution] public class TestStatefulJob : IJob { public void Execute(IJobExecutionContext context) { } } public class TestJob : IJob { public void Execute(IJobExecutionContext context) { } } private static readonly TimeSpan testTimeout = TimeSpan.FromSeconds(125); public class TestJobWithSync : IJob { public void Execute(IJobExecutionContext context) { try { List<DateTime> jobExecTimestamps = (List<DateTime>) context.Scheduler.Context.Get(DateStamps); Barrier barrier = (Barrier) context.Scheduler.Context.Get(Barrier); jobExecTimestamps.Add(DateTime.UtcNow); barrier.SignalAndWait(testTimeout); } catch (Exception e) { Console.Write(e); Assert.Fail("Await on barrier was interrupted: " + e); } } } [DisallowConcurrentExecution] [PersistJobDataAfterExecution] public class TestAnnotatedJob : IJob { public void Execute(IJobExecutionContext context) { } } [Test] public void TestAbilityToFireImmediatelyWhenStartedBefore() { List<DateTime> jobExecTimestamps = new List<DateTime>(); Barrier barrier = new Barrier(2); IScheduler sched = CreateScheduler("testAbilityToFireImmediatelyWhenStartedBefore", 5); sched.Context.Put(Barrier, barrier); sched.Context.Put(DateStamps, jobExecTimestamps); sched.Start(); Thread.Yield(); IJobDetail job1 = JobBuilder.Create<TestJobWithSync>() .WithIdentity("job1") .Build(); ITrigger trigger1 = TriggerBuilder.Create() .ForJob(job1) .Build(); DateTime sTime = DateTime.UtcNow; sched.ScheduleJob(job1, trigger1); barrier.SignalAndWait(testTimeout); sched.Shutdown(false); DateTime fTime = jobExecTimestamps[0]; Assert.That(fTime - sTime < TimeSpan.FromMilliseconds(7000), "Immediate trigger did not fire within a reasonable amount of time."); } [Test] public void TestAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob() { List<DateTime> jobExecTimestamps = new List<DateTime>(); Barrier barrier = new Barrier(2); IScheduler sched = CreateScheduler("testAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob", 5); sched.Clear(); sched.Context.Put(Barrier, barrier); sched.Context.Put(DateStamps, jobExecTimestamps); sched.Start(); Thread.Yield(); IJobDetail job1 = JobBuilder.Create<TestJobWithSync>() .WithIdentity("job1"). StoreDurably().Build(); sched.AddJob(job1, false); DateTime sTime = DateTime.UtcNow; sched.TriggerJob(job1.Key); barrier.SignalAndWait(testTimeout); sched.Shutdown(false); DateTime fTime = jobExecTimestamps[0]; Assert.That(fTime - sTime < TimeSpan.FromMilliseconds(7000), "Immediate trigger did not fire within a reasonable amount of time."); // This is dangerously subjective! but what else to do? } [Test] public void TestAbilityToFireImmediatelyWhenStartedAfter() { List<DateTime> jobExecTimestamps = new List<DateTime>(); Barrier barrier = new Barrier(2); IScheduler sched = CreateScheduler("testAbilityToFireImmediatelyWhenStartedAfter", 5); sched.Context.Put(Barrier, barrier); sched.Context.Put(DateStamps, jobExecTimestamps); IJobDetail job1 = JobBuilder.Create<TestJobWithSync>().WithIdentity("job1").Build(); ITrigger trigger1 = TriggerBuilder.Create().ForJob(job1).Build(); DateTime sTime = DateTime.UtcNow; sched.Start(); sched.ScheduleJob(job1, trigger1); barrier.SignalAndWait(testTimeout); sched.Shutdown(false); DateTime fTime = jobExecTimestamps[0]; Assert.That((fTime - sTime < TimeSpan.FromMilliseconds(7000)), "Immediate trigger did not fire within a reasonable amount of time."); // This is dangerously subjective! but what else to do? } [Test] public void TestScheduleMultipleTriggersForAJob() { IJobDetail job = JobBuilder.Create<TestJob>().WithIdentity("job1", "group1").Build(); ITrigger trigger1 = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever()) .Build(); ITrigger trigger2 = TriggerBuilder.Create() .WithIdentity("trigger2", "group1") .StartNow() .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever()) .Build(); Collection.ISet<ITrigger> triggersForJob = new Collection.HashSet<ITrigger>(); triggersForJob.Add(trigger1); triggersForJob.Add(trigger2); IScheduler sched = CreateScheduler("testScheduleMultipleTriggersForAJob", 5); sched.Start(); sched.ScheduleJob(job, triggersForJob, true); IList<ITrigger> triggersOfJob = sched.GetTriggersOfJob(job.Key); Assert.That(triggersOfJob.Count, Is.EqualTo(2)); Assert.That(triggersOfJob.Contains(trigger1)); Assert.That(triggersOfJob.Contains(trigger2)); sched.Shutdown(false); } [Test] public void TestDurableStorageFunctions() { IScheduler sched = CreateScheduler("testDurableStorageFunctions", 2); sched.Clear(); // test basic storage functions of scheduler... IJobDetail job = JobBuilder.Create<TestJob>() .WithIdentity("j1") .StoreDurably() .Build(); Assert.That(sched.CheckExists(new JobKey("j1")), Is.False, "Unexpected existence of job named 'j1'."); sched.AddJob(job, false); Assert.That(sched.CheckExists(new JobKey("j1")), "Unexpected non-existence of job named 'j1'."); IJobDetail nonDurableJob = JobBuilder.Create<TestJob>() .WithIdentity("j2") .Build(); try { sched.AddJob(nonDurableJob, false); Assert.Fail("Storage of non-durable job should not have succeeded."); } catch (SchedulerException) { Assert.That(sched.CheckExists(new JobKey("j2")), Is.False, "Unexpected existence of job named 'j2'."); } sched.AddJob(nonDurableJob, false, true); Assert.That(sched.CheckExists(new JobKey("j2")), "Unexpected non-existence of job named 'j2'."); } [Test] public void TestShutdownWithoutWaitIsUnclean() { List<DateTime> jobExecTimestamps = new List<DateTime>(); Barrier barrier = new Barrier(2); IScheduler scheduler = CreateScheduler("testShutdownWithoutWaitIsUnclean", 8); try { scheduler.Context.Put(Barrier, barrier); scheduler.Context.Put(DateStamps, jobExecTimestamps); scheduler.Start(); string jobName = Guid.NewGuid().ToString(); scheduler.AddJob(JobBuilder.Create<TestJobWithSync>().WithIdentity(jobName).StoreDurably().Build(), false); scheduler.ScheduleJob(TriggerBuilder.Create().ForJob(jobName).StartNow().Build()); while (scheduler.GetCurrentlyExecutingJobs().Count == 0) { Thread.Sleep(50); } } finally { scheduler.Shutdown(false); } barrier.SignalAndWait(testTimeout); } [Test] public void TestShutdownWithWaitIsClean() { bool shutdown = false; List<DateTime> jobExecTimestamps = new List<DateTime>(); Barrier barrier = new Barrier(2); IScheduler scheduler = CreateScheduler("testShutdownWithoutWaitIsUnclean", 8); try { scheduler.Context.Put(Barrier, barrier); scheduler.Context.Put(DateStamps, jobExecTimestamps); scheduler.Start(); string jobName = Guid.NewGuid().ToString(); scheduler.AddJob(JobBuilder.Create<TestJobWithSync>().WithIdentity(jobName).StoreDurably().Build(), false); scheduler.ScheduleJob(TriggerBuilder.Create().ForJob(jobName).StartNow().Build()); while (scheduler.GetCurrentlyExecutingJobs().Count == 0) { Thread.Sleep(50); } } finally { ThreadStart threadStart = () => { try { scheduler.Shutdown(true); shutdown = true; } catch (SchedulerException ex) { throw new Exception("exception: " + ex.Message, ex); } }; var t = new Thread(threadStart); t.Start(); Thread.Sleep(1000); Assert.That(shutdown, Is.False); barrier.SignalAndWait(testTimeout); t.Join(); } } public class SampleSignaler : ISchedulerSignaler { internal int fMisfireCount = 0; public void NotifyTriggerListenersMisfired(ITrigger trigger) { fMisfireCount++; } public void NotifySchedulerListenersFinalized(ITrigger trigger) { } public void SignalSchedulingChange(DateTimeOffset? candidateNewNextFireTimeUtc) { } public void NotifySchedulerListenersError(string message, SchedulerException jpe) { } public void NotifySchedulerListenersJobDeleted(JobKey jobKey) { } } } }
namespace ButtonSpecPlayground { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.groupBoxProperties = new System.Windows.Forms.GroupBox(); this.propertyGrid = new System.Windows.Forms.PropertyGrid(); this.buttonClose = new System.Windows.Forms.Button(); this.kryptonHeaderGroup1 = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup(); this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); this.kryptonButtonAdd = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonRemove = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonClear = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.groupBoxExample = new System.Windows.Forms.GroupBox(); this.groupBoxButtonSpecs = new System.Windows.Forms.GroupBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.labelInstructions = new System.Windows.Forms.Label(); this.groupBoxPrimary = new System.Windows.Forms.GroupBox(); this.kryptonButtonBottomP = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.kryptonButton1 = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButton2 = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButton3 = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonTopP = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonRightP = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonLeftP = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.groupBoxSecondary = new System.Windows.Forms.GroupBox(); this.kryptonButtonBottomS = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonTopS = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonRightS = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonLeftS = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.groupBoxProperties.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1.Panel)).BeginInit(); this.kryptonHeaderGroup1.SuspendLayout(); this.groupBoxExample.SuspendLayout(); this.groupBoxButtonSpecs.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBoxPrimary.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBoxSecondary.SuspendLayout(); this.SuspendLayout(); // // groupBoxProperties // this.groupBoxProperties.Controls.Add(this.propertyGrid); this.groupBoxProperties.Location = new System.Drawing.Point(285, 12); this.groupBoxProperties.Name = "groupBoxProperties"; this.groupBoxProperties.Size = new System.Drawing.Size(294, 436); this.groupBoxProperties.TabIndex = 2; this.groupBoxProperties.TabStop = false; this.groupBoxProperties.Text = "Properties for Selected ButtonSpec"; // // propertyGrid // this.propertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.propertyGrid.Location = new System.Drawing.Point(6, 19); this.propertyGrid.Name = "propertyGrid"; this.propertyGrid.Size = new System.Drawing.Size(282, 411); this.propertyGrid.TabIndex = 0; this.propertyGrid.ToolbarVisible = false; // // buttonClose // this.buttonClose.Location = new System.Drawing.Point(504, 454); this.buttonClose.Name = "buttonClose"; this.buttonClose.Size = new System.Drawing.Size(75, 23); this.buttonClose.TabIndex = 3; this.buttonClose.Text = "Close"; this.buttonClose.UseVisualStyleBackColor = true; this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click); // // kryptonHeaderGroup1 // this.kryptonHeaderGroup1.CollapseTarget = ComponentFactory.Krypton.Toolkit.HeaderGroupCollapsedTarget.CollapsedToPrimary; this.kryptonHeaderGroup1.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.ControlClient; this.kryptonHeaderGroup1.GroupBorderStyle = ComponentFactory.Krypton.Toolkit.PaletteBorderStyle.ControlClient; this.kryptonHeaderGroup1.HeaderStylePrimary = ComponentFactory.Krypton.Toolkit.HeaderStyle.Primary; this.kryptonHeaderGroup1.HeaderStyleSecondary = ComponentFactory.Krypton.Toolkit.HeaderStyle.Secondary; this.kryptonHeaderGroup1.Location = new System.Drawing.Point(11, 23); this.kryptonHeaderGroup1.Name = "kryptonHeaderGroup1"; this.kryptonHeaderGroup1.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonHeaderGroup1.Size = new System.Drawing.Size(246, 165); this.kryptonHeaderGroup1.TabIndex = 0; // // kryptonManager1 // this.kryptonManager1.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Blue; // // kryptonButtonAdd // this.kryptonButtonAdd.AutoSize = true; this.kryptonButtonAdd.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonAdd.Location = new System.Drawing.Point(10, 25); this.kryptonButtonAdd.Name = "kryptonButtonAdd"; this.kryptonButtonAdd.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonAdd.Size = new System.Drawing.Size(65, 27); this.kryptonButtonAdd.TabIndex = 0; this.kryptonButtonAdd.Values.Text = "Add"; this.kryptonButtonAdd.Click += new System.EventHandler(this.kryptonButtonAdd_Click); // // kryptonButtonRemove // this.kryptonButtonRemove.AutoSize = true; this.kryptonButtonRemove.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonRemove.Enabled = false; this.kryptonButtonRemove.Location = new System.Drawing.Point(11, 56); this.kryptonButtonRemove.Name = "kryptonButtonRemove"; this.kryptonButtonRemove.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonRemove.Size = new System.Drawing.Size(64, 27); this.kryptonButtonRemove.TabIndex = 1; this.kryptonButtonRemove.Values.Text = "Remove"; this.kryptonButtonRemove.Click += new System.EventHandler(this.kryptonButtonRemove_Click); // // kryptonButtonClear // this.kryptonButtonClear.AutoSize = true; this.kryptonButtonClear.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonClear.Enabled = false; this.kryptonButtonClear.Location = new System.Drawing.Point(11, 87); this.kryptonButtonClear.Name = "kryptonButtonClear"; this.kryptonButtonClear.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonClear.Size = new System.Drawing.Size(64, 27); this.kryptonButtonClear.TabIndex = 2; this.kryptonButtonClear.Values.Text = "Clear"; this.kryptonButtonClear.Click += new System.EventHandler(this.kryptonButtonClear_Click); // // groupBoxExample // this.groupBoxExample.Controls.Add(this.kryptonHeaderGroup1); this.groupBoxExample.Location = new System.Drawing.Point(12, 12); this.groupBoxExample.Name = "groupBoxExample"; this.groupBoxExample.Size = new System.Drawing.Size(267, 198); this.groupBoxExample.TabIndex = 0; this.groupBoxExample.TabStop = false; this.groupBoxExample.Text = "Example HeaderGroup"; // // groupBoxButtonSpecs // this.groupBoxButtonSpecs.Controls.Add(this.kryptonButtonAdd); this.groupBoxButtonSpecs.Controls.Add(this.kryptonButtonClear); this.groupBoxButtonSpecs.Controls.Add(this.kryptonButtonRemove); this.groupBoxButtonSpecs.Location = new System.Drawing.Point(12, 216); this.groupBoxButtonSpecs.Name = "groupBoxButtonSpecs"; this.groupBoxButtonSpecs.Size = new System.Drawing.Size(85, 154); this.groupBoxButtonSpecs.TabIndex = 1; this.groupBoxButtonSpecs.TabStop = false; this.groupBoxButtonSpecs.Text = "ButtonSpec"; // // groupBox1 // this.groupBox1.Controls.Add(this.labelInstructions); this.groupBox1.Location = new System.Drawing.Point(11, 376); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(268, 72); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "Instructions"; // // labelInstructions // this.labelInstructions.Location = new System.Drawing.Point(8, 20); this.labelInstructions.Name = "labelInstructions"; this.labelInstructions.Size = new System.Drawing.Size(250, 50); this.labelInstructions.TabIndex = 0; this.labelInstructions.Text = "Use the Add/Remove buttons to create/delete ButtonSpec instances. Click the butt" + "on in order to display its properties in the property window."; // // groupBoxPrimary // this.groupBoxPrimary.Controls.Add(this.kryptonButtonBottomP); this.groupBoxPrimary.Controls.Add(this.groupBox2); this.groupBoxPrimary.Controls.Add(this.kryptonButtonTopP); this.groupBoxPrimary.Controls.Add(this.kryptonButtonRightP); this.groupBoxPrimary.Controls.Add(this.kryptonButtonLeftP); this.groupBoxPrimary.Location = new System.Drawing.Point(103, 216); this.groupBoxPrimary.Name = "groupBoxPrimary"; this.groupBoxPrimary.Size = new System.Drawing.Size(85, 154); this.groupBoxPrimary.TabIndex = 3; this.groupBoxPrimary.TabStop = false; this.groupBoxPrimary.Text = "Primary"; // // kryptonButtonBottomP // this.kryptonButtonBottomP.AutoSize = true; this.kryptonButtonBottomP.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonBottomP.Location = new System.Drawing.Point(11, 118); this.kryptonButtonBottomP.Name = "kryptonButtonBottomP"; this.kryptonButtonBottomP.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonBottomP.Size = new System.Drawing.Size(64, 27); this.kryptonButtonBottomP.TabIndex = 5; this.kryptonButtonBottomP.Values.Text = "Bottom"; this.kryptonButtonBottomP.Click += new System.EventHandler(this.kryptonButtonBottomP_Click); // // groupBox2 // this.groupBox2.Controls.Add(this.kryptonButton1); this.groupBox2.Controls.Add(this.kryptonButton2); this.groupBox2.Controls.Add(this.kryptonButton3); this.groupBox2.Location = new System.Drawing.Point(96, 0); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(90, 130); this.groupBox2.TabIndex = 4; this.groupBox2.TabStop = false; this.groupBox2.Text = "Primary"; // // kryptonButton1 // this.kryptonButton1.AutoSize = true; this.kryptonButton1.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButton1.Location = new System.Drawing.Point(10, 28); this.kryptonButton1.Name = "kryptonButton1"; this.kryptonButton1.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButton1.Size = new System.Drawing.Size(65, 27); this.kryptonButton1.TabIndex = 0; this.kryptonButton1.Values.Text = "Top"; // // kryptonButton2 // this.kryptonButton2.AutoSize = true; this.kryptonButton2.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButton2.Enabled = false; this.kryptonButton2.Location = new System.Drawing.Point(11, 90); this.kryptonButton2.Name = "kryptonButton2"; this.kryptonButton2.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButton2.Size = new System.Drawing.Size(64, 27); this.kryptonButton2.TabIndex = 2; this.kryptonButton2.Values.Text = "Right"; // // kryptonButton3 // this.kryptonButton3.AutoSize = true; this.kryptonButton3.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButton3.Enabled = false; this.kryptonButton3.Location = new System.Drawing.Point(11, 59); this.kryptonButton3.Name = "kryptonButton3"; this.kryptonButton3.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButton3.Size = new System.Drawing.Size(64, 27); this.kryptonButton3.TabIndex = 1; this.kryptonButton3.Values.Text = "Left"; // // kryptonButtonTopP // this.kryptonButtonTopP.AutoSize = true; this.kryptonButtonTopP.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonTopP.Location = new System.Drawing.Point(10, 25); this.kryptonButtonTopP.Name = "kryptonButtonTopP"; this.kryptonButtonTopP.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonTopP.Size = new System.Drawing.Size(65, 27); this.kryptonButtonTopP.TabIndex = 0; this.kryptonButtonTopP.Values.Text = "Top"; this.kryptonButtonTopP.Click += new System.EventHandler(this.kryptonButtonTopP_Click); // // kryptonButtonRightP // this.kryptonButtonRightP.AutoSize = true; this.kryptonButtonRightP.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonRightP.Location = new System.Drawing.Point(11, 87); this.kryptonButtonRightP.Name = "kryptonButtonRightP"; this.kryptonButtonRightP.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonRightP.Size = new System.Drawing.Size(64, 27); this.kryptonButtonRightP.TabIndex = 2; this.kryptonButtonRightP.Values.Text = "Right"; this.kryptonButtonRightP.Click += new System.EventHandler(this.kryptonButtonRightP_Click); // // kryptonButtonLeftP // this.kryptonButtonLeftP.AutoSize = true; this.kryptonButtonLeftP.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonLeftP.Location = new System.Drawing.Point(11, 56); this.kryptonButtonLeftP.Name = "kryptonButtonLeftP"; this.kryptonButtonLeftP.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonLeftP.Size = new System.Drawing.Size(64, 27); this.kryptonButtonLeftP.TabIndex = 1; this.kryptonButtonLeftP.Values.Text = "Left"; this.kryptonButtonLeftP.Click += new System.EventHandler(this.kryptonButtonLeftP_Click); // // groupBoxSecondary // this.groupBoxSecondary.Controls.Add(this.kryptonButtonBottomS); this.groupBoxSecondary.Controls.Add(this.kryptonButtonTopS); this.groupBoxSecondary.Controls.Add(this.kryptonButtonRightS); this.groupBoxSecondary.Controls.Add(this.kryptonButtonLeftS); this.groupBoxSecondary.Location = new System.Drawing.Point(194, 216); this.groupBoxSecondary.Name = "groupBoxSecondary"; this.groupBoxSecondary.Size = new System.Drawing.Size(85, 154); this.groupBoxSecondary.TabIndex = 5; this.groupBoxSecondary.TabStop = false; this.groupBoxSecondary.Text = "Secondary"; // // kryptonButtonBottomS // this.kryptonButtonBottomS.AutoSize = true; this.kryptonButtonBottomS.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonBottomS.Location = new System.Drawing.Point(11, 118); this.kryptonButtonBottomS.Name = "kryptonButtonBottomS"; this.kryptonButtonBottomS.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonBottomS.Size = new System.Drawing.Size(64, 27); this.kryptonButtonBottomS.TabIndex = 6; this.kryptonButtonBottomS.Values.Text = "Bottom"; this.kryptonButtonBottomS.Click += new System.EventHandler(this.kryptonButtonBottomS_Click); // // kryptonButtonTopS // this.kryptonButtonTopS.AutoSize = true; this.kryptonButtonTopS.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonTopS.Location = new System.Drawing.Point(10, 25); this.kryptonButtonTopS.Name = "kryptonButtonTopS"; this.kryptonButtonTopS.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonTopS.Size = new System.Drawing.Size(65, 27); this.kryptonButtonTopS.TabIndex = 0; this.kryptonButtonTopS.Values.Text = "Top"; this.kryptonButtonTopS.Click += new System.EventHandler(this.kryptonButtonTopS_Click); // // kryptonButtonRightS // this.kryptonButtonRightS.AutoSize = true; this.kryptonButtonRightS.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonRightS.Location = new System.Drawing.Point(11, 87); this.kryptonButtonRightS.Name = "kryptonButtonRightS"; this.kryptonButtonRightS.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonRightS.Size = new System.Drawing.Size(64, 27); this.kryptonButtonRightS.TabIndex = 2; this.kryptonButtonRightS.Values.Text = "Right"; this.kryptonButtonRightS.Click += new System.EventHandler(this.kryptonButtonRightS_Click); // // kryptonButtonLeftS // this.kryptonButtonLeftS.AutoSize = true; this.kryptonButtonLeftS.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Standalone; this.kryptonButtonLeftS.Location = new System.Drawing.Point(11, 56); this.kryptonButtonLeftS.Name = "kryptonButtonLeftS"; this.kryptonButtonLeftS.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Global; this.kryptonButtonLeftS.Size = new System.Drawing.Size(64, 27); this.kryptonButtonLeftS.TabIndex = 1; this.kryptonButtonLeftS.Values.Text = "Left"; this.kryptonButtonLeftS.Click += new System.EventHandler(this.kryptonButtonLeftS_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(587, 485); this.Controls.Add(this.groupBoxSecondary); this.Controls.Add(this.groupBoxPrimary); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBoxButtonSpecs); this.Controls.Add(this.groupBoxExample); this.Controls.Add(this.buttonClose); this.Controls.Add(this.groupBoxProperties); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form1"; this.Text = "ButtonSpec Playground"; this.groupBoxProperties.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1.Panel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1)).EndInit(); this.kryptonHeaderGroup1.ResumeLayout(false); this.groupBoxExample.ResumeLayout(false); this.groupBoxButtonSpecs.ResumeLayout(false); this.groupBoxButtonSpecs.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBoxPrimary.ResumeLayout(false); this.groupBoxPrimary.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBoxSecondary.ResumeLayout(false); this.groupBoxSecondary.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBoxProperties; private System.Windows.Forms.PropertyGrid propertyGrid; private System.Windows.Forms.Button buttonClose; private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroup1; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonAdd; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonRemove; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonClear; private System.Windows.Forms.GroupBox groupBoxExample; private System.Windows.Forms.GroupBox groupBoxButtonSpecs; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label labelInstructions; private System.Windows.Forms.GroupBox groupBoxPrimary; private System.Windows.Forms.GroupBox groupBox2; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButton1; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButton2; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButton3; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonTopP; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonRightP; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonLeftP; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonBottomP; private System.Windows.Forms.GroupBox groupBoxSecondary; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonBottomS; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonTopS; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonRightS; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonLeftS; } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.IO; namespace FluorineFx.Util { /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// http://java.sun.com/j2se/1.5.0/docs/api/java/nio/ByteBuffer.html /// /// The following invariant holds for the mark, position, limit, and capacity values: /// 0 lte mark lte position lte limit lte capacity /// </summary> [CLSCompliant(false)] public class ByteBuffer : Stream { private MemoryStream _stream; private bool _autoExpand; private long _bookmark; /// <summary> /// Initializes a new instance of the ByteBuffer class. /// </summary> /// <param name="stream">Wraps the MemoryStream into a buffer.</param> public ByteBuffer(MemoryStream stream) { _stream = stream; ClearBookmark(); } /// <summary> /// Allocates a new byte buffer. /// The new buffer's position will be zero, its limit will be its capacity, /// and its mark will be undefined. /// It will have a backing array, and its array offset will be zero. /// </summary> /// <param name="capacity"></param> /// <returns></returns> public static ByteBuffer Allocate(int capacity) { MemoryStream ms = new MemoryStream(capacity); ByteBuffer buffer = new ByteBuffer(ms); buffer.Limit = capacity; return buffer; } /// <summary> /// Wraps a byte array into a buffer. /// The new buffer will be backed by the given byte array; that is, modifications /// to the buffer will cause the array to be modified and vice versa. /// The new buffer's capacity will be array.length, its position will be offset, /// its limit will be offset + length, and its mark will be undefined. /// </summary> /// <param name="array">Byte array to wrap.</param> /// <param name="offset">Offset in the byte array.</param> /// <param name="length"></param> /// <returns></returns> public static ByteBuffer Wrap(byte[] array, int offset, int length) { MemoryStream ms = new MemoryStream(array, offset, length, true, true); ms.Capacity = array.Length; ms.SetLength(offset + length); ms.Position = offset; return new ByteBuffer(ms); } /// <summary> /// Wraps a byte array into a buffer. /// The new buffer will be backed by the given byte array; that is, modifications /// to the buffer will cause the array to be modified and vice versa. /// The new buffer's capacity and limit will be array.length, its position will be zero, /// and its mark will be undefined. /// </summary> /// <param name="array"></param> /// <returns></returns> public static ByteBuffer Wrap(byte[] array) { return Wrap(array, 0, array.Length); } /// <summary> /// Turns on or off autoExpand /// </summary> public bool AutoExpand { get{ return _autoExpand; } set{ _autoExpand = value; } } /// <summary> /// Returns this buffer's capacity. /// </summary> public int Capacity { get{ return (int)_stream.Capacity; } } /// <summary> /// Returns this buffer's limit. /// </summary> public int Limit { get{ return (int)_stream.Length; } set{ _stream.SetLength(value); } } /// <summary> /// Returns the number of elements between the current position and the limit. /// </summary> public int Remaining { get{ return this.Limit - (int)this.Position; } } /// <summary> /// Tells whether there are any elements between the current position and the limit. /// </summary> public bool HasRemaining { get{ return this.Remaining > 0; } } /// <summary> /// Gets the current bookmark value. /// </summary> public long Bookmark { get { return _bookmark; } } /// <summary> /// Sets this buffer's bookmark at its position. /// </summary> /// <returns>Returns this bookmark value.</returns> public long Mark() { _bookmark = this.Position; return _bookmark; } /// <summary> /// Clears the current bookmark. /// </summary> public void ClearBookmark() { _bookmark = -1; } /// <summary> /// Resets this buffer's position to the previously-marked position. /// Invoking this method neither changes nor discards the mark's value. /// </summary> public void Reset() { if( _bookmark != -1 ) this.Position = _bookmark; } /// <summary> /// Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. /// </summary> public void Clear() { ClearBookmark(); this.Position = 0; } #if !(NET_1_1) /// <summary> /// Releases all resources used by this object. /// </summary> /// <param name="disposing">Indicates if this is a dispose call dispose.</param> protected override void Dispose(bool disposing) { if (disposing) { if (_stream != null) _stream.Dispose(); _stream = null; } base.Dispose(disposing); } #endif /// <summary> /// Flips this buffer. The limit is set to the current position and then /// the position is set to zero. If the mark is defined then it is discarded. /// </summary> public void Flip() { ClearBookmark(); this.Limit = (int)this.Position; this.Position = 0; } /// <summary> /// Rewinds this buffer. The position is set to zero and the mark is discarded. /// </summary> public void Rewind() { ClearBookmark(); this.Position = 0; } /// <summary> /// Writes the given byte into this buffer at the current position, and then increments the position. /// </summary> /// <param name="value"></param> /// <returns></returns> public void Put(byte value) { this.WriteByte(value); } /// <summary> /// Relative bulk put method. /// /// This method transfers bytes into this buffer from the given source array. /// If there are more bytes to be copied from the array than remain in this buffer, /// that is, if length > remaining(), then no bytes are transferred and a /// BufferOverflowException is thrown. /// /// Otherwise, this method copies length bytes from the given array into this buffer, /// starting at the given offset in the array and at the current position of this buffer. /// The position of this buffer is then incremented by length. /// </summary> /// <param name="src">The array from which bytes are to be read.</param> /// <param name="offset">The offset within the array of the first byte to be read; must be non-negative and no larger than the array length.</param> /// <param name="length">The number of bytes to be read from the given array; must be non-negative and no larger than length - offset.</param> public void Put(byte[] src, int offset, int length) { _stream.Write(src, offset, length); } /// <summary> /// This method transfers the entire content of the given source byte array into this buffer. /// </summary> /// <param name="src">The array from which bytes are to be read.</param> public void Put(byte[] src) { Put(src, 0, src.Length); } /// <summary> /// Appends a byte buffer to this ByteArray. /// </summary> /// <param name="src">The byte buffer to append.</param> public void Append(byte[] src) { Append(src, 0, src.Length); } /// <summary> /// Appends a byte buffer to this ByteArray. /// </summary> /// <param name="src">The byte buffer to append.</param> /// <param name="offset">Offset in the byte buffer.</param> /// <param name="length">Number of bytes to append.</param> public void Append(byte[] src, int offset, int length) { long position = this.Position; this.Position = this.Limit; Put(src, offset, length); this.Position = position; } /// <summary> /// This method transfers the bytes remaining in the given source buffer into this buffer. /// If there are more bytes remaining in the source buffer than in this buffer, /// that is, if src.remaining() > remaining(), then no bytes are transferred /// and a BufferOverflowException is thrown. /// /// Otherwise, this method copies n = src.remaining() bytes from the given buffer into this buffer, /// starting at each buffer's current position. The positions of both buffers are then /// incremented by n. /// </summary> /// <param name="src">The source buffer from which bytes are to be read; must not be this buffer.</param> public void Put(ByteBuffer src) { while(src.HasRemaining) Put(src.Get()); } /// <summary> /// Transfers the specified number of bytes from the given source buffer into this buffer. /// </summary> /// <param name="src">The source buffer from which bytes are to be read; must not be this buffer.</param> /// <param name="count">Number of bytes to transfer.</param> public void Put(ByteBuffer src, int count) { for(int i=0; i < count; i++) { Put(src.Get()); } } /// <summary> /// Absolute put method. /// Writes the given byte into this buffer at the given index. /// </summary> /// <param name="index">The index.</param> /// <param name="value">The byte to write.</param> public void Put(int index, byte value) { _stream.GetBuffer()[index] = value; } /// <summary> /// Relative get method. Reads the byte at this buffer's current position, and then increments the position. /// </summary> /// <returns></returns> public byte Get() { return (byte)this.ReadByte(); } /// <summary> /// Reads a 4-byte signed integer using network byte order encoding. /// </summary> /// <returns>The 4-byte signed integer.</returns> public int GetInt() { // Read the next 4 bytes, shift and add byte[] bytes = this.ReadBytes(4); return ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]); } /// <summary> /// Reads a 2-byte signed integer using network byte order encoding. /// </summary> /// <returns>The 2-byte signed integer.</returns> public short GetShort() { //Read the next 2 bytes, shift and add. byte[] bytes = this.ReadBytes(2); return (short)((bytes[0] << 8) | bytes[1]); } /// <summary> /// Absolute get method. Reads the byte at the given index. /// </summary> /// <param name="index"></param> /// <returns></returns> public byte Get(int index) { return _stream.GetBuffer()[index]; } public byte this[int index] { get { return Get(index); } set { Put(index, value); } } /// <summary> /// Writes the stream contents to a byte array, regardless of the Position property. /// </summary> /// <returns>A new byte array.</returns> /// <remarks> /// This method omits unused bytes in ByteBuffer from the array. To get the entire buffer, use the GetBuffer method. /// </remarks> public byte[] ToArray() { return _stream.ToArray(); } /// <summary> /// Returns the array of unsigned bytes from which this stream was created. /// </summary> /// <returns> /// The byte array from which this ByteBuffer was created, or the underlying array if a byte array was not provided to the ByteBuffer constructor during construction of the current instance. /// </returns> public byte[] GetBuffer() { return _stream.GetBuffer(); } /// <summary> /// Compacts this buffer /// /// The bytes between the buffer's current position and its limit, if any, /// are copied to the beginning of the buffer. That is, the byte at /// index p = position() is copied to index zero, the byte at index p + 1 is copied /// to index one, and so forth until the byte at index limit() - 1 is copied /// to index n = limit() - 1 - p. /// The buffer's position is then set to n+1 and its limit is set to its capacity. /// The mark, if defined, is discarded. /// The buffer's position is set to the number of bytes copied, rather than to zero, /// so that an invocation of this method can be followed immediately by an invocation of /// another relative put method. /// </summary> public void Compact() { if( this.Position == 0 ) return; for(int i = (int)this.Position; i < this.Limit; i++) { byte value = this.Get(i); this.Put(i - (int)this.Position, value); } //this.Position = this.Limit - this.Position; //this.Limit = this.Capacity; this.Limit = this.Limit - (int)this.Position; this.Position = 0; } /// <summary> /// Forwards the position of this buffer as the specified size bytes. /// </summary> /// <param name="size"></param> public void Skip(int size) { this.Position += size; } /// <summary> /// Fills this buffer with the specified value. /// </summary> /// <param name="value"></param> /// <param name="count"></param> public void Fill(byte value, int count) { for(int i = 0; i < count; i++) this.Put(value); } #region Stream /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> public override bool CanRead { get { return _stream.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return _stream.CanSeek; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> public override bool CanWrite { get { return _stream.CanWrite; } } /// <summary> /// Closes the current stream and releases any resources associated with the current stream. /// </summary> public override void Close() { _stream.Close (); } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> public override void Flush() { _stream.Flush(); } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public override long Length { get { return _stream.Length; } } /// <summary> /// Gets or sets the position within the current stream. /// </summary> public override long Position { get { return _stream.Position; } set { _stream.Position = value; if (_bookmark > value) { //discard bookmark _bookmark = 0; } } } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> public override int Read(byte[] buffer, int offset, int count) { return _stream.Read(buffer, offset, count); } /// <summary> /// Relative bulk get method. /// This method transfers bytes from this buffer into the given destination array. /// An invocation of this method behaves in exactly the same way as the invocation buffer.Get(a, 0, a.Length) /// </summary> /// <param name="buffer">An array of bytes.</param> /// <returns>The total number of bytes read into the buffer.</returns> public int Read(byte[] buffer) { return _stream.Read(buffer, 0, buffer.Length); } /// <summary> /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { return _stream.ReadByte(); } /// <summary> /// Sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the origin parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> public override long Seek(long offset, SeekOrigin origin) { return _stream.Seek(offset, origin); } /// <summary> /// Sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> public override void SetLength(long value) { _stream.SetLength(value); } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> public override void Write(byte[] buffer, int offset, int count) { _stream.Write(buffer, offset, count); } /// <summary> /// Writes a byte to the current position in the stream and advances the position within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) { _stream.WriteByte (value); } #endregion Stream /// <summary> /// Reads count bytes from the current stream into a byte array and advances the current position by count bytes. /// </summary> /// <param name="count"></param> /// <returns></returns> public byte[] ReadBytes( int count ) { byte[] bytes = new byte[count]; for(int i = 0; i < count; i++) { bytes[i] = (byte)this.ReadByte(); } return bytes; } /// <summary> /// Writes a 32-bit signed integer to the current position using variable length unsigned 29-bit integer encoding. /// </summary> /// <param name="value">A 32-bit signed integer.</param> public void WriteMediumInt(int value) { byte[] bytes = new byte[3]; bytes[0] = (byte) (0xFF & (value >> 16)); bytes[1] = (byte) (0xFF & (value >> 8)); bytes[2] = (byte) (0xFF & (value >> 0)); this.Write(bytes, 0, bytes.Length); } public void WriteReverseInt(int value) { byte[] bytes = new byte[4]; bytes[3] = (byte) (0xFF & (value >> 24)); bytes[2] = (byte) (0xFF & (value >> 16)); bytes[1] = (byte) (0xFF & (value >> 8)); bytes[0] = (byte) (0xFF & value); this.Write(bytes, 0, bytes.Length); } private void WriteBigEndian(byte[] bytes) { WriteBigEndian((int)this.Position, bytes); } private void WriteBigEndian(int index, byte[] bytes) { for (int i = bytes.Length - 1, j = 0; i >= 0; i--, j++) { this.Put(index + j, bytes[i]); } this.Position += bytes.Length; } private void WriteBytes(int index, byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { this.Put(index + i, bytes[i]); } } /// <summary> /// Writes a 16-bit unsigned integer to the current position. /// </summary> /// <param name="value">A 16-bit unsigned integer.</param> public void PutShort(short value) { byte[] bytes = BitConverter.GetBytes(value); WriteBigEndian(bytes); } /// <summary> /// Relative put method for writing an int value. /// Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four. /// </summary> /// <param name="value">The int value to be written.</param> public void PutInt(int value) { byte[] bytes = BitConverter.GetBytes(value); //this.Write(bytes, 0, bytes.Length); WriteBigEndian(bytes); } /// <summary> /// Absolute put method for writing an int value. /// Writes four bytes containing the given int value, in the current byte order, into this buffer at the given index. /// </summary> /// <param name="index">The index at which the bytes will be written.</param> /// <param name="value">The int value to be written.</param> public void PutInt(int index, int value) { byte[] bytes = BitConverter.GetBytes(value); for(int i = bytes.Length-1, j = 0; i >= 0; i--, j++) { this.Put( index + j, bytes[i] ); } } /// <summary> /// Absolute put method for writing an int value. /// Writes four bytes containing the given int value, in the current byte order, into this buffer at the given index. /// </summary> /// <param name="index">The index at which the bytes will be written.</param> /// <param name="value">The int value to be written.</param> public void Put(int index, UInt32 value) { byte[] bytes = BitConverter.GetBytes(value); this.WriteBytes(index, bytes); } /* public void Put(UInt16 value) { byte[] bytes = BitConverter.GetBytes(value); this.Put(bytes); } */ public void Put(int index, UInt16 value) { byte[] bytes = BitConverter.GetBytes(value); this.WriteBytes(index, bytes); } public int ReadUInt24() { byte[] bytes = this.ReadBytes(3); int value = bytes[0] << 16 | bytes[1] << 8 | bytes[2]; return value; } /// <summary> /// Reads a 4-byte signed integer. /// </summary> /// <returns>The 4-byte signed integer.</returns> public int ReadReverseInt() { byte[] bytes = this.ReadBytes(4); int val = 0; val += bytes[3] << 24; val += bytes[2] << 16; val += bytes[1] << 8; val += bytes[0]; return val; } /// <summary> /// Puts an in buffer stream onto an out buffer stream and returns the bytes written. /// </summary> /// <param name="output"></param> /// <param name="input"></param> /// <param name="numBytesMax"></param> /// <returns></returns> public static int Put(ByteBuffer output, ByteBuffer input, int numBytesMax) { int limit = input.Limit; int numBytesRead = (numBytesMax > input.Remaining) ? input.Remaining : numBytesMax; /* input.Limit = (int)input.Position + numBytesRead; output.Put(input); input.Limit = limit; */ output.Put(input, numBytesRead); return numBytesRead; } /// <summary> /// Write the buffer content to a file. /// </summary> /// <param name="file"></param> public void Dump(string file) { using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { byte[] buffer = this.ToArray(); fs.Write(buffer, 0, buffer.Length); fs.Close(); } } } }
using System; using System.Data; using Csla; using Csla.Data; namespace ParentLoadRO.Business.ERCLevel { /// <summary> /// B02_Continent (read only object).<br/> /// This is a generated base class of <see cref="B02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="B03_SubContinentObjects"/> of type <see cref="B03_SubContinentColl"/> (1:M relation to <see cref="B04_SubContinent"/>)<br/> /// This class is an item of <see cref="B01_ContinentColl"/> collection. /// </remarks> [Serializable] public partial class B02_Continent : ReadOnlyBase<B02_Continent> { #region ParentList Property /// <summary> /// Maintains metadata about <see cref="ParentList"/> property. /// </summary> [NotUndoable] [NonSerialized] public static readonly PropertyInfo<B01_ContinentColl> ParentListProperty = RegisterProperty<B01_ContinentColl>(p => p.ParentList); /// <summary> /// Provide access to the parent list reference for use in child object code. /// </summary> /// <value>The parent list reference.</value> public B01_ContinentColl ParentList { get { return ReadProperty(ParentListProperty); } internal set { LoadProperty(ParentListProperty, value); } } #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continent ID", -1); /// <summary> /// Gets the Continent ID. /// </summary> /// <value>The Continent ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continent Name"); /// <summary> /// Gets the Continent Name. /// </summary> /// <value>The Continent Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_Child> B03_Continent_SingleObjectProperty = RegisterProperty<B03_Continent_Child>(p => p.B03_Continent_SingleObject, "B03 Continent Single Object"); /// <summary> /// Gets the B03 Continent Single Object ("parent load" child property). /// </summary> /// <value>The B03 Continent Single Object.</value> public B03_Continent_Child B03_Continent_SingleObject { get { return GetProperty(B03_Continent_SingleObjectProperty); } private set { LoadProperty(B03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_ReChild> B03_Continent_ASingleObjectProperty = RegisterProperty<B03_Continent_ReChild>(p => p.B03_Continent_ASingleObject, "B03 Continent ASingle Object"); /// <summary> /// Gets the B03 Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The B03 Continent ASingle Object.</value> public B03_Continent_ReChild B03_Continent_ASingleObject { get { return GetProperty(B03_Continent_ASingleObjectProperty); } private set { LoadProperty(B03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<B03_SubContinentColl> B03_SubContinentObjectsProperty = RegisterProperty<B03_SubContinentColl>(p => p.B03_SubContinentObjects, "B03 SubContinent Objects"); /// <summary> /// Gets the B03 Sub Continent Objects ("parent load" child property). /// </summary> /// <value>The B03 Sub Continent Objects.</value> public B03_SubContinentColl B03_SubContinentObjects { get { return GetProperty(B03_SubContinentObjectsProperty); } private set { LoadProperty(B03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="B02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="B02_Continent"/> object.</returns> internal static B02_Continent GetB02_Continent(SafeDataReader dr) { B02_Continent obj = new B02_Continent(); obj.Fetch(dr); obj.LoadProperty(B03_SubContinentObjectsProperty, new B03_SubContinentColl()); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B02_Continent() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="B02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> internal void FetchChildren(SafeDataReader dr) { dr.NextResult(); while (dr.Read()) { var child = B03_Continent_Child.GetB03_Continent_Child(dr); var obj = ParentList.FindB02_ContinentByParentProperties(child.continent_ID1); obj.LoadProperty(B03_Continent_SingleObjectProperty, child); } dr.NextResult(); while (dr.Read()) { var child = B03_Continent_ReChild.GetB03_Continent_ReChild(dr); var obj = ParentList.FindB02_ContinentByParentProperties(child.continent_ID2); obj.LoadProperty(B03_Continent_ASingleObjectProperty, child); } dr.NextResult(); var b03_SubContinentColl = B03_SubContinentColl.GetB03_SubContinentColl(dr); b03_SubContinentColl.LoadItems(ParentList); dr.NextResult(); while (dr.Read()) { var child = B05_SubContinent_Child.GetB05_SubContinent_Child(dr); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B05_SubContinent_ReChild.GetB05_SubContinent_ReChild(dr); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID2); obj.LoadChild(child); } dr.NextResult(); var b05_CountryColl = B05_CountryColl.GetB05_CountryColl(dr); b05_CountryColl.LoadItems(b03_SubContinentColl); dr.NextResult(); while (dr.Read()) { var child = B07_Country_Child.GetB07_Country_Child(dr); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B07_Country_ReChild.GetB07_Country_ReChild(dr); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID2); obj.LoadChild(child); } dr.NextResult(); var b07_RegionColl = B07_RegionColl.GetB07_RegionColl(dr); b07_RegionColl.LoadItems(b05_CountryColl); dr.NextResult(); while (dr.Read()) { var child = B09_Region_Child.GetB09_Region_Child(dr); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B09_Region_ReChild.GetB09_Region_ReChild(dr); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID2); obj.LoadChild(child); } dr.NextResult(); var b09_CityColl = B09_CityColl.GetB09_CityColl(dr); b09_CityColl.LoadItems(b07_RegionColl); dr.NextResult(); while (dr.Read()) { var child = B11_City_Child.GetB11_City_Child(dr); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B11_City_ReChild.GetB11_City_ReChild(dr); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID2); obj.LoadChild(child); } dr.NextResult(); var b11_CityRoadColl = B11_CityRoadColl.GetB11_CityRoadColl(dr); b11_CityRoadColl.LoadItems(b09_CityColl); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations to manage Azure SQL Database and Database /// Server Security Alert policy. Contains operations to: Create, /// Retrieve and Update policy. /// </summary> internal partial class SecurityAlertPolicyOperations : IServiceOperations<SqlManagementClient>, ISecurityAlertPolicyOperations { /// <summary> /// Initializes a new instance of the SecurityAlertPolicyOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SecurityAlertPolicyOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Creates or updates an Azure SQL Database security alert policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// alert policy applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Azure /// SQL Database security alert policy. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateOrUpdateDatebaseSecurityAlertPolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseSecurityAlertPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatebaseSecurityAlertPolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/securityAlertPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject databaseSecurityAlertPolicyCreateOrUpdateParametersValue = new JObject(); requestDoc = databaseSecurityAlertPolicyCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); databaseSecurityAlertPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.State != null) { propertiesValue["state"] = parameters.Properties.State; } if (parameters.Properties.DisabledAlerts != null) { propertiesValue["disabledAlerts"] = parameters.Properties.DisabledAlerts; } if (parameters.Properties.EmailAddresses != null) { propertiesValue["emailAddresses"] = parameters.Properties.EmailAddresses; } if (parameters.Properties.EmailAccountAdmins != null) { propertiesValue["emailAccountAdmins"] = parameters.Properties.EmailAccountAdmins; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns an Azure SQL Database security alert policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// alert policy applies. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get database security alert policy /// request. /// </returns> public async Task<DatabaseSecurityAlertPolicyGetResponse> GetDatabaseSecurityAlertPolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "GetDatabaseSecurityAlertPolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/securityAlertPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DatabaseSecurityAlertPolicyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DatabaseSecurityAlertPolicyGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DatabaseSecurityAlertPolicy securityAlertPolicyInstance = new DatabaseSecurityAlertPolicy(); result.SecurityAlertPolicy = securityAlertPolicyInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DatabaseSecurityAlertPolicyProperties propertiesInstance = new DatabaseSecurityAlertPolicyProperties(); securityAlertPolicyInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken disabledAlertsValue = propertiesValue["disabledAlerts"]; if (disabledAlertsValue != null && disabledAlertsValue.Type != JTokenType.Null) { string disabledAlertsInstance = ((string)disabledAlertsValue); propertiesInstance.DisabledAlerts = disabledAlertsInstance; } JToken emailAddressesValue = propertiesValue["emailAddresses"]; if (emailAddressesValue != null && emailAddressesValue.Type != JTokenType.Null) { string emailAddressesInstance = ((string)emailAddressesValue); propertiesInstance.EmailAddresses = emailAddressesInstance; } JToken emailAccountAdminsValue = propertiesValue["emailAccountAdmins"]; if (emailAccountAdminsValue != null && emailAccountAdminsValue.Type != JTokenType.Null) { string emailAccountAdminsInstance = ((string)emailAccountAdminsValue); propertiesInstance.EmailAccountAdmins = emailAccountAdminsInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); securityAlertPolicyInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); securityAlertPolicyInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); securityAlertPolicyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); securityAlertPolicyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); securityAlertPolicyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Copyright 2017 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 * * 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.IO; using System.Net; using Firebase.Storage.Internal; namespace Firebase.Storage { /// <summary> /// Represents an Exception resulting from an operation on a /// <see cref="StorageReference" /> /// </summary> [Serializable] public sealed class StorageException : Exception { /// <returns>An unknown error has occurred. See the inner exception or /// <see cref="StorageException.HttpResultCode" /> for more information. /// </returns> public const int ErrorUnknown = -13000; /// <returns>The specified object could not be found on the server.</returns> public const int ErrorObjectNotFound = -13010; /// <returns>The specified bucket could not be found on the server.</returns> public const int ErrorBucketNotFound = -13011; /// <returns>The specified project could not be found on the server.</returns> public const int ErrorProjectNotFound = -13012; /// <returns>Free Tier quota has been exceeded. Change your pricing plan /// to avoid this error.</returns> public const int ErrorQuotaExceeded = -13013; /// <returns>The given signin credentials are not valid.</returns> public const int ErrorNotAuthenticated = -13020; /// <returns>The given signin credentials are not allowed to perform this operation.</returns> public const int ErrorNotAuthorized = -13021; /// <returns>The retry timeout was exceeded. Check your network connection /// or increase the value of one of <see cref="FirebaseStorage.MaxDownloadRetryTime" /> /// <see cref="FirebaseStorage.MaxUploadRetryTime" /> /// or <see cref="FirebaseStorage.MaxOperationRetryTime" /> /// </returns> public const int ErrorRetryLimitExceeded = -13030; /// <returns>There was an error validating the operation due to a checksum failure.</returns> public const int ErrorInvalidChecksum = -13031; /// <returns>The operation was canceled from the client.</returns> public const int ErrorCanceled = -13040; // Maps C++ error codes to StorageException errors and HTTP status code (where appropriate). // NOTE: The C++ implementation does not forward HTTP status codes to the user visible API. // Since the Mono implementation exposes HTTP status codes in StorageException, the following // table adds the HTTP status code for each error where appropriate. private static readonly Dictionary<ErrorInternal, Tuple<int, HttpStatusCode>> errorToStorageErrorAndHttpStatusCode = new Dictionary<ErrorInternal, Tuple<int, HttpStatusCode>>() { { ErrorInternal.ErrorObjectNotFound, new Tuple<int, HttpStatusCode>(StorageException.ErrorObjectNotFound, HttpStatusCode.NotFound) }, { ErrorInternal.ErrorBucketNotFound, new Tuple<int, HttpStatusCode>(StorageException.ErrorBucketNotFound, HttpStatusCode.NotFound) }, { ErrorInternal.ErrorProjectNotFound, new Tuple<int, HttpStatusCode>(StorageException.ErrorProjectNotFound, HttpStatusCode.NotFound) }, { ErrorInternal.ErrorQuotaExceeded, new Tuple<int, HttpStatusCode>(StorageException.ErrorProjectNotFound, HttpStatusCode.ServiceUnavailable) }, { ErrorInternal.ErrorUnauthenticated, new Tuple<int, HttpStatusCode>(StorageException.ErrorNotAuthenticated, HttpStatusCode.Unauthorized) }, { ErrorInternal.ErrorUnauthorized, new Tuple<int, HttpStatusCode>(StorageException.ErrorNotAuthorized, HttpStatusCode.Unauthorized) }, { ErrorInternal.ErrorRetryLimitExceeded, new Tuple<int, HttpStatusCode>(StorageException.ErrorRetryLimitExceeded, HttpStatusCode.Conflict) }, { ErrorInternal.ErrorNonMatchingChecksum, new Tuple<int, HttpStatusCode>(StorageException.ErrorInvalidChecksum, HttpStatusCode.Conflict) }, { ErrorInternal.ErrorDownloadSizeExceeded, new Tuple<int, HttpStatusCode>(StorageException.ErrorUnknown, 0) }, { ErrorInternal.ErrorCancelled, new Tuple<int, HttpStatusCode>(StorageException.ErrorCanceled, 0) }, }; // Used to construct an exception for an unknown network error. private static readonly Tuple<int, HttpStatusCode> unknownError = new Tuple<int, HttpStatusCode>(StorageException.ErrorUnknown, HttpStatusCode.Ambiguous); internal StorageException(int errorCode, int httpResultCode, string errorMessage) : base(String.IsNullOrEmpty(errorMessage) ? GetErrorMessageForCode(errorCode) : errorMessage) { ErrorCode = errorCode; HttpResultCode = httpResultCode; } /// <summary> /// Construct a StorageException from an AggregateException class, converting FirebaseException /// fields if it's present. /// </summary> /// <param name="exception">AggregateException to wrap. This accepts an Exception for /// so that Task.Exception can be passed to the method without casting at the call site.</param> /// <returns>StorageException instance wrapper.</returns> internal static StorageException CreateFromException(Exception exception) { Tuple<int, HttpStatusCode> errorAndStatusCode; AggregateException aggregateException = (AggregateException)exception; FirebaseException firebaseException = null; string errorMessage = null; foreach (var innerException in aggregateException.InnerExceptions) { var storageException = innerException as StorageException; firebaseException = innerException as FirebaseException; if (storageException != null) { return storageException; } else if (firebaseException != null) { break; } } // Try to convert the exception to a StorageException. if (firebaseException == null) { errorMessage = exception.ToString(); errorAndStatusCode = unknownError; } else { errorMessage = firebaseException.Message; if (!errorToStorageErrorAndHttpStatusCode.TryGetValue( (ErrorInternal)firebaseException.ErrorCode, out errorAndStatusCode)) { errorAndStatusCode = unknownError; } } int httpStatusCodeInt = (int)errorAndStatusCode.Item2; return new StorageException(errorAndStatusCode.Item1, httpStatusCodeInt, errorMessage); } /// <returns> /// A code that indicates the type of error that occurred. This value will /// be one of the set of constants defined on <see cref="StorageException" />. /// </returns> public int ErrorCode { get; private set; } /// <returns>the Http result code (if one exists) from a network operation.</returns> public int HttpResultCode { get; private set; } /// <returns> /// True if this request failed due to a network condition that /// may be resolved in a future attempt. /// </returns> public bool IsRecoverableException { get { return ErrorCode == ErrorRetryLimitExceeded; } } // TODO(smiles): Since we have error strings baked into the C++ library, determine whether this // can be removed. internal static string GetErrorMessageForCode(int errorCode) { switch (errorCode) { case ErrorUnknown: { return "An unknown error occurred, please check the HTTP result code and inner " + "exception for server response."; } case ErrorObjectNotFound: { return "Object does not exist at location."; } case ErrorBucketNotFound: { return "Bucket does not exist."; } case ErrorProjectNotFound: { return "Project does not exist."; } case ErrorQuotaExceeded: { return "Quota for bucket exceeded, please view quota on www.firebase.google" + ".com/storage."; } case ErrorNotAuthenticated: { return "User is not authenticated, please authenticate using Firebase " + "Authentication and try again."; } case ErrorNotAuthorized: { return "User does not have permission to access this object."; } case ErrorRetryLimitExceeded: { return "The operation retry limit has been exceeded."; } case ErrorInvalidChecksum: { return "Object has a checksum which does not match. Please retry the operation."; } case ErrorCanceled: { return "The operation was cancelled."; } default: { return "An unknown error occurred, please check the HTTP result code and inner " + "exception for server response."; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; namespace Microsoft.Azure.Management.Network.Fluent { using Models; using System.Collections.Generic; using ResourceManager.Fluent.Core; using System.Threading.Tasks; using System.Threading; using System.Linq; using System; using Microsoft.Rest.Azure; /// <summary> /// Implementation for Network /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uTmV0d29ya0ltcGw= internal partial class NetworkImpl : GroupableParentResourceWithTags<INetwork, VirtualNetworkInner, NetworkImpl, INetworkManager, Network.Definition.IWithGroup, Network.Definition.IWithCreate, Network.Definition.IWithCreate, Network.Update.IUpdate>, INetwork, Network.Definition.IDefinition, Network.Update.IUpdate { private ICreatable<Microsoft.Azure.Management.Network.Fluent.IDdosProtectionPlan> ddosProtectionPlanCreatable; private Dictionary<string, ISubnet> subnets; private NetworkPeeringsImpl peerings; ///GENMHASH:7BEA0E65533989105BEBCE9663A14E3A:3881994DCADCE14215F82F0CC81BDD88 internal NetworkImpl(string name, VirtualNetworkInner innerModel, INetworkManager networkManager) : base(name, innerModel, networkManager) { } ///GENMHASH:6D9F740D6D73C56877B02D9F1C96F6E7:DDD01175DC699E92E7CD9E1C4C74A5A4 override protected void InitializeChildrenFromInner() { subnets = new Dictionary<string, ISubnet>(); IList<SubnetInner> inners = Inner.Subnets; if (inners != null) { foreach (var inner in inners) { SubnetImpl subnet = new SubnetImpl(inner, this); subnets[inner.Name] = subnet; } } peerings = new NetworkPeeringsImpl(this); } ///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:D273A9F25EE8363ADDB7479305202A25 protected override async Task<VirtualNetworkInner> GetInnerAsync(CancellationToken cancellationToken) { return await Manager.Inner.VirtualNetworks.GetAsync(ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:F792498DBF3C736E27E066C92C2E7F7A:129071765816A335066AAC27F7CCCEAD internal NetworkImpl WithSubnet(SubnetImpl subnet) { if (subnet != null) { subnets[subnet.Name()] = subnet; } return this; } ///GENMHASH:C46E686F6BFED9BDC32DE6EB942E24F4:5C325A68AD1779341F5DE4F1F9B669CB internal NetworkImpl WithDnsServer(string ipAddress) { if (Inner.DhcpOptions == null) Inner.DhcpOptions = new DhcpOptions(); if (Inner.DhcpOptions.DnsServers == null) Inner.DhcpOptions.DnsServers = new List<string>(); Inner.DhcpOptions.DnsServers.Add(ipAddress); return this; } ///GENMHASH:9047F7688B1B60794F60BC930616198C:5A25E7A3D3CA299925A5FF1DA732AFE4 internal NetworkImpl WithSubnet(string name, string cidr) { return DefineSubnet(name) .WithAddressPrefix(cidr) .Attach(); } ///GENMHASH:F6CBC7DFB0D824D353A7DFE6057B8612:8CF7AA492E5A9A8A95128893182A62A1 internal NetworkImpl WithSubnets(IDictionary<string, string> nameCidrPairs) { subnets.Clear(); foreach (var pair in nameCidrPairs) { WithSubnet(pair.Key, pair.Value); } return this; } ///GENMHASH:BCFE5A6437DFDD16AB17155407828358:D7A6E191BE445D616C7D7458438BA4AC internal NetworkImpl WithoutSubnet(string name) { subnets.Remove(name); return this; } ///GENMHASH:BF356D3C256200922092FDECCE2AEA83:2164178F2F2E4C2173DC1A4CB8E69169 internal NetworkImpl WithAddressSpace(string cidr) { if (Inner.AddressSpace == null) Inner.AddressSpace = new AddressSpace(); if (Inner.AddressSpace.AddressPrefixes == null) Inner.AddressSpace.AddressPrefixes = new List<string>(); Inner.AddressSpace.AddressPrefixes.Add(cidr); return this; } ///GENMHASH:0A2FDD020AE5A41E49EC1B3AEB02B394:3B60772E45391CEB653A6108BC6868A5 internal SubnetImpl DefineSubnet(string name) { SubnetInner inner = new SubnetInner(name: name); return new SubnetImpl(inner, this); } ///GENMHASH:0A630A9A81A6D7FB1D87E339FE830A51:FD878AA481D05018C98B67E014CFC475 internal IReadOnlyList<string> AddressSpaces() { if (Inner.AddressSpace == null) return new List<string>(); else if (Inner.AddressSpace.AddressPrefixes == null) return new List<string>(); else return Inner.AddressSpace.AddressPrefixes?.ToList(); } ///GENMHASH:286FDAB5963B6F7C00ABEDCF6FE545B5:6FEBAF2F043487BFE65A5D9D04AA1315 internal IReadOnlyList<string> DnsServerIPs() { if (Inner.DhcpOptions == null) return new List<string>(); else if (Inner.DhcpOptions.DnsServers == null) return new List<string>(); else return Inner.DhcpOptions.DnsServers?.ToList(); } ///GENMHASH:690E8F594CD13FA2074316AFD9B45928:8131F4AA7A989D064C8AB8B74BFCAD25 internal IReadOnlyDictionary<string, ISubnet> Subnets() { return subnets; } ///GENMHASH:AC21A10EE2E745A89E94E447800452C1:E0C348C98FD0505C2908FDDC5F7096A1 override protected void BeforeCreating() { // Ensure address spaces if (AddressSpaces().Count == 0) { WithAddressSpace("10.0.0.0/16"); // Default address space } if (IsInCreateMode) { // Create a subnet as needed, covering the entire first address space if (subnets.Count == 0) { WithSubnet("subnet1", AddressSpaces()[0]); } } // Reset and update subnets Inner.Subnets = InnersFromWrappers<SubnetInner, ISubnet>(subnets.Values); } ///GENMHASH:F91F57741BB7E185BF012523964DEED0:B855D73B977281A4DC1F154F5A7D4DC5 protected override void AfterCreating() { InitializeChildrenFromInner(); } ///GENMHASH:073D775B4A47FA2FF6211510FDF879F4:D226D5E398319C2E7C55CCC94D6E4793 internal SubnetImpl UpdateSubnet(string name) { ISubnet subnet; subnets.TryGetValue(name, out subnet); return (SubnetImpl)subnet; } ///GENMHASH:359B78C1848B4A526D723F29D8C8C558:A394B5B2A4C946983BF7F8DE2DAA697E protected async override Task<VirtualNetworkInner> CreateInnerAsync(CancellationToken cancellationToken) { if (ddosProtectionPlanCreatable != null) { var ddosProtectionPlan = this.CreatedResource(ddosProtectionPlanCreatable.Key); WithExistingDdosProtectionPlan(ddosProtectionPlan.Id); } ddosProtectionPlanCreatable = null; return await this.Manager.Inner.VirtualNetworks.CreateOrUpdateAsync(this.ResourceGroupName, this.Name, this.Inner, cancellationToken); } ///GENMHASH:6A291EDC22581C4F2CC3D65986E9F5A3:B5C775B96E4C8B181BD73D9F917D80A6 private IPAddressAvailabilityResultInner CheckIPAvailability(string ipAddress) { if (ipAddress == null) { return null; } IPAddressAvailabilityResultInner result = null; try { result = Extensions.Synchronize(() => Manager.Networks.Inner.CheckIPAddressAvailabilityAsync( ResourceGroupName, Name, ipAddress)); } catch (CloudException e) { if (!e.Body.Code.Equals("PrivateIPAddressNotInAnySubnet", StringComparison.OrdinalIgnoreCase)) { throw e; // Rethrow if the exception reason is anything other than IP address not found } } return result; } ///GENMHASH:B7779950F6715602F8E2A9BD80364364:10D7E4D988246C2703C9CB4955EDDB07 public string DdosProtectionPlanId() { return Inner.DdosProtectionPlan == null ? null : Inner.DdosProtectionPlan.Id; } ///GENMHASH:6AC74D6FDBE69EBF2E6C71EBFAA28ABC:315575632095FCDF2361295DB923A6A6 public bool IsDdosProtectionEnabled() { return Inner.EnableDdosProtection.GetValueOrDefault(); } ///GENMHASH:8C8A52E21D5AB87F54C56A8705429BCB:4454DD801F596261F97DAB3093878A56 public bool IsVmProtectionEnabled() { return Inner.EnableVmProtection.GetValueOrDefault(); } ///GENMHASH:DAC0ADBD485D3FA7934FDCF3DF6AFB33:7A77202DEFA9CB2CDFBB1A2FD00F7FFA public INetworkPeerings Peerings() { return peerings; } ///GENMHASH:3C42C3EE58ED8EB273637D89B5D06905:46B0FEC0CFADACBCE7C272DDBAE1CF1D public bool IsPrivateIPAddressInNetwork(string ipAddress) { IPAddressAvailabilityResultInner result = CheckIPAvailability(ipAddress); return (result != null) ? true : false; } ///GENMHASH:975EDC5E759341EA29306B7C9EABDB32:881709B76B00095442458D0AB341E78F public NetworkImpl WithExistingDdosProtectionPlan(string planId) { Inner.EnableDdosProtection = true; Inner.DdosProtectionPlan = new SubResource(planId); return this; } ///GENMHASH:B93BCE53CDE70A01B7CFE70DD6DAF4DA:860FFB37184E1F1CDD3880F84DBB0BD3 public NetworkImpl WithNewDdosProtectionPlan() { Inner.EnableDdosProtection = true; var ddosProtectionPlanWithGroup = Manager.DdosProtectionPlans .Define(SdkContext.RandomResourceName(Name, 20)) .WithRegion(Region); var ddosProtectionPlanCreatable = this.newGroup != null ? ddosProtectionPlanWithGroup.WithNewResourceGroup(this.newGroup) : ddosProtectionPlanWithGroup.WithExistingResourceGroup(this.ResourceGroupName); AddCreatableDependency(ddosProtectionPlanCreatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:2DDC261430ADA2CF9ED379E7C096EA18:B86A968ED1807214F1A8C9FB5538CA47 public NetworkImpl WithoutAddressSpace(string cidr) { if (cidr == null) { // Skip } else if (Inner.AddressSpace == null) { // Skip } else if (Inner.AddressSpace.AddressPrefixes == null) { // Skip } else { Inner.AddressSpace.AddressPrefixes.Remove(cidr); } return this; } ///GENMHASH:09F7B9785A174DDAD832D685CC62A692:FB965F085372AEB63F5C3458757B644F public NetworkImpl WithoutDdosProtectionPlan() { Inner.EnableDdosProtection = false; Inner.DdosProtectionPlan = null; return this; } ///GENMHASH:BE68A28EB6432591B6E97F14DA41AB51:7FEA84D711B94AA3A0E20A20D2DCFF94 public NetworkImpl WithoutVmProtection() { Inner.EnableVmProtection = false; return this; } public NetworkImpl WithVmProtection() { Inner.EnableVmProtection = true; return this; } ///GENMHASH:6ACD1798F2E9D87878DA2A89A9C924EC:C881614C8CEC0248E97A20723E81741D public bool IsPrivateIPAddressAvailable(string ipAddress) { IPAddressAvailabilityResultInner result = CheckIPAvailability(ipAddress); if (result == null) { return false; } else if (result.Available == null) { return false; } else { return result.Available.Value; } } protected override async Task<VirtualNetworkInner> ApplyTagsToInnerAsync(CancellationToken cancellationToken = new CancellationToken()) { return await this.Manager.Inner.VirtualNetworks.UpdateTagsAsync(ResourceGroupName, Name, Inner.Tags, cancellationToken); } } }
// 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. /* TEST: Usage * DESCRIPTION: Three usage scenarios that monitor the number of live handles and GC Collections */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; // the class that holds the HandleCollectors public class HandleCollectorTest { private static HandleCollector s_hc = new HandleCollector("hc", 100); public HandleCollectorTest() { s_hc.Add(); } public static int Count { get { return s_hc.Count; } } ~HandleCollectorTest() { s_hc.Remove(); } public static void Reset() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); s_hc = new HandleCollector("hc", 100); } } public class Usage { private int _numTests = 0; private int _numInstances = 100; private const int deltaPercent = 10; // ensures GC Collections occur when handle count exceeds maximum private bool Case1() { _numTests++; // clear GC GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); HandleCollectorTest h; int original = GC.CollectionCount(0); // create objects and let them go out of scope for (int i = 0; i < _numInstances; i++) h = new HandleCollectorTest(); h = null; GC.WaitForPendingFinalizers(); // Collection should not have occurred if (GC.CollectionCount(0) != original) { Console.WriteLine("Early collection!"); Console.WriteLine("Case 1 Failed!"); return false; } new HandleCollectorTest(); if ((GC.CollectionCount(0) - original) > 0) { Console.WriteLine("Case 1 Passed!"); return true; } Console.WriteLine("Expected collection did not occur!"); Console.WriteLine("Case 1 Failed!"); return false; } // ensures GC Collection does not occur when handle count stays below maximum private bool Case2() { _numTests++; int handleCount = 0; for (int i = 0; i < _numInstances; i++) { new HandleCollectorTest(); GC.WaitForPendingFinalizers(); handleCount = HandleCollectorTest.Count; //Note that the GC should occur when handle count is 101 but it will happen at anytime after a creation and we stick to the previous //count to avoid error } Console.WriteLine("{0}, {1}", handleCount, _numInstances); if (handleCount == _numInstances) { Console.WriteLine("Case 2 Passed!"); return true; } Console.WriteLine("Case 2 Failed!"); return false; } // ensures GC Collections frequency decrease by threshold private bool Case3() { _numTests++; int gcCount = GC.CollectionCount(2); int handleCount = HandleCollectorTest.Count; int prevHandleCount = HandleCollectorTest.Count; List<HandleCollectorTest> list = new List<HandleCollectorTest>(); for (int i = 0; i < deltaPercent; i++) { do { HandleCollectorTest h = new HandleCollectorTest(); if ((HandleCollectorTest.Count % 2) == 0) list.Add(h); GC.WaitForPendingFinalizers(); if (GC.CollectionCount(2) != gcCount) { gcCount = GC.CollectionCount(2); break; } else handleCount = HandleCollectorTest.Count; } while (true); // ensure threshold is increasing if (!CheckPercentageIncrease(handleCount, prevHandleCount)) { Console.WriteLine("Case 3 failed: threshold not increasing!"); return false; } prevHandleCount = handleCount; } Console.WriteLine("Case 3 Passed!"); return true; } // Checks that the threshold increases are within 0.2 error margine of deltaPercent private bool CheckPercentageIncrease(int current, int previous) { bool retValue = true; if (previous != 0) { double value = ((double)(current - previous)) / (double)previous; double expected = (double)deltaPercent / 100; double errorMargin = Math.Abs((double)(value - expected) / (double)expected); retValue = (errorMargin < 0.2); } return retValue; } public bool RunTest() { int numPassed = 0; if (Case1()) { numPassed++; } HandleCollectorTest.Reset(); if (Case2()) { numPassed++; } HandleCollectorTest.Reset(); if (Case3()) { numPassed++; } return (numPassed == _numTests); } public static int Main() { if (GC.CollectionCount(0) > 20) { Console.WriteLine("GC Stress is enabled"); Console.WriteLine("Abort Test"); return 100; } Usage u = new Usage(); if (u.RunTest()) { Console.WriteLine(); Console.WriteLine("Test Passed!"); return 100; } Console.WriteLine(); Console.WriteLine("Test Failed!"); return 1; } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // David Stephensen (mailto:David.Stephensen@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Reflection; using System.IO; using MigraDoc.DocumentObjectModel.Internals; using MigraDoc.DocumentObjectModel.Fields; using MigraDoc.DocumentObjectModel.Shapes; namespace MigraDoc.DocumentObjectModel { /// <summary> /// A ParagraphElements collection contains the individual objects of a paragraph. /// </summary> public class ParagraphElements : DocumentObjectCollection { /// <summary> /// Initializes a new instance of the ParagraphElements class. /// </summary> public ParagraphElements() { } /// <summary> /// Initializes a new instance of the ParagraphElements class with the specified parent. /// </summary> internal ParagraphElements(DocumentObject parent) : base(parent) { } /// <summary> /// Gets a ParagraphElement by its index. /// </summary> public new DocumentObject this[int index] { get { return base[index] as DocumentObject; } } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new ParagraphElements Clone() { return (ParagraphElements)DeepCopy(); } /// <summary> /// Adds a Text object. /// </summary> /// <param name="text">Content of the new Text object.</param> /// <returns>Returns a new Text object.</returns> public Text AddText(string text) { if (text == null) throw new ArgumentNullException("text"); #if true Text txt = null; string[] lines = text.Split('\n'); int lineCount = lines.Length; for (int line = 0; line < lineCount; line++) { string[] tabParts = lines[line].Split('\t'); int count = tabParts.Length; for (int idx = 0; idx < count; idx++) { if (tabParts[idx].Length != 0) { txt = new Text(tabParts[idx]); this.Add(txt); } if (idx < count - 1) this.AddTab(); } if (line < lineCount - 1) this.AddLineBreak(); } return txt; #else Text txt = new Text(); txt.Content = text; this.Add(txt); return txt; #endif } /// <summary> /// Adds a single character repeated the specified number of times to the paragraph. /// </summary> public Text AddChar(char ch, int count) { return AddText(new string(ch, count)); } /// <summary> /// Adds a single character to the paragraph. /// </summary> public Text AddChar(char ch) { return AddText(new string(ch, 1)); } /// <summary> /// Adds a Character object. /// </summary> public Character AddCharacter(SymbolName symbolType) { return AddCharacter(symbolType, 1); } /// <summary> /// Adds one or more Character objects. /// </summary> public Character AddCharacter(SymbolName symbolType, int count) { Character character = new Character(); this.Add(character); character.SymbolName = symbolType; character.Count = count; return character; } /// <summary> /// Adds a Character object defined by a character. /// </summary> public Character AddCharacter(char ch) { return AddCharacter((SymbolName)ch, 1); } /// <summary> /// Adds one or more Character objects defined by a character. /// </summary> public Character AddCharacter(char ch, int count) { return AddCharacter((SymbolName)ch, count); } /// <summary> /// Adds a space character as many as count. /// </summary> public Character AddSpace(int count) { return this.AddCharacter(DocumentObjectModel.SymbolName.Blank, count); } /// <summary> /// Adds a horizontal tab. /// </summary> public Character AddTab() { return AddCharacter(SymbolName.Tab, 1); } /// <summary> /// Adds a line break. /// </summary> public Character AddLineBreak() { return AddCharacter(SymbolName.LineBreak, 1); } /// <summary> /// Adds a new FormattedText. /// </summary> public FormattedText AddFormattedText() { FormattedText formattedText = new FormattedText(); this.Add(formattedText); return formattedText; } /// <summary> /// Adds a new FormattedText object with the given format. /// </summary> public FormattedText AddFormattedText(TextFormat textFormat) { FormattedText formattedText = AddFormattedText(); if ((textFormat & TextFormat.Bold) == TextFormat.Bold) formattedText.Bold = true; if ((textFormat & TextFormat.NotBold) == TextFormat.NotBold) formattedText.Bold = false; if ((textFormat & TextFormat.Italic) == TextFormat.Italic) formattedText.Italic = true; if ((textFormat & TextFormat.NotItalic) == TextFormat.NotItalic) formattedText.Italic = false; if ((textFormat & TextFormat.Underline) == TextFormat.Underline) formattedText.Underline = Underline.Single; if ((textFormat & TextFormat.NoUnderline) == TextFormat.NoUnderline) formattedText.Underline = Underline.None; return formattedText; } /// <summary> /// Adds a new FormattedText with the given Font. /// </summary> public FormattedText AddFormattedText(Font font) { FormattedText formattedText = new FormattedText(); formattedText.Font.ApplyFont(font); this.Add(formattedText); return formattedText; } /// <summary> /// Adds a new FormattedText with the given text. /// </summary> public FormattedText AddFormattedText(string text) { FormattedText formattedText = new FormattedText(); formattedText.AddText(text); this.Add(formattedText); return formattedText; } /// <summary> /// Adds a new FormattedText object with the given text and format. /// </summary> public FormattedText AddFormattedText(string text, TextFormat textFormat) { FormattedText formattedText = AddFormattedText(textFormat); formattedText.AddText(text); return formattedText; } /// <summary> /// Adds a new FormattedText object with the given text and font. /// </summary> public FormattedText AddFormattedText(string text, Font font) { FormattedText formattedText = AddFormattedText(font); formattedText.AddText(text); return formattedText; } /// <summary> /// Adds a new FormattedText object with the given text and style. /// </summary> public FormattedText AddFormattedText(string text, string style) { FormattedText formattedText = AddFormattedText(text); formattedText.Style = style; return formattedText; } /// <summary> /// Adds a new Hyperlink of Type "Local", i.e. the Target is a Bookmark within the Document /// </summary> public Hyperlink AddHyperlink(string name) { Hyperlink hyperlink = new Hyperlink(); hyperlink.Name = name; this.Add(hyperlink); return hyperlink; } /// <summary> /// Adds a new Hyperlink /// </summary> public Hyperlink AddHyperlink(string name, HyperlinkType type) { Hyperlink hyperlink = new Hyperlink(); hyperlink.Name = name; hyperlink.Type = type; this.Add(hyperlink); return hyperlink; } /// <summary> /// Adds a new Bookmark. /// </summary> public BookmarkField AddBookmark(string name) { BookmarkField fieldBookmark = new BookmarkField(); fieldBookmark.Name = name; this.Add(fieldBookmark); return fieldBookmark; } /// <summary> /// Adds a new PageField. /// </summary> public PageField AddPageField() { PageField fieldPage = new PageField(); this.Add(fieldPage); return fieldPage; } /// <summary> /// Adds a new RefFieldPage. /// </summary> public PageRefField AddPageRefField(string name) { PageRefField fieldPageRef = new PageRefField(); fieldPageRef.Name = name; this.Add(fieldPageRef); return fieldPageRef; } /// <summary> /// Adds a new NumPagesField. /// </summary> public NumPagesField AddNumPagesField() { NumPagesField fieldNumPages = new NumPagesField(); this.Add(fieldNumPages); return fieldNumPages; } /// <summary> /// Adds a new SectionField. /// </summary> public SectionField AddSectionField() { SectionField fieldSection = new SectionField(); this.Add(fieldSection); return fieldSection; } /// <summary> /// Adds a new SectionPagesField. /// </summary> public SectionPagesField AddSectionPagesField() { SectionPagesField fieldSectionPages = new SectionPagesField(); this.Add(fieldSectionPages); return fieldSectionPages; } /// <summary> /// Adds a new DateField. /// </summary> /// public DateField AddDateField() { DateField fieldDate = new DateField(); this.Add(fieldDate); return fieldDate; } /// <summary> /// Adds a new DateField with the given format. /// </summary> public DateField AddDateField(string format) { DateField fieldDate = new DateField(); fieldDate.Format = format; this.Add(fieldDate); return fieldDate; } /// <summary> /// Adds a new InfoField with the given type. /// </summary> public InfoField AddInfoField(InfoFieldType iType) { InfoField fieldInfo = new InfoField(); fieldInfo.Name = iType.ToString(); this.Add(fieldInfo); return fieldInfo; } /// <summary> /// Adds a new Footnote with the specified Text. /// </summary> public Footnote AddFootnote(string text) { Footnote footnote = new Footnote(); Paragraph par = footnote.Elements.AddParagraph(); par.AddText(text); Add(footnote); return footnote; } /// <summary> /// Adds a new Footnote. /// </summary> public Footnote AddFootnote() { Footnote footnote = new Footnote(); Add(footnote); return footnote; } /// <summary> /// Adds a new Image. /// </summary> public Image AddImage(string name) { Image image = new Image(); image.Name = name; Add(image); return image; } /// <summary> /// Adds a new image to the collection from a MemoryStream. /// </summary> /// <returns></returns> public Image AddImage(MemoryStream stream) { Image image = new Image(); image.StreamBased = true; image.ImageStream = stream; image.Name = String.Empty; Add(image); return image; } /// <summary> /// /// </summary> public override void Add(DocumentObject docObj) { base.Add(docObj); } #endregion #region Internal /// <summary> /// Converts ParagraphElements into DDL. /// </summary> internal override void Serialize(Serializer serializer) { int count = Count; for (int index = 0; index < count; ++index) { DocumentObject element = this[index]; element.Serialize(serializer); } } /// <summary> /// Returns the meta object of this instance. /// </summary> internal override Meta Meta { get { if (meta == null) meta = new Meta(typeof(ParagraphElements)); return meta; } } static Meta meta; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Security; #pragma warning disable 0618 // ComInterfaceType.InterfaceIsDual is obsolete namespace System.Data.Common { internal static class UnsafeNativeMethods { // // Oleaut32 // [DllImport(Interop.Libraries.OleAut32, CharSet = CharSet.Unicode, PreserveSig = true)] static internal extern System.Data.OleDb.OleDbHResult GetErrorInfo( [In] Int32 dwReserved, [Out, MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo); [Guid("00000567-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity] internal interface ADORecordConstruction { [return: MarshalAs(UnmanagedType.Interface)] object get_Row(); //void put_Row( // [In, MarshalAs(UnmanagedType.Interface)] object pRow); //void put_ParentRow( // [In, MarshalAs(UnmanagedType.Interface)]object pRow); } [Guid("00000283-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity] internal interface ADORecordsetConstruction { [return: MarshalAs(UnmanagedType.Interface)] object get_Rowset(); [Obsolete("not used", true)] void put_Rowset(/*deleted parameters signature*/); /*[return:MarshalAs(UnmanagedType.SysInt)]*/ IntPtr get_Chapter(); //[[PreserveSig] //iint put_Chapter ( // [In] // IntPtr pcRefCount); //[[PreserveSig] //iint get_RowPosition ( // [Out, MarshalAs(UnmanagedType.Interface)] // out object ppRowPos); //[[PreserveSig] //iint put_RowPosition ( // [In, MarshalAs(UnmanagedType.Interface)] // object pRowPos); } [Guid("0000050E-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity] internal interface Recordset15 { [Obsolete("not used", true)] void get_Properties(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_AbsolutePosition(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_AbsolutePosition(/*deleted parameters signature*/); [Obsolete("not used", true)] void putref_ActiveConnection(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_ActiveConnection(/*deleted parameters signature*/); /*[return:MarshalAs(UnmanagedType.Variant)]*/ object get_ActiveConnection(); [Obsolete("not used", true)] void get_BOF(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Bookmark(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_Bookmark(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_CacheSize(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_CacheSize(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_CursorType(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_CursorType(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_EOF(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Fields(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_LockType(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_LockType(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_MaxRecords(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_MaxRecords(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_RecordCount(/*deleted parameters signature*/); [Obsolete("not used", true)] void putref_Source(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_Source(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Source(/*deleted parameters signature*/); [Obsolete("not used", true)] void AddNew(/*deleted parameters signature*/); [Obsolete("not used", true)] void CancelUpdate(/*deleted parameters signature*/); [PreserveSig] System.Data.OleDb.OleDbHResult Close(); [Obsolete("not used", true)] void Delete(/*deleted parameters signature*/); [Obsolete("not used", true)] void GetRows(/*deleted parameters signature*/); [Obsolete("not used", true)] void Move(/*deleted parameters signature*/); [Obsolete("not used", true)] void MoveNext(); [Obsolete("not used", true)] void MovePrevious(); [Obsolete("not used", true)] void MoveFirst(); [Obsolete("not used", true)] void MoveLast(); [Obsolete("not used", true)] void Open(/*deleted parameters signature*/); [Obsolete("not used", true)] void Requery(/*deleted parameters signature*/); [Obsolete("not used", true)] void _xResync(/*deleted parameters signature*/); [Obsolete("not used", true)] void Update(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_AbsolutePage(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_AbsolutePage(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_EditMode(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Filter(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_Filter(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_PageCount(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_PageSize(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_PageSize(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Sort(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_Sort(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Status(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_State(/*deleted parameters signature*/); [Obsolete("not used", true)] void _xClone(/*deleted parameters signature*/); [Obsolete("not used", true)] void UpdateBatch(/*deleted parameters signature*/); [Obsolete("not used", true)] void CancelBatch(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_CursorLocation(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_CursorLocation(/*deleted parameters signature*/); [PreserveSig] System.Data.OleDb.OleDbHResult NextRecordset( [Out]out object RecordsAffected, [Out, MarshalAs(UnmanagedType.Interface)] out object ppiRs); //[ Obsolete("not used", true)] void Supports(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void get_Collect(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void put_Collect(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void get_MarshalOptions(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void put_MarshalOptions(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void Find(/*deleted parameters signature*/); } [Guid("00000562-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity] internal interface _ADORecord { [Obsolete("not used", true)] void get_Properties(/*deleted parameters signature*/); /*[return:MarshalAs(UnmanagedType.Variant)]*/ object get_ActiveConnection(); [Obsolete("not used", true)] void put_ActiveConnection(/*deleted parameters signature*/); [Obsolete("not used", true)] void putref_ActiveConnection(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_State(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Source(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_Source(/*deleted parameters signature*/); [Obsolete("not used", true)] void putref_Source(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_Mode(/*deleted parameters signature*/); [Obsolete("not used", true)] void put_Mode(/*deleted parameters signature*/); [Obsolete("not used", true)] void get_ParentURL(/*deleted parameters signature*/); [Obsolete("not used", true)] void MoveRecord(/*deleted parameters signature*/); [Obsolete("not used", true)] void CopyRecord(/*deleted parameters signature*/); [Obsolete("not used", true)] void DeleteRecord(/*deleted parameters signature*/); [Obsolete("not used", true)] void Open(/*deleted parameters signature*/); [PreserveSig] System.Data.OleDb.OleDbHResult Close(); //[ Obsolete("not used", true)] void get_Fields(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void get_RecordType(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void GetChildren(/*deleted parameters signature*/); //[ Obsolete("not used", true)] void Cancel(); } /* typedef ULONGLONG DBLENGTH; // Offset within a rowset typedef LONGLONG DBROWOFFSET; // Number of rows typedef LONGLONG DBROWCOUNT; typedef ULONGLONG DBCOUNTITEM; // Ordinal (column number, etc.) typedef ULONGLONG DBORDINAL; typedef LONGLONG DB_LORDINAL; // Bookmarks typedef ULONGLONG DBBKMARK; // Offset in the buffer typedef ULONGLONG DBBYTEOFFSET; // Reference count of each row/accessor handle typedef ULONG DBREFCOUNT; // Parameters typedef ULONGLONG DB_UPARAMS; typedef LONGLONG DB_LPARAMS; // hash values corresponding to the elements (bookmarks) typedef DWORDLONG DBHASHVALUE; // For reserve typedef DWORDLONG DB_DWRESERVE; typedef LONGLONG DB_LRESERVE; typedef ULONGLONG DB_URESERVE; */ [ComImport, Guid("0C733A8C-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), SuppressUnmanagedCodeSecurity] internal interface IAccessor { [Obsolete("not used", true)] void AddRefAccessor(/*deleted parameters signature*/); /*[local] HRESULT CreateAccessor( [in] DBACCESSORFLAGS dwAccessorFlags, [in] DBCOUNTITEM cBindings, [in, size_is(cBindings)] const DBBINDING rgBindings[], [in] DBLENGTH cbRowSize, [out] HACCESSOR * phAccessor, [out, size_is(cBindings)] DBBINDSTATUS rgStatus[] );*/ [PreserveSig] System.Data.OleDb.OleDbHResult CreateAccessor( [In] int dwAccessorFlags, [In] IntPtr cBindings, [In] /*tagDBBINDING[]*/SafeHandle rgBindings, [In] IntPtr cbRowSize, [Out] out IntPtr phAccessor, [In, Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4)] int[] rgStatus); [Obsolete("not used", true)] void GetBindings(/*deleted parameters signature*/); /*[local] HRESULT ReleaseAccessor( [in] HACCESSOR hAccessor, [in, out, unique] DBREFCOUNT * pcRefCount );*/ [PreserveSig] System.Data.OleDb.OleDbHResult ReleaseAccessor( [In] IntPtr hAccessor, [Out] out int pcRefCount); } [Guid("0C733A93-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IChapteredRowset { [Obsolete("not used", true)] void AddRefChapter(/*deleted parameters signature*/); /*[local] HRESULT ReleaseChapter( [in] HCHAPTER hChapter, [out] DBREFCOUNT * pcRefCount );*/ [PreserveSig] System.Data.OleDb.OleDbHResult ReleaseChapter( [In] IntPtr hChapter, [Out] out int pcRefCount); } [Guid("0C733A11-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IColumnsInfo { /*[local] HRESULT GetColumnInfo( [in, out] DBORDINAL * pcColumns, [out, size_is(,(ULONG)*pcColumns)] DBCOLUMNINFO ** prgInfo, [out] OLECHAR ** ppStringsBuffer );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetColumnInfo( [Out] out IntPtr pcColumns, [Out] out IntPtr prgInfo, [Out] out IntPtr ppStringsBuffer); //[PreserveSig] //int MapColumnIDs(/* deleted parameters*/); } [Guid("0C733A10-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IColumnsRowset { /*[local] HRESULT GetAvailableColumns( [in, out] DBORDINAL * pcOptColumns, [out, size_is(,(ULONG)*pcOptColumns)] DBID ** prgOptColumns );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetAvailableColumns( [Out] out IntPtr pcOptColumns, [Out] out IntPtr prgOptColumns); /*[local] HRESULT GetColumnsRowset( [in] IUnknown * pUnkOuter, [in] DBORDINAL cOptColumns, [in, size_is((ULONG)cOptColumns)] const DBID rgOptColumns[], [in] REFIID riid, [in] ULONG cPropertySets, [in, out, size_is((ULONG)cPropertySets)] DBPROPSET rgPropertySets[], [out, iid_is(riid)] IUnknown ** ppColRowset );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetColumnsRowset( [In] IntPtr pUnkOuter, [In] IntPtr cOptColumns, [In] SafeHandle rgOptColumns, [In] ref Guid riid, [In] int cPropertySets, [In] IntPtr rgPropertySets, [Out, MarshalAs(UnmanagedType.Interface)] out IRowset ppColRowset); } [Guid("0C733A26-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface ICommandPrepare { /*[local] HRESULT Prepare( [in] ULONG cExpectedRuns );*/ [PreserveSig] System.Data.OleDb.OleDbHResult Prepare( [In] int cExpectedRuns); //[PreserveSig] //int Unprepare(); } [Guid("0C733A79-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface ICommandProperties { /*[local] HRESULT GetProperties( [in] const ULONG cPropertyIDSets, [in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[], [in, out] ULONG * pcPropertySets, [out, size_is(,*pcPropertySets)] DBPROPSET ** prgPropertySets );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetProperties( [In] int cPropertyIDSets, [In] SafeHandle rgPropertyIDSets, [Out] out int pcPropertySets, [Out] out IntPtr prgPropertySets); /*[local] HRESULT SetProperties( [in] ULONG cPropertySets, [in, out, unique, size_is(cPropertySets)] DBPROPSET rgPropertySets[] );*/ [PreserveSig] System.Data.OleDb.OleDbHResult SetProperties( [In] int cPropertySets, [In] SafeHandle rgPropertySets); } [Guid("0C733A27-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface ICommandText { /*[local] HRESULT Cancel( );*/ [PreserveSig] System.Data.OleDb.OleDbHResult Cancel(); /*[local] HRESULT Execute( [in] IUnknown * pUnkOuter, [in] REFIID riid, [in, out] DBPARAMS * pParams, [out] DBROWCOUNT * pcRowsAffected, [out, iid_is(riid)] IUnknown ** ppRowset );*/ [PreserveSig] System.Data.OleDb.OleDbHResult Execute( [In] IntPtr pUnkOuter, [In] ref Guid riid, [In] System.Data.OleDb.tagDBPARAMS pDBParams, [Out] out IntPtr pcRowsAffected, [Out, MarshalAs(UnmanagedType.Interface)] out object ppRowset); [Obsolete("not used", true)] void GetDBSession(/*deleted parameter signature*/); [Obsolete("not used", true)] void GetCommandText(/*deleted parameter signature*/); /*[local] HRESULT SetCommandText( [in] REFGUID rguidDialect, [in, unique] LPCOLESTR pwszCommand );*/ [PreserveSig] System.Data.OleDb.OleDbHResult SetCommandText( [In] ref Guid rguidDialect, [In, MarshalAs(UnmanagedType.LPWStr)] string pwszCommand); } [Guid("0C733A64-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface ICommandWithParameters { [Obsolete("not used", true)] void GetParameterInfo(/*deleted parameters signature*/); [Obsolete("not used", true)] void MapParameterNames(/*deleted parameter signature*/); /*[local] HRESULT SetParameterInfo( [in] DB_UPARAMS cParams, [in, unique, size_is((ULONG)cParams)] const DB_UPARAMS rgParamOrdinals[], [in, unique, size_is((ULONG)cParams)] const DBPARAMBINDINFO rgParamBindInfo[] );*/ [PreserveSig] System.Data.OleDb.OleDbHResult SetParameterInfo( [In] IntPtr cParams, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] rgParamOrdinals, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Struct)] System.Data.OleDb.tagDBPARAMBINDINFO[] rgParamBindInfo); } [Guid("2206CCB1-19C1-11D1-89E0-00C04FD7A829"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IDataInitialize { } [Guid("0C733A89-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IDBInfo { /*[local] HRESULT GetKeywords( [out] LPOLESTR * ppwszKeywords );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetKeywords( [Out, MarshalAs(UnmanagedType.LPWStr)] out string ppwszKeywords); /*[local] HRESULT GetLiteralInfo( [in] ULONG cLiterals, [in, size_is(cLiterals)] const DBLITERAL rgLiterals[], [in, out] ULONG * pcLiteralInfo, [out, size_is(,*pcLiteralInfo)] DBLITERALINFO ** prgLiteralInfo, [out] OLECHAR ** ppCharBuffer );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetLiteralInfo( [In] int cLiterals, [In, MarshalAs(UnmanagedType.LPArray)] int[] rgLiterals, [Out] out int pcLiteralInfo, [Out] out IntPtr prgLiteralInfo, [Out] out IntPtr ppCharBuffer); } [Guid("0C733A8A-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IDBProperties { /*[local] HRESULT GetProperties( [in] const ULONG cPropertyIDSets, [in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[], [in, out] ULONG * pcPropertySets, [out, size_is(,*pcPropertySets)] DBPROPSET ** prgPropertySets );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetProperties( [In] int cPropertyIDSets, [In] SafeHandle rgPropertyIDSets, [Out] out int pcPropertySets, [Out] out IntPtr prgPropertySets); [PreserveSig] System.Data.OleDb.OleDbHResult GetPropertyInfo( [In] int cPropertyIDSets, [In] SafeHandle rgPropertyIDSets, [Out] out int pcPropertySets, [Out] out IntPtr prgPropertyInfoSets, [Out] out IntPtr ppDescBuffer); [PreserveSig] System.Data.OleDb.OleDbHResult SetProperties( [In] int cPropertySets, [In] SafeHandle rgPropertySets); } [Guid("0C733A7B-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IDBSchemaRowset { /*[local] HRESULT GetRowset( [in] IUnknown * pUnkOuter, [in] REFGUID rguidSchema, [in] ULONG cRestrictions, [in, size_is(cRestrictions)] const VARIANT rgRestrictions[], [in] REFIID riid, [in] ULONG cPropertySets, [in, out, unique, size_is(cPropertySets)] DBPROPSET rgPropertySets[], [out, iid_is(riid)] IUnknown ** ppRowset );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetRowset( [In] IntPtr pUnkOuter, [In] ref Guid rguidSchema, [In] int cRestrictions, [In, MarshalAs(UnmanagedType.LPArray)] object[] rgRestrictions, [In] ref Guid riid, [In] int cPropertySets, [In] IntPtr rgPropertySets, [Out, MarshalAs(UnmanagedType.Interface)] out IRowset ppRowset); /*[local] HRESULT GetSchemas( [in, out] ULONG * pcSchemas, [out, size_is(,*pcSchemas)] GUID ** prgSchemas, [out, size_is(,*pcSchemas)] ULONG ** prgRestrictionSupport );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetSchemas( [Out] out int pcSchemas, [Out] out IntPtr rguidSchema, [Out] out IntPtr prgRestrictionSupport); } [Guid("1CF2B120-547D-101B-8E65-08002B2BD119"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IErrorInfo { [Obsolete("not used", true)] void GetGUID(/*deleted parameter signature*/); [PreserveSig] System.Data.OleDb.OleDbHResult GetSource( [Out, MarshalAs(UnmanagedType.BStr)] out string pBstrSource); [PreserveSig] System.Data.OleDb.OleDbHResult GetDescription( [Out, MarshalAs(UnmanagedType.BStr)] out string pBstrDescription); //[ Obsolete("not used", true)] void GetHelpFile(/*deleted parameter signature*/); //[ Obsolete("not used", true)] void GetHelpContext(/*deleted parameter signature*/); } #if false MIDL_INTERFACE("1CF2B120-547D-101B-8E65-08002B2BD119") IErrorInfo : public IUnknown virtual HRESULT STDMETHODCALLTYPE GetGUID( /* [out] */ GUID *pGUID) = 0; virtual HRESULT STDMETHODCALLTYPE GetSource( /* [out] */ BSTR *pBstrSource) = 0; virtual HRESULT STDMETHODCALLTYPE GetDescription( /* [out] */ BSTR *pBstrDescription) = 0; virtual HRESULT STDMETHODCALLTYPE GetHelpFile( /* [out] */ BSTR *pBstrHelpFile) = 0; virtual HRESULT STDMETHODCALLTYPE GetHelpContext( /* [out] */ DWORD *pdwHelpContext) = 0; #endif [Guid("0C733A67-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IErrorRecords { [Obsolete("not used", true)] void AddErrorRecord(/*deleted parameter signature*/); [Obsolete("not used", true)] void GetBasicErrorInfo(/*deleted parameter signature*/); [PreserveSig] System.Data.OleDb.OleDbHResult GetCustomErrorObject( // may return E_NOINTERFACE when asking for IID_ISQLErrorInfo [In] Int32 ulRecordNum, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out ISQLErrorInfo ppObject); [return: MarshalAs(UnmanagedType.Interface)] IErrorInfo GetErrorInfo( [In] Int32 ulRecordNum, [In] Int32 lcid); [Obsolete("not used", true)] void GetErrorParameters(/*deleted parameter signature*/); Int32 GetRecordCount(); } #if false MIDL_INTERFACE("0c733a67-2a1c-11ce-ade5-00aa0044773d") IErrorRecords : public IUnknown virtual /* [local] */ HRESULT STDMETHODCALLTYPE AddErrorRecord( /* [in] */ ERRORINFO *pErrorInfo, /* [in] */ DWORD dwLookupID, /* [in] */ DISPPARAMS *pdispparams, /* [in] */ IUnknown *punkCustomError, /* [in] */ DWORD dwDynamicErrorID) = 0; virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBasicErrorInfo( /* [in] */ ULONG ulRecordNum, /* [out] */ ERRORINFO *pErrorInfo) = 0; virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetCustomErrorObject( /* [in] */ ULONG ulRecordNum, /* [in] */ REFIID riid, /* [iid_is][out] */ IUnknown **ppObject) = 0; virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetErrorInfo( /* [in] */ ULONG ulRecordNum, /* [in] */ LCID lcid, /* [out] */ IErrorInfo **ppErrorInfo) = 0; virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetErrorParameters( /* [in] */ ULONG ulRecordNum, /* [out] */ DISPPARAMS *pdispparams) = 0; virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetRecordCount( /* [out] */ ULONG *pcRecords) = 0; #endif [Guid("0C733A90-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IMultipleResults { /*[local] HRESULT GetResult( [in] IUnknown * pUnkOuter, [in] DBRESULTFLAG lResultFlag, [in] REFIID riid, [out] DBROWCOUNT * pcRowsAffected, [out, iid_is(riid)] IUnknown ** ppRowset );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetResult( [In] IntPtr pUnkOuter, [In] IntPtr lResultFlag, [In] ref Guid riid, [Out] out IntPtr pcRowsAffected, [Out, MarshalAs(UnmanagedType.Interface)] out object ppRowset); } #if false enum DBRESULTFLAGENUM { DBRESULTFLAG_DEFAULT = 0, DBRESULTFLAG_ROWSET = 1, DBRESULTFLAG_ROW = 2 } MIDL_INTERFACE("0c733a90-2a1c-11ce-ade5-00aa0044773d") IMultipleResults : public IUnknown virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetResult( /* [in] */ IUnknown *pUnkOuter, /* [in] */ DBRESULTFLAG lResultFlag, /* [in] */ REFIID riid, /* [out] */ DBROWCOUNT *pcRowsAffected, /* [iid_is][out] */ IUnknown **ppRowset) = 0; #endif [Guid("0C733A69-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IOpenRowset { [PreserveSig] System.Data.OleDb.OleDbHResult OpenRowset( [In] IntPtr pUnkOuter, [In] System.Data.OleDb.tagDBID pTableID, [In] IntPtr pIndexID, [In] ref Guid riid, [In] int cPropertySets, [In] IntPtr rgPropertySets, [Out, MarshalAs(UnmanagedType.Interface)] out object ppRowset); } [Guid("0C733AB4-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IRow { [PreserveSig] System.Data.OleDb.OleDbHResult GetColumns( [In] IntPtr cColumns, [In, Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Struct)] System.Data.OleDb.tagDBCOLUMNACCESS[] rgColumns); //[ Obsolete("not used", true)] void GetSourceRowset(/*deleted parameter signature*/); //[ Obsolete("not used", true)] void Open(/*deleted parameter signature*/); } [Guid("0C733A7C-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IRowset { [Obsolete("not used", true)] void AddRefRows(/*deleted parameter signature*/); /*HRESULT GetData( [in] HROW hRow, [in] HACCESSOR hAccessor, [out] void * pData );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetData( [In] IntPtr hRow, [In] IntPtr hAccessor, [In] IntPtr pData); /*HRESULT GetNextRows( [in] HCHAPTER hReserved, [in] DBROWOFFSET lRowsOffset, [in] DBROWCOUNT cRows, [out] DBCOUNTITEM * pcRowsObtained, [out, size_is(,cRows)] HROW ** prghRows );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetNextRows( [In] IntPtr hChapter, [In] IntPtr lRowsOffset, [In] IntPtr cRows, [Out] out IntPtr pcRowsObtained, [In] ref IntPtr pprghRows); /*HRESULT ReleaseRows( [in] DBCOUNTITEM cRows, [in, size_is(cRows)] const HROW rghRows[], [in, size_is(cRows)] DBROWOPTIONS rgRowOptions[], [out, size_is(cRows)] DBREFCOUNT rgRefCounts[], [out, size_is(cRows)] DBROWSTATUS rgRowStatus[] );*/ [PreserveSig] System.Data.OleDb.OleDbHResult ReleaseRows( [In] IntPtr cRows, [In] SafeHandle rghRows, [In/*, MarshalAs(UnmanagedType.LPArray)*/] IntPtr/*int[]*/ rgRowOptions, [In/*, Out, MarshalAs(UnmanagedType.LPArray)*/] IntPtr/*int[]*/ rgRefCounts, [In/*, Out, MarshalAs(UnmanagedType.LPArray)*/] IntPtr/*int[]*/ rgRowStatus); [Obsolete("not used", true)] void RestartPosition(/*deleted parameter signature*/); } [Guid("0C733A55-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface IRowsetInfo { /*[local] HRESULT GetProperties( [in] const ULONG cPropertyIDSets, [in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[], [in, out] ULONG * pcPropertySets, [out, size_is(,*pcPropertySets)] DBPROPSET ** prgPropertySets );*/ [PreserveSig] System.Data.OleDb.OleDbHResult GetProperties( [In] int cPropertyIDSets, [In] SafeHandle rgPropertyIDSets, [Out] out int pcPropertySets, [Out] out IntPtr prgPropertySets); [PreserveSig] System.Data.OleDb.OleDbHResult GetReferencedRowset( [In] IntPtr iOrdinal, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IRowset ppRowset); //[PreserveSig] //int GetSpecification(/*deleted parameter signature*/); } [Guid("0C733A74-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface ISQLErrorInfo { [return: MarshalAs(UnmanagedType.I4)] Int32 GetSQLInfo( [Out, MarshalAs(UnmanagedType.BStr)] out String pbstrSQLState); } [Guid("0C733A5F-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity] internal interface ITransactionLocal { [PreserveSig] int Commit ( [In] bool fRetaining, [In] uint grfTC, [In] uint grfRM ); [PreserveSig] int Abort ( [In] IntPtr pboidReason, [In] bool fRetaining, [In] bool fAsync ); [Obsolete("not used", true)] void GetTransactionInfo(/*deleted parameter signature*/); [Obsolete("not used", true)] void GetOptionsObject(/*deleted parameter signature*/); [PreserveSig] System.Data.OleDb.OleDbHResult StartTransaction( [In] int isoLevel, [In] int isoFlags, [In] IntPtr pOtherOptions, [Out] out int pulTransactionLevel); } // we wrap the vtable entry which is just a function pointer as a delegate // since code (unlike data) doesn't move around within the process, it is safe to cache the delegate // we do not expect native to change its vtable entry at run-time (especially since these are free-threaded objects) // however to be extra safe double check the function pointer is the same as the cached delegate // whenever we encounter a new instance of the data // dangerous delegate around IUnknown::QueryInterface (0th vtable entry) [SuppressUnmanagedCodeSecurity()] internal delegate int IUnknownQueryInterface( IntPtr pThis, ref Guid riid, ref IntPtr ppInterface); // dangerous delegate around IDataInitialize::GetDataSource (4th vtable entry) [SuppressUnmanagedCodeSecurity()] internal delegate System.Data.OleDb.OleDbHResult IDataInitializeGetDataSource( IntPtr pThis, // first parameter is always the 'this' value, must use use result from QI IntPtr pUnkOuter, int dwClsCtx, [MarshalAs(UnmanagedType.LPWStr)] string pwszInitializationString, ref Guid riid, ref System.Data.OleDb.DataSourceWrapper ppDataSource); // dangerous wrapper around IDBInitialize::Initialize (4th vtable entry) [SuppressUnmanagedCodeSecurity()] internal delegate System.Data.OleDb.OleDbHResult IDBInitializeInitialize( IntPtr pThis); // first parameter is always the 'this' value, must use use result from QI // dangerous wrapper around IDBCreateSession::CreateSession (4th vtable entry) [SuppressUnmanagedCodeSecurity()] internal delegate System.Data.OleDb.OleDbHResult IDBCreateSessionCreateSession( IntPtr pThis, // first parameter is always the 'this' value, must use use result from QI IntPtr pUnkOuter, ref Guid riid, ref System.Data.OleDb.SessionWrapper ppDBSession); // dangerous wrapper around IDBCreateCommand::CreateCommand (4th vtable entry) [SuppressUnmanagedCodeSecurity()] internal delegate System.Data.OleDb.OleDbHResult IDBCreateCommandCreateCommand( IntPtr pThis, // first parameter is always the 'this' value, must use use result from QI IntPtr pUnkOuter, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] ref object ppCommand); // // Advapi32.dll Integrated security functions // [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct Trustee { internal IntPtr _pMultipleTrustee; // PTRUSTEE internal int _MultipleTrusteeOperation; // MULTIPLE_TRUSTEE_OPERATION internal int _TrusteeForm; // TRUSTEE_FORM internal int _TrusteeType; // TRUSTEE_TYPE [MarshalAs(UnmanagedType.LPTStr)] internal string _name; internal Trustee(string name) { _pMultipleTrustee = IntPtr.Zero; _MultipleTrusteeOperation = 0; // NO_MULTIPLE_TRUSTEE _TrusteeForm = 1; // TRUSTEE_IS_NAME _TrusteeType = 1; // TRUSTEE_IS_USER _name = name; } } [DllImport(Interop.Libraries.Advapi32, EntryPoint = "CreateWellKnownSid", SetLastError = true, CharSet = CharSet.Unicode)] static internal extern int CreateWellKnownSid( int sidType, byte[] domainSid, [Out] byte[] resultSid, ref uint resultSidLength); } }
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC 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; namespace Tiraggo.DynamicQuery { /// <summary> /// The query type /// </summary> public enum tgQueryType { /// <summary> /// Unassigned /// </summary> Unassigned = 0, /// <summary> /// TableDirect /// </summary> TableDirect, /// <summary> /// StoredProcedure /// </summary> StoredProcedure, /// <summary> /// Database Function /// </summary> Function, /// <summary> /// DynamicQuery /// </summary> DynamicQuery, /// <summary> /// DynamicQuery returns only the SQL, doesn't execute the query /// </summary> DynamicQueryParseOnly, /// <summary> /// Raw Text /// </summary> Text, /// <summary> /// ManyToMany - Used internally by the EntitySpaces Hierarchical code. /// </summary> ManyToMany } /// <summary> /// The type of SubOperator such as ToLower /// </summary> /// Aggregate and GROUP BY Feature Support by DBMS: /// <code> /// MS MS My SQ Vista Fire Post /// Feature SQL Acces SQL Lite DB bird gre Oracle Ads /// --------------- ----- ----- ----- ----- ----- ----- ----- ------ ----- /// Avg Y Y Y Y Y Y Y Y Y /// Count Y Y Y Y Y Y Y Y Y /// Max Y Y Y Y Y Y Y Y Y /// Min Y Y Y Y Y Y Y Y Y /// Sum Y Y Y Y Y Y Y Y Y /// StdDev Y Y Y - Y - Y (4) - /// Var Y Y Y - - - Y Y - /// Aggregate in /// ORDER BY Y Y (1) Y (3) Y Y Y Y /// GROUP BY - - - Y (3) Y Y Y - /// WITH ROLLUP Y - (2) - Y - - Y - /// COUNT(DISTINCT) Y - Y - Y Y Y Y Y /// /// Notes: /// (1) - MySQL - accepts an aggregate's alias in an /// ORDER BY clause. /// (2) - MySQL - WITH ROLLUP and ORDER BY are mutually /// exclusive /// (3) - VistaDB - will not ORDER BY or GROUP BY 'COUNT(*)' /// the rest works fine. /// (4) - Uses TRUNC(STDDEV(column),10) to avoid overflow errors /// /// </code> [Serializable] public enum tgQuerySubOperatorType { /// <summary> /// Unassigned /// </summary> Unassigned = 0, /// <summary> /// Convert to upper case /// </summary> ToUpper, /// <summary> /// Convert to lower case /// </summary> ToLower, /// <summary> /// Left trim any leading spaces /// </summary> LTrim, /// <summary> /// Right trin any trailing spaces /// </summary> RTrim, /// <summary> /// Trim both leading and trailing spaces /// </summary> Trim, /// <summary> /// Return a sub-string /// </summary> SubString, /// <summary> /// Return the first non null evaluating expresssion /// </summary> Coalesce, /// <summary> /// Returns only the date of a datetime type /// </summary> Date, /// <summary> /// If the string contains multi-byte characters, and the proper collation is being used, /// LENGTH returns the number of characters, not the number of bytes. If string is of /// BINARY data type, the LENGTH function behaves as BYTE_LENGTH. /// </summary> Length, /// <summary> /// Rounds the numeric-expression to the specified integer-expression amount of places after the decimal point. /// </summary> Round, /// <summary> /// Returns the value of part of a datetime value. /// </summary> DatePart, /// <summary> /// Average /// </summary> Avg, /// <summary> /// Count /// </summary> Count, /// <summary> /// Maximum /// </summary> Max, /// <summary> /// Minimum /// </summary> Min, /// <summary> /// Standard Deviation /// </summary> StdDev, /// <summary> /// Variance /// </summary> Var, /// <summary> /// Sum /// </summary> Sum, /// <summary> /// /// </summary> Cast } /// <summary> /// The direction used by DynamicQuery.AddOrderBy /// </summary> public enum tgOrderByDirection { /// <summary> /// Unassigned /// </summary> Unassigned = 0, /// <summary> /// Ascending /// </summary> Ascending, /// <summary> /// Descending /// </summary> Descending }; /// <summary> /// The type of comparison in a Where clause /// </summary> [Serializable] public enum tgComparisonOperand { /// <summary> /// Unassigned /// </summary> Unassigned = 0, /// <summary> /// Equal Comparison /// </summary> Equal = 1, /// <summary> /// Not Equal Comparison /// </summary> NotEqual, /// <summary> /// Greater Than Comparison /// </summary> GreaterThan, /// <summary> /// Greater Than or Equal Comparison /// </summary> GreaterThanOrEqual, /// <summary> /// Less Than Comparison /// </summary> LessThan, /// <summary> /// Less Than or Equal Comparison /// </summary> LessThanOrEqual, /// <summary> /// Like Comparison, "%s%" does it have an 's' in it? "s%" does it begin with 's'? /// </summary> Like, /// <summary> /// Is the value null in the database /// </summary> IsNull, /// <summary> /// Is the value non-null in the database /// </summary> IsNotNull, /// <summary> /// Is the value between two parameters? /// Note that Between can be for other data types than just dates. /// </summary> Between, /// <summary> /// Is the value in a list, ie, "4,5,6,7,8" /// </summary> In, /// <summary> /// NOT in a list, ie not in, "4,5,6,7,8" /// </summary> NotIn, /// <summary> /// Not Like Comparison, "%s%", anything that does not it have an 's' in it. /// </summary> NotLike, /// <summary> /// SQL Server only - /// Contains is used to search columns containing /// character-based data types for precise or /// fuzzy (less precise) matches to single words and phrases. /// The column must have a Full Text index. /// </summary> Contains, /// <summary> /// A subquery is being used in an Exists command /// </summary> Exists, /// <summary> /// A subquery is being used in an Not Exists command /// </summary> NotExists }; /// <summary> /// The conjunction used between WhereParameters /// </summary> public enum tgConjunction { /// <summary> /// WhereParameters are used via the default passed into DynamicQuery.Load. /// </summary> Unassigned = 0, /// <summary> /// WhereParameters are joined via "And" /// </summary> And, /// <summary> /// WhereParameters are joined via "Or" /// </summary> Or, /// <summary> /// WhereParameters are joined via "And Not" /// </summary> AndNot, /// <summary> /// WhereParameters are joined via "Or Not" /// </summary> OrNot }; /// <summary> /// The Parenthesis used in queries, '(' and ')' /// </summary> public enum tgParenthesis { /// <summary> /// Unassigned. /// </summary> Unassigned = 0, /// <summary> /// WhereParameters need an open paren '(' /// </summary> Open, /// <summary> /// WhereParameters need a closing paren ')' /// </summary> Close }; /// <summary> /// ANY, ALL, and SOME are SubQuery qualifiers. /// <remarks> /// SubQuery qualifiers precede the SubQuery they apply to. For most databases, ANY and SOME are synonymous. /// Usually, if you use an operator (= | &lt;> | != | > | >= | !> | &lt; | &lt;= | !&lt;) in a Where clause against a SubQuery, /// then the SubQuery must return a single value. By applying a qualifier to the SubQuery, you can use operators against SubQueries /// that return multiple results. /// </remarks> /// </summary> /// <example> /// Notice, below, that the ALL qualifier is set to true for the SubQuery with "cq.es.All = true". /// This query searches for the DateAdded for Customers whose Manager = 3. /// <code> /// // DateAdded for Customers whose Manager = 3 /// CustomerQuery cq = new CustomerQuery("c"); /// cq.es.All = true; // &lt;== This will set it to tgSubquerySearchCondition.ALL /// cq.Select(cq.DateAdded); /// cq.Where(cq.Manager == 3); /// /// // OrderID and CustID where the OrderDate is /// // less than all of the dates in the CustomerQuery above. /// OrderQuery oq = new OrderQuery("o"); /// oq.Select( /// oq.OrderID, /// oq.CustID /// ); /// oq.Where(oq.OrderDate &lt; cq); /// /// OrderCollection collection = new OrderCollection(); /// collection.Load(oq); /// </code> /// </example> public enum tgSubquerySearchCondition { /// <summary> /// Unassigned. /// </summary> Unassigned = 0, /// <summary> /// scalar_expression { = | &lt;> | != | > | >= | !> | &lt; | &lt;= | !&lt; } ALL ( subquery ) /// </summary> All, /// <summary> /// scalar_expression { = | &lt;> | != | > | >= | !> | &lt; | &lt;= | !&lt; } ANY ( subquery ) /// </summary> Any, /// <summary> /// scalar_expression { = | &lt;> | != | > | >= | !> | &lt; | &lt;= | !&lt; } Some ( subquery ) /// </summary> Some } /// <summary> /// The Type of Join /// </summary> public enum tgJoinType { /// <summary> /// Unassigned. /// </summary> Unassigned = 0, /// <summary> /// INNER JOIN /// </summary> InnerJoin, /// <summary> /// LEFT OUTER JOIN /// </summary> LeftJoin, /// <summary> /// RIGHT OUTER JOIN /// </summary> RightJoin, /// <summary> /// FULL OUTER JOIN /// </summary> FullJoin, /// <summary> /// CROSS JOIN /// </summary> CrossJoin }; /// <summary> /// The type of Combination /// </summary> public enum tgSetOperationType { /// <summary> /// Unassigned. /// </summary> Unassigned = 0, /// <summary> /// UNION /// </summary> Union, /// <summary> /// UNION ALL /// </summary> UnionAll, /// <summary> /// INTERSECT /// </summary> Intersect, /// <summary> /// EXCEPT /// </summary> Except } /// <summary> /// Used to Track arithmetic expression in the DynamicQuery API /// </summary> public enum tgArithmeticOperator { /// <summary> /// Unassigned. /// </summary> Unassigned = 0, /// <summary> /// Addition /// </summary> Add, /// <summary> /// Subtraction /// </summary> Subtract, /// <summary> /// Multiplication /// </summary> Multiply, /// <summary> /// Division /// </summary> Divide, /// <summary> /// Returns the remainder of one number divided by another. /// </summary> Modulo }; /// <summary> /// Used to track the type of Cast requested, set automatically by the implicit cast /// operators such as (tgString)query.Age. See also <see cref="tgQueryItem.Cast"/> /// </summary> public enum tgCastType { /// <summary> /// Unassigned. /// </summary> Unassigned = 0, /// <summary> /// Self Explanatory /// </summary> Boolean, /// <summary> /// Self Explanatory /// </summary> Byte, /// <summary> /// Self Explanatory /// </summary> Char, /// <summary> /// Self Explanatory /// </summary> DateTime, /// <summary> /// Self Explanatory /// </summary> Double, /// <summary> /// Self Explanatory /// </summary> Decimal, /// <summary> /// Self Explanatory /// </summary> Guid, /// <summary> /// Self Explanatory /// </summary> Int16, /// <summary> /// Self Explanatory /// </summary> Int32, /// <summary> /// Self Explanatory /// </summary> Int64, /// <summary> /// Self Explanatory /// </summary> Single, /// <summary> /// Self Explanatory /// </summary> String } /// <summary> /// Used to track data types in various places within the EntitySpaces Architecture /// </summary> public enum tgSystemType { /// <summary> /// Unassigned. /// </summary> Unassigned = 0, /// <summary> /// System.Boolean /// </summary> Boolean, /// <summary> /// System.Byte /// </summary> Byte, /// <summary> /// System.Byte /// </summary> Binary, /// <summary> /// System.Char /// </summary> Char, /// <summary> /// System.DateTime /// </summary> DateTime, /// <summary> /// System.DateTimeOffset /// </summary> DateTimeOffset, /// <summary> /// System.Double /// </summary> Double, /// <summary> /// System.Decimal /// </summary> Decimal, /// <summary> /// System.Guid /// </summary> Guid, /// <summary> /// System.Int16 /// </summary> Int16, /// <summary> /// System.Int32 /// </summary> Int32, /// <summary> /// System.Int64 /// </summary> Int64, /// <summary> /// System.Object /// </summary> Object, /// <summary> /// System.SByte /// </summary> SByte, /// <summary> /// System.Single /// </summary> Single, /// <summary> /// System.String /// </summary> String, /// <summary> /// System.TimeSpan /// </summary> TimeSpan, /// <summary> /// System.UInt16 /// </summary> UInt16, /// <summary> /// System.UInt32 /// </summary> UInt32, /// <summary> /// System.UInt64 /// </summary> UInt64, // Arrays /// <summary> /// System.Boolean[] /// </summary> BooleanArray, /// <summary> /// System.Byte[] /// </summary> ByteArray, /// <summary> /// System.Char[] /// </summary> CharArray, /// <summary> /// System.DateTime[] /// </summary> DateTimeArray, /// <summary> /// System.Double[] /// </summary> DoubleArray, /// <summary> /// System.Decimal[] /// </summary> DecimalArray, /// <summary> /// System.Guid[] /// </summary> GuidArray, /// <summary> /// System.Int16[] /// </summary> Int16Array, /// <summary> /// System.Int32[] /// </summary> Int32Array, /// <summary> /// System.Int32[] /// </summary> Int64Array, /// <summary> /// System.Object[] /// </summary> ObjectArray, /// <summary> /// System.SByte[] /// </summary> SByteArray, /// <summary> /// System.Single[] /// </summary> SingleArray, /// <summary> /// System.String[] /// </summary> StringArray, /// <summary> /// System.TimeSpan[] /// </summary> TimeSpanArray, /// <summary> /// System.UInt16[] /// </summary> UInt16Array, /// <summary> /// System.UInt32[] /// </summary> UInt32Array, /// <summary> /// System.UInt64[] /// </summary> UInt64Array }; }
using J2N.IO; using Lucene.Net.Diagnostics; using Lucene.Net.Util.Fst; using System; using System.IO; using System.Runtime.CompilerServices; namespace Lucene.Net.Store { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Base <see cref="IndexInput"/> implementation that uses an array /// of <see cref="ByteBuffer"/>s to represent a file. /// <para/> /// Because Java's <see cref="ByteBuffer"/> uses an <see cref="int"/> to address the /// values, it's necessary to access a file greater /// <see cref="int.MaxValue"/> in size using multiple byte buffers. /// <para/> /// For efficiency, this class requires that the buffers /// are a power-of-two (<c>chunkSizePower</c>). /// </summary> public abstract class ByteBufferIndexInput : IndexInput { private ByteBuffer[] buffers; private readonly long chunkSizeMask; private readonly int chunkSizePower; private int offset; private long length; private string sliceDescription; private int curBufIndex; private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex] private bool isClone = false; // LUCENENET: Using ConditionalWeakTable rather than WeakIdenityMap. ConditionalWeakTable // uses RuntimeHelpers.GetHashCode() to find the item, so technically, it IS an identity collection. private ConditionalWeakTable<ByteBufferIndexInput, BoolRefWrapper> clones; private class BoolRefWrapper { private bool value; // .NET port: this is needed as bool is not a reference type public BoolRefWrapper(bool value) { this.value = value; } public static implicit operator bool(BoolRefWrapper value) { return value.value; } public static implicit operator BoolRefWrapper(bool value) { return new BoolRefWrapper(value); } } internal ByteBufferIndexInput(string resourceDescription, ByteBuffer[] buffers, long length, int chunkSizePower, bool trackClones) : base(resourceDescription) { //this.buffers = buffers; // LUCENENET: this is set in SetBuffers() this.length = length; this.chunkSizePower = chunkSizePower; this.chunkSizeMask = (1L << chunkSizePower) - 1L; // LUCENENET: Using ConditionalWeakTable rather than WeakIdenityMap. ConditionalWeakTable // uses RuntimeHelpers.GetHashCode() to find the item, so technically, it IS an identity collection. this.clones = trackClones ? new ConditionalWeakTable<ByteBufferIndexInput, BoolRefWrapper>() : null; if (Debugging.AssertsEnabled) { Debugging.Assert(chunkSizePower >= 0 && chunkSizePower <= 30); Debugging.Assert(((long)((ulong)length >> chunkSizePower)) < int.MaxValue); } // LUCENENET specific: MMapIndexInput calls SetBuffers() to populate // the buffers, so we need to skip that call if it is null here, and // do the seek inside SetBuffers() if (buffers != null) { SetBuffers(buffers); } } // LUCENENET specific for encapsulating buffers field. internal void SetBuffers(ByteBuffer[] buffers) // necessary for MMapIndexInput { this.buffers = buffers; Seek(0L); } public override sealed byte ReadByte() { // LUCENENET: Refactored to avoid calls on invalid conditions instead of // catching and re-throwing exceptions in the normal workflow. EnsureOpen(); if (curBuf.HasRemaining) { return curBuf.Get(); } do { curBufIndex++; if (curBufIndex >= buffers.Length) { throw new EndOfStreamException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.Position = 0; } while (!curBuf.HasRemaining); return curBuf.Get(); } public override sealed void ReadBytes(byte[] b, int offset, int len) { // LUCENENET: Refactored to avoid calls on invalid conditions instead of // catching and re-throwing exceptions in the normal workflow. EnsureOpen(); int curAvail = curBuf.Remaining; if (len <= curAvail) { curBuf.Get(b, offset, len); } else { while (len > curAvail) { curBuf.Get(b, offset, curAvail); len -= curAvail; offset += curAvail; curBufIndex++; if (curBufIndex >= buffers.Length) { throw new EndOfStreamException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.Position = 0; curAvail = curBuf.Remaining; } curBuf.Get(b, offset, len); } } /// <summary> /// NOTE: this was readShort() in Lucene /// </summary> public override sealed short ReadInt16() { // LUCENENET: Refactored to avoid calls on invalid conditions instead of // catching and re-throwing exceptions in the normal workflow. EnsureOpen(); if (curBuf.Remaining >= 2) { return curBuf.GetInt16(); } return base.ReadInt16(); } /// <summary> /// NOTE: this was readInt() in Lucene /// </summary> public override sealed int ReadInt32() { // LUCENENET: Refactored to avoid calls on invalid conditions instead of // catching and re-throwing exceptions in the normal workflow. EnsureOpen(); if (curBuf.Remaining >= 4) { return curBuf.GetInt32(); } return base.ReadInt32(); } /// <summary> /// NOTE: this was readLong() in Lucene /// </summary> public override sealed long ReadInt64() { // LUCENENET: Refactored to avoid calls on invalid conditions instead of // catching and re-throwing exceptions in the normal workflow. EnsureOpen(); if (curBuf.Remaining >= 8) { return curBuf.GetInt64(); } return base.ReadInt64(); } public override sealed long GetFilePointer() { // LUCENENET: Refactored to avoid calls on invalid conditions instead of // catching and re-throwing exceptions in the normal workflow. EnsureOpen(); return (((long)curBufIndex) << chunkSizePower) + curBuf.Position - offset; } public override sealed void Seek(long pos) { // necessary in case offset != 0 and pos < 0, but pos >= -offset if (pos < 0L) { throw new ArgumentException("Seeking to negative position: " + this); } pos += offset; // we use >> here to preserve negative, so we will catch AIOOBE, // in case pos + offset overflows. int bi = (int)(pos >> chunkSizePower); try { ByteBuffer b = buffers[bi]; b.Position = ((int)(pos & chunkSizeMask)); // write values, on exception all is unchanged this.curBufIndex = bi; this.curBuf = b; } catch (IndexOutOfRangeException) { throw new EndOfStreamException("seek past EOF: " + this); } catch (ArgumentException) { throw new EndOfStreamException("seek past EOF: " + this); } catch (NullReferenceException) { throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this); } } public override sealed long Length => length; public override sealed object Clone() { ByteBufferIndexInput clone = BuildSlice(0L, this.length); try { clone.Seek(GetFilePointer()); } catch (IOException ioe) { throw new Exception("Should never happen: " + this, ioe); } return clone; } /// <summary> /// Creates a slice of this index input, with the given description, offset, and length. The slice is seeked to the beginning. /// </summary> public ByteBufferIndexInput Slice(string sliceDescription, long offset, long length) { if (isClone) // well we could, but this is stupid { throw new InvalidOperationException("cannot slice() " + sliceDescription + " from a cloned IndexInput: " + this); } ByteBufferIndexInput clone = BuildSlice(offset, length); clone.sliceDescription = sliceDescription; try { clone.Seek(0L); } catch (IOException ioe) { throw new Exception("Should never happen: " + this, ioe); } return clone; } private ByteBufferIndexInput BuildSlice(long offset, long length) { if (buffers == null) { throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this); } if (offset < 0 || length < 0 || offset + length > this.length) { throw new ArgumentException("slice() " + sliceDescription + " out of bounds: offset=" + offset + ",length=" + length + ",fileLength=" + this.length + ": " + this); } // include our own offset into the final offset: offset += this.offset; ByteBufferIndexInput clone = (ByteBufferIndexInput)base.Clone(); clone.isClone = true; // we keep clone.clones, so it shares the same map with original and we have no additional cost on clones if (Debugging.AssertsEnabled) Debugging.Assert(clone.clones == this.clones); clone.buffers = BuildSlice(buffers, offset, length); clone.offset = (int)(offset & chunkSizeMask); clone.length = length; // register the new clone in our clone list to clean it up on closing: if (clones != null) { this.clones.Add(clone, true); } return clone; } /// <summary> /// Returns a sliced view from a set of already-existing buffers: /// the last buffer's <see cref="J2N.IO.Buffer.Limit"/> will be correct, but /// you must deal with <paramref name="offset"/> separately (the first buffer will not be adjusted) /// </summary> private ByteBuffer[] BuildSlice(ByteBuffer[] buffers, long offset, long length) { long sliceEnd = offset + length; int startIndex = (int)((long)((ulong)offset >> chunkSizePower)); int endIndex = (int)((long)((ulong)sliceEnd >> chunkSizePower)); // we always allocate one more slice, the last one may be a 0 byte one ByteBuffer[] slices = new ByteBuffer[endIndex - startIndex + 1]; for (int i = 0; i < slices.Length; i++) { slices[i] = buffers[startIndex + i].Duplicate(); } // set the last buffer's limit for the sliced view. slices[slices.Length - 1].Limit = ((int)(sliceEnd & chunkSizeMask)); return slices; } private void UnsetBuffers() { buffers = null; curBuf = null; curBufIndex = 0; } // LUCENENET specific - rather than using all of this exception catching nonsense // for control flow, we check whether we are disposed first. private void EnsureOpen() { if (buffers == null || curBuf == null) { throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this); } } protected override void Dispose(bool disposing) { if (disposing) { try { if (buffers == null) { return; } // make local copy, then un-set early ByteBuffer[] bufs = buffers; UnsetBuffers(); if (clones != null) { clones.Remove(this); } if (isClone) { return; } // for extra safety unset also all clones' buffers: if (clones != null) { // LUCENENET: Since .NET will GC types that go out of scope automatically, // this isn't strictly necessary. However, we are doing it anyway when // the enumerator is available (.NET Standard 2.1+) #if FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR foreach (var pair in clones) { if (Debugging.AssertsEnabled) Debugging.Assert(pair.Key.isClone); pair.Key.UnsetBuffers(); } this.clones.Clear(); #endif this.clones = null; // LUCENENET: de-reference the table so it can be GC'd } foreach (ByteBuffer b in bufs) { FreeBuffer(b); // LUCENENET: This calls Dispose() when necessary } } finally { UnsetBuffers(); } } } /// <summary> /// Called when the contents of a buffer will be no longer needed. /// </summary> protected abstract void FreeBuffer(ByteBuffer b); public override sealed string ToString() { if (sliceDescription != null) { return base.ToString() + " [slice=" + sliceDescription + "]"; } else { return base.ToString(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MediatR; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using VodManager.Helpers; using VodManager.Models; using VodManager.Hubs; namespace VodManager.Services { public class RabbitDataHandler : INotificationHandler<RabbitRawRunChangeEvent>, INotificationHandler<RabbitRawSceneChangeEvent>, INotificationHandler<RabbitRawTimerChangeEvent> { private readonly VodManagerContext dbCtx; private readonly ILogger<RabbitDataHandler> logger; private readonly IMediator mediator; private readonly IHubContext<RunUpdateHub, IRunUpdateHub> runUpdateHub; private readonly TwitchHelper twitchHelper; private readonly IOptionsSnapshot<VodManagerOptions> optionsSnapshot; public RabbitDataHandler( VodManagerContext dbCtx, ILogger<RabbitDataHandler> logger, IMediator mediator, IHubContext<RunUpdateHub, IRunUpdateHub> runUpdateHub, TwitchHelper twitchHelper, IOptionsSnapshot<VodManagerOptions> optionsSnapshot) { this.dbCtx = dbCtx; this.logger = logger; this.mediator = mediator; this.runUpdateHub = runUpdateHub; this.twitchHelper = twitchHelper; this.optionsSnapshot = optionsSnapshot; } private long ParseTimeToken(JToken time) { JToken iso = time["iso"]; if (iso != null) return iso.Value<DateTimeOffset>().ToUnixTimeSeconds(); JToken unix = time["unix"]; if (unix != null) return Convert.ToInt64(unix.Value<double>()); throw new ArgumentException("time entry contains no known time format"); } private Task<JObject> ParseJson(string json, CancellationToken cancellationToken) { var reader = new JsonTextReader(new StringReader(json)) { DateParseHandling = DateParseHandling.DateTimeOffset }; return JObject.LoadAsync(reader, cancellationToken); } public async Task Handle(RabbitRawRunChangeEvent runEvent, CancellationToken cancellationToken) { JObject dataObj = await ParseJson(runEvent.Data, cancellationToken); RunChangedEvent evt = new RunChangedEvent() { Timestamp = ParseTimeToken(dataObj["time"]) }; Run newRun = null; if (dataObj.TryGetValue("run", out JToken run) && run.HasValues) { evt.RunID = run["id"].Value<int>() + 1; evt.GameName = run["game"].Value<string>(); evt.CategoryName = run["category"].Value<string>(); foreach (JToken team in run["teams"]) foreach(JToken player in team["players"]) evt.PlayerNamesTwitch.Add(player["name"].Value<string>(), player["social"]["twitch"].Value<string>()); if (!await dbCtx.Runs.AnyAsync(r => r.ID == evt.RunID, cancellationToken)) { newRun = new Run() { ID = evt.RunID, RelevantEvent = evt }; dbCtx.Runs.Add(newRun); evt.DataProcessed = true; } } await dbCtx.RunChangedEvents.AddAsync(evt, cancellationToken); await dbCtx.SaveChangesAsync(cancellationToken); if (newRun != null) await runUpdateHub.Clients.All.UpdateRun(newRun, optionsSnapshot.Value); _ = mediator.Publish(new RabbitRunChangeEvent() { Data = dataObj, EventID = evt.ID, RunChangedEvent = evt }); } public async Task Handle(RabbitRawSceneChangeEvent sceneEvent, CancellationToken cancellationToken) { JObject dataObj = await ParseJson(sceneEvent.Data, cancellationToken); if (!dataObj["gameScene"].Value<bool>()) return; SceneEvent evt = new SceneEvent() { Timestamp = ParseTimeToken(dataObj["time"]), SceneName = dataObj["scene"].Value<string>() }; switch (dataObj["action"].Value<string>().ToLower()) { case "start": evt.SceneEventType = SceneEventType.Start; break; case "end": evt.SceneEventType = SceneEventType.End; break; default: throw new ArgumentException("Unsupported scene action"); } try { var twitchRes = await twitchHelper.GetCurrentPastBroadcastInfoAsync(cancellationToken); evt.TwitchPastBroadcastID = twitchRes.VideoID; evt.TwitchPastBroadcastStartTimestamp = twitchRes.StartTimestamp; } catch(Exception e) { logger.LogWarning(e, "Failed getting current twitch past broadcast"); evt.TwitchPastBroadcastID = 0; evt.TwitchPastBroadcastStartTimestamp = 0; } await dbCtx.SceneEvents.AddAsync(evt, cancellationToken); await dbCtx.SaveChangesAsync(cancellationToken); _ = mediator.Publish(new RabbitSceneChangeEvent() { Data = dataObj, EventID = evt.ID, SceneEvent = evt }); } public async Task Handle(RabbitRawTimerChangeEvent timerEvent, CancellationToken cancellationToken) { JObject dataObj = await ParseJson(timerEvent.Data, cancellationToken); TimerEvent evt = new TimerEvent() { Timestamp = ParseTimeToken(dataObj["time"]) }; switch (dataObj["desc"].Value<string>().ToLower()) { case "started": evt.TimerEventType = TimerEventType.Start; break; case "finished": evt.TimerEventType = TimerEventType.Finish; break; case "reset": evt.TimerEventType = TimerEventType.Reset; break; default: throw new ArgumentException("Unsupported timer description"); } try { var twitchRes = await twitchHelper.GetCurrentPastBroadcastInfoAsync(cancellationToken); evt.TwitchPastBroadcastID = twitchRes.VideoID; evt.TwitchPastBroadcastStartTimestamp = twitchRes.StartTimestamp; } catch (Exception e) { logger.LogWarning(e, "Failed getting current twitch past broadcast"); evt.TwitchPastBroadcastID = 0; evt.TwitchPastBroadcastStartTimestamp = 0; } await dbCtx.TimerEvents.AddAsync(evt, cancellationToken); await dbCtx.SaveChangesAsync(cancellationToken); _ = mediator.Publish(new RabbitTimerChangeEvent() { Data = dataObj, EventID = evt.ID, TimerEvent = evt }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Compute; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Describes a virtual machine scale set virtual machine. /// </summary> [Rest.Serialization.JsonTransformation] public partial class VirtualMachineScaleSetVM : Resource { /// <summary> /// Initializes a new instance of the VirtualMachineScaleSetVM class. /// </summary> public VirtualMachineScaleSetVM() { CustomInit(); } /// <summary> /// Initializes a new instance of the VirtualMachineScaleSetVM class. /// </summary> /// <param name="location">Resource location</param> /// <param name="id">Resource Id</param> /// <param name="name">Resource name</param> /// <param name="type">Resource type</param> /// <param name="tags">Resource tags</param> /// <param name="instanceId">The virtual machine instance ID.</param> /// <param name="sku">The virtual machine SKU.</param> /// <param name="latestModelApplied">Specifies whether the latest model /// has been applied to the virtual machine.</param> /// <param name="vmId">Azure VM unique ID.</param> /// <param name="instanceView">The virtual machine instance /// view.</param> /// <param name="hardwareProfile">The hardware profile.</param> /// <param name="storageProfile">The storage profile.</param> /// <param name="osProfile">The OS profile.</param> /// <param name="networkProfile">The network profile.</param> /// <param name="diagnosticsProfile">The diagnostics profile.</param> /// <param name="availabilitySet">The reference Id of the availability /// set to which this virtual machine belongs.</param> /// <param name="provisioningState">The provisioning state, which only /// appears in the response.</param> /// <param name="licenseType">The license type, which is for bring your /// own license scenario.</param> /// <param name="plan">The purchase plan when deploying virtual machine /// from VM Marketplace images.</param> /// <param name="resources">The virtual machine child extension /// resources.</param> public VirtualMachineScaleSetVM(string location, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string instanceId = default(string), Sku sku = default(Sku), bool? latestModelApplied = default(bool?), string vmId = default(string), VirtualMachineInstanceView instanceView = default(VirtualMachineInstanceView), HardwareProfile hardwareProfile = default(HardwareProfile), StorageProfile storageProfile = default(StorageProfile), OSProfile osProfile = default(OSProfile), NetworkProfile networkProfile = default(NetworkProfile), DiagnosticsProfile diagnosticsProfile = default(DiagnosticsProfile), SubResource availabilitySet = default(SubResource), string provisioningState = default(string), string licenseType = default(string), Plan plan = default(Plan), IList<VirtualMachineExtension> resources = default(IList<VirtualMachineExtension>)) : base(location, id, name, type, tags) { InstanceId = instanceId; Sku = sku; LatestModelApplied = latestModelApplied; VmId = vmId; InstanceView = instanceView; HardwareProfile = hardwareProfile; StorageProfile = storageProfile; OsProfile = osProfile; NetworkProfile = networkProfile; DiagnosticsProfile = diagnosticsProfile; AvailabilitySet = availabilitySet; ProvisioningState = provisioningState; LicenseType = licenseType; Plan = plan; Resources = resources; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets the virtual machine instance ID. /// </summary> [JsonProperty(PropertyName = "instanceId")] public string InstanceId { get; private set; } /// <summary> /// Gets the virtual machine SKU. /// </summary> [JsonProperty(PropertyName = "sku")] public Sku Sku { get; private set; } /// <summary> /// Gets specifies whether the latest model has been applied to the /// virtual machine. /// </summary> [JsonProperty(PropertyName = "properties.latestModelApplied")] public bool? LatestModelApplied { get; private set; } /// <summary> /// Gets azure VM unique ID. /// </summary> [JsonProperty(PropertyName = "properties.vmId")] public string VmId { get; private set; } /// <summary> /// Gets the virtual machine instance view. /// </summary> [JsonProperty(PropertyName = "properties.instanceView")] public VirtualMachineInstanceView InstanceView { get; private set; } /// <summary> /// Gets or sets the hardware profile. /// </summary> [JsonProperty(PropertyName = "properties.hardwareProfile")] public HardwareProfile HardwareProfile { get; set; } /// <summary> /// Gets or sets the storage profile. /// </summary> [JsonProperty(PropertyName = "properties.storageProfile")] public StorageProfile StorageProfile { get; set; } /// <summary> /// Gets or sets the OS profile. /// </summary> [JsonProperty(PropertyName = "properties.osProfile")] public OSProfile OsProfile { get; set; } /// <summary> /// Gets or sets the network profile. /// </summary> [JsonProperty(PropertyName = "properties.networkProfile")] public NetworkProfile NetworkProfile { get; set; } /// <summary> /// Gets or sets the diagnostics profile. /// </summary> [JsonProperty(PropertyName = "properties.diagnosticsProfile")] public DiagnosticsProfile DiagnosticsProfile { get; set; } /// <summary> /// Gets or sets the reference Id of the availability set to which this /// virtual machine belongs. /// </summary> [JsonProperty(PropertyName = "properties.availabilitySet")] public SubResource AvailabilitySet { get; set; } /// <summary> /// Gets the provisioning state, which only appears in the response. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; private set; } /// <summary> /// Gets or sets the license type, which is for bring your own license /// scenario. /// </summary> [JsonProperty(PropertyName = "properties.licenseType")] public string LicenseType { get; set; } /// <summary> /// Gets or sets the purchase plan when deploying virtual machine from /// VM Marketplace images. /// </summary> [JsonProperty(PropertyName = "plan")] public Plan Plan { get; set; } /// <summary> /// Gets the virtual machine child extension resources. /// </summary> [JsonProperty(PropertyName = "resources")] public IList<VirtualMachineExtension> Resources { get; private set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (StorageProfile != null) { StorageProfile.Validate(); } if (Resources != null) { foreach (var element in Resources) { if (element != null) { element.Validate(); } } } } } }
#region Copyright (c) 2020 Filip Fodemski // // Copyright (c) 2020 Filip Fodemski // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files // (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE // #endregion using System; using System.Collections.Generic; using System.Linq; using SmartGraph.Common; using SmartGraph.Dag.Interfaces; namespace SmartGraph.Dag.Algorithms { public interface IAlgorithm { void Run(); void Reset(); } public interface IDFSAlgorithm { IList<IVertex> VisitOrder { get; } } public class EquivalenceClasses : IAlgorithm { private int[] dad; private IGraph graph; private IDictionary<IVertex, int> visitOrder; private bool hasRun; #if false // This code has been left here for illustration // purposes - its easier to understand what this algorithm // is doing, but the actual implementation used is optimized. private bool Find( IVertex vx, IVertex vy, bool doit) { int i = (int) visitOrder[vx]; int j = (int) visitOrder[vy]; while ( dad[i] > 0 ) i = dad[i]; while ( dad[j] > 0 ) j = dad[j]; if ( doit && (i != j) ) dad[j] = i; return (i != j); } #else private bool Find(IVertex vx, IVertex vy, bool doit) { int x = (int)visitOrder[vx]; int y = (int)visitOrder[vy]; int i = x; int j = y; while (dad[i] > 0) i = dad[i]; while (dad[j] > 0) j = dad[j]; int t = 0; while (dad[x] > 0) { t = x; x = dad[x]; dad[t] = i; } while (dad[y] > 0) { t = y; y = dad[y]; dad[t] = j; } if (doit && (i != j)) { if (dad[j] < dad[i]) { dad[j] += dad[i] - 1; dad[i] = j; } else { dad[i] += dad[j] - 1; dad[j] = i; } } return (i != j); } #endif public EquivalenceClasses(IGraph graph) { Guard.AssertNotNull(graph, "graph"); if (graph.Vertices.Count == 0) { throw new ArgumentException("Graph has no vertices"); } this.graph = graph; Reset(); } public void Run() { if (!hasRun) { foreach (var edge in graph.Edges) { // NOTE: the inversion of source -> target direction Find(edge.Target, edge.Source, true); } hasRun = true; } } public void Reset() { hasRun = false; var vertexCount = graph.Vertices.Count; dad = new int[vertexCount]; visitOrder = new Dictionary<IVertex, int>(vertexCount); for (int i = 0; i < vertexCount; ++i) { dad[i] = 0; } int vi = 0; foreach (var v in graph.Vertices) { visitOrder[v] = vi++; } } public bool IsEquivalent(IVertex x, IVertex y) { return x == y || !Find(x, y, false); } /// <summary> /// Return an IList of IList's. Each list corresponds to an equivalence /// class and contains all the vertices belonging to the equivalence class. /// </summary> public IList<IList<IVertex>> GetClasses() { Run(); var graphVertices = graph.Vertices; var eqmap = new List<IList<IVertex>>(); foreach (var x in graphVertices) { foreach (var y in graphVertices) { if (IsEquivalent(x, y)) { bool found = false; foreach (var eqlist in eqmap) { IVertex first = eqlist[0]; if (IsEquivalent(x, first)) { found = true; if (!eqlist.Contains(x)) { eqlist.Add(x); } if (!eqlist.Contains(y)) { eqlist.Add(y); } } } if (!found) { var eqlist = new List<IVertex>(); eqlist.Add(x); if (x != y) { eqlist.Add(y); } eqmap.Add(eqlist); } } } } return eqmap; } } public abstract class DFSVisitor : IDFSAlgorithm { protected enum Colour { White, Gray, Black } protected IGraph graph; protected IVertex startVertex; protected IDictionary<IVertex, Colour> colourMap = new Dictionary<IVertex, Colour>(); protected IList<IVertex> visitOrder = new List<IVertex>(); protected bool visitWholeGraph; protected bool hasRun; protected DFSVisitor(IVertex start) { Guard.AssertNotNull(start, "start"); Guard.AssertNotNull(start.Owner, "start.Owner"); graph = start.Owner; startVertex = start; Reset(); } protected DFSVisitor(IGraph graph) { Guard.AssertNotNull(graph, "graph"); Guard.AssertNotNull(graph.Vertices, "graph.Vertices"); if (graph.Vertices.Count == 0) { throw new ArgumentException("The graph has no vertices"); } this.graph = graph; visitWholeGraph = true; Reset(); } #region DFS Implementation private void RunDFS() { var graphVertices = graph.Vertices; var first = graphVertices.First(); if (visitWholeGraph) { startVertex = first; } if (startVertex != null) { StartVertex(startVertex); Visit(startVertex); } if (visitWholeGraph) { graphVertices .Where(v => Colour.White == colourMap[v]) .ForEach(v => Visit(v)); } } private void Visit(IVertex v) { colourMap[v] = Colour.Gray; DiscoverVertex(v); if (v.OutEdges.Count > 0) { foreach (var e in v.OutEdges) { var t = e.Target; ExamineEdge(e); switch (colourMap[t]) { case Colour.White: TreeEdge(e); Visit(t); break; case Colour.Gray: BackEdge(e); break; case Colour.Black: ForwardOrCrossEdge(e); break; } } } colourMap[v] = Colour.Black; FinishVertex(v); } #endregion #region IAlgorithm Implementation public virtual void Run() { if (!hasRun) { RunDFS(); hasRun = true; } } public virtual void Reset() { hasRun = false; visitOrder.Clear(); graph.Vertices.ForEach(v => colourMap[v] = Colour.White); } #endregion public virtual IList<IVertex> VisitOrder { get { Run(); return visitOrder; } } #region DFSVisitor Default Implementation protected virtual void BackEdge(IEdge edge) { throw new InvalidOperationException("Cycle detected on edge " + edge.Name); } protected virtual void StartVertex(IVertex v) { } protected virtual void DiscoverVertex(IVertex v) { } protected virtual void FinishVertex(IVertex v) { } protected virtual void ExamineEdge(IEdge e) { } protected virtual void TreeEdge(IEdge e) { } protected virtual void ForwardOrCrossEdge(IEdge e) { } #endregion } public class DepthFirstSearch : DFSVisitor { public DepthFirstSearch(IVertex start) : base(start) { } public DepthFirstSearch(IGraph graph) : base(graph) { } protected override void BackEdge(IEdge edge) { throw new InvalidOperationException("Cycle detected on edge " + edge.Name); } protected override void FinishVertex(IVertex v) { visitOrder.Add(v); } } public class TopologicalSort : DFSVisitor { public TopologicalSort(IVertex start) : base(start) { } public TopologicalSort(IGraph graph) : base(graph) { } protected override void BackEdge(IEdge edge) { throw new InvalidOperationException("Cycle detected on edge " + edge.Name); } protected override void FinishVertex(IVertex v) { visitOrder.Insert(0, v); } } }
// // Volume.cs // // Author: // Alex Launi <alex.launi@gmail.com> // // Copyright (c) 2010 Alex Launi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if ENABLE_GIO_HARDWARE using System; using System.Collections.Generic; using Mono.Unix; using Banshee.Hardware; using GLib; using System.Threading; namespace Banshee.Hardware.Gio { class RawVolume : RawDevice { const string FileSystemFree = "filesystem::free"; const string FileSystemSize = "filesystem::size"; const string FileSystemReadOnly = "filesystem::readonly"; public GLib.Volume Volume { get; set; } public long Available { get { try { using (var file_info = Volume.MountInstance.Root.QueryFilesystemInfo (FileSystemFree, null)) return (long) file_info.GetAttributeULong (FileSystemFree); } catch { return 0; } } } public ulong Capacity { get { try { using (var file_info = Volume.MountInstance.Root.QueryFilesystemInfo (FileSystemSize, null)) return file_info.GetAttributeULong (FileSystemSize); } catch { return 0; } } } public bool CanEject{ get { return Volume.CanEject (); } } public bool CanMount { get { return Volume.CanMount (); } } public bool CanUnmount { get { return IsMounted && Volume.MountInstance.CanUnmount; } } public override string IdMediaPlayer { get { return UdevMetadata.IdMediaDevice; } } public bool IsMounted { get { return Volume.MountInstance != null; } } public bool IsReadOnly { get { try { using (var file_info = Volume.MountInstance.Root.QueryFilesystemInfo (FileSystemReadOnly, null)) return file_info.GetAttributeBoolean (FileSystemReadOnly); } catch { return true; } } } public override bool IsRemovable { get { return Volume.CanEject (); } } // FIXME: iPhones have an empty UUID so we should return their serial instead. public override string Identifier { get { return Uuid; } } // FIXME public override string Model { get { return UdevMetadata.Model; } } public string MountPoint { get { return Volume.MountInstance == null ? null : Volume.MountInstance.Root.Path; } } public override string Name { get { return Volume.Name; } } // FIXME public override string Serial { get { return UdevMetadata.Serial; } } // FIXME public override string Subsystem { get { return UdevMetadata.Subsystem; } } //FIXME public override string Vendor { get { return UdevMetadata.Vendor; } } public RawVolume (GLib.Volume volume, Manager manager, GioVolumeMetadataSource gioMetadata, UdevMetadataSource udevMetadata) : base (manager, gioMetadata, udevMetadata) { Volume = volume; } public void Eject () { if (CanEject) { Volume.Eject (MountUnmountFlags.Force, null, (s, result) => { try { if (!Volume.EjectWithOperationFinish (result)) { Hyena.Log.ErrorFormat ("Failed to eject {0}", Volume.Name); } } catch (Exception e) { Hyena.Log.Exception (e); } }); } } public override string GetPropertyString (string key) { return UdevMetadata.GetPropertyString (key); } public override double GetPropertyDouble (string key) { return UdevMetadata.GetPropertyDouble (key); } public override bool GetPropertyBoolean (string key) { return UdevMetadata.GetPropertyBoolean (key); } public override int GetPropertyInteger (string key) { return UdevMetadata.GetPropertyInteger (key); } public override ulong GetPropertyUInt64 (string key) { return UdevMetadata.GetPropertyUInt64 (key); } public override string[] GetPropertyStringList (string key) { return UdevMetadata.GetPropertyStringList (key); } public override bool PropertyExists (string key) { return UdevMetadata.PropertyExists (key); } public void Mount () { if (CanMount) Volume.Mount (MountMountFlags.None, null, null, null); } public void Unmount () { if (CanUnmount) { ManualResetEvent handle = new ManualResetEvent (false); Volume.MountInstance.UnmountWithOperation (MountUnmountFlags.Force, null, null, delegate { handle.Set (); }); handle.WaitOne (TimeSpan.FromSeconds (5)); } } public override IDeviceMediaCapabilities MediaCapabilities { get { return new DeviceMediaCapabilities (this); } } public override string Product { get { return "Product Not Implemented"; } } public override string Uuid { get { return Volume.Uuid ?? UdevMetadata.Uuid; } } public RawBlockDevice Parent { get { if (Volume.Drive == null) { return null; } return new RawBlockDevice (Volume.Drive, Manager, new GioDriveMetadetaSource (Volume.Drive), new UdevMetadataSource (Manager.GudevDeviceFromGioDrive (Volume.Drive))); } } public bool ShouldIgnore { get { return false; } } public string FileSystem { get { return Volume.MountInstance.Root.UriScheme; } } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Windows.Forms; using System.Drawing; using System.Threading; using Microsoft.DirectX.DirectInput; using LibSystem; namespace LibHumanInputDevices { public class JoystickEventArgs : EventArgs { private bool m_mandatory; private int m_position; public bool mandatory { get { return m_mandatory; } } public int position { get { return m_position; } } // 0 to 32767 (center) to 65535 public JoystickEventArgs(bool mnd, int pos) { m_mandatory = mnd; m_position = pos; } } public class RPButtonsEventArgs : EventArgs { private bool m_pressed; private int m_button; public bool pressed { get { return m_pressed; } } public int button { get { return m_button; } } public RPButtonsEventArgs(bool prsd, int btn) { m_pressed = prsd; m_button = btn; } public override string ToString() { return "Btn: " + m_button + (m_pressed ? " pressed" : " released"); } } public delegate void JoystickEventHandler(Object sender, JoystickEventArgs e); public delegate void ButtonEventHandler(Object sender, RPButtonsEventArgs e); public class LogitechRumblepad { public event JoystickEventHandler leftJoystickVertMoved; public event JoystickEventHandler rightJoystickVertMoved; public event ButtonEventHandler btnChangedState; private Device m_gamepad = null; private Control m_mainForm = null; public LogitechRumblepad(Control mainForm, TreeView tvDevices) { m_mainForm = mainForm; //PopulateAllDevices(tvDevices); } public void init() { ensureGamepad(); gamepadTickerTimer = new System.Windows.Forms.Timer(); gamepadTickerTimer.Interval = 20; gamepadTickerTimer.Tick += new EventHandler(gamepadTicker); gamepadTickerTimer.Start(); Tracer.WriteLine("OK: Gamepad ticker ON"); } private void ensureGamepad() { if (m_gamepad == null) { int tryCnt = 3; while (m_gamepad == null && tryCnt-- > 0) { try { DeviceList dl = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly); foreach (DeviceInstance di in dl) { m_gamepad = new Device(di.InstanceGuid); Tracer.Trace("GameControl device found: " + m_gamepad.DeviceInformation.ProductName + " - " + m_gamepad.DeviceInformation.InstanceName); if (m_gamepad.DeviceInformation.ProductName.ToLower().IndexOf("rumble") >= 0) { //set cooperative level. m_gamepad.SetCooperativeLevel( m_mainForm, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background); //Set axis mode absolute. m_gamepad.Properties.AxisModeAbsolute = true; //Acquire joystick for capturing. m_gamepad.Acquire(); string info = "Rumblepad: " + m_gamepad.DeviceInformation.InstanceName + " state: " + m_gamepad.CurrentJoystickState; Tracer.WriteLine(info); break; } } } catch (Exception exc) { Tracer.Error(exc.ToString()); Thread.Sleep(1000); } } if (m_gamepad == null) { //Throw exception if gamepad not found. throw new Exception("No gamepad found."); } } } public void Close() { if (gamepadTickerTimer != null) { gamepadTickerTimer.Enabled = false; gamepadTickerTimer.Dispose(); gamepadTickerTimer = null; } if (m_gamepad != null) { m_gamepad.Unacquire(); m_gamepad.Dispose(); m_gamepad = null; } } private void PopulateAllDevices(TreeView tvDevices) { //Add "All Devices" node to TreeView TreeNode allNode = new TreeNode("All Devices"); tvDevices.Nodes.Add(allNode); //Populate All devices foreach (DeviceInstance di in Manager.Devices) { //Get Device name TreeNode nameNode = new TreeNode(di.InstanceName); //Is device attached? TreeNode attachedNode = new TreeNode( "Attached = " + Manager.GetDeviceAttached(di.ProductGuid)); //Get device Guid TreeNode guidNode = new TreeNode( "Guid = " + di.InstanceGuid); //Add nodes nameNode.Nodes.Add(attachedNode); nameNode.Nodes.Add(guidNode); allNode.Nodes.Add(nameNode); } } private void PopulatePointers(TreeView tvDevices) { //Add "Pointer Devices" node to TreeView TreeNode pointerNode = new TreeNode("Pointer Devices"); tvDevices.Nodes.Add(pointerNode); //Populate Attached Mouse/Pointing Devices foreach (DeviceInstance di in Manager.GetDevices(DeviceClass.Pointer, EnumDevicesFlags.AttachedOnly)) // DeviceClass.GameControl { //Get device name TreeNode nameNode = new TreeNode(di.InstanceName); nameNode.Tag = di; TreeNode guidNode = new TreeNode("Guid = " + di.InstanceGuid); //Add nodes nameNode.Nodes.Add(guidNode); pointerNode.Nodes.Add(nameNode); } } private System.Windows.Forms.Timer gamepadTickerTimer = null; public void gamepadTicker(object obj, System.EventArgs args) { try { //Tracer.WriteLine("...gamepad ticker... " + DateTime.Now); queryGamepad(); } catch { } gamepadTickerTimer.Enabled = true; } //private string lastJInfo = ""; private long lastMandatoryTicks = DateTime.Now.Ticks; private int mandatoryIntervalMs = 100; private int m_leftVpos = -1; private int m_rightVpos = -1; private byte[] m_buttonStates = null; private void queryGamepad() { if (m_gamepad != null) { //Get gamepad State. JoystickState state = m_gamepad.CurrentJoystickState; bool mandatory = DateTime.Now.Ticks > (lastMandatoryTicks + mandatoryIntervalMs * 10000); if (mandatory) { lastMandatoryTicks = DateTime.Now.Ticks; } /* string info = ""; //info = state.ToString().Replace("\n"," ") + " "; ////Capture Position. info += "X:" + state.X + " "; info += "Y:" + state.Y + " "; info += "Z:" + state.Z + " "; //info += "sldr0:" + state.GetSlider()[0] + " "; //info += "sldr1:" + state.GetSlider()[1] + " "; //info += "Rx:" + state.Rx + " "; //info += "Ry:" + state.Ry + " "; info += "Rz:" + state.Rz + " "; */ //Capture Buttons. byte[] buttons = state.GetButtons(); if (m_buttonStates == null) { m_buttonStates = new byte[buttons.Length]; for (int i = 0; i < m_buttonStates.Length; i++) { m_buttonStates[i] = 0; } } for (int i = 0; i < buttons.Length; i++) { if (buttons[i] != m_buttonStates[i]) { //info += "Btn:" + (i + 1) + " "; RPButtonsEventArgs btnArgs = null; if (buttons[i] > m_buttonStates[i]) { // button pressed btnArgs = new RPButtonsEventArgs(true, i + 1); } else if (buttons[i] < m_buttonStates[i]) { // button released btnArgs = new RPButtonsEventArgs(false, i + 1); } if (btnArgs != null && btnChangedState != null) { btnChangedState(this, btnArgs); } m_buttonStates[i] = buttons[i]; } } if ((m_leftVpos != state.Y || mandatory) && leftJoystickVertMoved != null) { JoystickEventArgs args = new JoystickEventArgs(mandatory, state.Y); m_leftVpos = state.Y; leftJoystickVertMoved(this, args); } if ((m_rightVpos != state.Rz || mandatory) && rightJoystickVertMoved != null) { JoystickEventArgs args = new JoystickEventArgs(mandatory, state.Rz); m_rightVpos = state.Rz; rightJoystickVertMoved(this, args); } } } } }
namespace Nancy.Authentication.Forms { using System; using Bootstrapper; using Cookies; using Cryptography; using Helpers; using Nancy.Extensions; using Responses; using Security; /// <summary> /// Nancy forms authentication implementation /// </summary> public static class FormsAuthentication { /// <summary> /// The query string key for storing the return url /// </summary> private const string REDIRECT_QUERYSTRING_KEY = "returnUrl"; private static string formsAuthenticationCookieName = "_ncfa"; // TODO - would prefer not to hold this here, but the redirect response needs it private static FormsAuthenticationConfiguration currentConfiguration; /// <summary> /// Gets or sets the forms authentication cookie name /// </summary> public static string FormsAuthenticationCookieName { get { return formsAuthenticationCookieName; } set { formsAuthenticationCookieName = value; } } /// <summary> /// Enables forms authentication for the application /// </summary> /// <param name="pipelines">Pipelines to add handlers to (usually "this")</param> /// <param name="configuration">Forms authentication configuration</param> public static void Enable(IPipelines pipelines, FormsAuthenticationConfiguration configuration) { if (pipelines == null) { throw new ArgumentNullException("pipelines"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } if (!configuration.IsValid) { throw new ArgumentException("Configuration is invalid", "configuration"); } currentConfiguration = configuration; pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration)); pipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration)); } /// <summary> /// Creates a response that sets the authentication cookie and redirects /// the user back to where they came from. /// </summary> /// <param name="context">Current context</param> /// <param name="userIdentifier">User identifier guid</param> /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param> /// <param name="fallbackRedirectUrl">Url to redirect to if none in the querystring</param> /// <returns>Nancy response with redirect.</returns> public static Response UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = "/") { var redirectUrl = fallbackRedirectUrl; if (context.Request.Query[REDIRECT_QUERYSTRING_KEY].HasValue) { redirectUrl = context.Request.Query[REDIRECT_QUERYSTRING_KEY]; } var response = context.GetRedirect(redirectUrl); var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration); response.AddCookie(authenticationCookie); return response; } /// <summary> /// Logs the user in. /// </summary> /// <param name="userIdentifier">User identifier guid</param> /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param> /// <returns>Nancy response with status <see cref="HttpStatusCode.OK"/></returns> public static Response UserLoggedInResponse(Guid userIdentifier, DateTime? cookieExpiry = null) { var response = (Response)HttpStatusCode.OK; var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration); response.AddCookie(authenticationCookie); return response; } /// <summary> /// Logs the user out and redirects them to a URL /// </summary> /// <param name="context">Current context</param> /// <param name="redirectUrl">URL to redirect to</param> /// <returns>Nancy response</returns> public static Response LogOutAndRedirectResponse(NancyContext context, string redirectUrl) { var response = context.GetRedirect(redirectUrl); var authenticationCookie = BuildLogoutCookie(currentConfiguration); response.AddCookie(authenticationCookie); return response; } /// <summary> /// Logs the user out. /// </summary> /// <returns>Nancy response</returns> public static Response LogOutResponse() { var response = (Response)HttpStatusCode.OK; var authenticationCookie = BuildLogoutCookie(currentConfiguration); response.AddCookie(authenticationCookie); return response; } /// <summary> /// Gets the pre request hook for loading the authenticated user's details /// from the cookie. /// </summary> /// <param name="configuration">Forms authentication configuration to use</param> /// <returns>Pre request hook delegate</returns> private static Func<NancyContext, Response> GetLoadAuthenticationHook(FormsAuthenticationConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException("configuration"); } return context => { var userGuid = GetAuthenticatedUserFromCookie(context, configuration); if (userGuid != Guid.Empty) { context.CurrentUser = configuration.UserMapper.GetUserFromIdentifier(userGuid); } return null; }; } /// <summary> /// Gets the post request hook for redirecting to the login page /// </summary> /// <param name="configuration">Forms authentication configuration to use</param> /// <returns>Post request hook delegate</returns> private static Action<NancyContext> GetRedirectToLoginHook(FormsAuthenticationConfiguration configuration) { return context => { if (context.Response.StatusCode == HttpStatusCode.Unauthorized) { context.Response = context.GetRedirect( string.Format("{0}?{1}={2}", configuration.RedirectUrl, REDIRECT_QUERYSTRING_KEY, context.ToFullPath("~" + context.Request.Path + HttpUtility.UrlEncode(context.Request.Url.Query)))); } }; } /// <summary> /// Gets the authenticated user GUID from the incoming request cookie if it exists /// and is valid. /// </summary> /// <param name="context">Current context</param> /// <param name="configuration">Current configuration</param> /// <returns>Returns user guid, or Guid.Empty if not present or invalid</returns> private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration) { if (!context.Request.Cookies.ContainsKey(formsAuthenticationCookieName)) { return Guid.Empty; } var cookieValue = DecryptAndValidateAuthenticationCookie(context.Request.Cookies[formsAuthenticationCookieName], configuration); Guid returnGuid; if (String.IsNullOrEmpty(cookieValue) || !Guid.TryParse(cookieValue, out returnGuid)) { return Guid.Empty; } return returnGuid; } /// <summary> /// Build the forms authentication cookie /// </summary> /// <param name="userIdentifier">Authenticated user identifier</param> /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param> /// <param name="configuration">Current configuration</param> /// <returns>Nancy cookie instance</returns> private static INancyCookie BuildCookie(Guid userIdentifier, DateTime? cookieExpiry, FormsAuthenticationConfiguration configuration) { var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration); var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true) { Expires = cookieExpiry }; return cookie; } /// <summary> /// Builds a cookie for logging a user out /// </summary> /// <param name="configuration">Current configuration</param> /// <returns>Nancy cookie instance</returns> private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration) { return new NancyCookie(formsAuthenticationCookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) }; } /// <summary> /// Encrypt and sign the cookie contents /// </summary> /// <param name="cookieValue">Plain text cookie value</param> /// <param name="configuration">Current configuration</param> /// <returns>Encrypted and signed string</returns> private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration) { var encryptedCookie = configuration.CryptographyConfiguration.EncryptionProvider.Encrypt(cookieValue); var hmacBytes = GenerateHmac(encryptedCookie, configuration); var hmacString = Convert.ToBase64String(hmacBytes); return String.Format("{1}{0}", encryptedCookie, hmacString); } /// <summary> /// Generate a hmac for the encrypted cookie string /// </summary> /// <param name="encryptedCookie">Encrypted cookie string</param> /// <param name="configuration">Current configuration</param> /// <returns>Hmac byte array</returns> private static byte[] GenerateHmac(string encryptedCookie, FormsAuthenticationConfiguration configuration) { return configuration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedCookie); } /// <summary> /// Decrypt and validate an encrypted and signed cookie value /// </summary> /// <param name="cookieValue">Encrypted and signed cookie value</param> /// <param name="configuration">Current configuration</param> /// <returns>Decrypted value, or empty on error or if failed validation</returns> private static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration) { // TODO - shouldn't this be automatically decoded by nancy cookie when that change is made? var decodedCookie = Helpers.HttpUtility.UrlDecode(cookieValue); var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength); var encryptedCookie = decodedCookie.Substring(hmacStringLength); var hmacString = decodedCookie.Substring(0, hmacStringLength); var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider; // Check the hmacs, but don't early exit if they don't match var hmacBytes = Convert.FromBase64String(hmacString); var newHmac = GenerateHmac(encryptedCookie, configuration); var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength); var decrypted = encryptionProvider.Decrypt(encryptedCookie); // Only return the decrypted result if the hmac was ok return hmacValid ? decrypted : String.Empty; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using Toucan.Sample.Models; using Toucan.Sample.Models.AccountViewModels; using Toucan.Sample.Services; namespace Toucan.Sample.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToLocal(returnUrl); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid code."); return View(model); } } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.Collections.Generic; using System.Linq; using erl.Oracle.TnsNames.Antlr4.Runtime.Atn; using erl.Oracle.TnsNames.Antlr4.Runtime.Misc; using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen; namespace erl.Oracle.TnsNames.Antlr4.Runtime { /// <summary> /// A parser simulator that mimics what ANTLR's generated /// parser code does. /// </summary> /// <remarks> /// A parser simulator that mimics what ANTLR's generated /// parser code does. A ParserATNSimulator is used to make /// predictions via adaptivePredict but this class moves a pointer through the /// ATN to simulate parsing. ParserATNSimulator just /// makes us efficient rather than having to backtrack, for example. /// This properly creates parse trees even for left recursive rules. /// We rely on the left recursive rule invocation and special predicate /// transitions to make left recursive rules work. /// See TestParserInterpreter for examples. /// </remarks> public class ParserInterpreter : Parser { private readonly string _grammarFileName; private readonly ATN _atn; protected internal readonly BitSet pushRecursionContextStates; private readonly string[] _ruleNames; [NotNull] private readonly IVocabulary vocabulary; private readonly Stack<Tuple<ParserRuleContext, int>> _parentContextStack = new Stack<Tuple<ParserRuleContext, int>>(); public ParserInterpreter(string grammarFileName, IVocabulary vocabulary, IEnumerable<string> ruleNames, ATN atn, ITokenStream input) : base(input) { this._grammarFileName = grammarFileName; this._atn = atn; this._ruleNames = ruleNames.ToArray(); this.vocabulary = vocabulary; // identify the ATN states where pushNewRecursionContext must be called this.pushRecursionContextStates = new BitSet(atn.states.Count); foreach (ATNState state in atn.states) { if (!(state is StarLoopEntryState)) { continue; } if (((StarLoopEntryState)state).isPrecedenceDecision) { this.pushRecursionContextStates.Set(state.stateNumber); } } // get atn simulator that knows how to do predictions Interpreter = new ParserATNSimulator(this, atn, null, null); } public override ATN Atn { get { return _atn; } } public override IVocabulary Vocabulary { get { return vocabulary; } } public override string[] RuleNames { get { return _ruleNames; } } public override string GrammarFileName { get { return _grammarFileName; } } /// <summary>Begin parsing at startRuleIndex</summary> public virtual ParserRuleContext Parse(int startRuleIndex) { RuleStartState startRuleStartState = _atn.ruleToStartState[startRuleIndex]; InterpreterRuleContext rootContext = new InterpreterRuleContext(null, ATNState.InvalidStateNumber, startRuleIndex); if (startRuleStartState.isPrecedenceRule) { EnterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0); } else { EnterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex); } while (true) { ATNState p = AtnState; switch (p.StateType) { case StateType.RuleStop: { // pop; return from rule if (RuleContext.IsEmpty) { if (startRuleStartState.isPrecedenceRule) { ParserRuleContext result = RuleContext; Tuple<ParserRuleContext, int> parentContext = _parentContextStack.Pop(); UnrollRecursionContexts(parentContext.Item1); return result; } else { ExitRule(); return rootContext; } } VisitRuleStopState(p); break; } default: { try { VisitState(p); } catch (RecognitionException e) { State = _atn.ruleToStopState[p.ruleIndex].stateNumber; Context.exception = e; ErrorHandler.ReportError(this, e); ErrorHandler.Recover(this, e); } break; } } } } public override void EnterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence) { _parentContextStack.Push(Tuple.Create(RuleContext, localctx.invokingState)); base.EnterRecursionRule(localctx, state, ruleIndex, precedence); } protected internal virtual ATNState AtnState { get { return _atn.states[State]; } } protected internal virtual void VisitState(ATNState p) { int edge; if (p.NumberOfTransitions > 1) { ErrorHandler.Sync(this); edge = Interpreter.AdaptivePredict(TokenStream, ((DecisionState)p).decision, RuleContext); } else { edge = 1; } Transition transition = p.Transition(edge - 1); switch (transition.TransitionType) { case TransitionType.EPSILON: { if (pushRecursionContextStates.Get(p.stateNumber) && !(transition.target is LoopEndState)) { InterpreterRuleContext ctx = new InterpreterRuleContext(_parentContextStack.Peek().Item1, _parentContextStack.Peek().Item2, RuleContext.RuleIndex); PushNewRecursionContext(ctx, _atn.ruleToStartState[p.ruleIndex].stateNumber, RuleContext.RuleIndex); } break; } case TransitionType.ATOM: { Match(((AtomTransition)transition).token); break; } case TransitionType.RANGE: case TransitionType.SET: case TransitionType.NOT_SET: { if (!transition.Matches(TokenStream.LA(1), TokenConstants.MinUserTokenType, 65535)) { ErrorHandler.RecoverInline(this); } MatchWildcard(); break; } case TransitionType.WILDCARD: { MatchWildcard(); break; } case TransitionType.RULE: { RuleStartState ruleStartState = (RuleStartState)transition.target; int ruleIndex = ruleStartState.ruleIndex; InterpreterRuleContext ctx_1 = new InterpreterRuleContext(RuleContext, p.stateNumber, ruleIndex); if (ruleStartState.isPrecedenceRule) { EnterRecursionRule(ctx_1, ruleStartState.stateNumber, ruleIndex, ((RuleTransition)transition).precedence); } else { EnterRule(ctx_1, transition.target.stateNumber, ruleIndex); } break; } case TransitionType.PREDICATE: { PredicateTransition predicateTransition = (PredicateTransition)transition; if (!Sempred(RuleContext, predicateTransition.ruleIndex, predicateTransition.predIndex)) { throw new FailedPredicateException(this); } break; } case TransitionType.ACTION: { ActionTransition actionTransition = (ActionTransition)transition; Action(RuleContext, actionTransition.ruleIndex, actionTransition.actionIndex); break; } case TransitionType.PRECEDENCE: { if (!Precpred(RuleContext, ((PrecedencePredicateTransition)transition).precedence)) { throw new FailedPredicateException(this, string.Format("precpred(_ctx, {0})", ((PrecedencePredicateTransition)transition).precedence)); } break; } default: { throw new NotSupportedException("Unrecognized ATN transition type."); } } State = transition.target.stateNumber; } protected internal virtual void VisitRuleStopState(ATNState p) { RuleStartState ruleStartState = _atn.ruleToStartState[p.ruleIndex]; if (ruleStartState.isPrecedenceRule) { Tuple<ParserRuleContext, int> parentContext = _parentContextStack.Pop(); UnrollRecursionContexts(parentContext.Item1); State = parentContext.Item2; } else { ExitRule(); } RuleTransition ruleTransition = (RuleTransition)_atn.states[State].Transition(0); State = ruleTransition.followState.stateNumber; } } }
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; namespace SharpMath.Plotting.Functions { /*[Serializable] public abstract class PlotFunction<T> : IPlotFunction<T> { public abstract double Value(T x); public static PlotFunction<T> Create(IPlotFunction<T> f) { return Create(x => f.Value(x)); } public static PlotFunction<T> Create(Func<T, double> f) { return new InnerFunction(f); } public static implicit operator PlotFunction<T>(double a) { return Create(x => a); } public static PlotFunction<T> operator +(PlotFunction<T> f, PlotFunction<T> g) { return Create(x => f.Value(x) + g.Value(x)); } public static PlotFunction<T> operator +(PlotFunction<T> f, double a) { return Create(x => f.Value(x) + a); } public static PlotFunction<T> operator +(double a, PlotFunction<T> f) { return f + a; } public static PlotFunction<T> operator -(PlotFunction<T> f) { return Create(x => -f.Value(x)); } public static PlotFunction<T> operator -(PlotFunction<T> f, PlotFunction<T> g) { return Create(x => f.Value(x) - g.Value(x)); } public static PlotFunction<T> operator -(PlotFunction<T> f, double a) { return Create(x => f.Value(x) - a); } public static PlotFunction<T> operator -(double a, PlotFunction<T> f) { return Create(x => a - f.Value(x)); } public static PlotFunction<T> operator *(PlotFunction<T> f, PlotFunction<T> g) { return Create(x => f.Value(x) * g.Value(x)); } public static PlotFunction<T> operator *(PlotFunction<T> f, double a) { return Create(x => f.Value(x) * a); } public static PlotFunction<T> operator *(double a, PlotFunction<T> f) { return f * a; } public static PlotFunction<T> operator /(PlotFunction<T> f, PlotFunction<T> g) { return Create(x => f.Value(x) / g.Value(x)); } public static PlotFunction<T> operator /(PlotFunction<T> f, double a) { return Create(x => f.Value(x) / a); } public static PlotFunction<T> operator /(double a, PlotFunction<T> f) { return Create(x => a / f.Value(x)); } [Serializable] private class InnerFunction : PlotFunction<T> { private Func<T, double> f; public InnerFunction(Func<T, double> f) { this.f = f; } public override double Value(T x) { return f(x); } } }*/ [Serializable] public abstract class PlotFunction : IPlotFunction { public abstract double Value(double x); public static PlotFunction Create(IPlotFunction f) { return Create(x => f.Value(x)); } public static PlotFunction Create(Func<double, double> f) { return new InnerFunction(f); } public static implicit operator PlotFunction(double a) { return Create(x => a); } public static PlotFunction operator +(PlotFunction f, PlotFunction g) { return Create(x => f.Value(x) + g.Value(x)); } public static PlotFunction operator +(PlotFunction f, double a) { return Create(x => f.Value(x) + a); } public static PlotFunction operator +(double a, PlotFunction f) { return f + a; } public static PlotFunction operator -(PlotFunction f) { return Create(x => -f.Value(x)); } public static PlotFunction operator -(PlotFunction f, PlotFunction g) { return Create(x => f.Value(x) - g.Value(x)); } public static PlotFunction operator -(PlotFunction f, double a) { return Create(x => f.Value(x) - a); } public static PlotFunction operator -(double a, PlotFunction f) { return Create(x => a - f.Value(x)); } public static PlotFunction operator *(PlotFunction f, PlotFunction g) { return Create(x => f.Value(x) * g.Value(x)); } public static PlotFunction operator *(PlotFunction f, double a) { return Create(x => f.Value(x) * a); } public static PlotFunction operator *(double a, PlotFunction f) { return f * a; } public static PlotFunction operator /(PlotFunction f, PlotFunction g) { return Create(x => f.Value(x) / g.Value(x)); } public static PlotFunction operator /(PlotFunction f, double a) { return Create(x => f.Value(x) / a); } public static PlotFunction operator /(double a, PlotFunction f) { return Create(x => a / f.Value(x)); } [Serializable] private class InnerFunction : PlotFunction { private Func<double, double> f; public InnerFunction(Func<double, double> f) { this.f = f; } public override double Value(double x) { return f(x); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: NodesFound.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Territorium.Kademlia.Protocol { /// <summary>Holder for reflection information generated from NodesFound.proto</summary> public static partial class FindNodeResponseReflection { #region Descriptor /// <summary>File descriptor for NodesFound.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FindNodeResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZGaW5kTm9kZVJlc3BvbnNlLnByb3RvImMKEEZpbmROb2RlUmVzcG9uc2US", "FgoOb3JpZ2luX2FkZHJlc3MYASABKAwSGwoTZGVzdGluYXRpb25fYWRkcmVz", "cxgCIAEoDBIaChJub2Rlc19mb3VuZF9zb19mYXIYAyABKAxCIKoCHVRlcnJp", "dG9yaXVtLkthZGVtbGlhLlByb3RvY29sYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Territorium.Kademlia.Protocol.NodesFound), global::Territorium.Kademlia.Protocol.NodesFound.Parser, new[]{ "OriginAddress", "DestinationAddress", "NodesFoundSoFar" }, null, null, null) })); } #endregion } #region Messages public sealed partial class NodesFound : pb::IMessage<NodesFound> { private static readonly pb::MessageParser<NodesFound> _parser = new pb::MessageParser<NodesFound>(() => new NodesFound()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<NodesFound> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Territorium.Kademlia.Protocol.FindNodeResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public NodesFound() => OnConstruction(); partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public NodesFound(NodesFound other) : this() { originAddress_ = other.originAddress_; destinationAddress_ = other.destinationAddress_; nodesFoundSoFar_ = other.nodesFoundSoFar_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public NodesFound Clone() { return new NodesFound(this); } /// <summary>Field number for the "origin_address" field.</summary> public const int OriginAddressFieldNumber = 1; private pb::ByteString originAddress_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString OriginAddress { get => originAddress_; set => originAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } /// <summary>Field number for the "destination_address" field.</summary> public const int DestinationAddressFieldNumber = 2; private pb::ByteString destinationAddress_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString DestinationAddress { get => destinationAddress_; set => destinationAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } /// <summary>Field number for the "nodes_found_so_far" field.</summary> public const int NodesFoundSoFarFieldNumber = 3; private pb::ByteString nodesFoundSoFar_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString NodesFoundSoFar { get => nodesFoundSoFar_; set => nodesFoundSoFar_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as NodesFound); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(NodesFound other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (OriginAddress != other.OriginAddress) return false; if (DestinationAddress != other.DestinationAddress) return false; if (NodesFoundSoFar != other.NodesFoundSoFar) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (OriginAddress.Length != 0) hash ^= OriginAddress.GetHashCode(); if (DestinationAddress.Length != 0) hash ^= DestinationAddress.GetHashCode(); if (NodesFoundSoFar.Length != 0) hash ^= NodesFoundSoFar.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (OriginAddress.Length != 0) { output.WriteRawTag(10); output.WriteBytes(OriginAddress); } if (DestinationAddress.Length != 0) { output.WriteRawTag(18); output.WriteBytes(DestinationAddress); } if (NodesFoundSoFar.Length != 0) { output.WriteRawTag(26); output.WriteBytes(NodesFoundSoFar); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (OriginAddress.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(OriginAddress); } if (DestinationAddress.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(DestinationAddress); } if (NodesFoundSoFar.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(NodesFoundSoFar); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(NodesFound other) { if (other == null) { return; } if (other.OriginAddress.Length != 0) { OriginAddress = other.OriginAddress; } if (other.DestinationAddress.Length != 0) { DestinationAddress = other.DestinationAddress; } if (other.NodesFoundSoFar.Length != 0) { NodesFoundSoFar = other.NodesFoundSoFar; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch (tag) { default: input.SkipLastField(); break; case 10: { OriginAddress = input.ReadBytes(); break; } case 18: { DestinationAddress = input.ReadBytes(); break; } case 26: { NodesFoundSoFar = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
/* Copyright (c) 2004-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Web; using System.Xml; using System.Threading; using System.Collections; using System.ComponentModel; using PHP; using PHP.Core; using Convert = PHP.Core.Convert; using System.Web.Configuration; using System.Diagnostics; namespace PHP.Library { #region Enumerations /// <summary> /// Assertion options. /// </summary> public enum AssertOption { /// <summary> /// Whether assertions are evaluated. /// </summary> [ImplementsConstant("ASSERT_ACTIVE")] Active, /// <summary> /// Whether an error is reported if assertion fails. /// </summary> [ImplementsConstant("ASSERT_WARNING")] ReportWarning, /// <summary> /// Whether script execution is terminated if assertion fails. /// </summary> [ImplementsConstant("ASSERT_BAIL")] Terminate, /// <summary> /// Whether to disable error reporting during assertion evaluation. /// </summary> [ImplementsConstant("ASSERT_QUIET_EVAL")] Quiet, /// <summary> /// The user callback to be called if assertion fails. /// Can be a <B>null</B> reference which means no function is called. /// </summary> [ImplementsConstant("ASSERT_CALLBACK")] Callback } #endregion /// <summary> /// Class manipulating PHP configuration. /// The class is provided only for backward compatibility with PHP and /// is intended to be used only by a compiler of PHP language. /// </summary> /// <threadsafety static="true"/> public static class PhpIni { #region Default values for Core options having no equivalent in configuration record /// <summary> /// Default value for "default_mimetype" PHP configuration option. /// </summary> public const string DefaultMimetype = "text/html"; /// <summary> /// Default value for "default_charset" PHP configuration option. /// </summary> public static readonly string DefaultCharset = Configuration.Application.Globalization.PageEncoding.HeaderName; /// <summary> /// A value of "error_log" option meaning System log. /// </summary> public const string ErrorLogSysLog = "syslog"; #endregion #region Core Options internal static object GetSetRestoreCoreOption(LocalConfiguration local, string option, object value, IniAction action) { LocalConfiguration @default = Configuration.DefaultLocal; GlobalConfiguration global = Configuration.Global; ApplicationConfiguration app = Configuration.Application; switch (option) { #region <paths> case "extension_dir": Debug.Assert(action == IniAction.Get); return app.Paths.Libraries; #endregion #region <compiler> case "short_open_tag": Debug.Assert(action == IniAction.Get); return app.Compiler.ShortOpenTags; case "asp_tags": Debug.Assert(action == IniAction.Get); return app.Compiler.AspTags; #endregion #region <error-control> case "html_errors": return GSR(ref local.ErrorControl.HtmlMessages, @default.ErrorControl.HtmlMessages, value, action); case "display_errors": return GSR(ref local.ErrorControl.DisplayErrors, @default.ErrorControl.DisplayErrors, value, action); case "error_append_string": return GSR(ref local.ErrorControl.ErrorAppendString, @default.ErrorControl.ErrorAppendString, value, action); case "error_prepend_string": return GSR(ref local.ErrorControl.ErrorPrependString, @default.ErrorControl.ErrorPrependString, value, action); case "log_errors": return GSR(ref local.ErrorControl.EnableLogging, @default.ErrorControl.EnableLogging, value, action); case "error_log": return GsrErrorLog(local, @default, value, action); case "error_reporting": switch (action) { case IniAction.Get: return ErrorReporting(); case IniAction.Set: return ErrorReporting(Convert.ObjectToInteger(value)); case IniAction.Restore: return ErrorReporting((int)@default.ErrorControl.ReportErrors); } break; #endregion #region <output-control> case "implicit_flush": Debug.Assert(action == IniAction.Get); return @default.OutputControl.ImplicitFlush; case "output_handler": Debug.Assert(action == IniAction.Get); IPhpConvertible handler = @default.OutputControl.OutputHandler; return (handler != null) ? handler.ToString() : null; case "output_buffering": Debug.Assert(action == IniAction.Get); return @default.OutputControl.OutputBuffering; #endregion #region <request-control> case "max_execution_time": { object result = GSR(ref local.RequestControl.ExecutionTimeout, @default.RequestControl.ExecutionTimeout, value, action); // applies the timeout: if (action != IniAction.Get) ScriptContext.CurrentContext.ApplyExecutionTimeout(local.RequestControl.ExecutionTimeout); return result; } case "ignore_user_abort": { object result = GSR(ref local.RequestControl.IgnoreUserAbort, @default.RequestControl.IgnoreUserAbort, value, action); // enables/disables disconnection tracking: if (action != IniAction.Get) RequestContext.CurrentContext.TrackClientDisconnection = !local.RequestControl.IgnoreUserAbort; return result; } #endregion #region <file-system> case "allow_url_fopen": return GSR(ref local.FileSystem.AllowUrlFopen, @default.FileSystem.AllowUrlFopen, value, action); case "user_agent": return GSR(ref local.FileSystem.UserAgent, @default.FileSystem.UserAgent, value, action); case "from": return GSR(ref local.FileSystem.AnonymousFtpPassword, @default.FileSystem.AnonymousFtpPassword, value, action); case "default_socket_timeout": return GSR(ref local.FileSystem.DefaultSocketTimeout, @default.FileSystem.DefaultSocketTimeout, value, action); case "include_path": return GSR(ref local.FileSystem.IncludePaths, @default.FileSystem.IncludePaths, value, action); #endregion #region <variables> case "zend.ze1_compatibility_mode": Debug.Assert(action != IniAction.Set || OptionValueToBoolean(value) == false); return false;// GSR(ref local.Variables.ZendEngineV1Compatible, @default.Variables.ZendEngineV1Compatible, value, action); case "magic_quotes_runtime": return GSR(ref local.Variables.QuoteRuntimeVariables, @default.Variables.QuoteRuntimeVariables, value, action); case "magic_quotes_sybase": Debug.Assert(action == IniAction.Get || OptionValueToBoolean(value) == local.Variables.QuoteInDbManner); return local.Variables.QuoteInDbManner; //GSR(ref local.Variables.QuoteInDbManner, @default.Variables.QuoteInDbManner, value, action); case "magic_quotes_gpc": Debug.Assert(action == IniAction.Get || OptionValueToBoolean(value) == global.GlobalVariables.QuoteGpcVariables); return global.GlobalVariables.QuoteGpcVariables; case "register_argc_argv": Debug.Assert(action == IniAction.Get); return global.GlobalVariables.RegisterArgcArgv; case "register_globals": Debug.Assert(action == IniAction.Get); return global.GlobalVariables.RegisterGlobals; case "register_long_arrays": Debug.Assert(action == IniAction.Get); return global.GlobalVariables.RegisterLongArrays; case "variables_order": return GsrVariablesOrder(local, @default, value, action); case "unserialize_callback_func": return GSR(ref local.Variables.DeserializationCallback, @default.Variables.DeserializationCallback, value, action); case "always_populate_raw_post_data": switch (action) { case IniAction.Restore: local.Variables.AlwaysPopulateRawPostData = false; break; case IniAction.Set: local.Variables.AlwaysPopulateRawPostData = Convert.ObjectToBoolean(value); break; } return local.Variables.AlwaysPopulateRawPostData; #endregion #region <posted-files> case "file_uploads": Debug.Assert(action == IniAction.Get); return global.PostedFiles.Accept; case "upload_tmp_dir": Debug.Assert(action == IniAction.Get); return global.PostedFiles.TempPath; case "post_max_size": case "upload_max_filesize": { Debug.Assert(action == IniAction.Get); HttpContext context; if (!Web.EnsureHttpContext(out context)) return null; HttpRuntimeSection http_runtime_section = (HttpRuntimeSection)context.GetSection("system.web/httpRuntime"); return (http_runtime_section != null) ? http_runtime_section.MaxRequestLength * 1024 : 0;// values in config are in kB, PHP's in B } #endregion #region <assert> case "assert.active": return GSR(ref local.Assertion.Active, @default.Assertion.Active, value, action); case "assert.bail": return GSR(ref local.Assertion.Terminate, @default.Assertion.Terminate, value, action); case "assert.quiet_eval": return GSR(ref local.Assertion.Quiet, @default.Assertion.Quiet, value, action); case "assert.warning": return GSR(ref local.Assertion.ReportWarning, @default.Assertion.ReportWarning, value, action); case "assert.callback": return GSR(ref local.Assertion.Callback, @default.Assertion.Callback, value, action); #endregion #region <safe-mode> case "safe_mode": Debug.Assert(action == IniAction.Get); return global.SafeMode.Enabled; case "open_basedir": Debug.Assert(action == IniAction.Get); return global.SafeMode.GetAllowedPathPrefixesJoin(); case "safe_mode_exec_dir": Debug.Assert(action == IniAction.Get); return global.SafeMode.ExecutionDirectory; #endregion #region <session> case "session.save_handler": return PhpSession.GsrHandler(local, @default, value, action); case "session.auto_start": Debug.Assert(action == IniAction.Get); return local.Session.AutoStart; case "session.name": Debug.Assert(action == IniAction.Get); return PhpSession.Name(); #endregion #region others case "default_charset": return GsrDefaultCharset(value, action); case "default_mimetype": return GsrDefaultMimetype(value, action); case "memory_limit": return GsrMemoryLimit(value, action); case "disable_functions": return GsrDisableFunctions(value, action); #endregion } Debug.Fail("Option '" + option + "' is supported but not implemented."); return null; } /// <summary> /// Writes Core legacy options and their values to XML text stream. /// Skips options whose values are the same as default values of Phalanger. /// </summary> /// <param name="writer">XML writer.</param> /// <param name="options">A hashtable containing PHP names and option values. Consumed options are removed from the table.</param> /// <param name="writePhpNames">Whether to add "phpName" attribute to option nodes.</param> public static void CoreOptionsToXml(XmlTextWriter writer, Hashtable options, bool writePhpNames) // GENERICS: <string,string> { if (writer == null) throw new ArgumentNullException("writer"); if (options == null) throw new ArgumentNullException("options"); ApplicationConfiguration app = new ApplicationConfiguration(); GlobalConfiguration global = new GlobalConfiguration(); LocalConfiguration local = new LocalConfiguration(); PhpIniXmlWriter ow = new PhpIniXmlWriter(writer, options, writePhpNames); ow.StartSection("compiler"); ow.WriteOption("short_open_tag", "ShortOpenTag", true, app.Compiler.ShortOpenTags); ow.WriteOption("asp_tags", "AspTags", false, app.Compiler.AspTags); ow.StartSection("variables"); //ow.WriteOption("zend.ze1_compatibility_mode", "ZendEngineV1Compatible", false, local.Variables.ZendEngineV1Compatible); ow.WriteOption("register_globals", "RegisterGlobals", false, global.GlobalVariables.RegisterGlobals); ow.WriteOption("register_argc_argv", "RegisterArgcArgv", true, global.GlobalVariables.RegisterArgcArgv); ow.WriteOption("register_long_arrays", "RegisterLongArrays", true, global.GlobalVariables.RegisterLongArrays); ow.WriteOption("variables_order", "RegisteringOrder", "EGPCS", local.Variables.RegisteringOrder); //ow.WriteOption("magic_quotes_gpc", "QuoteGpcVariables", true, global.GlobalVariables.QuoteGpcVariables); ow.WriteOption("magic_quotes_runtime", "QuoteRuntimeVariables", false, local.Variables.QuoteRuntimeVariables); //ow.WriteOption("magic_quotes_sybase", "QuoteInDbManner", false, local.Variables.QuoteInDbManner); ow.WriteOption("unserialize_callback_func", "DeserializationCallback", null, local.Variables.DeserializationCallback); ow.StartSection("output-control"); ow.WriteOption("output_buffering", "OutputBuffering", false, local.OutputControl.OutputBuffering); ow.WriteOption("output_handler", "OutputHandler", null, local.OutputControl.OutputHandler); ow.WriteOption("implicit_flush", "ImplicitFlush", false, local.OutputControl.ImplicitFlush); ow.WriteOption("default_mimetype", "ContentType", "text/html", DefaultMimetype); ow.WriteOption("default_charset", "Charset", "", DefaultCharset); ow.StartSection("request-control"); ow.WriteOption("max_execution_time", "ExecutionTimeout", 30, local.RequestControl.ExecutionTimeout); ow.WriteOption("ignore_user_abort", "IgnoreUserAbort", false, local.RequestControl.IgnoreUserAbort); ow.StartSection("error-control"); ow.WriteEnumOption("error_reporting", "ReportErrors", (int)PhpErrorSet.AllButStrict, (int)local.ErrorControl.ReportErrors, typeof(PhpError)); ow.WriteOption("display_errors", "DisplayErrors", true, local.ErrorControl.DisplayErrors); ow.WriteOption("html_errors", "HtmlMessages", true, local.ErrorControl.HtmlMessages); ow.WriteOption("docref_root", "DocRefRoot", null, local.ErrorControl.DocRefRoot.ToString()); ow.WriteOption("docref_ext", "DocRefExtension", null, local.ErrorControl.DocRefExtension); ow.WriteErrorLog("error_log", null, local.ErrorControl.SysLog, local.ErrorControl.LogFile); ow.WriteOption("log_errors", "EnableLogging", false, local.ErrorControl.EnableLogging); ow.WriteOption("error_prepend_string", "ErrorPrependString", null, local.ErrorControl.ErrorPrependString); ow.WriteOption("error_append_string", "ErrorAppendString", null, local.ErrorControl.ErrorAppendString); ow.StartSection("session-control"); ow.WriteOption("session.auto_start", "AutoStart", false, local.Session.AutoStart); ow.WriteOption("session.save_handler", "Handler", "files", local.Session.Handler.Name); ow.StartSection("assertion"); ow.WriteOption("assert.active", "Active", true, local.Assertion.Active); ow.WriteOption("assert.warning", "ReportWarning", true, local.Assertion.ReportWarning); ow.WriteOption("assert.bail", "Terminate", false, local.Assertion.Terminate); ow.WriteOption("assert.quiet_eval", "Quiet", false, local.Assertion.Quiet); ow.WriteOption("assert.callback", "Callback", null, local.Assertion.Callback); ow.StartSection("safe-mode"); ow.WriteOption("safe_mode", "Enabled", false, global.SafeMode.Enabled); ow.WriteOption("open_basedir", "AllowedPathPrefixes", null, global.SafeMode.GetAllowedPathPrefixesJoin()); ow.WriteOption("safe_mode_exec_dir", "ExecutionDirectory", null, global.SafeMode.ExecutionDirectory); ow.StartSection("posted-files"); ow.WriteOption("file_uploads", "Accept", true, global.PostedFiles.Accept); ow.WriteOption("upload_tmp_dir", "TempPath", null, global.PostedFiles.TempPath); ow.StartSection("file-system"); ow.WriteOption("allow_url_fopen", "AllowUrlFopen", true, local.FileSystem.AllowUrlFopen); ow.WriteOption("default_socket_timeout", "DefaultSocketTimeout", 60, local.FileSystem.DefaultSocketTimeout); ow.WriteOption("user_agent", "UserAgent", null, local.FileSystem.UserAgent); ow.WriteOption("from", "AnonymousFtpPassword", null, local.FileSystem.AnonymousFtpPassword); ow.WriteOption("include_path", "IncludePaths", ".", local.FileSystem.IncludePaths); ow.WriteEnd(); } #endregion #region Public GSRs internal static bool OptionValueToBoolean(object value) { string sval = value as string; if (sval != null) { switch (sval.ToLower(System.Globalization.CultureInfo.InvariantCulture)) // we dont need any unicode chars lowercased properly, CurrentCulture is slow { case "on": case "yes": return true; case "off": case "no": case "none": return false; } } return Convert.ObjectToBoolean(value); } /// <summary> /// Gets, sets or restores boolean option. /// </summary> public static object GSR(ref bool option, bool defaultValue, object value, IniAction action) { object result = option; switch (action) { case IniAction.Set: option = OptionValueToBoolean(value); break; case IniAction.Restore: option = defaultValue; break; } return result; } /// <summary> /// Gets, sets or restores integer option. /// </summary> public static object GSR(ref int option, int defaultValue, object value, IniAction action) { object result = option; switch (action) { case IniAction.Set: option = Convert.ObjectToInteger(value); break; case IniAction.Restore: option = defaultValue; break; } return result; } /// <summary> /// Gets, sets or restores double option. /// </summary> public static object GSR(ref double option, double defaultValue, object value, IniAction action) { object result = option; switch (action) { case IniAction.Set: option = Convert.ObjectToDouble(value); break; case IniAction.Restore: option = defaultValue; break; } return result; } /// <summary> /// Gets, sets or restores string option. /// </summary> public static object GSR(ref string option, string defaultValue, object value, IniAction action) { object result = option; switch (action) { case IniAction.Set: option = Convert.ObjectToString(value); break; case IniAction.Restore: option = defaultValue; break; } return result; } /// <summary> /// Gets, sets or restores callback option. /// </summary> public static object GSR(ref PhpCallback option, PhpCallback defaultValue, object value, IniAction action) { object result = option; switch (action) { case IniAction.Set: option = Convert.ObjectToCallback(value); break; case IniAction.Restore: option = defaultValue; break; } return result; } #endregion #region Special GSRs /// <summary> /// Gets, sets or restores "default_charset" option. /// </summary> private static object GsrDefaultCharset(object value, IniAction action) { HttpContext context; if (!Web.EnsureHttpContext(out context)) return null; object result = context.Response.Charset; switch (action) { case IniAction.Set: context.Response.Charset = Convert.ObjectToString(value); break; case IniAction.Restore: context.Response.Charset = DefaultCharset; break; } return result; } /// <summary> /// Gets, sets or restores "default_mimetype" option. /// </summary> private static object GsrDefaultMimetype(object value, IniAction action) { HttpContext context; if (!Web.EnsureHttpContext(out context)) return null; object result = context.Response.ContentType; switch (action) { case IniAction.Set: context.Response.ContentType = Convert.ObjectToString(value); break; case IniAction.Restore: context.Response.ContentType = DefaultMimetype; break; } return result; } /// <summary> /// Gets, sets or restores "memory_limit" option. /// </summary> private static object GsrMemoryLimit(object value, IniAction action) { object result = -1; switch (action) { case IniAction.Set: case IniAction.Restore: PhpException.ArgumentValueNotSupported("memory_limit", action); break; } return result; } /// <summary> /// Gets, sets or restores "disable_functions" option. /// </summary> private static object GsrDisableFunctions(object value, IniAction action) { object result = ""; switch (action) { case IniAction.Set: case IniAction.Restore: PhpException.ArgumentValueNotSupported("disable_functions", action); break; } return result; } /// <summary> /// Gets, sets or restores "variables_order" option. /// </summary> private static object GsrVariablesOrder(LocalConfiguration local, LocalConfiguration @default, object value, IniAction action) { object result = local.Variables.RegisteringOrder; switch (action) { case IniAction.Set: string svalue = Convert.ObjectToString(value); if (!LocalConfiguration.VariablesSection.ValidateRegisteringOrder(svalue)) PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_registering_order")); else local.Variables.RegisteringOrder = svalue; break; case IniAction.Restore: local.Variables.RegisteringOrder = @default.Variables.RegisteringOrder; break; } return result; } /// <summary> /// Gets, sets or restores "error_log" option. /// </summary> private static object GsrErrorLog(LocalConfiguration local, LocalConfiguration @default, object value, IniAction action) { if (action == IniAction.Restore) { local.ErrorControl.LogFile = @default.ErrorControl.LogFile; local.ErrorControl.SysLog = @default.ErrorControl.SysLog; return null; } string result = (local.ErrorControl.SysLog) ? ErrorLogSysLog : local.ErrorControl.LogFile; if (action == IniAction.Set) { string svalue = Convert.ObjectToString(value); local.ErrorControl.SysLog = (string.Compare(svalue, ErrorLogSysLog, StringComparison.InvariantCultureIgnoreCase) == 0); local.ErrorControl.LogFile = (local.ErrorControl.SysLog) ? svalue : null; } return result; } #endregion #region ini_get, ini_set, ini_restore, get_cfg_var, ini_alter /// <summary> /// Gets the value of a configuration option. /// </summary> /// <param name="option">The option name (case sensitive).</param> /// <returns>The option old value conveted to string or <B>false</B> on error.</returns> /// <exception cref="PhpException">The option is not supported (Warning).</exception> [ImplementsFunction("ini_get")] public static object Get(string option) { bool error; object result = IniOptions.TryGetSetRestore(option, null, IniAction.Get, out error); if (error) return false; return Convert.ObjectToString(result); } /// <summary> /// Sets the value of a configuration option. /// </summary> /// <param name="option">The option name (case sensitive).</param> /// <param name="value">The option new value.</param> /// <returns>The option old value converted to string or <B>false</B> on error.</returns> /// <exception cref="PhpException">The option is not supported (Warning).</exception> /// <exception cref="PhpException">The option cannot be set by script (Warning).</exception> [ImplementsFunction("ini_set")] public static object Set(string option, object value) { bool error; object result = IniOptions.TryGetSetRestore(option, value, IniAction.Set, out error); if (error) return false; return Convert.ObjectToString(result); } /// <summary> /// Restores the value of a configuration option to its global value. /// No value is returned. /// </summary> /// <param name="option">The option name (case sensitive).</param> /// <exception cref="PhpException">The option is not supported (Warning).</exception> [ImplementsFunction("ini_restore")] public static void Restore(string option) { bool error; IniOptions.TryGetSetRestore(option, null, IniAction.Restore, out error); } /// <summary> /// Gets the value of a configuration option (alias for <see cref="Get"/>). /// </summary> /// <param name="option">The option name (case sensitive).</param> /// <returns>The option old value conveted to string or <B>false</B> on error.</returns> /// <exception cref="PhpException">The option is not supported (Warning).</exception> [ImplementsFunction("get_cfg_var")] public static object GetCfgVar(string option) { return Get(option); } /// <summary> /// Sets the value of a configuration option (alias for <see cref="Set"/>). /// </summary> /// <param name="option">The option name (case sensitive).</param> /// <param name="value">The option new value converted to string.</param> /// <returns>The option old value.</returns> /// <exception cref="PhpException">The option is not supported (Warning).</exception> /// <exception cref="PhpException">The option cannot be set by script (Warning).</exception> [ImplementsFunction("ini_alter")] public static object Alter(string option, object value) { return Set(option, value); } #endregion #region get_all /// <summary> /// Retrieves an array of all configuration entries. /// </summary> /// <seealso cref="GetAll(string)"/> [ImplementsFunction("ini_get_all")] public static PhpArray GetAll() { return (PhpArray)IniOptions.GetAllOptionStates(null, new PhpArray(0, IniOptions.Count)); } /// <summary> /// Retrieves an array of configuration entries of a specified extension. /// </summary> /// <param name="extension">The PHP internal extension name.</param> /// <remarks> /// For each supported configuration option an entry is added to the resulting array. /// The key is the name of the option and the value is an array having three entries: /// <list type="bullet"> /// <item><c>global_value</c> - global value of the option</item> /// <item><c>local_value</c> - local value of the option</item> /// <item><c>access</c> - 7 (PHP_INI_ALL), 6 (PHP_INI_PERDIR | PHP_INI_SYSTEM) or 4 (PHP_INI_SYSTEM)</item> /// </list> /// </remarks> [ImplementsFunction("ini_get_all")] public static PhpArray GetAll(string extension) { PhpArray result = new PhpArray(); // adds options from managed libraries: IniOptions.GetAllOptionStates(extension, result); return result; } #endregion #region assert_options /// <summary> /// Gets a value of an assert option. /// </summary> /// <param name="option">The option which value to get.</param> /// <returns>The value of the option.</returns> [ImplementsFunction("assert_options")] public static object AssertOptions(AssertOption option) { return AssertOptions(option, null, IniAction.Get); } /// <summary> /// Sets a value of an assert option. /// </summary> /// <param name="option">The option which value to get.</param> /// <param name="value">The new value for the option.</param> /// <returns>The value of the option.</returns> [ImplementsFunction("assert_options")] public static object AssertOptions(AssertOption option, object value) { return AssertOptions(option, value, IniAction.Set); } /// <summary> /// Implementation of <see cref="AssertOptions(AssertOption)"/> and <see cref="AssertOptions(AssertOption,object)"/>. /// </summary> /// <remarks>Only gets/sets. No restore.</remarks> private static object AssertOptions(AssertOption option, object value, IniAction action) { LocalConfiguration config = Configuration.Local; switch (option) { case AssertOption.Active: return GSR(ref config.Assertion.Active, false, value, action); case AssertOption.Callback: return GSR(ref config.Assertion.Callback, null, value, action); case AssertOption.Quiet: return GSR(ref config.Assertion.Quiet, false, value, action); case AssertOption.Terminate: return GSR(ref config.Assertion.Terminate, false, value, action); case AssertOption.ReportWarning: return GSR(ref config.Assertion.ReportWarning, false, value, action); default: PhpException.InvalidArgument("option"); return false; } } #endregion #region get_include_path, set_include_path, restore_include_path /// <summary> /// Gets a value of "include_path" option. /// </summary> /// <returns>The current value.</returns> [ImplementsFunction("get_include_path")] public static string GetIncludePath() { return Configuration.Local.FileSystem.IncludePaths; } /// <summary> /// Sets a new value of "include_path" option. /// </summary> /// <returns>A previous value.</returns> [ImplementsFunction("set_include_path")] public static string SetIncludePath(string value) { LocalConfiguration config = Configuration.Local; string result = config.FileSystem.IncludePaths; config.FileSystem.IncludePaths = value; return result; } /// <summary> /// Restores a value of "include_path" option from global configuration. /// No value is returned. /// </summary> [ImplementsFunction("restore_include_path")] public static void RestoreIncludePath() { Configuration.Local.FileSystem.IncludePaths = Configuration.DefaultLocal.FileSystem.IncludePaths; } #endregion #region get_magic_quotes_gpc, get_magic_quotes_runtime, set_magic_quotes_runtime /// <summary> /// Gets a value of "magic_quotes_gpc" option. /// </summary> /// <returns>The current value.</returns> [ImplementsFunction("get_magic_quotes_gpc")] public static bool GetMagicQuotesGPC() { return Configuration.Global.GlobalVariables.QuoteGpcVariables; } /// <summary> /// Gets a value of "magic_quotes_runtime" option. /// </summary> /// <returns>The current value.</returns> [ImplementsFunction("get_magic_quotes_runtime")] public static bool GetMagicQuotesRuntime() { return Configuration.Local.Variables.QuoteRuntimeVariables; } /// <summary> /// Sets a new value of "magic_quotes_runtime" option. /// </summary> /// <param name="value">The new value.</param> /// <returns>A previous value.</returns> [ImplementsFunction("set_magic_quotes_runtime")] public static bool SetMagicQuotesRuntime(bool value) { LocalConfiguration local = Configuration.Local; bool result = local.Variables.QuoteRuntimeVariables; local.Variables.QuoteRuntimeVariables = value; return result; } #endregion #region error_reporting, set_error_handler, restore_error_handler, set_exception_handler, restore_exception_handler /// <summary> /// Retrieves the current error reporting level. /// </summary> /// <returns> /// The bitmask of error types which are reported. Returns 0 if error reporting is disabled /// by means of @ operator. /// </returns> [ImplementsFunction("error_reporting")] public static int ErrorReporting() { return ScriptContext.CurrentContext.ErrorReportingLevel; } /// <summary> /// Sets a new level of error reporting. /// </summary> /// <param name="level">The new level.</param> /// <returns>The original level.</returns> [ImplementsFunction("error_reporting")] public static int ErrorReporting(int level) { if ((level & (int)PhpErrorSet.All) == 0 && level != 0) PhpException.InvalidArgument("level"); ScriptContext context = ScriptContext.CurrentContext; int result = context.ErrorReportingLevel; context.Config.ErrorControl.ReportErrors = PhpErrorSet.All & (PhpErrorSet)level; return result; } /// <summary> /// Internal record in the error handler stack. /// </summary> private class ErrorHandlerRecord { /// <summary> /// Error handler callback. /// </summary> public PhpCallback ErrorHandler; /// <summary> /// Error types to be handled. /// </summary> public PhpError ErrorTypes; /// <summary> /// Public constructor of the class. /// </summary> /// <param name="handler">Error handler callback.</param> /// <param name="errors">Error types to be handled.</param> public ErrorHandlerRecord(PhpCallback handler, PhpError errors) { ErrorHandler = handler; ErrorTypes = errors; } } /// <summary> /// Stores user error handlers which has been rewritten by a new one. /// </summary> [ThreadStatic] private static Stack OldUserErrorHandlers; // GENERICS: <ErrorHandlerRecord> /// <summary> /// Stores user exception handlers which has been rewritten by a new one. /// </summary> [ThreadStatic] private static Stack OldUserExceptionHandlers; // GENERICS: <PhpCallback> /// <summary> /// Clears <see cref="OldUserErrorHandlers"/> and <see cref="OldUserExceptionHandlers"/> on request end. /// </summary> private static void ClearOldUserHandlers() { OldUserErrorHandlers = null; OldUserExceptionHandlers = null; } /// <summary> /// Sets user defined handler to handle errors. /// </summary> /// <param name="caller">The class context used to bind the callback.</param> /// <param name="newHandler">The user callback called to handle an error.</param> /// <returns> /// The PHP representation of previous user handler, <B>null</B> if there is no user one, or /// <B>false</B> if <paramref name="newHandler"/> is invalid or empty. /// </returns> /// <remarks> /// Stores old user handlers on the stack so that it is possible to /// go back to arbitrary previous user handler. /// </remarks> [ImplementsFunction("set_error_handler", FunctionImplOptions.NeedsClassContext)] public static object SetErrorHandler(PHP.Core.Reflection.DTypeDesc caller, PhpCallback newHandler) { return SetErrorHandler(caller, newHandler, (int)PhpErrorSet.Handleable); } /// <summary> /// Sets user defined handler to handle errors. /// </summary> /// <param name="caller">The class context used to bind the callback.</param> /// <param name="newHandler">The user callback called to handle an error.</param> /// <param name="errorTypes">Error types to be handled by the handler.</param> /// <returns> /// The PHP representation of previous user handler, <B>null</B> if there is no user one, or /// <B>false</B> if <paramref name="newHandler"/> is invalid or empty. /// </returns> /// <remarks> /// Stores old user handlers on the stack so that it is possible to /// go back to arbitrary previous user handler. /// </remarks> [ImplementsFunction("set_error_handler", FunctionImplOptions.NeedsClassContext)] public static object SetErrorHandler(PHP.Core.Reflection.DTypeDesc caller, PhpCallback newHandler, int errorTypes) { if (!PhpArgument.CheckCallback(newHandler, caller, "newHandler", 0, false)) return null; PhpCallback old_handler = Configuration.Local.ErrorControl.UserHandler; PhpError old_errors = Configuration.Local.ErrorControl.UserHandlerErrors; // previous handler was defined by user => store it into the stack: if (old_handler != null) { if (OldUserErrorHandlers == null) { OldUserErrorHandlers = new Stack(5); RequestContext.RequestEnd += new Action(ClearOldUserHandlers); } OldUserErrorHandlers.Push(new ErrorHandlerRecord(old_handler, old_errors)); } // sets the current handler: Configuration.Local.ErrorControl.UserHandler = newHandler; Configuration.Local.ErrorControl.UserHandlerErrors = (PhpError)errorTypes; // returns the previous handler: return (old_handler != null) ? old_handler.ToPhpRepresentation() : null; } /// <summary> /// Restores the previous user error handler if there was any. /// </summary> [ImplementsFunction("restore_error_handler")] public static bool RestoreErrorHandler() { // if some user handlers has been stored in the stack then restore the top-most, otherwise set to null: if (OldUserErrorHandlers != null && OldUserErrorHandlers.Count > 0) { ErrorHandlerRecord record = (ErrorHandlerRecord)OldUserErrorHandlers.Pop(); Configuration.Local.ErrorControl.UserHandler = record.ErrorHandler; Configuration.Local.ErrorControl.UserHandlerErrors = record.ErrorTypes; } else { Configuration.Local.ErrorControl.UserHandler = null; Configuration.Local.ErrorControl.UserHandlerErrors = (PhpError)PhpErrorSet.None; } return true; } /// <summary> /// Sets user defined handler to handle exceptions. /// </summary> /// <param name="caller">The class context used to bind the callback.</param> /// <param name="newHandler">The user callback called to handle an exceptions.</param> /// <returns> /// The PHP representation of previous user handler, <B>null</B> if there is no user one, or /// <B>false</B> if <paramref name="newHandler"/> is invalid or empty. /// </returns> /// <remarks> /// Stores old user handlers on the stack so that it is possible to /// go back to arbitrary previous user handler. /// </remarks> [ImplementsFunction("set_exception_handler", FunctionImplOptions.NeedsClassContext)] public static object SetExceptionHandler(PHP.Core.Reflection.DTypeDesc caller, PhpCallback newHandler) { if (!PhpArgument.CheckCallback(newHandler, caller, "newHandler", 0, false)) return null; PhpCallback old_handler = Configuration.Local.ErrorControl.UserExceptionHandler; // previous handler was defined by user => store it into the stack: if (old_handler != null) { if (OldUserExceptionHandlers == null) { OldUserExceptionHandlers = new Stack(5); RequestContext.RequestEnd += new Action(ClearOldUserHandlers); } OldUserExceptionHandlers.Push(old_handler); } // sets the current handler: Configuration.Local.ErrorControl.UserExceptionHandler = newHandler; // returns the previous handler: return (old_handler != null) ? old_handler.ToPhpRepresentation() : null; } /// <summary> /// Restores the previous user error handler if there was any. /// </summary> [ImplementsFunction("restore_exception_handler")] public static bool RestoreExceptionHandler() { if (OldUserExceptionHandlers != null && OldUserExceptionHandlers.Count > 0) Configuration.Local.ErrorControl.UserExceptionHandler = (PhpCallback)OldUserExceptionHandlers.Pop(); else Configuration.Local.ErrorControl.UserExceptionHandler = null; return true; } #endregion #region set_time_limit, ignore_user_abort /// <summary> /// Sets the request time-out in seconds (configuration option "max_execution_time"). /// No value is returned. /// </summary> /// <param name="seconds">The time-out setting for request.</param> [ImplementsFunction("set_time_limit")] public static void SetTimeLimit(int seconds) { ScriptContext.CurrentContext.ApplyExecutionTimeout(seconds); } /// <summary> /// Get a value of a configuration option "ignore_user_abort". /// </summary> /// <returns>The current value of the option.</returns> [ImplementsFunction("ignore_user_abort")] public static bool IgnoreUserAbort() { return Configuration.Local.RequestControl.IgnoreUserAbort; } /// <summary> /// Sets a value of a configuration option "ignore_user_abort". /// </summary> /// <param name="value">The new value of the option.</param> /// <returns>The previous value of the option.</returns> /// <exception cref="PhpException">Web request PHP context is not available (Warning).</exception> [ImplementsFunction("ignore_user_abort")] public static bool IgnoreUserAbort(bool value) { RequestContext context; if (!Web.EnsureRequestContext(out context)) return true; LocalConfiguration local = Configuration.Local; bool result = local.RequestControl.IgnoreUserAbort; local.RequestControl.IgnoreUserAbort = value; // enables/disables disconnection tracking: context.TrackClientDisconnection = !value; return result; } #endregion } #region PhpIniXmlWriter public sealed class PhpIniXmlWriter { private readonly XmlTextWriter writer; private readonly Hashtable options; // GENERICS: <string,string> private readonly bool writePhpNames; private string startSection; private bool sectionOpened; public PhpIniXmlWriter(XmlTextWriter writer, Hashtable options, bool writePhpNames) { this.writer = writer; this.options = options; this.writePhpNames = writePhpNames; } public void WriteEnd() { if (sectionOpened) writer.WriteEndElement(); } public void StartSection(string name) { startSection = name; } private void StartElement() { if (startSection != null) { if (sectionOpened) writer.WriteEndElement(); writer.WriteStartElement(startSection); startSection = null; sectionOpened = true; } } private void WriteSetNode(string phpName, string xmlName, string value) { StartElement(); writer.WriteStartElement("set"); writer.WriteAttributeString("name", xmlName); writer.WriteAttributeString("value", value); if (writePhpNames) writer.WriteAttributeString("phpName", phpName); writer.WriteEndElement(); } private void WriteEnumSetNode(string phpName, string xmlName, int value, Type type) { StartElement(); writer.WriteStartElement("set"); writer.WriteAttributeString("name", xmlName); if (writePhpNames) writer.WriteAttributeString("phpName", phpName); writer.WriteStartElement("clear"); writer.WriteEndElement(); writer.WriteStartElement("add"); writer.WriteAttributeString("value", Enum.Format(type, value, "G")); writer.WriteEndElement(); writer.WriteEndElement(); } public void WriteOption(string phpName, string xmlName, string phpValue, string defValue) { if (options.ContainsKey(phpName)) { phpValue = (string)options[phpName]; options.Remove(phpName); } if (phpValue == null) phpValue = ""; if (defValue == null) defValue = ""; if (phpValue != defValue) WriteSetNode(phpName, xmlName, phpValue); } public void WriteOption(string phpName, string xmlName, bool phpValue, bool defValue) { if (options.ContainsKey(phpName)) { phpValue = Core.Convert.StringToBoolean((string)options[phpName]); options.Remove(phpName); } if (phpValue != defValue) WriteSetNode(phpName, xmlName, phpValue ? "true" : "false"); } public void WriteByteSize(string phpName, string xmlName, int phpValue, int defValue) { if (options.ContainsKey(phpName)) { phpValue = Core.Convert.StringByteSizeToInteger((string)options[phpName]); options.Remove(phpName); } if (phpValue != defValue) WriteSetNode(phpName, xmlName, phpValue.ToString()); } public void WriteOption(string phpName, string xmlName, int phpValue, int defValue) { if (options.ContainsKey(phpName)) { phpValue = Core.Convert.StringToInteger((string)options[phpName]); options.Remove(phpName); } if (phpValue != defValue) WriteSetNode(phpName, xmlName, phpValue.ToString()); } public void WriteOption(string phpName, string xmlName, double phpValue, double defValue) { if (options.ContainsKey(phpName)) { phpValue = Core.Convert.StringToDouble((string)options[phpName]); options.Remove(phpName); } if (phpValue != defValue) WriteSetNode(phpName, xmlName, phpValue.ToString()); } public void WriteOption(string phpName, string xmlName, string phpValue, PhpCallback defValue) { WriteOption(phpName, xmlName, phpValue, (defValue != null) ? ((IPhpConvertible)defValue).ToString() : null); } internal void WriteErrorLog(string phpName, string phpValue, bool defSysLog, string defLogFile) { if (options.ContainsKey(phpName)) { phpValue = (string)options[phpName]; options.Remove(phpName); } bool phpSysLog = phpValue == PhpIni.ErrorLogSysLog; string phpLogFile = phpSysLog ? null : phpValue; if (phpLogFile == null) phpLogFile = ""; if (defLogFile == null) defLogFile = ""; if (phpLogFile != defLogFile) WriteSetNode(phpName, "LogFile", phpLogFile); if (phpSysLog != defSysLog) WriteSetNode(phpName, "SysLog", phpSysLog ? "true" : "false"); } public void WriteEnumOption(string phpName, string xmlName, int phpValue, int defValue, Type type) { if (options.ContainsKey(phpName)) { phpValue = Core.Convert.StringToInteger((string)options[phpName]); options.Remove(phpName); } if (phpValue != defValue) WriteEnumSetNode(phpName, xmlName, phpValue, type); } } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ComVisible(true)] public class AutomationObject { private readonly IOptionService _optionService; internal AutomationObject(IOptionService optionService) { _optionService = optionService; } public int AutoComment { get { return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration); } set { SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value); } } public int BringUpOnIdentifier { get { return GetBooleanOption(CompletionOptions.TriggerOnTypingLetters); } set { SetBooleanOption(CompletionOptions.TriggerOnTypingLetters, value); } } [Obsolete("This SettingStore option has now been deprecated in favor of CSharpClosedFileDiagnostics")] public int ClosedFileDiagnostics { get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); } set { // Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics'). // So, we invoke the setter only for value = 0. if (value == 0) { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); } } } public int CSharpClosedFileDiagnostics { get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); } set { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); } } public int DisplayLineSeparators { get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); } set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); } } public int EnableHighlightRelatedKeywords { get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); } } public int EnterOutliningModeOnOpen { get { return GetBooleanOption(FeatureOnOffOptions.Outlining); } set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); } } public int ExtractMethod_AllowMovingDeclaration { get { return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration); } set { SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value); } } public int ExtractMethod_DoNotPutOutOrRefOnStruct { get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); } set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); } } public int Formatting_TriggerOnBlockCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, value); } } public int Formatting_TriggerOnPaste { get { return GetBooleanOption(FeatureOnOffOptions.FormatOnPaste); } set { SetBooleanOption(FeatureOnOffOptions.FormatOnPaste, value); } } public int Formatting_TriggerOnStatementCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, value); } } public int HighlightReferences { get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); } } public int Indent_BlockContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); } set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); } } public int Indent_Braces { get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); } set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); } } public int Indent_CaseContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); } } public int Indent_CaseLabels { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); } } public int Indent_FlushLabelsLeft { get { var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); return option == LabelPositionOptions.LeftMost ? 1 : 0; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); _optionService.SetOptions(optionSet); } } public int Indent_UnindentLabels { get { var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); return (int)option; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value); _optionService.SetOptions(optionSet); } } public int InsertNewlineOnEnterWithWholeWord { get { return GetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord); } set { SetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, value); } } public int NewLines_AnonymousTypeInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); } } public int NewLines_Braces_AnonymousMethod { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); } } public int NewLines_Braces_AnonymousTypeInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); } } public int NewLines_Braces_ControlFlow { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); } } public int NewLines_Braces_LambdaExpressionBody { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); } } public int NewLines_Braces_Method { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); } } public int NewLines_Braces_Property { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); } } public int NewLines_Braces_Accessor { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); } } public int NewLines_Braces_ObjectInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); } } public int NewLines_Braces_Type { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); } } public int NewLines_Keywords_Catch { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); } } public int NewLines_Keywords_Else { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); } } public int NewLines_Keywords_Finally { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); } } public int NewLines_ObjectInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); } } public int NewLines_QueryExpression_EachClause { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); } } public int Refactoring_Verification_Enabled { get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); } set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); } } public int RenameSmartTagEnabled { get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); } set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); } } public int RenameTrackingPreview { get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); } set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); } } public int ShowKeywords { get { return GetBooleanOption(CompletionOptions.IncludeKeywords); } set { SetBooleanOption(CompletionOptions.IncludeKeywords, value); } } public int ShowSnippets { get { return GetBooleanOption(CSharpCompletionOptions.IncludeSnippets); } set { SetBooleanOption(CSharpCompletionOptions.IncludeSnippets, value); } } public int SortUsings_PlaceSystemFirst { get { return GetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst); } set { SetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst, value); } } public int AddImport_SuggestForTypesInReferenceAssemblies { get { return GetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies); } set { SetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies, value); } } public int AddImport_SuggestForTypesInNuGetPackages { get { return GetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages); } set { SetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages, value); } } public int Space_AfterBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); } } public int Space_AfterCast { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); } } public int Space_AfterComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); } } public int Space_AfterDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); } } public int Space_AfterMethodCallName { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); } } public int Space_AfterMethodDeclarationName { get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); } set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); } } public int Space_AfterSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); } } public int Space_AroundBinaryOperator { get { var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return option == BinaryOperatorSpacingOptions.Single ? 1 : 0; } set { var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore; var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option); _optionService.SetOptions(optionSet); } } public int Space_BeforeBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); } } public int Space_BeforeComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); } } public int Space_BeforeDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); } } public int Space_BeforeOpenSquare { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); } } public int Space_BeforeSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); } } public int Space_BetweenEmptyMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); } } public int Space_BetweenEmptyMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); } } public int Space_BetweenEmptySquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); } } public int Space_InControlFlowConstruct { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); } } public int Space_WithinCastParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); } } public int Space_WithinExpressionParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); } } public int Space_WithinMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); } } public int Space_WithinMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); } } public int Space_WithinOtherParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); } } public int Space_WithinSquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); } } public int Style_QualifyMemberAccessWithThisOrMe { get { return GetBooleanOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe); } set { SetBooleanOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe, value); } } public int Style_UseVarWhenDeclaringLocals { get { return GetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); } set { SetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals, value); } } public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return (int)option; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value); _optionService.SetOptions(optionSet); } } public int Wrapping_IgnoreSpacesAroundVariableDeclaration { get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); } } public int Wrapping_KeepStatementsOnSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); } } public int Wrapping_PreserveSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); } } private int GetBooleanOption(Option<bool> key) { return _optionService.GetOption(key) ? 1 : 0; } private int GetBooleanOption(PerLanguageOption<bool> key) { return _optionService.GetOption(key, LanguageNames.CSharp) ? 1 : 0; } private void SetBooleanOption(Option<bool> key, int value) { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, value != 0); _optionService.SetOptions(optionSet); } private void SetBooleanOption(PerLanguageOption<bool> key, int value) { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, LanguageNames.CSharp, value != 0); _optionService.SetOptions(optionSet); } private int GetBooleanOption(PerLanguageOption<bool?> key) { var option = _optionService.GetOption(key, LanguageNames.CSharp); if (!option.HasValue) { return -1; } return option.Value ? 1 : 0; } private void SetBooleanOption(PerLanguageOption<bool?> key, int value) { bool? boolValue = (value < 0) ? (bool?)null : (value > 0); var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, LanguageNames.CSharp, boolValue); _optionService.SetOptions(optionSet); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.InternalAbstractions; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.MultilevelSDKLookup { public class GivenThatICareAboutMultilevelSDKLookup : IDisposable { private static IDictionary<string, string> s_DefaultEnvironment = new Dictionary<string, string>() { {"COREHOST_TRACE", "1" }, // The SDK being used may be crossgen'd for a different architecture than we are building for. // Turn off ready to run, so an x64 crossgen'd SDK can be loaded in an x86 process. {"COMPlus_ReadyToRun", "0" }, }; private RepoDirectoriesProvider RepoDirectories; private TestProjectFixture PreviouslyBuiltAndRestoredPortableTestProjectFixture; private string _currentWorkingDir; private string _userDir; private string _executableDir; private string _cwdSdkBaseDir; private string _userSdkBaseDir; private string _exeSdkBaseDir; private string _cwdSelectedMessage; private string _userSelectedMessage; private string _exeSelectedMessage; private string _sdkDir; private string _multilevelDir; private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]"; public GivenThatICareAboutMultilevelSDKLookup() { // From the artifacts dir, it's possible to find where the sharedFrameworkPublish folder is. We need // to locate it because we'll copy its contents into other folders string artifactsDir = Environment.GetEnvironmentVariable("TEST_ARTIFACTS"); string builtDotnet = Path.Combine(artifactsDir, "sharedFrameworkPublish"); // The dotnetMultilevelSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseMultilevelDir = Path.Combine(artifactsDir, "dotnetMultilevelSDKLookup"); _multilevelDir = SharedFramework.CalculateUniqueTestDirectory(baseMultilevelDir); // The three tested locations will be the cwd, the user folder and the exe dir. cwd and user are no longer supported. // All dirs will be placed inside the multilevel folder _currentWorkingDir = Path.Combine(_multilevelDir, "cwd"); _userDir = Path.Combine(_multilevelDir, "user"); _executableDir = Path.Combine(_multilevelDir, "exe"); // It's necessary to copy the entire publish folder to the exe dir because // we'll need to build from it. The CopyDirectory method automatically creates the dest dir SharedFramework.CopyDirectory(builtDotnet, _executableDir); RepoDirectories = new RepoDirectoriesProvider(builtDotnet: _executableDir); // SdkBaseDirs contain all available version folders _cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk"); _userSdkBaseDir = Path.Combine(_userDir, ".dotnet", RepoDirectories.BuildArchitecture, "sdk"); _exeSdkBaseDir = Path.Combine(_executableDir, "sdk"); // Create directories Directory.CreateDirectory(_cwdSdkBaseDir); Directory.CreateDirectory(_userSdkBaseDir); Directory.CreateDirectory(_exeSdkBaseDir); // Restore and build PortableApp from exe dir PreviouslyBuiltAndRestoredPortableTestProjectFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .BuildProject(); var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture; // Set a dummy framework version (9999.0.0) in the exe sharedFx location. We will // always pick the framework from this to avoid interference with the sharedFxLookup string exeDirDummyFxVersion = Path.Combine(_executableDir, "shared", "Microsoft.NETCore.App", "9999.0.0"); string builtSharedFxDir = fixture.BuiltDotnet.GreatestVersionSharedFxPath; SharedFramework.CopyDirectory(builtSharedFxDir, exeDirDummyFxVersion); // The actual SDK version can be obtained from the built fixture. We'll use it to // locate the sdkDir from which we can get the files contained in the version folder string sdkBaseDir = Path.Combine(fixture.SdkDotnet.BinPath, "sdk"); var sdkVersionDirs = Directory.EnumerateDirectories(sdkBaseDir) .Select(p => Path.GetFileName(p)); string greatestVersionSdk = sdkVersionDirs .Where(p => !string.Equals(p, "NuGetFallbackFolder", StringComparison.OrdinalIgnoreCase)) .OrderByDescending(p => p.ToLower()) .First(); _sdkDir = Path.Combine(sdkBaseDir, greatestVersionSdk); // Trace messages used to identify from which folder the SDK was picked _cwdSelectedMessage = $"Using dotnet SDK dll=[{_cwdSdkBaseDir}"; _userSelectedMessage = $"Using dotnet SDK dll=[{_userSdkBaseDir}"; _exeSelectedMessage = $"Using dotnet SDK dll=[{_exeSdkBaseDir}"; } public void Dispose() { PreviouslyBuiltAndRestoredPortableTestProjectFixture.Dispose(); if (!TestProject.PreserveTestRuns()) { Directory.Delete(_multilevelDir, true); } } [Fact] public void SdkLookup_Global_Json_Single_Digit_Patch_Rollup() { var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Set specified CLI version = 9999.3.4-global-dummy SetGlobalJsonVersion("SingleDigit-global.json"); // Add some dummy versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.4.1", "9999.3.4-dummy"); // Specified CLI version: 9999.3.4-global-dummy // CWD: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible SDK version for global.json version"); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.3"); // Specified CLI version: 9999.3.4-global-dummy // CWD: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3 // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible SDK version for global.json version"); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4"); // Specified CLI version: 9999.3.4-global-dummy // CWD: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4 // Expected: 9999.3.4 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.5-dummy"); // Specified CLI version: 9999.3.4-global-dummy // CWD: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy // Expected: 9999.3.5-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.600"); // Specified CLI version: 9999.3.4-global-dummy // CWD: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600 // Expected: 9999.3.5-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4-global-dummy"); // Specified CLI version: 9999.3.4-global-dummy // CWD: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600, 9999.3.4-global-dummy // Expected: 9999.3.4-global-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected sdk versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.3.4-dummy") .And .HaveStdOutContaining("9999.3.4-global-dummy") .And .HaveStdOutContaining("9999.4.1") .And .HaveStdOutContaining("9999.3.3") .And .HaveStdOutContaining("9999.3.4") .And .HaveStdOutContaining("9999.3.600") .And .HaveStdOutContaining("9999.3.5-dummy"); } [Fact] public void SdkLookup_Global_Json_Two_Part_Patch_Rollup() { var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Set specified CLI version = 9999.3.304-global-dummy SetGlobalJsonVersion("TwoPart-global.json"); // Add some dummy versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.57", "9999.3.4-dummy"); // Specified CLI version: 9999.3.304-global-dummy // CWD: empty // User: empty // Exe: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible SDK version for global.json version"); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.300", "9999.7.304-global-dummy"); // Specified CLI version: 9999.3.304-global-dummy // CWD: empty // User: empty // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("A compatible SDK version for global.json version"); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304"); // Specified CLI version: 9999.3.304-global-dummy // CWD: empty // User: empty // Exe: 99999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304 // Expected: 9999.3.304 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.399", "9999.3.399-dummy", "9999.3.400"); // Specified CLI version: 9999.3.304-global-dummy // CWD: empty // User: empty // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400 // Expected: 9999.3.399 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.2400, 9999.3.3004"); // Specified CLI version: 9999.3.304-global-dummy // CWD: empty // User: empty // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Expected: 9999.3.399 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304-global-dummy"); // Specified CLI version: 9999.3.304-global-dummy // CWD: empty // User: empty // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy // Expected: 9999.3.304-global-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected sdk versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.3.57") .And .HaveStdOutContaining("9999.3.4-dummy") .And .HaveStdOutContaining("9999.3.300") .And .HaveStdOutContaining("9999.7.304-global-dummy") .And .HaveStdOutContaining("9999.3.399") .And .HaveStdOutContaining("9999.3.399-dummy") .And .HaveStdOutContaining("9999.3.400") .And .HaveStdOutContaining("9999.3.2400") .And .HaveStdOutContaining("9999.3.3004") .And .HaveStdOutContaining("9999.3.304") .And .HaveStdOutContaining("9999.3.304-global-dummy"); } [Fact] public void SdkLookup_Negative_Version() { var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Add a negative CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "-1.-1.-1"); // Specified CLI version: none // CWD: empty // User: empty // Exe: -1.-1.-1 // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("It was not possible to find any SDK version"); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified CLI version: none // CWD: empty // User: empty // Exe: -1.-1.-1, 9999.0.4 // Expected: 9999.0.4 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Verify we have the expected sdk versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.0.4"); } [Fact] public void SdkLookup_Must_Pick_The_Highest_Semantic_Version() { var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Add dummy versions in the exe dir AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.0", "9999.0.3-dummy"); // Specified CLI version: none // CWD: empty // User: empty // Exe: 9999.0.0, 9999.0.3-dummy // Expected: 9999.0.3-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3-dummy", _dotnetSdkDllMessageTerminator)); // Add dummy versions in the exe dir AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.3"); // Specified CLI version: none // CWD: empty // User: empty // Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3 // Expected: 9999.0.3 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3", _dotnetSdkDllMessageTerminator)); // Add dummy versions AddAvailableSdkVersions(_userSdkBaseDir, "9999.0.200"); AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0"); AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.100"); // Specified CLI version: none // CWD: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100 // Expected: 9999.0.100 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add a dummy version in the exe dir AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.80"); // Specified CLI version: none // CWD: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100, 9999.0.80 // Expected: 9999.0.100 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add a dummy version in the user dir AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.5500000"); // Specified CLI version: none // CWD: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000 // Expected: 9999.0.5500000 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.5500000", _dotnetSdkDllMessageTerminator)); // Add a dummy version in the user dir AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.52000000"); // Specified CLI version: none // CWD: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000, 9999.0.52000000 // Expected: 9999.0.5500000 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.52000000", _dotnetSdkDllMessageTerminator)); // Verify we have the expected sdk versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.0.0") .And .HaveStdOutContaining("9999.0.3-dummy") .And .HaveStdOutContaining("9999.0.3") .And .HaveStdOutContaining("9999.0.100") .And .HaveStdOutContaining("9999.0.80") .And .HaveStdOutContaining("9999.0.5500000") .And .HaveStdOutContaining("9999.0.52000000"); } // This method adds a list of new sdk version folders in the specified // sdkBaseDir. The files are copied from the _sdkDir. Also, the dotnet.runtimeconfig.json // file is overwritten in order to use a dummy framework version (9999.0.0) // Remarks: // - If the sdkBaseDir does not exist, then a DirectoryNotFoundException // is thrown. // - If a specified version folder already exists, then it is deleted and replaced // with the contents of the _builtSharedFxDir. private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { DirectoryInfo sdkBaseDirInfo = new DirectoryInfo(sdkBaseDir); if (!sdkBaseDirInfo.Exists) { throw new DirectoryNotFoundException(); } string dummyRuntimeConfig = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", "dotnet.runtimeconfig.json"); foreach (string version in availableVersions) { string newSdkDir = Path.Combine(sdkBaseDir, version); SharedFramework.CopyDirectory(_sdkDir, newSdkDir); string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json"); File.Copy(dummyRuntimeConfig, runtimeConfig, true); } } // Put a global.json file in the cwd in order to specify a CLI public void SetGlobalJsonVersion(string globalJsonFileName) { string destFile = Path.Combine(_currentWorkingDir, "global.json"); string srcFile = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", globalJsonFileName); File.Copy(srcFile, destFile, true); } } }
/* Copyright (c) 2004-2006 Pavel Novak and Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; namespace Udger.Parser { /// <summary> /// Perl regular expression specific options that are not captured by .NET <see cref="RegexOptions"/> or by /// transformation of the regular expression itself. /// </summary> [Flags] enum PerlRegexOptions { None = 0, Evaluate = 1, Ungreedy = 2, Anchored = 4, DollarMatchesEndOfStringOnly = 8, UTF8 = 16 } /// <summary> /// Implements PERL extended regular expressions as they are implemented in PHP. /// </summary> /// <threadsafety static="true"/> #region PerlRegExpConverter /// <summary> /// Used for converting PHP Perl like regular expressions to .NET regular expressions. /// </summary> sealed class PerlRegExpConverter { #region Properties /// <summary> /// Regular expression used for matching quantifiers, they are changed ungreedy to greedy and vice versa if /// needed. /// </summary> private static Regex quantifiers { get { if (_quantifiers == null) _quantifiers = new Regex(@"\G(?:\?|\*|\+|\{[0-9]+,[0-9]*\})"); return _quantifiers; } } private static Regex _quantifiers; /// <summary> /// Regular expression for POSIX regular expression classes matching. /// </summary> private static Regex posixCharClasses { get { if (_posixCharClasses == null) _posixCharClasses = new Regex("^\\[:(^)?(alpha|alnum|ascii|cntrl|digit|graph|lower|print|punct|space|upper|word|xdigit):]", RegexOptions.Singleline); return _posixCharClasses; } } private static Regex _posixCharClasses = null; /// <summary> /// Original perl regular expression passed to the constructor. /// </summary> private string perlRegEx; /// <summary> /// Returns <see cref="Regex"/> class that can be used for matching. /// </summary> public Regex/*!*/ Regex { get { return regex; } } private Regex/*!*/ regex; /// <summary> /// .NET regular expression string. May be <B>null</B> if <see cref="regex"/> is already set. /// </summary> private string dotNetMatchExpression; /// <summary> /// Returns .NET replacement string. /// </summary> public string DotNetReplaceExpression { get { return dotNetReplaceExpression; } } private string dotNetReplaceExpression; /// <summary> /// <see cref="RegexOptions"/> which should be set while matching the expression. May be <B>null</B> /// if <see cref="regex"/> is already set. /// </summary> public RegexOptions DotNetOptions { get { return dotNetOptions; } } private RegexOptions dotNetOptions; public PerlRegexOptions PerlOptions { get { return perlOptions; } } private PerlRegexOptions perlOptions = PerlRegexOptions.None; public Encoding/*!*/ Encoding { get { return encoding; } } private readonly Encoding/*!*/ encoding; #endregion /// <summary> /// Creates new <see cref="PerlRegExpConverter"/> and converts Perl regular expression to .NET. /// </summary> /// <param name="pattern">Perl regular expression to convert.</param> /// <param name="replacement">Perl replacement string to convert or a <B>null</B> reference for match only.</param> /// <param name="encoding">Encoding used in the case the pattern is a binary string.</param> public PerlRegExpConverter(string pattern, string replacement, Encoding/*!*/ encoding) { if (encoding == null) throw new ArgumentNullException("encoding"); this.encoding = encoding; ConvertPattern(pattern); if (replacement != null) dotNetReplaceExpression = ConvertReplacement(replacement); } private void ConvertPattern(string pattern) { string string_pattern = null; string_pattern = pattern; LoadPerlRegex(string_pattern); dotNetMatchExpression = ConvertRegex(perlRegEx, perlOptions, encoding); try { // dotNetOptions |= RegexOptions.Compiled; regex = new Regex(dotNetMatchExpression, dotNetOptions); } catch (ArgumentException e) { throw new ArgumentException(ExtractExceptionalMessage(e.Message)); } } /// <summary> /// Extracts the .NET exceptional message from the message stored in an exception. /// The message has format 'parsing "{pattern}" - {message}\r\nParameter name {pattern}' in .NET 1.1. /// </summary> private string ExtractExceptionalMessage(string message) { if (message != null) { message = message.Replace(dotNetMatchExpression, "<pattern>"); int i = message.IndexOf("\r\n"); if (i >= 0) message = message.Substring(0, i); i = message.IndexOf("-"); if (i >= 0) message = message.Substring(i + 2); } return message; } internal string ConvertString(string str, int start, int length) { if ((perlOptions & PerlRegexOptions.UTF8) != 0 /*&& !StringUtils.IsAsciiString(str, start, length)*/) return Encoding.UTF8.GetString(encoding.GetBytes(str.Substring(start, length))); else return str.Substring(start, length); } internal string ConvertBytes(byte[] bytes, int start, int length) { if ((perlOptions & PerlRegexOptions.UTF8) != 0) return Encoding.UTF8.GetString(bytes, start, length); else return encoding.GetString(bytes, start, length); } private void LoadPerlRegex(byte[] pattern) { if (pattern == null) pattern = new byte[0]; int regex_start, regex_end; StringBuilder upattern = new StringBuilder(); upattern.Append(pattern); FindRegexDelimiters(upattern, out regex_start, out regex_end); ParseRegexOptions(upattern, regex_end + 2, out dotNetOptions, out perlOptions); perlRegEx = ConvertBytes(pattern, regex_start, regex_end - regex_start + 1); } private void LoadPerlRegex(string pattern) { if (pattern == null) pattern = ""; int regex_start, regex_end; StringBuilder upattern = new StringBuilder(); upattern.Append(pattern); FindRegexDelimiters(upattern, out regex_start, out regex_end); ParseRegexOptions(upattern, regex_end + 2, out dotNetOptions, out perlOptions); perlRegEx = ConvertString(pattern, regex_start, regex_end - regex_start + 1); } private void FindRegexDelimiters(StringBuilder pattern, out int start, out int end) { int i = 0; while (i < pattern.Length && Char.IsWhiteSpace(pattern[i])) i++; if (i == pattern.Length) throw new ArgumentException("RegExp empty"); char start_delimiter = pattern[i++]; if (Char.IsLetterOrDigit(start_delimiter) || start_delimiter == '\\') throw new ArgumentException("Something bad with delimiter"); start = i; char end_delimiter; if (start_delimiter == '[') end_delimiter = ']'; else if (start_delimiter == '(') end_delimiter = ')'; else if (start_delimiter == '{') end_delimiter = '}'; else if (start_delimiter == '<') end_delimiter = '>'; else end_delimiter = start_delimiter; int depth = 1; while (i < pattern.Length) { if (pattern[i] == '\\' && i + 1 < pattern.Length) { i += 2; continue; } else if (pattern[i] == end_delimiter) // (1) should precede (2) to handle end_delim == start_delim case { depth--; if (depth == 0) break; } else if (pattern[i] == start_delimiter) // (2) { depth++; } i++; } if (i == pattern.Length) throw new ArgumentException("No end delimiter"); end = i - 1; } private static void ParseRegexOptions(StringBuilder pattern, int start, out RegexOptions dotNetOptions, out PerlRegexOptions extraOptions) { dotNetOptions = RegexOptions.None; extraOptions = PerlRegexOptions.None; for (int i = start; i < pattern.Length; i++) { char option = pattern[i]; switch (option) { case 'i': // PCRE_CASELESS dotNetOptions |= RegexOptions.IgnoreCase; break; case 'm': // PCRE_MULTILINE dotNetOptions |= RegexOptions.Multiline; break; case 's': // PCRE_DOTALL dotNetOptions |= RegexOptions.Singleline; break; case 'x': // PCRE_EXTENDED dotNetOptions |= RegexOptions.IgnorePatternWhitespace; break; case 'e': // evaluate as PHP code extraOptions |= PerlRegexOptions.Evaluate; break; case 'A': // PCRE_ANCHORED extraOptions |= PerlRegexOptions.Anchored; break; case 'D': // PCRE_DOLLAR_ENDONLY extraOptions |= PerlRegexOptions.DollarMatchesEndOfStringOnly; break; case 'S': // spend more time studythe pattern - ignore break; case 'U': // PCRE_UNGREEDY extraOptions |= PerlRegexOptions.Ungreedy; break; case 'u': // PCRE_UTF8 extraOptions |= PerlRegexOptions.UTF8; break; /* case 'X': // PCRE_EXTRA throw new Exception("Modifier not supported"); default: throw new Exception("Modifier unknown"); */ } } // inconsistent options check: if ( (dotNetOptions & RegexOptions.Multiline) != 0 && (extraOptions & PerlRegexOptions.DollarMatchesEndOfStringOnly) != 0 ) { throw new Exception("Modifier inconsistent"); } } private static int AlphaNumericToDigit(char x) { switch (x) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'A': return 10; case 'B': return 11; case 'C': return 12; case 'D': return 13; case 'E': return 14; case 'F': return 15; } return 17; } /// <summary> /// Parses escaped sequences: "\[xX][0-9A-Fa-f]{2}", "\[xX]\{[0-9A-Fa-f]{0,4}\}", "\[0-7]{3}", /// "\[pP]{Unicode Category}" /// </summary> private static bool ParseEscapeCode(Encoding/*!*/ encoding, string/*!*/ str, ref int pos, ref char ch, ref bool escaped) { //Debug.Assert(encoding != null && str != null && pos >= 0 && pos < str.Length && str[pos] == '\\'); if (pos + 3 >= str.Length) return false; int number = 0; if (str[pos + 1] == 'x') { if (str[pos + 2] == '{') { // hexadecimal number encoding a Unicode character: int i = pos + 3; while (i < str.Length && str[i] != '}' && number < Char.MaxValue) { int digit = AlphaNumericToDigit(str[i]); if (digit > 16) return false; number = (number << 4) + digit; i++; } if (number > Char.MaxValue || i >= str.Length) return false; pos = i; ch = (char)number; escaped = IsCharRegexSpecial(ch); } else { // hexadecimal number encoding single-byte character: for (int i = pos + 2; i < pos + 4; i++) { //Debug.Assert(i < str.Length); int digit = AlphaNumericToDigit(str[i]); if (digit > 16) return false; number = (number << 4) + digit; } pos += 3; char[] chars = encoding.GetChars(new byte[] { (byte)number }); if (chars.Length == 1) ch = chars[0]; else ch = (char)number; escaped = IsCharRegexSpecial(ch); } return true; } else if (str[pos + 1] >= '0' && str[pos + 1] <= '7') { // octal number: for (int i = pos + 1; i < pos + 4; i++) { //Debug.Assert(i < str.Length); int digit = AlphaNumericToDigit(str[i]); if (digit > 8) return false; number = (number << 3) + digit; } pos += 3; ch = encoding.GetChars(new byte[] { (byte)number })[0]; escaped = IsCharRegexSpecial(ch); return true; } else if (str[pos + 1] == 'p' || str[pos + 1] == 'P') { bool complement = str[pos + 1] == 'P'; int cat_start; if (str[pos + 2] == '{') { if (!complement && str[pos + 3] == '^') { complement = true; cat_start = pos + 4; } else cat_start = pos + 3; } else { cat_start = pos + 2; } //UnicodeCategoryGroup group; //UnicodeCategory category; //int cat_length = StringUtils.ParseUnicodeDesignation(str, cat_start, out group, out category); int cat_length = str.Length; int cat_end = cat_start + cat_length - 1; // unknown category: //if (cat_length == 0) return false; // check closing brace: if (str[pos + 2] == '{' && (cat_end + 1 >= str.Length || str[cat_end + 1] != '}')) return false; // TODO: custom categories on .NET 2? // Unicode category: // ?? if (complement) pos = pos; return false; } else if (str[pos + 1] == 'X') { return false; } return false; } /// <summary> /// Characters that must be encoded in .NET regexp /// </summary> static char[] encodeChars = new char[] { '.', '$', '(', ')', '*', '+', '?', '[', ']', '{', '}', '\\', '^', '|' }; /// <summary> /// Returns true if character needs to be escaped in .NET regex /// </summary> private static bool IsCharRegexSpecial(char ch) { return Array.IndexOf(encodeChars, ch) != -1; } /// <summary> /// Converts Perl match expression (only, without delimiters, options etc.) to .NET regular expression. /// </summary> /// <param name="perlExpr">Perl regular expression to convert.</param> /// <param name="opt">Regexp options - some of them must be processed by changes in match string.</param> /// <param name="encoding">Encoding.</param> /// <returns>Resulting .NET regular expression.</returns> private static string ConvertRegex(string perlExpr, PerlRegexOptions opt, Encoding/*!*/ encoding) { // Ranges in bracket expressions should be replaced with appropriate characters // assume no conversion will be performed, create string builder with exact length. Only in // case there is a range StringBuilder would be prolonged, +1 for Anchored StringBuilder result = new StringBuilder(perlExpr.Length + 1); // Anchored means that the string should match only at the start of the string, add '^' // at the beginning if there is no one if ((opt & PerlRegexOptions.Anchored) != 0 && (perlExpr.Length == 0 || perlExpr[0] != '^')) result.Append('^'); // set to true after a quantifier is matched, if there is second quantifier just behind the // first it is an error bool last_quantifier = false; // 4 means we're switching from 3 back to 2 - ie. "a-b-c" // (we need to make a difference here because second "-" shouldn't be expanded) bool leaving_range = false; bool escaped = false; int state = 0; int group_state = 0; int i = 0; while (i < perlExpr.Length) { char ch = perlExpr[i]; escaped = false; if (ch == '\\' && !ParseEscapeCode(encoding, perlExpr, ref i, ref ch, ref escaped)) { i++; //Debug.Assert(i < perlExpr.Length, "Regex cannot end with backslash."); ch = perlExpr[i]; // some characters (like '_') don't need to be escaped in .net if (ch == '_') escaped = false; else escaped = true; } switch (state) { case 0: // outside of character class if (escaped) { result.Append('\\'); result.Append(ch); last_quantifier = false; break; } // In perl regexps, named groups are written like this: "(?P<name> ... )" // If the group is starting here, we need to skip the 'P' character (see state 4) switch (group_state) { case 0: group_state = (ch == '(') ? 1 : 0; break; case 1: group_state = (ch == '?') ? 2 : 0; break; case 2: if (ch == 'P') { i++; continue; } break; } if ((opt & PerlRegexOptions.Ungreedy) != 0) { // match quantifier ?,*,+,{n,m} at the position i: Match m = quantifiers.Match(perlExpr, i); // quantifier matched; quentifier '?' hasn't to be preceded by '(' - a grouping construct '(?' if (m.Success && (m.Value != "?" || i == 0 || perlExpr[i - 1] != '(')) { // two quantifiers: if (last_quantifier) throw new ArgumentException("regexp_duplicate_quantifier"); // append quantifier: result.Append(perlExpr, i, m.Length); i += m.Length; if (i < perlExpr.Length && perlExpr[i] == '?') { // skip question mark to make the quantifier greedy: i++; } else if (i < perlExpr.Length && perlExpr[i] == '+') { // TODO: we do not yet support possesive quantifiers // so we just skip the attribute it and pray // nobody will ever realize :-) i++; } else { // add question mark to make the quantifier lazy: if (result.Length != 0 && result[result.Length - 1] == '?') { // HACK: Due to the issue in .NET regex we can't use "??" because it isn't interpreted correctly!! // (for example "^(ab)??$" matches with "abab", but it shouldn't!!) } else result.Append('?'); } last_quantifier = true; continue; } } last_quantifier = false; if (ch == '$' && (opt & PerlRegexOptions.DollarMatchesEndOfStringOnly) != 0) { // replaces '$' with '\z': result.Append(@"\z"); break; } if (ch == '[') state = 1; result.Append(ch); break; case 1: // first character of character class if (escaped) { result.Append('\\'); result.Append(ch); state = 2; break; } // special characters: if (ch == '^' || ch == ']' || ch == '-') { result.Append(ch); } else { // other characters are not consumed here, for example [[:space:]abc] will not match if the first // [ is appended here. state = 2; goto case 2; } break; case 2: // inside of character class if (escaped) { result.Append('\\'); result.Append(ch); leaving_range = false; break; } if (ch == '-' && !leaving_range) { state = 3; break; } leaving_range = false; // posix character classes Match match = posixCharClasses.Match(perlExpr.Substring(i), 0); if (match.Success) { string chars = CountCharacterClass(match.Groups[2].Value); if (chars == null) throw new ArgumentException(/*TODO*/ String.Format("Unknown character class '{0}'", match.Groups[2].Value)); if (match.Groups[1].Value.Length > 0) throw new ArgumentException(/*TODO*/ "POSIX character classes negation not supported."); result.Append(chars); i += match.Length - 1; // +1 is added just behind the switch break; } if (ch == ']') state = 0; if (ch == '-') result.Append("\\x2d"); else result.Append(ch); break; case 3: // range previous character was '-' if (!escaped && ch == ']') { result.Append("-]"); state = 0; break; } string range; int error; if (!CountRange(result[result.Length - 1], ch, out range, out error, encoding)) { if ((error != 1) || (!CountUnicodeRange(result[result.Length - 1], ch, out range))) { //Debug.Assert(error == 2); throw new ArgumentException("range_first_character_greater"); } } result.Append(EscapeBracketExpressionSpecialChars(range)); // left boundary is duplicated, but doesn't matter... state = 2; leaving_range = true; break; } i++; } return result.ToString(); } /// <summary> /// Escapes characters that have special meaning in bracket expression to make them ordinary characters. /// </summary> /// <param name="chars">String possibly containing characters with special meaning.</param> /// <returns>String with escaped characters.</returns> internal static string EscapeBracketExpressionSpecialChars(string chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars.Length; i++) { char ch = chars[i]; switch (ch) { // case '^': // not necessary, not at the beginning have no special meaning case '\\': case ']': case '-': sb.Append('\\'); goto default; default: sb.Append(ch); break; } } return sb.ToString(); } /// <summary> /// Takes endpoints of a range and returns string containing appropriate characters. /// </summary> /// <param name="firstCharacter">First endpoint of a range.</param> /// <param name="secondCharacter">Second endpoint of a range.</param> /// <param name="characters">String containing all characters that are to be in the range.</param> /// <param name="result">Integer specifying an error. Value 1 means characters specified cannot /// be expressed in current encoding, value of 2 first character is greater than second.</param> /// <returns><B>True</B> if range was succesfuly counted, <B>false</B> otherwise.</returns> internal static bool CountRange(char firstCharacter, char secondCharacter, out string characters, out int result, Encoding encoding) { // initialize out parameters characters = null; result = 0; char[] chars = new char[2]; chars[0] = firstCharacter; chars[1] = secondCharacter; byte[] two_bytes = new byte[encoding.GetMaxByteCount(2)]; // convert endpoints and test if characters are "normal" - they can be stored in one byte if (encoding.GetBytes(chars, 0, 2, two_bytes, 0) != 2) { result = 1; return false; } if (two_bytes[0] > two_bytes[1]) { result = 2; return false; } // array for bytes that will be converted to unicode string byte[] bytes = new byte[two_bytes[1] - two_bytes[0] + 1]; int i = 0; for (int ch = two_bytes[0]; ch <= two_bytes[1]; i++, ch++) { // casting to byte is OK, ch is always in byte range thanks to ch <= two_bytes[1] condition bytes[i] = (byte)ch; } characters = encoding.GetString(bytes, 0, i); return true; } /// <summary> /// Takes character class name and returns string containing appropriate characters. /// Returns <B>null</B> if has got unknown character class name. /// </summary> /// <param name="chClassName">Character class name.</param> /// <returns>String containing characters from character class.</returns> internal static string CountCharacterClass(string chClassName) { string ret = null; switch (chClassName) { case "alnum": ret = @"\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}"; break; case "digit": ret = @"\p{Nd}"; break; case "punct": ret = @"\p{P}\p{S}"; break; case "alpha": ret = @"\p{Ll}\p{Lu}\p{Lt}\p{Lo}"; break; case "graph": ret = @"\p{L}\p{M}\p{N}\p{P}\p{S}"; break; case "space": ret = @"\s"; break; case "blank": ret = @" \t"; break; case "lower": ret = @"\p{Ll}"; break; case "upper": ret = @"\p{Lu}"; break; case "cntrl": ret = @"\p{Cc}"; break; case "print": ret = @"\p{L}\p{M}\p{N}\p{P}\p{S}\p{Zs}"; break; case "xdigit": ret = @"abcdefABCDEF\d"; break; case "ascii": ret = @"\u0000-\u007F"; break; case "word": ret = @"_\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}"; break; } return ret; } /// <summary> /// Simple version of 'PosixRegExp.BracketExpression.CountRange' function. Generates string /// with all characters in specified range, but uses unicode encoding. /// </summary> /// <param name="f">Lower bound</param> /// <param name="t">Upper bound</param> /// <param name="range">Returned string</param> /// <returns>Returns false if lower bound is larger than upper bound</returns> private static bool CountUnicodeRange(char f, char t, out string range) { range = ""; if (f > t) return false; StringBuilder sb = new StringBuilder(t - f); for (char c = f; c <= t; c++) sb.Append(c); range = sb.ToString(); return true; } /// <summary> /// Modifies regular expression so it matches only at the beginning of the string. /// </summary> /// <param name="expr">Regular expression to modify.</param> private static void ModifyRegExpAnchored(ref string expr) { // anchored means regular expression should match only at the beginning of the string // => add ^ at the beginning if there is no one. if (expr.Length == 0 || expr[0] != '^') expr.Insert(0, "^"); } internal static bool IsDigitGroupReference(string replacement, int i) { return (replacement[i] == '$' || replacement[i] == '\\') && (i + 1 < replacement.Length && Char.IsDigit(replacement, i + 1)); } internal static bool IsParenthesizedGroupReference(string replacement, int i) { return replacement[i] == '$' && i + 3 < replacement.Length && replacement[i + 1] == '{' && Char.IsDigit(replacement, i + 2) && ( replacement[i + 3] == '}' || i + 4 < replacement.Length && replacement[i + 4] == '}' && Char.IsDigit(replacement, i + 3) ); } /// <summary> /// Converts substitutions of the form \\xx to $xx (perl to .NET format). /// </summary> /// <param name="replacement">String possibly containing \\xx substitutions.</param> /// <returns>String with converted $xx substitution format.</returns> private string ConvertReplacement(string replacement) { StringBuilder result = new StringBuilder(); int[] group_numbers = regex.GetGroupNumbers(); int max_number = (group_numbers.Length > 0) ? group_numbers[group_numbers.Length - 1] : 0; int i = 0; while (i < replacement.Length) { if (IsDigitGroupReference(replacement, i) || IsParenthesizedGroupReference(replacement, i)) { int add = 0; i++; if (replacement[i] == '{') { i++; add = 1; } int number = replacement[i++] - '0'; if (i < replacement.Length && Char.IsDigit(replacement, i)) { number = number * 10 + replacement[i]; i++; } // insert only existing group references (others replaced with empty string): if (number <= max_number) { result.Append('$'); result.Append('{'); result.Append(number.ToString()); result.Append('}'); } i += add; } else if (replacement[i] == '$') { // there is $ and it is not a substitution - duplicate it: result.Append("$$"); i++; } else if (replacement[i] == '\\' && i + 1 < replacement.Length) { if (replacement[i + 1] == '\\') { // two backslashes, replace with one: result.Append('\\'); i += 2; } else { // backslash + some character, skip two characters result.Append(replacement, i, 2); i += 2; } } else { // no substitution, no backslash (or backslash at the end of string) result.Append(replacement, i++, 1); } } return result.ToString(); } } #endregion }
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceDefinitions.Serialization { public sealed class ResourceDefinitionSerializationTests : IClassFixture<IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext>> { private readonly IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext> _testContext; private readonly SerializationFakers _fakers = new(); public ResourceDefinitionSerializationTests(IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext> testContext) { _testContext = testContext; testContext.UseController<StudentsController>(); testContext.UseController<ScholarshipsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceDefinition<StudentDefinition>(); services.AddSingleton<IEncryptionService, AesEncryptionService>(); services.AddSingleton<ResourceDefinitionHitCounter>(); services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>)); }); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); hitCounter.Reset(); } [Fact] public async Task Encrypts_on_get_primary_resources() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); List<Student> students = _fakers.Student.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Student>(); dbContext.Students.AddRange(students); await dbContext.SaveChangesAsync(); }); const string route = "/students"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); string socialSecurityNumber1 = encryptionService.Decrypt((string)responseDocument.Data.ManyValue[0].Attributes["socialSecurityNumber"]); socialSecurityNumber1.Should().Be(students[0].SocialSecurityNumber); string socialSecurityNumber2 = encryptionService.Decrypt((string)responseDocument.Data.ManyValue[1].Attributes["socialSecurityNumber"]); socialSecurityNumber2.Should().Be(students[1].SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Encrypts_on_get_primary_resources_with_ToMany_include() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); List<Scholarship> scholarships = _fakers.Scholarship.Generate(2); scholarships[0].Participants = _fakers.Student.Generate(2); scholarships[1].Participants = _fakers.Student.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Scholarship>(); dbContext.Scholarships.AddRange(scholarships); await dbContext.SaveChangesAsync(); }); const string route = "/scholarships?include=participants"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Included.Should().HaveCount(4); string socialSecurityNumber1 = encryptionService.Decrypt((string)responseDocument.Included[0].Attributes["socialSecurityNumber"]); socialSecurityNumber1.Should().Be(scholarships[0].Participants[0].SocialSecurityNumber); string socialSecurityNumber2 = encryptionService.Decrypt((string)responseDocument.Included[1].Attributes["socialSecurityNumber"]); socialSecurityNumber2.Should().Be(scholarships[0].Participants[1].SocialSecurityNumber); string socialSecurityNumber3 = encryptionService.Decrypt((string)responseDocument.Included[2].Attributes["socialSecurityNumber"]); socialSecurityNumber3.Should().Be(scholarships[1].Participants[0].SocialSecurityNumber); string socialSecurityNumber4 = encryptionService.Decrypt((string)responseDocument.Included[3].Attributes["socialSecurityNumber"]); socialSecurityNumber4.Should().Be(scholarships[1].Participants[1].SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Encrypts_on_get_primary_resource_by_ID() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Student student = _fakers.Student.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Students.Add(student); await dbContext.SaveChangesAsync(); }); string route = $"/students/{student.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); string socialSecurityNumber = encryptionService.Decrypt((string)responseDocument.Data.SingleValue.Attributes["socialSecurityNumber"]); socialSecurityNumber.Should().Be(student.SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Encrypts_on_get_secondary_resources() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship scholarship = _fakers.Scholarship.Generate(); scholarship.Participants = _fakers.Student.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(scholarship); await dbContext.SaveChangesAsync(); }); string route = $"/scholarships/{scholarship.StringId}/participants"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); string socialSecurityNumber1 = encryptionService.Decrypt((string)responseDocument.Data.ManyValue[0].Attributes["socialSecurityNumber"]); socialSecurityNumber1.Should().Be(scholarship.Participants[0].SocialSecurityNumber); string socialSecurityNumber2 = encryptionService.Decrypt((string)responseDocument.Data.ManyValue[1].Attributes["socialSecurityNumber"]); socialSecurityNumber2.Should().Be(scholarship.Participants[1].SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Encrypts_on_get_secondary_resource() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship scholarship = _fakers.Scholarship.Generate(); scholarship.PrimaryContact = _fakers.Student.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(scholarship); await dbContext.SaveChangesAsync(); }); string route = $"/scholarships/{scholarship.StringId}/primaryContact"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); string socialSecurityNumber = encryptionService.Decrypt((string)responseDocument.Data.SingleValue.Attributes["socialSecurityNumber"]); socialSecurityNumber.Should().Be(scholarship.PrimaryContact.SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Encrypts_on_get_secondary_resource_with_ToOne_include() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship scholarship = _fakers.Scholarship.Generate(); scholarship.PrimaryContact = _fakers.Student.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(scholarship); await dbContext.SaveChangesAsync(); }); string route = $"/scholarships/{scholarship.StringId}?include=primaryContact"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Included.Should().HaveCount(1); string socialSecurityNumber = encryptionService.Decrypt((string)responseDocument.Included[0].Attributes["socialSecurityNumber"]); socialSecurityNumber.Should().Be(scholarship.PrimaryContact.SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Decrypts_on_create_resource() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); string newName = _fakers.Student.Generate().Name; string newSocialSecurityNumber = _fakers.Student.Generate().SocialSecurityNumber; var requestBody = new { data = new { type = "students", attributes = new { name = newName, socialSecurityNumber = encryptionService.Encrypt(newSocialSecurityNumber) } } }; const string route = "/students"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); string socialSecurityNumber = encryptionService.Decrypt((string)responseDocument.Data.SingleValue.Attributes["socialSecurityNumber"]); socialSecurityNumber.Should().Be(newSocialSecurityNumber); int newStudentId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { Student studentInDatabase = await dbContext.Students.FirstWithIdAsync(newStudentId); studentInDatabase.SocialSecurityNumber.Should().Be(newSocialSecurityNumber); }); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnDeserialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Encrypts_on_create_resource_with_included_ToOne_relationship() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Student existingStudent = _fakers.Student.Generate(); string newProgramName = _fakers.Scholarship.Generate().ProgramName; decimal newAmount = _fakers.Scholarship.Generate().Amount; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Students.Add(existingStudent); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "scholarships", attributes = new { programName = newProgramName, amount = newAmount }, relationships = new { primaryContact = new { data = new { type = "students", id = existingStudent.StringId } } } } }; const string route = "/scholarships?include=primaryContact"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Included.Should().HaveCount(1); string socialSecurityNumber = encryptionService.Decrypt((string)responseDocument.Included[0].Attributes["socialSecurityNumber"]); socialSecurityNumber.Should().Be(existingStudent.SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Decrypts_on_update_resource() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Student existingStudent = _fakers.Student.Generate(); string newSocialSecurityNumber = _fakers.Student.Generate().SocialSecurityNumber; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Students.Add(existingStudent); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "students", id = existingStudent.StringId, attributes = new { socialSecurityNumber = encryptionService.Encrypt(newSocialSecurityNumber) } } }; string route = $"/students/{existingStudent.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); string socialSecurityNumber = encryptionService.Decrypt((string)responseDocument.Data.SingleValue.Attributes["socialSecurityNumber"]); socialSecurityNumber.Should().Be(newSocialSecurityNumber); await _testContext.RunOnDatabaseAsync(async dbContext => { Student studentInDatabase = await dbContext.Students.FirstWithIdAsync(existingStudent.Id); studentInDatabase.SocialSecurityNumber.Should().Be(newSocialSecurityNumber); }); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnDeserialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Encrypts_on_update_resource_with_included_ToMany_relationship() { // Arrange var encryptionService = _testContext.Factory.Services.GetRequiredService<IEncryptionService>(); var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship existingScholarship = _fakers.Scholarship.Generate(); existingScholarship.Participants = _fakers.Student.Generate(3); decimal newAmount = _fakers.Scholarship.Generate().Amount; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(existingScholarship); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "scholarships", id = existingScholarship.StringId, attributes = new { amount = newAmount }, relationships = new { participants = new { data = new[] { new { type = "students", id = existingScholarship.Participants[0].StringId }, new { type = "students", id = existingScholarship.Participants[2].StringId } } } } } }; string route = $"/scholarships/{existingScholarship.StringId}?include=participants"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Included.Should().HaveCount(2); string socialSecurityNumber1 = encryptionService.Decrypt((string)responseDocument.Included[0].Attributes["socialSecurityNumber"]); socialSecurityNumber1.Should().Be(existingScholarship.Participants[0].SocialSecurityNumber); string socialSecurityNumber2 = encryptionService.Decrypt((string)responseDocument.Included[1].Attributes["socialSecurityNumber"]); socialSecurityNumber2.Should().Be(existingScholarship.Participants[2].SocialSecurityNumber); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize), (typeof(Student), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSerialize) }, options => options.WithStrictOrdering()); } [Fact] public async Task Skips_on_get_ToOne_relationship() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship scholarship = _fakers.Scholarship.Generate(); scholarship.PrimaryContact = _fakers.Student.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(scholarship); await dbContext.SaveChangesAsync(); }); string route = $"/scholarships/{scholarship.StringId}/relationships/primaryContact"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(scholarship.PrimaryContact.StringId); hitCounter.HitExtensibilityPoints.Should().BeEmpty(); } [Fact] public async Task Skips_on_get_ToMany_relationship() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship scholarship = _fakers.Scholarship.Generate(); scholarship.Participants = _fakers.Student.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(scholarship); await dbContext.SaveChangesAsync(); }); string route = $"/scholarships/{scholarship.StringId}/relationships/participants"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(scholarship.Participants[0].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(scholarship.Participants[1].StringId); hitCounter.HitExtensibilityPoints.Should().BeEmpty(); } [Fact] public async Task Skips_on_update_ToOne_relationship() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship existingScholarship = _fakers.Scholarship.Generate(); Student existingStudent = _fakers.Student.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingScholarship, existingStudent); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "students", id = existingStudent.StringId } }; string route = $"/scholarships/{existingScholarship.StringId}/relationships/primaryContact"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEmpty(); } [Fact] public async Task Skips_on_set_ToMany_relationship() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship existingScholarship = _fakers.Scholarship.Generate(); List<Student> existingStudents = _fakers.Student.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(existingScholarship); dbContext.Students.AddRange(existingStudents); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "students", id = existingStudents[0].StringId }, new { type = "students", id = existingStudents[1].StringId } } }; string route = $"/scholarships/{existingScholarship.StringId}/relationships/participants"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEmpty(); } [Fact] public async Task Skips_on_add_to_ToMany_relationship() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship existingScholarship = _fakers.Scholarship.Generate(); List<Student> existingStudents = _fakers.Student.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(existingScholarship); dbContext.Students.AddRange(existingStudents); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "students", id = existingStudents[0].StringId }, new { type = "students", id = existingStudents[1].StringId } } }; string route = $"/scholarships/{existingScholarship.StringId}/relationships/participants"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEmpty(); } [Fact] public async Task Skips_on_remove_from_ToMany_relationship() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); Scholarship existingScholarship = _fakers.Scholarship.Generate(); existingScholarship.Participants = _fakers.Student.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Scholarships.Add(existingScholarship); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "students", id = existingScholarship.Participants[0].StringId }, new { type = "students", id = existingScholarship.Participants[1].StringId } } }; string route = $"/scholarships/{existingScholarship.StringId}/relationships/participants"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEmpty(); } } }
// **************************************************************** // Copyright 2007, 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 NUnit.Framework; namespace NUnit.TestData.FixtureSetUpTearDown { [TestFixture] public class SetUpAndTearDownFixture { public int setUpCount = 0; public int tearDownCount = 0; [TestFixtureSetUp] public virtual void Init() { setUpCount++; } [TestFixtureTearDown] public virtual void Destroy() { tearDownCount++; } [Test] public void Success() { } [Test] public void EvenMoreSuccess() { } } [TestFixture, Explicit] public class ExplicitSetUpAndTearDownFixture { public int setUpCount = 0; public int tearDownCount = 0; [TestFixtureSetUp] public virtual void Init() { setUpCount++; } [TestFixtureTearDown] public virtual void Destroy() { tearDownCount++; } [Test] public void Success(){} [Test] public void EvenMoreSuccess(){} } [TestFixture] public class InheritSetUpAndTearDown : SetUpAndTearDownFixture { [Test] public void AnotherTest(){} [Test] public void YetAnotherTest(){} } [TestFixture] public class DefineInheritSetUpAndTearDown : SetUpAndTearDownFixture { public int derivedSetUpCount; public int derivedTearDownCount; [TestFixtureSetUp] public override void Init() { derivedSetUpCount++; } [TestFixtureTearDown] public override void Destroy() { derivedTearDownCount++; } [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class DerivedSetUpAndTearDownFixture : SetUpAndTearDownFixture { public int derivedSetUpCount; public int derivedTearDownCount; public bool baseSetUpCalledFirst; public bool baseTearDownCalledLast; [TestFixtureSetUp] public void Init2() { derivedSetUpCount++; baseSetUpCalledFirst = this.setUpCount > 0; } [TestFixtureTearDown] public void Destroy2() { derivedTearDownCount++; baseTearDownCalledLast = this.tearDownCount == 0; } [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class StaticSetUpAndTearDownFixture { public static int setUpCount = 0; public static int tearDownCount = 0; [TestFixtureSetUp] public static void Init() { setUpCount++; } [TestFixtureTearDown] public static void Destroy() { tearDownCount++; } } [TestFixture] public class DerivedStaticSetUpAndTearDownFixture : StaticSetUpAndTearDownFixture { public static int derivedSetUpCount; public static int derivedTearDownCount; public static bool baseSetUpCalledFirst; public static bool baseTearDownCalledLast; [TestFixtureSetUp] public static void Init2() { derivedSetUpCount++; baseSetUpCalledFirst = setUpCount > 0; } [TestFixtureTearDown] public static void Destroy2() { derivedTearDownCount++; baseTearDownCalledLast = tearDownCount == 0; } } #if NET_2_0 [TestFixture] public static class StaticClassSetUpAndTearDownFixture { public static int setUpCount = 0; public static int tearDownCount = 0; [TestFixtureSetUp] public static void Init() { setUpCount++; } [TestFixtureTearDown] public static void Destroy() { tearDownCount++; } } #endif [TestFixture] public class MisbehavingFixture { public bool blowUpInSetUp = false; public bool blowUpInTearDown = false; public int setUpCount = 0; public int tearDownCount = 0; public void Reinitialize() { setUpCount = 0; tearDownCount = 0; blowUpInSetUp = false; blowUpInTearDown = false; } [TestFixtureSetUp] public void BlowUpInSetUp() { setUpCount++; if (blowUpInSetUp) throw new Exception("This was thrown from fixture setup"); } [TestFixtureTearDown] public void BlowUpInTearDown() { tearDownCount++; if ( blowUpInTearDown ) throw new Exception("This was thrown from fixture teardown"); } [Test] public void nothingToTest() { } } [TestFixture] public class ExceptionInConstructor { public ExceptionInConstructor() { throw new Exception( "This was thrown in constructor" ); } [Test] public void nothingToTest() { } } [TestFixture] public class IgnoreInFixtureSetUp { [TestFixtureSetUp] public void SetUpCallsIgnore() { Assert.Ignore( "TestFixtureSetUp called Ignore" ); } [Test] public void nothingToTest() { } } [TestFixture] public class SetUpAndTearDownWithTestInName { public int setUpCount = 0; public int tearDownCount = 0; [TestFixtureSetUp] public virtual void TestFixtureSetUp() { setUpCount++; } [TestFixtureTearDown] public virtual void TestFixtureTearDown() { tearDownCount++; } [Test] public void Success(){} [Test] public void EvenMoreSuccess(){} } [TestFixture, Ignore( "Do Not Run This" )] public class IgnoredFixture { public bool setupCalled = false; public bool teardownCalled = false; [TestFixtureSetUp] public virtual void ShouldNotRun() { setupCalled = true; } [TestFixtureTearDown] public virtual void NeitherShouldThis() { teardownCalled = true; } [Test] public void Success(){} [Test] public void EvenMoreSuccess(){} } [TestFixture] public class FixtureWithNoTests { public bool setupCalled = false; public bool teardownCalled = false; [TestFixtureSetUp] public virtual void Init() { setupCalled = true; } [TestFixtureTearDown] public virtual void Destroy() { teardownCalled = true; } } [TestFixture] public class DisposableFixture : IDisposable { public bool disposeCalled = false; [Test] public void OneTest() { } public void Dispose() { disposeCalled = true; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using StorageBlob = Microsoft.WindowsAzure.Storage.Blob; using StorageType = Microsoft.WindowsAzure.Storage.Blob.BlobType; namespace Management.Storage.ScenarioTest.Util { public class CloudBlobUtil { private CloudStorageAccount account; private CloudBlobClient client; private Random random; private const int PageBlobUnitSize = 512; private static List<string> HttpsCopyHosts; public string ContainerName { get; private set; } public string BlobName { get; private set; } public ICloudBlob Blob { get; private set; } public CloudBlobContainer Container { get; private set; } private CloudBlobUtil() { } /// <summary> /// init cloud blob util /// </summary> /// <param name="account">storage account</param> public CloudBlobUtil(CloudStorageAccount account) { this.account = account; client = account.CreateCloudBlobClient(); random = new Random(); } /// <summary> /// Create a random container with a random blob /// </summary> public void SetupTestContainerAndBlob() { ContainerName = Utility.GenNameString("container"); BlobName = Utility.GenNameString("blob"); CloudBlobContainer container = CreateContainer(ContainerName); Blob = CreateRandomBlob(container, BlobName); Container = container; } /// <summary> /// clean test container and blob /// </summary> public void CleanupTestContainerAndBlob() { if (String.IsNullOrEmpty(ContainerName)) { return; } RemoveContainer(ContainerName); ContainerName = string.Empty; BlobName = string.Empty; Blob = null; Container = null; } /// <summary> /// create a container with random properties and metadata /// </summary> /// <param name="containerName">container name</param> /// <returns>the created container object with properties and metadata</returns> public CloudBlobContainer CreateContainer(string containerName = "") { if (String.IsNullOrEmpty(containerName)) { containerName = Utility.GenNameString("container"); } CloudBlobContainer container = client.GetContainerReference(containerName); container.CreateIfNotExists(); //there is no properties to set container.FetchAttributes(); int minMetaCount = 1; int maxMetaCount = 5; int minMetaValueLength = 10; int maxMetaValueLength = 20; int count = random.Next(minMetaCount, maxMetaCount); for (int i = 0; i < count; i++) { string metaKey = Utility.GenNameString("metatest"); int valueLength = random.Next(minMetaValueLength, maxMetaValueLength); string metaValue = Utility.GenNameString("metavalue-", valueLength); container.Metadata.Add(metaKey, metaValue); } container.SetMetadata(); Test.Info(string.Format("create container '{0}'", containerName)); return container; } public CloudBlobContainer CreateContainer(string containerName, BlobContainerPublicAccessType permission) { CloudBlobContainer container = CreateContainer(containerName); BlobContainerPermissions containerPermission = new BlobContainerPermissions(); containerPermission.PublicAccess = permission; container.SetPermissions(containerPermission); return container; } /// <summary> /// create mutiple containers /// </summary> /// <param name="containerNames">container names list</param> /// <returns>a list of container object</returns> public List<CloudBlobContainer> CreateContainer(List<string> containerNames) { List<CloudBlobContainer> containers = new List<CloudBlobContainer>(); foreach (string name in containerNames) { containers.Add(CreateContainer(name)); } containers = containers.OrderBy(container => container.Name).ToList(); return containers; } /// <summary> /// remove specified container /// </summary> /// <param name="Container">Cloud blob container object</param> public void RemoveContainer(CloudBlobContainer Container) { RemoveContainer(Container.Name); } /// <summary> /// remove specified container /// </summary> /// <param name="containerName">container name</param> public void RemoveContainer(string containerName) { CloudBlobContainer container = client.GetContainerReference(containerName); container.DeleteIfExists(); Test.Info(string.Format("remove container '{0}'", containerName)); } /// <summary> /// remove a list containers /// </summary> /// <param name="containerNames">container names</param> public void RemoveContainer(List<string> containerNames) { foreach (string name in containerNames) { try { RemoveContainer(name); } catch (Exception e) { Test.Warn(string.Format("Can't remove container {0}. Exception: {1}", name, e.Message)); } } } /// <summary> /// create a new page blob with random properties and metadata /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">blob name</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreatePageBlob(CloudBlobContainer container, string blobName) { CloudPageBlob pageBlob = container.GetPageBlobReference(blobName); int size = random.Next(1, 10) * PageBlobUnitSize; pageBlob.Create(size); byte[] buffer = new byte[size]; string md5sum = Convert.ToBase64String(Helper.GetMD5(buffer)); pageBlob.Properties.ContentMD5 = md5sum; GenerateBlobPropertiesAndMetaData(pageBlob); Test.Info(string.Format("create page blob '{0}' in container '{1}'", blobName, container.Name)); return pageBlob; } /// <summary> /// create a block blob with random properties and metadata /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Block blob name</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreateBlockBlob(CloudBlobContainer container, string blobName) { CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName); int maxBlobSize = 1024 * 1024; string md5sum = string.Empty; int blobSize = random.Next(maxBlobSize); byte[] buffer = new byte[blobSize]; using (MemoryStream ms = new MemoryStream(buffer)) { random.NextBytes(buffer); //ms.Read(buffer, 0, buffer.Length); blockBlob.UploadFromStream(ms); md5sum = Convert.ToBase64String(Helper.GetMD5(buffer)); } blockBlob.Properties.ContentMD5 = md5sum; GenerateBlobPropertiesAndMetaData(blockBlob); Test.Info(string.Format("create block blob '{0}' in container '{1}'", blobName, container.Name)); return blockBlob; } /// <summary> /// generate random blob properties and metadata /// </summary> /// <param name="blob">ICloudBlob object</param> private void GenerateBlobPropertiesAndMetaData(ICloudBlob blob) { blob.Properties.ContentEncoding = Utility.GenNameString("encoding"); blob.Properties.ContentLanguage = Utility.GenNameString("lang"); int minMetaCount = 1; int maxMetaCount = 5; int minMetaValueLength = 10; int maxMetaValueLength = 20; int count = random.Next(minMetaCount, maxMetaCount); for (int i = 0; i < count; i++) { string metaKey = Utility.GenNameString("metatest"); int valueLength = random.Next(minMetaValueLength, maxMetaValueLength); string metaValue = Utility.GenNameString("metavalue-", valueLength); blob.Metadata.Add(metaKey, metaValue); } blob.SetProperties(); blob.SetMetadata(); blob.FetchAttributes(); } /// <summary> /// Create a blob with specified blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Blob name</param> /// <param name="type">Blob type</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreateBlob(CloudBlobContainer container, string blobName, StorageBlob.BlobType type) { if (type == StorageBlob.BlobType.BlockBlob) { return CreateBlockBlob(container, blobName); } else { return CreatePageBlob(container, blobName); } } /// <summary> /// create a list of blobs with random properties/metadata/blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">a list of blob names</param> /// <returns>a list of cloud page blobs</returns> public List<ICloudBlob> CreateRandomBlob(CloudBlobContainer container, List<string> blobNames) { List<ICloudBlob> blobs = new List<ICloudBlob>(); foreach (string blobName in blobNames) { blobs.Add(CreateRandomBlob(container, blobName)); } blobs = blobs.OrderBy(blob => blob.Name).ToList(); return blobs; } public List<ICloudBlob> CreateRandomBlob(CloudBlobContainer container) { int count = random.Next(1, 5); List<string> blobNames = new List<string>(); for (int i = 0; i < count; i++) { blobNames.Add(Utility.GenNameString("blob")); } return CreateRandomBlob(container, blobNames); } /// <summary> /// Create a list of blobs with random properties/metadata/blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Blob name</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreateRandomBlob(CloudBlobContainer container, string blobName) { int switchKey = 0; switchKey = random.Next(0, 2); if (switchKey == 0) { return CreatePageBlob(container, blobName); } else { return CreateBlockBlob(container, blobName); } } /// <summary> /// convert blob name into valid file name /// </summary> /// <param name="blobName">blob name</param> /// <returns>valid file name</returns> public string ConvertBlobNameToFileName(string blobName, string dir, DateTimeOffset? snapshotTime = null) { string fileName = blobName; //replace dirctionary Dictionary<string, string> replaceRules = new Dictionary<string, string>() { {"/", "\\"} }; foreach (KeyValuePair<string, string> rule in replaceRules) { fileName = fileName.Replace(rule.Key, rule.Value); } if (snapshotTime != null) { int index = fileName.LastIndexOf('.'); string prefix = string.Empty; string postfix = string.Empty; string timeStamp = string.Format("{0:u}", snapshotTime.Value); timeStamp = timeStamp.Replace(":", string.Empty).TrimEnd(new char[] { 'Z' }); if (index == -1) { prefix = fileName; postfix = string.Empty; } else { prefix = fileName.Substring(0, index); postfix = fileName.Substring(index); } fileName = string.Format("{0} ({1}){2}", prefix, timeStamp, postfix); } return Path.Combine(dir, fileName); } public string ConvertFileNameToBlobName(string fileName) { return fileName.Replace('\\', '/'); } /// <summary> /// list all the existing containers /// </summary> /// <returns>a list of cloudblobcontainer object</returns> public List<CloudBlobContainer> GetExistingContainers() { ContainerListingDetails details = ContainerListingDetails.All; return client.ListContainers(string.Empty, details).ToList(); } /// <summary> /// get the number of existing container /// </summary> /// <returns></returns> public int GetExistingContainerCount() { return GetExistingContainers().Count; } /// <summary> /// Create a snapshot for the specified ICloudBlob object /// </summary> /// <param name="blob">ICloudBlob object</param> public ICloudBlob SnapShot(ICloudBlob blob) { ICloudBlob snapshot = default(ICloudBlob); switch (blob.BlobType) { case StorageBlob.BlobType.BlockBlob: snapshot = ((CloudBlockBlob)blob).CreateSnapshot(); break; case StorageBlob.BlobType.PageBlob: snapshot = ((CloudPageBlob)blob).CreateSnapshot(); break; default: throw new ArgumentException(string.Format("Unsupport blob type {0} when create snapshot", blob.BlobType)); } Test.Info(string.Format("Create snapshot for '{0}' at {1}", blob.Name, snapshot.SnapshotTime)); return snapshot; } public static void PackContainerCompareData(CloudBlobContainer container, Dictionary<string, object> dic) { BlobContainerPermissions permissions = container.GetPermissions(); dic["PublicAccess"] = permissions.PublicAccess; dic["Permission"] = permissions; dic["LastModified"] = container.Properties.LastModified; } public static void PackBlobCompareData(ICloudBlob blob, Dictionary<string, object> dic) { dic["Length"] = blob.Properties.Length; dic["ContentType"] = blob.Properties.ContentType; dic["LastModified"] = blob.Properties.LastModified; dic["SnapshotTime"] = blob.SnapshotTime; } public static string ConvertCopySourceUri(string uri) { if (HttpsCopyHosts == null) { HttpsCopyHosts = new List<string>(); string httpsHosts = Test.Data.Get("HttpsCopyHosts"); string[] hosts = httpsHosts.Split(); foreach (string host in hosts) { if (!String.IsNullOrWhiteSpace(host)) { HttpsCopyHosts.Add(host); } } } //Azure always use https to copy from these hosts such windows.net bool useHttpsCopy = HttpsCopyHosts.Any(host => uri.IndexOf(host) != -1); if (useHttpsCopy) { return uri.Replace("http://", "https://"); } else { return uri; } } public static bool WaitForCopyOperationComplete(ICloudBlob destBlob, int maxRetry = 100) { int retryCount = 0; int sleepInterval = 1000; //ms if (destBlob == null) { return false; } do { if (retryCount > 0) { Test.Info(String.Format("{0}th check current copy state and it's {1}. Wait for copy completion", retryCount, destBlob.CopyState.Status)); } Thread.Sleep(sleepInterval); destBlob.FetchAttributes(); retryCount++; } while (destBlob.CopyState.Status == CopyStatus.Pending && retryCount < maxRetry); Test.Info(String.Format("Final Copy status is {0}", destBlob.CopyState.Status)); return destBlob.CopyState.Status != CopyStatus.Pending; } public static ICloudBlob GetBlob(CloudBlobContainer container, string blobName, StorageType blobType) { ICloudBlob blob = null; if (blobType == StorageType.BlockBlob) { blob = container.GetBlockBlobReference(blobName); } else { blob = container.GetPageBlobReference(blobName); } return blob; } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using DocIdSet = Lucene.Net.Search.DocIdSet; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using InfoStream = Lucene.Net.Util.InfoStream; using IOContext = Lucene.Net.Store.IOContext; using Query = Lucene.Net.Search.Query; using QueryWrapperFilter = Lucene.Net.Search.QueryWrapperFilter; /// <summary> /// Tracks the stream of BufferedDeletes. /// When <see cref="DocumentsWriterPerThread"/> flushes, its buffered /// deletes and updates are appended to this stream. We later /// apply them (resolve them to the actual /// docIDs, per segment) when a merge is started /// (only to the to-be-merged segments). We /// also apply to all segments when NRT reader is pulled, /// commit/close is called, or when too many deletes or updates are /// buffered and must be flushed (by RAM usage or by count). /// <para/> /// Each packet is assigned a generation, and each flushed or /// merged segment is also assigned a generation, so we can /// track which BufferedDeletes packets to apply to any given /// segment. /// </summary> internal class BufferedUpdatesStream { // TODO: maybe linked list? private readonly IList<FrozenBufferedUpdates> updates = new List<FrozenBufferedUpdates>(); // Starts at 1 so that SegmentInfos that have never had // deletes applied (whose bufferedDelGen defaults to 0) // will be correct: private long nextGen = 1; // used only by assert private Term lastDeleteTerm; private readonly InfoStream infoStream; private readonly AtomicInt64 bytesUsed = new AtomicInt64(); private readonly AtomicInt32 numTerms = new AtomicInt32(); public BufferedUpdatesStream(InfoStream infoStream) { this.infoStream = infoStream; } /// <summary> /// Appends a new packet of buffered deletes to the stream, /// setting its generation: /// </summary> public virtual long Push(FrozenBufferedUpdates packet) { lock (this) { /* * The insert operation must be atomic. If we let threads increment the gen * and push the packet afterwards we risk that packets are out of order. * With DWPT this is possible if two or more flushes are racing for pushing * updates. If the pushed packets get our of order would loose documents * since deletes are applied to the wrong segments. */ packet.DelGen = nextGen++; Debug.Assert(packet.Any()); Debug.Assert(CheckDeleteStats()); Debug.Assert(packet.DelGen < nextGen); Debug.Assert(updates.Count == 0 || updates[updates.Count - 1].DelGen < packet.DelGen, "Delete packets must be in order"); updates.Add(packet); numTerms.AddAndGet(packet.numTermDeletes); bytesUsed.AddAndGet(packet.bytesUsed); if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "push deletes " + packet + " delGen=" + packet.DelGen + " packetCount=" + updates.Count + " totBytesUsed=" + bytesUsed.Get()); } Debug.Assert(CheckDeleteStats()); return packet.DelGen; } } public virtual void Clear() { lock (this) { updates.Clear(); nextGen = 1; numTerms.Set(0); bytesUsed.Set(0); } } public virtual bool Any() { return bytesUsed.Get() != 0; } public virtual int NumTerms { get { return numTerms.Get(); } } public virtual long BytesUsed { get { return bytesUsed.Get(); } } public class ApplyDeletesResult { // True if any actual deletes took place: public bool AnyDeletes { get; private set; } // Current gen, for the merged segment: public long Gen { get; private set; } // If non-null, contains segments that are 100% deleted public IList<SegmentCommitInfo> AllDeleted { get; private set; } internal ApplyDeletesResult(bool anyDeletes, long gen, IList<SegmentCommitInfo> allDeleted) { this.AnyDeletes = anyDeletes; this.Gen = gen; this.AllDeleted = allDeleted; } } // Sorts SegmentInfos from smallest to biggest bufferedDelGen: private static readonly IComparer<SegmentCommitInfo> sortSegInfoByDelGen = new ComparerAnonymousInnerClassHelper(); private class ComparerAnonymousInnerClassHelper : IComparer<SegmentCommitInfo> { public ComparerAnonymousInnerClassHelper() { } public virtual int Compare(SegmentCommitInfo si1, SegmentCommitInfo si2) { long cmp = si1.BufferedDeletesGen - si2.BufferedDeletesGen; if (cmp > 0) { return 1; } else if (cmp < 0) { return -1; } else { return 0; } } } /// <summary> /// Resolves the buffered deleted Term/Query/docIDs, into /// actual deleted docIDs in the liveDocs <see cref="Util.IMutableBits"/> for /// each <see cref="SegmentReader"/>. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public virtual ApplyDeletesResult ApplyDeletesAndUpdates(IndexWriter.ReaderPool readerPool, IList<SegmentCommitInfo> infos) { lock (this) { long t0 = Environment.TickCount; if (infos.Count == 0) { return new ApplyDeletesResult(false, nextGen++, null); } Debug.Assert(CheckDeleteStats()); if (!Any()) { if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "applyDeletes: no deletes; skipping"); } return new ApplyDeletesResult(false, nextGen++, null); } if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "applyDeletes: infos=" + Arrays.ToString(infos) + " packetCount=" + updates.Count); } long gen = nextGen++; List<SegmentCommitInfo> infos2 = new List<SegmentCommitInfo>(); infos2.AddRange(infos); infos2.Sort(sortSegInfoByDelGen); CoalescedUpdates coalescedUpdates = null; bool anyNewDeletes = false; int infosIDX = infos2.Count - 1; int delIDX = updates.Count - 1; IList<SegmentCommitInfo> allDeleted = null; while (infosIDX >= 0) { //System.out.println("BD: cycle delIDX=" + delIDX + " infoIDX=" + infosIDX); FrozenBufferedUpdates packet = delIDX >= 0 ? updates[delIDX] : null; SegmentCommitInfo info = infos2[infosIDX]; long segGen = info.BufferedDeletesGen; if (packet != null && segGen < packet.DelGen) { // System.out.println(" coalesce"); if (coalescedUpdates == null) { coalescedUpdates = new CoalescedUpdates(); } if (!packet.isSegmentPrivate) { /* * Only coalesce if we are NOT on a segment private del packet: the segment private del packet * must only applied to segments with the same delGen. Yet, if a segment is already deleted * from the SI since it had no more documents remaining after some del packets younger than * its segPrivate packet (higher delGen) have been applied, the segPrivate packet has not been * removed. */ coalescedUpdates.Update(packet); } delIDX--; } else if (packet != null && segGen == packet.DelGen) { Debug.Assert(packet.isSegmentPrivate, "Packet and Segments deletegen can only match on a segment private del packet gen=" + segGen); //System.out.println(" eq"); // Lock order: IW -> BD -> RP Debug.Assert(readerPool.InfoIsLive(info)); ReadersAndUpdates rld = readerPool.Get(info, true); SegmentReader reader = rld.GetReader(IOContext.READ); int delCount = 0; bool segAllDeletes; try { DocValuesFieldUpdates.Container dvUpdates = new DocValuesFieldUpdates.Container(); if (coalescedUpdates != null) { //System.out.println(" del coalesced"); delCount += (int)ApplyTermDeletes(coalescedUpdates.TermsIterable(), rld, reader); delCount += (int)ApplyQueryDeletes(coalescedUpdates.QueriesIterable(), rld, reader); ApplyDocValuesUpdates(coalescedUpdates.numericDVUpdates, rld, reader, dvUpdates); ApplyDocValuesUpdates(coalescedUpdates.binaryDVUpdates, rld, reader, dvUpdates); } //System.out.println(" del exact"); // Don't delete by Term here; DocumentsWriterPerThread // already did that on flush: delCount += (int)ApplyQueryDeletes(packet.GetQueriesEnumerable(), rld, reader); ApplyDocValuesUpdates(Arrays.AsList(packet.numericDVUpdates), rld, reader, dvUpdates); ApplyDocValuesUpdates(Arrays.AsList(packet.binaryDVUpdates), rld, reader, dvUpdates); if (dvUpdates.Any()) { rld.WriteFieldUpdates(info.Info.Dir, dvUpdates); } int fullDelCount = rld.Info.DelCount + rld.PendingDeleteCount; Debug.Assert(fullDelCount <= rld.Info.Info.DocCount); segAllDeletes = fullDelCount == rld.Info.Info.DocCount; } finally { rld.Release(reader); readerPool.Release(rld); } anyNewDeletes |= delCount > 0; if (segAllDeletes) { if (allDeleted == null) { allDeleted = new List<SegmentCommitInfo>(); } allDeleted.Add(info); } if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "seg=" + info + " segGen=" + segGen + " segDeletes=[" + packet + "]; coalesced deletes=[" + (coalescedUpdates == null ? "null" : coalescedUpdates.ToString()) + "] newDelCount=" + delCount + (segAllDeletes ? " 100% deleted" : "")); } if (coalescedUpdates == null) { coalescedUpdates = new CoalescedUpdates(); } /* * Since we are on a segment private del packet we must not * update the coalescedDeletes here! We can simply advance to the * next packet and seginfo. */ delIDX--; infosIDX--; info.SetBufferedDeletesGen(gen); } else { //System.out.println(" gt"); if (coalescedUpdates != null) { // Lock order: IW -> BD -> RP Debug.Assert(readerPool.InfoIsLive(info)); ReadersAndUpdates rld = readerPool.Get(info, true); SegmentReader reader = rld.GetReader(IOContext.READ); int delCount = 0; bool segAllDeletes; try { delCount += (int)ApplyTermDeletes(coalescedUpdates.TermsIterable(), rld, reader); delCount += (int)ApplyQueryDeletes(coalescedUpdates.QueriesIterable(), rld, reader); DocValuesFieldUpdates.Container dvUpdates = new DocValuesFieldUpdates.Container(); ApplyDocValuesUpdates(coalescedUpdates.numericDVUpdates, rld, reader, dvUpdates); ApplyDocValuesUpdates(coalescedUpdates.binaryDVUpdates, rld, reader, dvUpdates); if (dvUpdates.Any()) { rld.WriteFieldUpdates(info.Info.Dir, dvUpdates); } int fullDelCount = rld.Info.DelCount + rld.PendingDeleteCount; Debug.Assert(fullDelCount <= rld.Info.Info.DocCount); segAllDeletes = fullDelCount == rld.Info.Info.DocCount; } finally { rld.Release(reader); readerPool.Release(rld); } anyNewDeletes |= delCount > 0; if (segAllDeletes) { if (allDeleted == null) { allDeleted = new List<SegmentCommitInfo>(); } allDeleted.Add(info); } if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "seg=" + info + " segGen=" + segGen + " coalesced deletes=[" + coalescedUpdates + "] newDelCount=" + delCount + (segAllDeletes ? " 100% deleted" : "")); } } info.SetBufferedDeletesGen(gen); infosIDX--; } } Debug.Assert(CheckDeleteStats()); if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "applyDeletes took " + (Environment.TickCount - t0) + " msec"); } // assert infos != segmentInfos || !any() : "infos=" + infos + " segmentInfos=" + segmentInfos + " any=" + any; return new ApplyDeletesResult(anyNewDeletes, gen, allDeleted); } } internal virtual long GetNextGen() { lock (this) { return nextGen++; } } // Lock order IW -> BD /// <summary> /// Removes any BufferedDeletes that we no longer need to /// store because all segments in the index have had the /// deletes applied. /// </summary> public virtual void Prune(SegmentInfos segmentInfos) { lock (this) { Debug.Assert(CheckDeleteStats()); long minGen = long.MaxValue; foreach (SegmentCommitInfo info in segmentInfos.Segments) { minGen = Math.Min(info.BufferedDeletesGen, minGen); } if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "prune sis=" + segmentInfos + " minGen=" + minGen + " packetCount=" + updates.Count); } int limit = updates.Count; for (int delIDX = 0; delIDX < limit; delIDX++) { if (updates[delIDX].DelGen >= minGen) { Prune(delIDX); Debug.Assert(CheckDeleteStats()); return; } } // All deletes pruned Prune(limit); Debug.Assert(!Any()); Debug.Assert(CheckDeleteStats()); } } private void Prune(int count) { lock (this) { if (count > 0) { if (infoStream.IsEnabled("BD")) { infoStream.Message("BD", "pruneDeletes: prune " + count + " packets; " + (updates.Count - count) + " packets remain"); } for (int delIDX = 0; delIDX < count; delIDX++) { FrozenBufferedUpdates packet = updates[delIDX]; numTerms.AddAndGet(-packet.numTermDeletes); Debug.Assert(numTerms.Get() >= 0); bytesUsed.AddAndGet(-packet.bytesUsed); Debug.Assert(bytesUsed.Get() >= 0); } updates.SubList(0, count).Clear(); } } } // Delete by Term private long ApplyTermDeletes(IEnumerable<Term> termsIter, ReadersAndUpdates rld, SegmentReader reader) { lock (this) { long delCount = 0; Fields fields = reader.Fields; if (fields == null) { // this reader has no postings return 0; } TermsEnum termsEnum = null; string currentField = null; DocsEnum docs = null; Debug.Assert(CheckDeleteTerm(null)); bool any = false; //System.out.println(Thread.currentThread().getName() + " del terms reader=" + reader); foreach (Term term in termsIter) { // Since we visit terms sorted, we gain performance // by re-using the same TermsEnum and seeking only // forwards if (!string.Equals(term.Field, currentField, StringComparison.Ordinal)) { Debug.Assert(currentField == null || currentField.CompareToOrdinal(term.Field) < 0); currentField = term.Field; Terms terms = fields.GetTerms(currentField); if (terms != null) { termsEnum = terms.GetIterator(termsEnum); } else { termsEnum = null; } } if (termsEnum == null) { continue; } Debug.Assert(CheckDeleteTerm(term)); // System.out.println(" term=" + term); if (termsEnum.SeekExact(term.Bytes)) { // we don't need term frequencies for this DocsEnum docsEnum = termsEnum.Docs(rld.LiveDocs, docs, DocsFlags.NONE); //System.out.println("BDS: got docsEnum=" + docsEnum); if (docsEnum != null) { while (true) { int docID = docsEnum.NextDoc(); //System.out.println(Thread.currentThread().getName() + " del term=" + term + " doc=" + docID); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } if (!any) { rld.InitWritableLiveDocs(); any = true; } // NOTE: there is no limit check on the docID // when deleting by Term (unlike by Query) // because on flush we apply all Term deletes to // each segment. So all Term deleting here is // against prior segments: if (rld.Delete(docID)) { delCount++; } } } } } return delCount; } } // DocValues updates private void ApplyDocValuesUpdates<T1>(IEnumerable<T1> updates, ReadersAndUpdates rld, SegmentReader reader, DocValuesFieldUpdates.Container dvUpdatesContainer) where T1 : DocValuesUpdate { lock (this) { Fields fields = reader.Fields; if (fields == null) { // this reader has no postings return; } // TODO: we can process the updates per DV field, from last to first so that // if multiple terms affect same document for the same field, we add an update // only once (that of the last term). To do that, we can keep a bitset which // marks which documents have already been updated. So e.g. if term T1 // updates doc 7, and then we process term T2 and it updates doc 7 as well, // we don't apply the update since we know T1 came last and therefore wins // the update. // We can also use that bitset as 'liveDocs' to pass to TermEnum.docs(), so // that these documents aren't even returned. string currentField = null; TermsEnum termsEnum = null; DocsEnum docs = null; //System.out.println(Thread.currentThread().getName() + " numericDVUpdate reader=" + reader); foreach (DocValuesUpdate update in updates) { Term term = update.term; int limit = update.docIDUpto; // TODO: we traverse the terms in update order (not term order) so that we // apply the updates in the correct order, i.e. if two terms udpate the // same document, the last one that came in wins, irrespective of the // terms lexical order. // we can apply the updates in terms order if we keep an updatesGen (and // increment it with every update) and attach it to each NumericUpdate. Note // that we cannot rely only on docIDUpto because an app may send two updates // which will get same docIDUpto, yet will still need to respect the order // those updates arrived. if (!string.Equals(term.Field, currentField, StringComparison.Ordinal)) { // if we change the code to process updates in terms order, enable this assert // assert currentField == null || currentField.CompareToOrdinal(term.Field) < 0; currentField = term.Field; Terms terms = fields.GetTerms(currentField); if (terms != null) { termsEnum = terms.GetIterator(termsEnum); } else { termsEnum = null; continue; // no terms in that field } } if (termsEnum == null) { continue; } // System.out.println(" term=" + term); if (termsEnum.SeekExact(term.Bytes)) { // we don't need term frequencies for this DocsEnum docsEnum = termsEnum.Docs(rld.LiveDocs, docs, DocsFlags.NONE); //System.out.println("BDS: got docsEnum=" + docsEnum); DocValuesFieldUpdates dvUpdates = dvUpdatesContainer.GetUpdates(update.field, update.type); if (dvUpdates == null) { dvUpdates = dvUpdatesContainer.NewUpdates(update.field, update.type, reader.MaxDoc); } int doc; while ((doc = docsEnum.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { //System.out.println(Thread.currentThread().getName() + " numericDVUpdate term=" + term + " doc=" + docID); if (doc >= limit) { break; // no more docs that can be updated for this term } dvUpdates.Add(doc, update.value); } } } } } public class QueryAndLimit { public Query Query { get; private set; } public int Limit { get; private set; } public QueryAndLimit(Query query, int limit) { this.Query = query; this.Limit = limit; } } // Delete by query private static long ApplyQueryDeletes(IEnumerable<QueryAndLimit> queriesIter, ReadersAndUpdates rld, SegmentReader reader) { long delCount = 0; AtomicReaderContext readerContext = reader.AtomicContext; bool any = false; foreach (QueryAndLimit ent in queriesIter) { Query query = ent.Query; int limit = ent.Limit; DocIdSet docs = (new QueryWrapperFilter(query)).GetDocIdSet(readerContext, reader.LiveDocs); if (docs != null) { DocIdSetIterator it = docs.GetIterator(); if (it != null) { while (true) { int doc = it.NextDoc(); if (doc >= limit) { break; } if (!any) { rld.InitWritableLiveDocs(); any = true; } if (rld.Delete(doc)) { delCount++; } } } } } return delCount; } // used only by assert private bool CheckDeleteTerm(Term term) { if (term != null) { Debug.Assert(lastDeleteTerm == null || term.CompareTo(lastDeleteTerm) > 0, "lastTerm=" + lastDeleteTerm + " vs term=" + term); } // TODO: we re-use term now in our merged iterable, but we shouldn't clone, instead copy for this assert lastDeleteTerm = term == null ? null : new Term(term.Field, BytesRef.DeepCopyOf(term.Bytes)); return true; } // only for assert private bool CheckDeleteStats() { int numTerms2 = 0; long bytesUsed2 = 0; foreach (FrozenBufferedUpdates packet in updates) { numTerms2 += packet.numTermDeletes; bytesUsed2 += packet.bytesUsed; } Debug.Assert(numTerms2 == numTerms.Get(), "numTerms2=" + numTerms2 + " vs " + numTerms.Get()); Debug.Assert(bytesUsed2 == bytesUsed.Get(), "bytesUsed2=" + bytesUsed2 + " vs " + bytesUsed); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using FluentAssertions; using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.DotNet.CoreSetup.Test; using Microsoft.NET.HostModel.AppHost; using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class StandaloneAppActivation : IClassFixture<StandaloneAppActivation.SharedTestState> { private readonly string AppHostExeName = RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("apphost"); private SharedTestState sharedTestState; public StandaloneAppActivation(StandaloneAppActivation.SharedTestState fixture) { sharedTestState = fixture; } [Fact] public void Running_Build_Output_Standalone_EXE_with_DepsJson_and_RuntimeConfig_Local_Succeeds() { var fixture = sharedTestState.StandaloneAppFixture_Built .Copy(); var appExe = fixture.TestProject.AppExe; Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World") .And.HaveStdOutContaining($"Framework Version:{sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}"); } [Fact] public void Running_Publish_Output_Standalone_EXE_with_DepsJson_and_RuntimeConfig_Local_Succeeds() { var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); var appExe = fixture.TestProject.AppExe; Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World") .And.HaveStdOutContaining($"Framework Version:{sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}"); } [Fact] public void Running_Publish_Output_Standalone_EXE_with_Unbound_AppHost_Fails() { var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); var appExe = fixture.TestProject.AppExe; string builtAppHost = Path.Combine(sharedTestState.RepoDirectories.HostArtifacts, AppHostExeName); File.Copy(builtAppHost, appExe, true); int exitCode = Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() .Execute(fExpectedToFail: true) .ExitCode; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { exitCode.Should().Be(-2147450731); } else { // Some Unix flavors filter exit code to ubyte. (exitCode & 0xFF).Should().Be(0x95); } } [Fact] public void Running_Publish_Output_Standalone_EXE_By_Renaming_dotnet_exe_Fails() { var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); var appExe = fixture.TestProject.AppExe; string hostExeName = RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("dotnet"); string builtHost = Path.Combine(sharedTestState.RepoDirectories.HostArtifacts, hostExeName); File.Copy(builtHost, appExe, true); int exitCode = Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() .Execute(fExpectedToFail: true) .ExitCode; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { exitCode.Should().Be(-2147450748); } else { // Some Unix flavors filter exit code to ubyte. (exitCode & 0xFF).Should().Be(0x84); } } [Fact] public void Running_Publish_Output_Standalone_EXE_By_Renaming_apphost_exe_Succeeds() { var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); var appExe = fixture.TestProject.AppExe; var renamedAppExe = fixture.TestProject.AppExe + RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("renamed"); File.Copy(appExe, renamedAppExe, true); Command.Create(renamedAppExe) .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World") .And.HaveStdOutContaining($"Framework Version:{sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}"); } [Fact] public void Running_Publish_Output_Standalone_EXE_With_Relative_Embedded_Path_Succeeds() { var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); var appExe = fixture.TestProject.AppExe; // Move whole directory to a subdirectory string currentOutDir = fixture.TestProject.OutputDirectory; string relativeNewPath = ".."; relativeNewPath = Path.Combine(relativeNewPath, "newDir"); string newOutDir = Path.Combine(currentOutDir, relativeNewPath); Directory.Move(currentOutDir, newOutDir); // Move the apphost exe back to original location string appExeName = Path.GetFileName(appExe); string sourceAppExePath = Path.Combine(newOutDir, appExeName); Directory.CreateDirectory(Path.GetDirectoryName(appExe)); File.Move(sourceAppExePath, appExe); // Modify the apphost to include relative path string appDll = fixture.TestProject.AppDll; string appDllName = Path.GetFileName(appDll); string relativeDllPath = Path.Combine(relativeNewPath, appDllName); BinaryUtils.SearchAndReplace(appExe, Encoding.UTF8.GetBytes(appDllName), Encoding.UTF8.GetBytes(relativeDllPath)); Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World") .And.HaveStdOutContaining($"Framework Version:{sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}"); } [Fact] public void Running_Publish_Output_Standalone_EXE_With_DOTNET_ROOT_Fails() { var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); var appExe = fixture.TestProject.AppExe; var appDll = fixture.TestProject.AppDll; // Move whole directory to a subdirectory string currentOutDir = fixture.TestProject.OutputDirectory; string relativeNewPath = ".."; relativeNewPath = Path.Combine(relativeNewPath, "newDir2"); string newOutDir = Path.Combine(currentOutDir, relativeNewPath); Directory.Move(currentOutDir, newOutDir); // Move the apphost exe and app dll back to original location string appExeName = Path.GetFileName(appExe); string sourceAppExePath = Path.Combine(newOutDir, appExeName); Directory.CreateDirectory(Path.GetDirectoryName(appExe)); File.Move(sourceAppExePath, appExe); string appDllName = Path.GetFileName(appDll); string sourceAppDllPath = Path.Combine(newOutDir, appDllName); File.Move(sourceAppDllPath, appDll); // This verifies a self-contained apphost cannot use DOTNET_ROOT to reference a flat // self-contained layout since a flat layout of the shared framework is not supported. Command.Create(appExe) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("DOTNET_ROOT", newOutDir) .EnvironmentVariable("DOTNET_ROOT(x86)", newOutDir) .CaptureStdErr() .CaptureStdOut() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining($"Using environment variable DOTNET_ROOT") // use the first part avoiding "(x86)" if present .And.HaveStdErrContaining($"=[{Path.GetFullPath(newOutDir)}] as runtime location.") // use the last part .And.HaveStdErrContaining("A fatal error occurred"); } [Fact] public void Running_Publish_Output_Standalone_EXE_with_Bound_AppHost_Succeeds() { var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); string appExe = fixture.TestProject.AppExe; UseBuiltAppHost(appExe); BindAppHost(appExe); Command.Create(appExe) .EnvironmentVariable("COREHOST_TRACE", "1") .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World") .And.HaveStdOutContaining($"Framework Version:{sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}"); } [Fact] public void Running_AppHost_with_GUI_No_Console() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // GUI app host is only supported on Windows. return; } var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); string appExe = fixture.TestProject.AppExe; // Mark the apphost as GUI, but don't bind it to anything - this will cause it to fail UseBuiltAppHost(appExe); MarkAppHostAsGUI(appExe); Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Fail() .And.HaveStdErrContaining("This executable is not bound to a managed DLL to execute."); } [Fact] public void Running_AppHost_with_GUI_Traces() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // GUI app host is only supported on Windows. return; } var fixture = sharedTestState.StandaloneAppFixture_Published .Copy(); string appExe = fixture.TestProject.AppExe; // Mark the apphost as GUI, but don't bind it to anything - this will cause it to fail UseBuiltAppHost(appExe); MarkAppHostAsGUI(appExe); string traceFilePath; Command.Create(appExe) .EnableHostTracingToFile(out traceFilePath) .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Fail() .And.FileExists(traceFilePath) .And.FileContains(traceFilePath, "This executable is not bound to a managed DLL to execute.") .And.HaveStdErrContaining("This executable is not bound to a managed DLL to execute."); FileUtils.DeleteFileIfPossible(traceFilePath); } private void UseBuiltAppHost(string appExe) { File.Copy(Path.Combine(sharedTestState.RepoDirectories.HostArtifacts, AppHostExeName), appExe, true); } private void BindAppHost(string appExe) { string appName = Path.GetFileNameWithoutExtension(appExe); string appDll = $"{appName}.dll"; string appDir = Path.GetDirectoryName(appExe); string appDirHostExe = Path.Combine(appDir, AppHostExeName); // Make a copy of apphost first, replace hash and overwrite app.exe, rather than // overwrite app.exe and edit in place, because the file is opened as "write" for // the replacement -- the test fails with ETXTBSY (exit code: 26) in Linux when // executing a file opened in "write" mode. File.Copy(appExe, appDirHostExe, true); using (var sha256 = SHA256.Create()) { // Replace the hash with the managed DLL name. var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes("foobar")); var hashStr = BitConverter.ToString(hash).Replace("-", "").ToLower(); BinaryUtils.SearchAndReplace(appDirHostExe, Encoding.UTF8.GetBytes(hashStr), Encoding.UTF8.GetBytes(appDll)); } File.Copy(appDirHostExe, appExe, true); } private void MarkAppHostAsGUI(string appExe) { string appDir = Path.GetDirectoryName(appExe); string appDirHostExe = Path.Combine(appDir, AppHostExeName); File.Copy(appExe, appDirHostExe, true); using (var sha256 = SHA256.Create()) { AppHostExtensions.SetWindowsGraphicalUserInterfaceBit(appDirHostExe); } File.Copy(appDirHostExe, appExe, true); } public class SharedTestState : IDisposable { public TestProjectFixture StandaloneAppFixture_Built { get; } public TestProjectFixture StandaloneAppFixture_Published { get; } public RepoDirectoriesProvider RepoDirectories { get; } public SharedTestState() { RepoDirectories = new RepoDirectoriesProvider(); var buildFixture = new TestProjectFixture("StandaloneApp", RepoDirectories); buildFixture .EnsureRestoredForRid(buildFixture.CurrentRid, RepoDirectories.CorehostPackages) .BuildProject(runtime: buildFixture.CurrentRid); var publishFixture = new TestProjectFixture("StandaloneApp", RepoDirectories); publishFixture .EnsureRestoredForRid(publishFixture.CurrentRid, RepoDirectories.CorehostPackages) .PublishProject(runtime: publishFixture.CurrentRid); ReplaceTestProjectOutputHostInTestProjectFixture(buildFixture); StandaloneAppFixture_Built = buildFixture; StandaloneAppFixture_Published = publishFixture; } public void Dispose() { StandaloneAppFixture_Built.Dispose(); StandaloneAppFixture_Published.Dispose(); } /* * This method is needed to workaround dotnet build not placing the host from the package * graph in the build output. * https://github.com/dotnet/cli/issues/2343 */ private static void ReplaceTestProjectOutputHostInTestProjectFixture(TestProjectFixture testProjectFixture) { var dotnet = testProjectFixture.BuiltDotnet; var testProjectHostPolicy = testProjectFixture.TestProject.HostPolicyDll; var testProjectHostFxr = testProjectFixture.TestProject.HostFxrDll; if (!File.Exists(testProjectHostPolicy)) { throw new Exception("host or hostpolicy does not exist in test project output. Is this a standalone app?"); } var dotnetHostPolicy = Path.Combine(dotnet.GreatestVersionSharedFxPath, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy")); var dotnetHostFxr = Path.Combine(dotnet.GreatestVersionHostFxrPath, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")); File.Copy(dotnetHostPolicy, testProjectHostPolicy, true); if (File.Exists(testProjectHostFxr)) { File.Copy(dotnetHostFxr, testProjectHostFxr, true); } } } } }
using System; using System.Collections; using System.Reflection; using System.Text; namespace HttpServer.Helpers { /// <summary> /// The object form class takes an object and creates form items for it. /// </summary> public class ObjectForm { private readonly object _object; private readonly string _action; private readonly string _name = string.Empty; private readonly string _method = "post"; /// <summary> /// Initializes a new instance of the <see cref="ObjectForm"/> class. /// </summary> /// <param name="method"></param> /// <param name="name">form name *and* id.</param> /// <param name="action">action to do when form is posted.</param> /// <param name="obj"></param> public ObjectForm(string action, string name, object obj, string method) : this(name, action, obj) { if (string.IsNullOrEmpty(method)) throw new ArgumentNullException("method"); _method = method.ToLower(); } /// <summary> /// Initializes a new instance of the <see cref="ObjectForm"/> class. /// </summary> /// <param name="name">form name *and* id.</param> /// <param name="action">action to do when form is posted.</param> /// <param name="obj">object to get values from</param> public ObjectForm(string action, string name, object obj) : this(action, obj) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); _name = name; } /// <summary> /// Initializes a new instance of the <see cref="ObjectForm"/> class. /// </summary> /// <param name="action">form action.</param> /// <param name="obj">object to get values from.</param> public ObjectForm(string action, object obj) { if (string.IsNullOrEmpty(action)) throw new ArgumentNullException("action"); if (obj == null) throw new ArgumentNullException("obj"); _object = obj; _action = action; } /// <summary> /// write out the FORM-tag. /// </summary> /// <returns>generated html code</returns> public string Begin() { return Begin(false); } /// <summary> /// Writeout the form tag /// </summary> /// <param name="isAjax">form should be posted through ajax.</param> /// <returns>generated html code</returns> public string Begin(bool isAjax) { string ajaxCode; if (isAjax) ajaxCode = "onsubmit=\"" + WebHelper.JSImplementation.AjaxFormOnSubmit() + "\""; else ajaxCode = string.Empty; if (!string.IsNullOrEmpty(_name)) return string.Format("<form method=\"{0}\" id=\"{1}\" name=\"{1}\" {3} action=\"{2}\">", _method, _name, _action, ajaxCode); else return string.Format("<form method=\"{0}\" action=\"{1}\" {2}>", _method, _action, ajaxCode); } /// <summary> /// Generates a text box. /// </summary> /// <param name="propertyName"></param> /// <param name="options"></param> /// <returns>generated html code</returns> public string Tb(string propertyName, params object[] options) { if (options.Length % 2 != 0) throw new ArgumentException("Options must consist of string, object, ... as key/value couple(s)."); if (options.Length == 0) return string.Format("<input type=\"text\" name=\"{0}[{1}]\" id=\"{0}_{1}\" value=\"{2}\" />", _name, propertyName, GetValue(propertyName)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < options.Length; i += 2) { sb.Append(options[i]); sb.Append("=\""); sb.Append(options[i + 1].ToString()); sb.Append("\""); } return string.Format("<input type=\"text\" name=\"{0}[{1}]\" id=\"{0}_{1}\" {3} value=\"{2}\" />", _name, propertyName, GetValue(propertyName), sb); } /// <summary> /// password box /// </summary> /// <param name="propertyName"></param> /// <param name="options"></param> /// <returns>generated html code</returns> public string Pb(string propertyName, params object[] options) { return string.Format("<input type=\"password\" name=\"{0}[{1}]\" id=\"{0}_{1}\" />", _name, propertyName); } /// <summary> /// Hiddens the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="options">The options.</param> /// <returns>generated html code</returns> public string Hidden(string propertyName, params object[] options) { return string.Format("<input type=\"hidden\" name=\"{0}[{1}]\" id=\"{0}_{1}\" value=\"{2}\" />", _name, propertyName, GetValue(propertyName)); } /// <summary> /// Labels the specified property name. /// </summary> /// <param name="propertyName">property in object.</param> /// <param name="label">caption</param> /// <returns>generated html code</returns> public string Label(string propertyName, string label) { return string.Format("<label for=\"{0}_{1}\">{2}</label>", _name, propertyName, label); } /// <summary> /// Generate a checkbox /// </summary> /// <param name="propertyName">property in object</param> /// <param name="value">checkbox value</param> /// <param name="options">additional html attributes.</param> /// <returns>generated html code</returns> public string Cb(string propertyName, string value, params object[] options) { string isChecked = string.Empty; object o = GetValue(propertyName); if (o.GetType() == typeof(bool) && (bool)o) isChecked = "checked=\"checked\""; else { int i; int.TryParse(o.ToString(), out i); if (i != 0) isChecked = "checked=\"checked\""; } return string.Format("<input type=\"hidden\" name=\"{0}\" id=\"{0}_{1}\" value=\"0\" /><input type=\"checkbox\" name=\"{0}[{1}]\" id=\"{0}_{1}\" value=\"{2}\" {3} />", _name, propertyName, value, isChecked); } /// <summary> /// Write a html select tag /// </summary> /// <param name="propertyName">object property.</param> /// <param name="idColumn">id column</param> /// <param name="titleColumn">The title column.</param> /// <param name="options">The options.</param> /// <returns></returns> public string Select(string propertyName, string idColumn, string titleColumn, params object[] options) { object o = _object.GetType().GetProperty(propertyName).GetValue(_object, null); return Select(propertyName, o as IEnumerable, idColumn, titleColumn, options); } /// <summary> /// Selects the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="items">The items.</param> /// <param name="idColumn">The id column.</param> /// <param name="titleColumn">The title column.</param> /// <param name="options">The options.</param> /// <returns></returns> public string Select(string propertyName, IEnumerable items, string idColumn, string titleColumn, params object[] options) { //object o = _object.GetType().GetProperty(propertyName).GetValue(_object, null); StringBuilder sb = new StringBuilder(); sb.AppendFormat("<select name=\"{0}[{1}]\">{2}", _name, propertyName, Environment.NewLine); if (items != null) foreach (object o1 in items) { sb.AppendFormat("<option value=\"{0}\">{1}</option>{2}", o1.GetType().GetProperty(idColumn).GetValue(o1, null), o1.GetType().GetProperty(titleColumn).GetValue(o1, null), Environment.NewLine); } sb.AppendLine("</select>"); return sb.ToString(); } /// <summary> /// Write a submit tag. /// </summary> /// <param name="value">button caption</param> /// <returns>html submit tag</returns> public string Submit(string value) { return string.Format("<input type=\"submit\" value=\"{0}\" />", value); } /// <summary> /// html end form tag /// </summary> /// <returns>html</returns> public string End() { return "</form>"; } private string GetValue(string propertyName) { Type type = _object.GetType(); PropertyInfo pi = type.GetProperty(propertyName); if (pi == null) throw new ArgumentException("Property " + propertyName + " not found for type " + type); object o = pi.GetValue(_object, null); if (o == null) return string.Empty; else return o.ToString(); } } }
#region -- License Terms -- // MessagePack for CLI // // Copyright (C) 2015-2018 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Contributors: // Samuel Cragg // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections.Generic; #if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // FEATURE_MPCONTRACT using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using MsgPack.Serialization.Polymorphic; namespace MsgPack.Serialization { partial class PolymorphismSchema { private static readonly Func<PolymorphicTypeVerificationContext, bool> DefaultTypeVerfiier = _ => true; /// <summary> /// Default instance (null object). /// </summary> #if UNITY && DEBUG public #else internal #endif static readonly PolymorphismSchema Default = new PolymorphismSchema(); /// <summary> /// ForPolymorphicObject( Type targetType ) /// </summary> internal static readonly MethodInfo ForPolymorphicObjectTypeEmbeddingMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicObject", new[] { typeof( Type ) } ); /// <summary> /// ForPolymorphicObject( Type targetType, IDictionary{byte, Type} codeTypeMapping ) /// </summary> internal static readonly MethodInfo ForPolymorphicObjectCodeTypeMappingMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicObject", new[] { typeof( Type ), typeof( IDictionary<string, Type> ) } ); /// <summary> /// ForContextSpecifiedCollection( Type targetType, PolymorphismSchema itemsSchema ) /// </summary> internal static readonly MethodInfo ForContextSpecifiedCollectionMethod = typeof( PolymorphismSchema ).GetMethod( "ForContextSpecifiedCollection", new[] { typeof( Type ), typeof( PolymorphismSchema ) } ); /// <summary> /// ForPolymorphicCollection( Type targetType, PolymorphismSchema itemsSchema ) /// </summary> internal static readonly MethodInfo ForPolymorphicCollectionTypeEmbeddingMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicCollection", new[] { typeof( Type ), typeof( PolymorphismSchema ) } ); /// <summary> /// ForPolymorphicCollection( Type targetType, IDictionary{byte, Type} codeTypeMapping, PolymorphismSchema itemsSchema ) /// </summary> internal static readonly MethodInfo ForPolymorphicCollectionCodeTypeMappingMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicCollection", new[] { typeof( Type ), typeof( IDictionary<string, Type> ), typeof( PolymorphismSchema ) } ); /// <summary> /// ForContextSpecifiedDictionary( Type targetType, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) /// </summary> internal static readonly MethodInfo ForContextSpecifiedDictionaryMethod = typeof( PolymorphismSchema ).GetMethod( "ForContextSpecifiedDictionary", new[] { typeof( Type ), typeof( PolymorphismSchema ), typeof( PolymorphismSchema ) } ); /// <summary> /// ForPolymorphicDictionary( Type targetType, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) /// </summary> internal static readonly MethodInfo ForPolymorphicDictionaryTypeEmbeddingMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicDictionary", new[] { typeof( Type ), typeof( PolymorphismSchema ), typeof( PolymorphismSchema ) } ); /// <summary> /// ForPolymorphicDictionary( Type targetType, IDictionary{byte, Type} codeTypeMapping, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) /// </summary> internal static readonly MethodInfo ForPolymorphicDictionaryCodeTypeMappingMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicDictionary", new[] { typeof( Type ), typeof( IDictionary<string, Type> ), typeof( PolymorphismSchema ), typeof( PolymorphismSchema ) } ); #if !NET35 && !UNITY /// <summary> /// ForPolymorphicTuple( Type targetType, PolymorphismSchema[] itemSchemaList ) /// </summary> internal static readonly MethodInfo ForPolymorphicTupleMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicTuple", new[] { typeof( Type ), typeof( PolymorphismSchema[]) } ); #endif // !NET35 && !UNITY internal static readonly ConstructorInfo CodeTypeMapConstructor = typeof( Dictionary<,> ).MakeGenericType( typeof( string ), typeof( Type ) ) .GetConstructor( new[] { typeof( int ) } ); internal static readonly MethodInfo AddToCodeTypeMapMethod = typeof( Dictionary<,> ).MakeGenericType( typeof( string ), typeof( Type ) ) .GetMethod( "Add", new[] { typeof( string ), typeof( Type ) } ); internal string DebugString { get { var buffer = new StringBuilder(); this.ToDebugString( buffer ); return buffer.ToString(); } } private void ToDebugString( StringBuilder buffer ) { buffer.Append( "{TargetType:" ).Append( this.TargetType ).Append( ", SchemaType:" ).Append( this.PolymorphismType ); switch ( this.ChildrenType ) { case PolymorphismSchemaChildrenType.CollectionItems: { buffer.Append( ", CollectionItemsSchema:" ); if ( this.ItemSchema == null ) { buffer.Append( "null" ); } else { this.ItemSchema.ToDebugString( buffer ); } break; } case PolymorphismSchemaChildrenType.DictionaryKeyValues: { buffer.Append( ", DictinoaryKeysSchema:" ); if ( this.KeySchema == null ) { buffer.Append( "null" ); } else { this.KeySchema.ToDebugString( buffer ); } buffer.Append( ", DictinoaryValuesSchema:" ); if ( this.ItemSchema == null ) { buffer.Append( "null" ); } else { this.ItemSchema.ToDebugString( buffer ); } break; } #if !NET35 && !UNITY case PolymorphismSchemaChildrenType.TupleItems: { buffer.Append( ", TupleItemsSchema:[" ); var isFirst = true; foreach ( var child in this._children ) { if ( isFirst ) { isFirst = false; } else { buffer.Append( ", " ); } if ( child == null ) { buffer.Append( "null" ); } else { child.ToDebugString( buffer ); } } break; } #endif // !NET35 && !UNITY } buffer.Append( '}' ); } internal static PolymorphismSchema Create( Type type, #if !UNITY SerializingMember? memberMayBeNull #else SerializingMember memberMayBeNull #endif // !UNITY ) { if ( type.GetIsValueType() ) { SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' is value type: {1}", memberMayBeNull == null #if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 ? type #else ? type.GetTypeInfo() #endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 #if !UNITY : memberMayBeNull.Value.Member, #else : memberMayBeNull.Member, #endif Default ); // Value types will never be polymorphic. return Default; } if ( memberMayBeNull == null ) { var schema = CreateCore( #if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 type, #else type.GetTypeInfo(), #endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 Default ); SerializerDebugging.TracePolimorphicSchemaEvent( "Returns root type schema for '{0}': {1}", #if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 type, #else type.GetTypeInfo(), #endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 schema ); return schema; } #if !UNITY var member = memberMayBeNull.Value; #else var member = memberMayBeNull; #endif // !UNITY return CreateCore( member.Member, CreateCore( #if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 type, #else type.GetTypeInfo(), #endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 Default ) ); } private static PolymorphismSchema CreateCore( MemberInfo member, PolymorphismSchema defaultSchema ) { var table = TypeTable.Create( member, defaultSchema ); var traits = member.GetMemberValueType().GetCollectionTraits( CollectionTraitOptions.None, allowNonCollectionEnumerableTypes: false ); switch ( traits.CollectionType ) { case CollectionKind.Array: { if ( !table.Member.Exists && !table.CollectionItem.Exists ) { SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have own nor items schema: {1}", member, defaultSchema ); return defaultSchema; } SerializerDebugging.TracePolimorphicSchemaEvent( "Returns collection schema for '{0}': {1}", member, defaultSchema ); return new PolymorphismSchema( member.GetMemberValueType(), table.Member.PolymorphismType, table.Member.CodeTypeMapping, table.Member.TypeVerifier, PolymorphismSchemaChildrenType.CollectionItems, new PolymorphismSchema( traits.ElementType, table.CollectionItem.PolymorphismType, table.CollectionItem.CodeTypeMapping, table.CollectionItem.TypeVerifier, PolymorphismSchemaChildrenType.None ) ); } case CollectionKind.Map: { if ( !table.Member.Exists && !table.DictionaryKey.Exists && !table.CollectionItem.Exists ) { SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have own, keys, nor items schema: {1}", member, defaultSchema ); return defaultSchema; } SerializerDebugging.TracePolimorphicSchemaEvent( "Returns dictionary schema for '{0}': {1}", member, defaultSchema ); return new PolymorphismSchema( member.GetMemberValueType(), table.Member.PolymorphismType, table.Member.CodeTypeMapping, table.Member.TypeVerifier, PolymorphismSchemaChildrenType.DictionaryKeyValues, new PolymorphismSchema( traits.ElementType.GetGenericArguments()[ 0 ], table.DictionaryKey.PolymorphismType, table.DictionaryKey.CodeTypeMapping, table.DictionaryKey.TypeVerifier, PolymorphismSchemaChildrenType.None ), new PolymorphismSchema( traits.ElementType.GetGenericArguments()[ 1 ], table.CollectionItem.PolymorphismType, table.CollectionItem.CodeTypeMapping, table.CollectionItem.TypeVerifier, PolymorphismSchemaChildrenType.None ) ); } default: { #if !NET35 && !UNITY if ( TupleItems.IsTuple( member.GetMemberValueType() ) ) { if ( table.TupleItems.Count == 0 ) { SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have any tuple items schema: {1}", member, defaultSchema ); return defaultSchema; } var tupleItemTypes = TupleItems.GetTupleItemTypes( member.GetMemberValueType() ); SerializerDebugging.TracePolimorphicSchemaEvent( "Returns tuple items schema for '{0}': {1}", member, defaultSchema ); return new PolymorphismSchema( member.GetMemberValueType(), PolymorphismType.None, EmptyMap, DefaultTypeVerfiier, PolymorphismSchemaChildrenType.TupleItems, table.TupleItems .Zip( tupleItemTypes, ( e, t ) => new { Entry = e, ItemType = t } ) .Select( e => new PolymorphismSchema( e.ItemType, e.Entry.PolymorphismType, e.Entry.CodeTypeMapping, e.Entry.TypeVerifier, PolymorphismSchemaChildrenType.None ) ).ToArray() ); } else #endif // !NET35 && !UNITY { if ( !table.Member.Exists ) { SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have own schema: {1}", member, defaultSchema ); return defaultSchema; } SerializerDebugging.TracePolimorphicSchemaEvent( "Returns type of member schema for '{0}'.", member, defaultSchema ); return new PolymorphismSchema( member.GetMemberValueType(), table.Member.PolymorphismType, table.Member.CodeTypeMapping, table.Member.TypeVerifier, PolymorphismSchemaChildrenType.None ); } } } } private struct TypeTable { public readonly TypeTableEntry Member; public readonly TypeTableEntry CollectionItem; public readonly TypeTableEntry DictionaryKey; #if !NET35 && !UNITY public readonly IList<TypeTableEntry> TupleItems; #endif // !NET35 && !UNITY private TypeTable( TypeTableEntry member, TypeTableEntry collectionItem, TypeTableEntry dictionaryKey #if !NET35 && !UNITY , IList<TypeTableEntry> tupleItems #endif // !NET35 && !UNITY ) { this.Member = member; this.CollectionItem = collectionItem; this.DictionaryKey = dictionaryKey; #if !NET35 && !UNITY this.TupleItems = tupleItems; #endif // !NET35 && !UNITY } public static TypeTable Create( MemberInfo member, PolymorphismSchema defaultSchema ) { return new TypeTable( TypeTableEntry.Create( member, PolymorphismTarget.Member, defaultSchema ), TypeTableEntry.Create( member, PolymorphismTarget.CollectionItem, defaultSchema.TryGetItemSchema() ), TypeTableEntry.Create( member, PolymorphismTarget.DictionaryKey, defaultSchema.TryGetKeySchema() ) #if !NET35 && !UNITY , TypeTableEntry.CreateTupleItems( member ) #endif // !NET35 && !UNITY ); } } private sealed class TypeTableEntry { #if !NET35 && !UNITY private static readonly TypeTableEntry[] EmptyEntries = new TypeTableEntry[ 0 ]; #endif // !NET35 && !UNITY private readonly Dictionary<string, Type> _knownTypeMapping = new Dictionary<string, Type>(); public IDictionary<string, Type> CodeTypeMapping { get { return this._knownTypeMapping; } } private bool _useTypeEmbedding; public PolymorphismType PolymorphismType { get { return this._useTypeEmbedding ? PolymorphismType.RuntimeType : this._knownTypeMapping.Count > 0 ? PolymorphismType.KnownTypes : PolymorphismType.None; } } public bool Exists { get { return this._useTypeEmbedding || this._knownTypeMapping.Count > 0; } } public Func<PolymorphicTypeVerificationContext, bool> TypeVerifier { get; private set; } private TypeTableEntry() { } public static TypeTableEntry Create( MemberInfo member, PolymorphismTarget targetType, PolymorphismSchema defaultSchema ) { var result = new TypeTableEntry(); var memberName = member.ToString(); foreach ( var attribute in member.GetCustomAttributes( false ) .OfType<IPolymorphicHelperAttribute>() .Where( a => a.Target == targetType ) ) { // TupleItem schema should never come here, so passing -1 as tupleItemNumber is OK. result.Interpret( attribute, memberName, -1 ); } if ( defaultSchema != null ) { // TupleItem schema should never come here, so passing -1 as tupleItemNumber is OK. result.SetDefault( targetType, memberName, -1, defaultSchema ); } return result; } #if !NET35 && !UNITY public static TypeTableEntry[] CreateTupleItems( MemberInfo member ) { if ( !TupleItems.IsTuple( member.GetMemberValueType() ) ) { return EmptyEntries; } var tupleItems = TupleItems.GetTupleItemTypes( member.GetMemberValueType() ); var result = tupleItems.Select( _ => new TypeTableEntry() ).ToArray(); foreach ( var attribute in member.GetCustomAttributes( false ) .OfType<IPolymorphicTupleItemTypeAttribute>() .OrderBy( a => a.ItemNumber ) ) { result[ attribute.ItemNumber - 1 ].Interpret( attribute, member.ToString(), attribute.ItemNumber ); } return result; } #endif // !NET35 && !UNITY private void Interpret( IPolymorphicHelperAttribute attribute, string memberName, int tupleItemNumber ) { var asKnown = attribute as IPolymorphicKnownTypeAttribute; if ( asKnown != null ) { this.SetKnownType( attribute.Target, memberName, tupleItemNumber, asKnown.TypeCode, asKnown.BindingType ); return; } #if DEBUG Contract.Assert( attribute is IPolymorphicRuntimeTypeAttribute, attribute + " is IPolymorphicRuntimeTypeAttribute" ); #endif // DEBUG if ( this._useTypeEmbedding ) { #if DEBUG Contract.Assert( attribute.Target == PolymorphismTarget.TupleItem, attribute.Target + " == PolymorphismTarget.TupleItem" ); #endif // DEBUG throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot specify multiple '{0}' to #{1} item of tuple type member '{2}'.", typeof( MessagePackRuntimeTupleItemTypeAttribute ), tupleItemNumber, memberName ) ); } this.SetRuntimeType( attribute.Target, memberName, tupleItemNumber, GetVerifier( attribute as IPolymorphicRuntimeTypeAttribute ) ); } private void SetDefault( PolymorphismTarget target, string memberName, int tupleItemNumber, PolymorphismSchema defaultSchema ) { if ( this._useTypeEmbedding || this._knownTypeMapping.Count > 0 ) { // Default is not required. return; } switch ( defaultSchema.PolymorphismType ) { case PolymorphismType.KnownTypes: { foreach ( var typeMapping in defaultSchema.CodeTypeMapping ) { this.SetKnownType( target, memberName, tupleItemNumber, typeMapping.Key, typeMapping.Value ); } break; } case PolymorphismType.RuntimeType: { this.SetRuntimeType( target, memberName, tupleItemNumber, defaultSchema.TypeVerifier ); break; } } } private void SetKnownType( PolymorphismTarget target, string memberName, int tupleItemNumber, string typeCode, Type bindingType ) { if ( this._useTypeEmbedding ) { throw new SerializationException( GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( target, memberName, tupleItemNumber ) ); } try { this._knownTypeMapping.Add( typeCode, bindingType ); this.TypeVerifier = DefaultTypeVerfiier; } catch ( ArgumentException ) { throw new SerializationException( GetCannotDuplicateKnownTypeCodeErrorMessage( target, typeCode, memberName, tupleItemNumber ) ); } } private void SetRuntimeType( PolymorphismTarget target, string memberName, int tupleItemNumber, Func<PolymorphicTypeVerificationContext, bool> typeVerifier ) { if ( this._knownTypeMapping.Count > 0 ) { throw new SerializationException( GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( target, memberName, tupleItemNumber ) ); } this.TypeVerifier = typeVerifier; this._useTypeEmbedding = true; } private static string GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( PolymorphismTarget target, string memberName, int? tupleItemNumber ) { switch ( target ) { case PolymorphismTarget.CollectionItem: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify '{0}' and '{1}' simultaneously to collection items of member '{2}' itself.", typeof( MessagePackRuntimeCollectionItemTypeAttribute ), typeof( MessagePackKnownCollectionItemTypeAttribute ), memberName ); } case PolymorphismTarget.DictionaryKey: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify '{0}' and '{1}' simultaneously to dictionary keys of member '{2}' itself.", typeof( MessagePackRuntimeDictionaryKeyTypeAttribute ), typeof( MessagePackKnownDictionaryKeyTypeAttribute ), memberName ); } case PolymorphismTarget.TupleItem: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify '{0}' and '{1}' simultaneously to #{2} item of tuple type member '{3}' itself.", typeof( MessagePackRuntimeTupleItemTypeAttribute ), typeof( MessagePackKnownTupleItemTypeAttribute ), tupleItemNumber, memberName ); } default: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify '{0}' and '{1}' simultaneously to member '{2}' itself.", typeof( MessagePackRuntimeTypeAttribute ), typeof( MessagePackKnownTypeAttribute ), memberName ); } } } private static string GetCannotDuplicateKnownTypeCodeErrorMessage( PolymorphismTarget target, string typeCode, string memberName, int tupleItemNumber ) { switch ( target ) { case PolymorphismTarget.CollectionItem: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify multiple types for ext-type code '{0}' for collection items of member '{1}'.", StringEscape.ForDisplay( typeCode ), memberName ); } case PolymorphismTarget.DictionaryKey: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify multiple types for ext-type code '{0}' for dictionary keys of member '{1}'.", StringEscape.ForDisplay( typeCode ), memberName ); } case PolymorphismTarget.TupleItem: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify multiple types for ext-type code '{0}' for #{1} item of tuple type member '{2}'.", StringEscape.ForDisplay( typeCode ), tupleItemNumber, memberName ); } default: { return String.Format( CultureInfo.CurrentCulture, "Cannot specify multiple types for ext-type code '{0}' for member '{1}'.", StringEscape.ForDisplay( typeCode ), memberName ); } } } private static Func<PolymorphicTypeVerificationContext, bool> GetVerifier( IPolymorphicRuntimeTypeAttribute attribute ) { if ( attribute.VerifierType == null ) { // Use default. return DefaultTypeVerfiier; } if ( String.IsNullOrEmpty( attribute.VerifierMethodName ) ) { throw new SerializationException( "VerifierMethodName cannot be null nor empty if VerifierType is specified." ); } // Explore [static] bool X(PolymorphicTypeVerificationContext) var method = attribute.VerifierType.GetRuntimeMethods().SingleOrDefault( m => IsVerificationMethod( m, attribute.VerifierMethodName ) ); if ( method == null ) { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "A public static or instance method named '{0}' with single parameter typed PolymorphicTypeVerificationContext in type '{1}'.", attribute.VerifierMethodName, attribute.VerifierMethodName ) ); } if ( method.IsStatic ) { return method.CreateDelegate( typeof( Func<PolymorphicTypeVerificationContext, bool> ) ) as Func<PolymorphicTypeVerificationContext, bool>; } else { return method.CreateDelegate( typeof( Func<PolymorphicTypeVerificationContext, bool> ), Activator.CreateInstance( attribute.VerifierType ) ) as Func<PolymorphicTypeVerificationContext, bool>; } } private static bool IsVerificationMethod( MethodInfo method, string name ) { if ( method.ReturnType != typeof( bool ) ) { return false; } if ( method.Name != name ) { return false; } var parameters = method.GetParameters(); return parameters.Length == 1 && parameters[ 0 ].ParameterType.IsAssignableFrom( typeof( PolymorphicTypeVerificationContext ) ); } } } }
// // Migrator.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2006-2007 Gabriel Burt // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Hyena.Data.Sqlite; using Banshee.Collection.Database; using Banshee.ServiceStack; using Banshee.Query; namespace Banshee.SmartPlaylist { internal class Migrator { private string [] criteria = new string [] { "songs", "minutes", "hours", "MB" }; private Dictionary<string, QueryOrder> order_hash = new Dictionary<string, QueryOrder> (); public static bool MigrateAll () { int version = ServiceManager.DbConnection.Query<int> ("SELECT Value FROM CoreConfiguration WHERE Key = 'SmartPlaylistVersion'"); if (version == 1) return true; try { ServiceManager.DbConnection.Execute ("BEGIN"); Migrator m = new Migrator (); using (IDataReader reader = ServiceManager.DbConnection.Query ( "SELECT SmartPlaylistID, Name, Condition, OrderBy, LimitNumber, LimitCriterion FROM CoreSmartPlaylists")) { while (reader.Read ()) { m.Migrate ( Convert.ToInt32 (reader[0]), reader[1] as string, reader[2] as string, reader[3] as string, reader[4] as string, reader[5] as string ); } } ServiceManager.DbConnection.Execute ("INSERT INTO CoreConfiguration (Key, Value) Values ('SmartPlaylistVersion', 1)"); ServiceManager.DbConnection.Execute ("COMMIT"); return true; } catch (Exception e) { ServiceManager.DbConnection.Execute ("ROLLBACK"); Log.Error ( Catalog.GetString ("Unable to Migrate Smart Playlists"), String.Format (Catalog.GetString ("Please file a bug with this error: {0}"), e.ToString ()), true ); return false; } } public Migrator () { order_hash.Add ("RANDOM()", BansheeQuery.FindOrder ("Random", true)); order_hash.Add ("AlbumTitle", BansheeQuery.FindOrder ("Album", true)); order_hash.Add ("Artist", BansheeQuery.FindOrder ("Artist", true)); order_hash.Add ("Genre", BansheeQuery.FindOrder ("Genre", true)); order_hash.Add ("Title", BansheeQuery.FindOrder ("Title", true)); order_hash.Add ("Rating DESC", BansheeQuery.FindOrder ("Rating", false)); order_hash.Add ("Rating ASC", BansheeQuery.FindOrder ("Rating", true)); order_hash.Add ("Score DESC", BansheeQuery.FindOrder ("Score", false)); order_hash.Add ("Score ASC", BansheeQuery.FindOrder ("Score", true)); order_hash.Add ("NumberOfPlays DESC", BansheeQuery.FindOrder ("PlayCount", false)); order_hash.Add ("NumberOfPlays ASC", BansheeQuery.FindOrder ("PlayCount", true)); order_hash.Add ("DateAddedStamp DESC", BansheeQuery.FindOrder ("DateAddedStamp", false)); order_hash.Add ("DateAddedStamp ASC", BansheeQuery.FindOrder ("DateAddedStamp", true)); order_hash.Add ("LastPlayedStamp DESC", BansheeQuery.FindOrder ("LastPlayedStamp", false)); order_hash.Add ("LastPlayedStamp ASC", BansheeQuery.FindOrder ("LastPlayedStamp", true)); } private void Migrate (int dbid, string Name, string Condition, string OrderBy, string LimitNumber, string LimitCriterion) { if (OrderBy != null && OrderBy != String.Empty) { QueryOrder order = order_hash [OrderBy]; OrderBy = order.Name; } LimitCriterion = criteria [Convert.ToInt32 (LimitCriterion)]; string ConditionXml = ParseCondition (Condition); ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@" UPDATE CoreSmartPlaylists SET Name = ?, Condition = ?, OrderBy = ?, LimitNumber = ?, LimitCriterion = ? WHERE SmartPlaylistID = ?", Name, ConditionXml, OrderBy, LimitNumber, LimitCriterion, dbid )); Log.Debug (String.Format ("Migrated Smart Playlist {0}", Name)); } private string ParseCondition (string value) { if (String.IsNullOrEmpty (value)) return null; // Check for ANDs or ORs and split into conditions as needed string [] conditions; bool ands = true; if (value.IndexOf(") AND (") != -1) { ands = true; conditions = System.Text.RegularExpressions.Regex.Split (value, "\\) AND \\("); } else if (value.IndexOf(") OR (") != -1) { ands = false; conditions = System.Text.RegularExpressions.Regex.Split (value, "\\) OR \\("); } else { conditions = new string [] {value}; } QueryListNode root = new QueryListNode (ands ? Keyword.And : Keyword.Or); // Remove leading spaces and parens from the first condition conditions[0] = conditions[0].Remove(0, 2); // Remove trailing spaces and last paren from the last condition string tmp = conditions[conditions.Length-1]; tmp = tmp.TrimEnd(new char[] {' '}); tmp = tmp.Substring(0, tmp.Length - 1); conditions[conditions.Length-1] = tmp; int count = 0; foreach (string condition in conditions) { // Add a new row for this condition string col, v1, v2; foreach (QueryOperator op in QueryOperator.Operators) { if (op.MatchesCondition (condition, out col, out v1, out v2)) { QueryTermNode term = new QueryTermNode (); QueryField field = BansheeQuery.FieldSet [col]; bool is_relative_date = false; if (field == null) { if (col.IndexOf ("DateAddedStamp") != -1) { field = BansheeQuery.FieldSet ["added"]; } else if (col.IndexOf ("LastPlayedStamp") != -1) { field = BansheeQuery.FieldSet ["lastplayed"]; } // Fix ugly implementation of playlist/smart playlist conditions if (op == QueryOperator.InPlaylist || op == QueryOperator.NotInPlaylist) { field = BansheeQuery.FieldSet ["playlist"]; } else if (op == QueryOperator.InSmartPlaylist || op == QueryOperator.NotInSmartPlaylist) { field = BansheeQuery.FieldSet ["smartplaylist"]; } if (field == null) { continue; } is_relative_date = true; } term.Field = field; if (op == QueryOperator.Between) { QueryListNode and = new QueryListNode (Keyword.And); QueryTermNode t2 = new QueryTermNode (); t2.Field = term.Field; if (is_relative_date) { ParseRelativeDateCondition (term, v1, field, ">="); ParseRelativeDateCondition (t2, v2, field, "<="); } else { term.Value = QueryValue.CreateFromUserQuery (v1, field); term.Operator = term.Value.OperatorSet ["<="]; t2.Value = QueryValue.CreateFromUserQuery (v2, field); t2.Operator = t2.Value.OperatorSet [">="]; } and.AddChild (term); and.AddChild (t2); root.AddChild (and); } else if (is_relative_date) { ParseRelativeDateCondition (term, v1, field, op.NewOp); root.AddChild (term); } else { term.Value = QueryValue.CreateFromUserQuery (v1, field); term.Operator = term.Value.OperatorSet [op.NewOp]; root.AddChild (term); } break; } } count++; } QueryNode node = root.Trim (); if (node != null) { //Console.WriteLine ("After XML: {0}", node.ToXml (BansheeQuery.FieldSet, true)); //Console.WriteLine ("After SQL: {0}", node.ToSql (BansheeQuery.FieldSet)); } return node == null ? String.Empty : node.ToXml (BansheeQuery.FieldSet); } private void ParseRelativeDateCondition (QueryTermNode term, string val, QueryField field, string op) { string new_op = op.Replace ('>', '^'); new_op = new_op.Replace ('<', '>'); new_op = new_op.Replace ('^', '<'); RelativeTimeSpanQueryValue date_value = new RelativeTimeSpanQueryValue (); // Have to flip the operator b/c of how we used to construct the SQL query term.Operator = date_value.OperatorSet [new_op]; // Have to negate the value b/c of how we used to constuct the SQL query date_value.SetRelativeValue (Convert.ToInt64 (val), TimeFactor.Second); term.Value = date_value; } public sealed class QueryOperator { public string NewOp; private string format; public string Format { get { return format; } } private QueryOperator (string new_op, string format) { NewOp = new_op; this.format = format; } public string FormatValues (bool text, string column, string value1, string value2) { if (text) return String.Format (format, "'", column, value1, value2); else return String.Format (format, "", column, value1, value2); } public bool MatchesCondition (string condition, out string column, out string value1, out string value2) { // Remove trailing parens from the end of the format b/c trailing parens are trimmed from the condition string regex = String.Format(format.Replace("(", "\\(").Replace(")", "\\)"), "'?", // ignore the single quotes if they exist "(.*)", // match the column "(.*)", // match the first value "(.*)" // match the second value ); //Console.WriteLine ("regex = {0}", regex); MatchCollection mc = System.Text.RegularExpressions.Regex.Matches (condition, regex); if (mc != null && mc.Count > 0 && mc[0].Groups.Count > 0) { column = mc[0].Groups[1].Captures[0].Value; value1 = mc[0].Groups[2].Captures[0].Value.Trim(new char[] {'\''}); if (mc[0].Groups.Count == 4) value2 = mc[0].Groups[3].Captures[0].Value.Trim(new char[] {'\''}); else value2 = null; return true; } else { column = value1 = value2 = null; return false; } } // calling lower() to have case insensitive comparisons with strings public static QueryOperator EQText = new QueryOperator("==", "lower({1}) = {0}{2}{0}"); public static QueryOperator NotEQText = new QueryOperator("!=", "lower({1}) != {0}{2}{0}"); public static QueryOperator EQ = new QueryOperator("==", "{1} = {0}{2}{0}"); public static QueryOperator NotEQ = new QueryOperator("!=", "{1} != {0}{2}{0}"); // TODO how to deal w/ between? public static QueryOperator Between = new QueryOperator("", "{1} BETWEEN {0}{2}{0} AND {0}{3}{0}"); public static QueryOperator LT = new QueryOperator("<", "{1} < {0}{2}{0}"); public static QueryOperator GT = new QueryOperator(">", "{1} > {0}{2}{0}"); public static QueryOperator GTE = new QueryOperator(">=", "{1} >= {0}{2}{0}"); // Note, the following lower() calls are necessary b/c of a sqlite bug which makes the LIKE // command case sensitive with certain characters. public static QueryOperator Like = new QueryOperator(":", "lower({1}) LIKE '%{2}%'"); public static QueryOperator NotLike = new QueryOperator("!:", "lower({1}) NOT LIKE '%{2}%'"); public static QueryOperator StartsWith = new QueryOperator("=", "lower({1}) LIKE '{2}%'"); public static QueryOperator EndsWith = new QueryOperator(":=", "lower({1}) LIKE '%{2}'"); // TODO these should either be made generic or moved somewhere else since they are Banshee/Track/Playlist specific. public static QueryOperator InPlaylist = new QueryOperator("==", "TrackID IN (SELECT TrackID FROM PlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator NotInPlaylist = new QueryOperator("!=", "TrackID NOT IN (SELECT TrackID FROM PlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator InSmartPlaylist = new QueryOperator("==", "TrackID IN (SELECT TrackID FROM SmartPlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator NotInSmartPlaylist = new QueryOperator("!=", "TrackID NOT IN (SELECT TrackID FROM SmartPlaylistEntries WHERE {1} = {0}{2}{0})"); public static QueryOperator [] Operators = new QueryOperator [] { EQText, NotEQText, EQ, NotEQ, Between, LT, GT, GTE, Like, NotLike, StartsWith, InPlaylist, NotInPlaylist, InSmartPlaylist, NotInSmartPlaylist }; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using DatenMeister.Core.EMOF.Interface.Common; using DatenMeister.Core.EMOF.Interface.Identifiers; using DatenMeister.Core.EMOF.Interface.Reflection; using DatenMeister.Core.Helper; using DatenMeister.Core.Provider; namespace DatenMeister.Core.EMOF.Implementation { /// <summary> /// Implements a reflective sequence as given by the MOF specification. /// The sequence needs to be correlated to a Mof Object /// </summary> public class MofReflectiveSequence : IReflectiveSequence, IHasExtent { /// <summary> /// Gets the name of the property /// </summary> internal string PropertyName { get; } /// <summary> /// Gets the mof object being assigned to the /// </summary> internal MofObject MofObject { get; } /// <summary> /// Gets or sets a flag indicating whether references shall be followed or not /// </summary> public bool NoReferences { get; set; } public MofReflectiveSequence(MofObject mofObject, string property) { MofObject = mofObject; PropertyName = property; } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <inheritdoc /> public IEnumerator<object> GetEnumerator() => Enumerate().GetEnumerator(); /// <summary> /// Performs an enumeration of all members of the collection /// </summary> /// <param name="noReferences">true, if UriReferences shall be resolved</param> /// <returns>Enumeration of collection</returns> internal IEnumerable<object> Enumerate(bool noReferences = false) { var result = GetPropertyAsEnumerable(); foreach (var item in result) { var convertedObject = MofObject.ConvertToMofObject(MofObject, PropertyName, item, noReferences || NoReferences); if (convertedObject != null) { yield return convertedObject; } } } /// <summary> /// Gets the given property as an enumerable /// </summary> /// <returns>Enumerable which was retrieved</returns> private IEnumerable<object> GetPropertyAsEnumerable() { if (MofObject.ProviderObject.IsPropertySet(PropertyName)) { var value = MofObject.ProviderObject.GetProperty(PropertyName); return value switch { IEnumerable<object> asEnumerable => asEnumerable, null => new object[] { }, _ => new[] {value} }; } return Array.Empty<object>(); } /// <inheritdoc /> public bool add(object? value) { var valueToBeAdded = MofExtent.ConvertForSetting(MofObject, value); if (valueToBeAdded != null) { var result = MofObject.ProviderObject.AddToProperty(PropertyName, valueToBeAdded); MofObject.SetContainer(MofObject.ProviderObject, valueToBeAdded); UpdateContent(); return result; } return false; } /// <inheritdoc /> public bool addAll(IReflectiveSequence value) { bool? result = null; foreach (var element in value) { if (element == null) continue; if (result == null) { result = add(element); } else { result |= add(element); } } return result == true; } /// <inheritdoc /> public void clear() { // Performs now the final deletion MofObject.ProviderObject.EmptyListForProperty(PropertyName); UpdateContent(); } /// <inheritdoc /> public bool remove(object? value) { if (value == null) return false; bool result; if (value is MofElement valueAsMofObject) { object asProviderObject; if (valueAsMofObject.ReferencedExtent != MofObject.ReferencedExtent) { asProviderObject = new UriReference( valueAsMofObject.GetUriExtentOf()?.uri(valueAsMofObject) ?? throw new InvalidOperationException( "Given uri is not known")); } else { asProviderObject = valueAsMofObject.ProviderObject; } result = MofObject.ProviderObject.RemoveFromProperty(PropertyName, asProviderObject); } else { result = MofObject.ProviderObject.RemoveFromProperty(PropertyName, value); } UpdateContent(); return result; } /// <inheritdoc /> public int size() => GetPropertyAsEnumerable().Count(); /// <inheritdoc /> public void add(int index, object value) { if (value == null) return; // null will never be added var valueToBeAdded = MofExtent.ConvertForSetting(MofObject, value); if (valueToBeAdded == null) return; MofObject.ProviderObject.AddToProperty(PropertyName, valueToBeAdded, index); UpdateContent(); } /// <inheritdoc /> public object get(int index) { var providerObject = GetPropertyAsEnumerable().ElementAt(index); return MofObject.ConvertToMofObject(MofObject, PropertyName, providerObject) ?? string.Empty; } /// <inheritdoc /> public void remove(int index) { var value = MofObject.ProviderObject.GetProperty(PropertyName) as IEnumerable<object>; var foundValue = value?.ElementAt(index); if (foundValue != null) { MofObject.ProviderObject.RemoveFromProperty( PropertyName, foundValue); UpdateContent(); } } /// <inheritdoc /> public object? set(int index, object value) { var valueToBeRemoved = GetPropertyAsEnumerable().ElementAt(index); MofObject.ProviderObject.RemoveFromProperty(PropertyName, valueToBeRemoved); add(index, value); var result = MofObject.ConvertToMofObject(MofObject, PropertyName, valueToBeRemoved); MofObject.Extent?.ChangeEventManager?.SendChangeEvent(MofObject); return result; } /// <inheritdoc /> public IExtent Extent => MofObject.Extent ?? MofObject.ReferencedExtent; /// <summary> /// Updates the content /// </summary> public void UpdateContent() { MofObject.Extent?.ChangeEventManager?.SendChangeEvent(MofObject); MofObject.Extent?.SignalUpdateOfContent(); } } }
using Xunit; namespace Jint.Tests.Ecma { [Trait("Category","Pass")] public class Test_11_4_1 : EcmaTest { [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-0-1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingANonReferenceNumber() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-2-1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingReturnedValueFromAFunction() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-2-2.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingANonReferenceBoolean() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-2-3.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingANonReferenceString() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-2-4.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingANonReferenceObj() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-2-5.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingANonReferenceNull() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-2-6.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingAnUnresolvableReference() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-3-1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorThrowsReferenceerrorWhenDeletingAnExplicitlyQualifiedYetUnresolvableReferenceBaseObjUndefined() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-3-2.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsTrueWhenDeletingAnExplicitlyQualifiedYetUnresolvableReferencePropertyUndefinedForBaseObj() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-3-3.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAnUnResolvableReference() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-3-a-1-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeTypeerrorIsThrownWhenDeletingNonConfigurableDataProperty() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4-a-1-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeTypeerrorIsThrownWhenDeletingNonConfigurableAccessorProperty() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4-a-2-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeTypeerrorIsnTThrownWhenDeletingConfigurableDataProperty() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4-a-3-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeTypeerrorIsnTThrownWhenDeletingConfigurableAccessorProperty() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4-a-4-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere2() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere3() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-10.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere4() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-11.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere5() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-12.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere6() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-13.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere7() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-14.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere8() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-15.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere9() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-16.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere10() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-17.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere11() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-2.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere12() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-3-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere13() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-3.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere14() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-4.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere15() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-5.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere16() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-6.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere17() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-7.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere18() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-8-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere19() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-8.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere20() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-9-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void ThisTestIsActuallyTestingTheDeleteInternalMethod8128SinceTheLanguageProvidesNoWayToDirectlyExerciseDeleteTheTestsArePlacedHere21() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-4.a-9.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsFalseWhenDeletingADirectReferenceToAVar() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsFalseWhenDeletingADirectReferenceToAFunctionArgument() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-2.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorReturnsFalseWhenDeletingADirectReferenceToAFunctionName() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-3.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableWhichIsAPrimitiveValueTypeNumber() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-1-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeArray() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-10-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeString() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-11-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeBoolean() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-12-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeNumber() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-13-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeDate() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-14-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeRegexp() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-15-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeError() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-16-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeArguments() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-17-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInObject() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-18-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInFunction() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-19-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAFunctionParameter() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-2-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInArray() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-20-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInString() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-21-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInBoolean() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-22-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInNumber() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-23-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInDate() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-24-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInRegexp() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-25-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingABuiltInError() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-26-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeTypeerrorIsThrownAfterDeletingAPropertyCallingPreventextensionsAndAttemptingToReassignTheProperty() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-27-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeTypeerrorIsThrownWhenDeletingRegexpLength() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-28-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAFunctionName() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-3-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAFunctionParameter2() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-4-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableWhichIsAPrimitiveTypeBoolean() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-5-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableWhichIsPrimitiveTypeBoolean() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-5gs.js", true); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableWhichIsAPrimitiveTypeString() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-6-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeObject() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-7-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAFunctionObject() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-8-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void StrictModeSyntaxerrorIsThrownWhenDeletingAVariableOfTypeFunctionDeclaration() { RunTest(@"TestCases/ch11/11.4/11.4.1/11.4.1-5-a-9-s.js", false); } [Fact] [Trait("Category", "11.4.1")] public void WhiteSpaceAndLineTerminatorBetweenDeleteAndUnaryexpressionAreAllowed() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void IfTypeXIsNotReferenceReturnTrue() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A2.1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void IfGetbaseXDoesnTHaveAPropertyGetpropertynameXReturnTrue() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A2.2_T1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void IfGetbaseXDoesnTHaveAPropertyGetpropertynameXReturnTrue2() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A2.2_T2.js", false); } [Fact] [Trait("Category", "11.4.1")] public void IfThePropertyHasTheDontdeleteAttributeReturnFalse() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A3.1.js", false); } [Fact] [Trait("Category", "11.4.1")] public void IfThePropertyDoesnTHaveTheDontdeleteAttributeReturnTrue() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A3.2.js", false); } [Fact] [Trait("Category", "11.4.1")] public void IfThePropertyDoesnTHaveTheDontdeleteAttributeRemoveTheProperty() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A3.3.js", false); } [Fact] [Trait("Category", "11.4.1")] public void DeleteOperatorRemovesPropertyWhichIsReferenceToTheObjectNotTheObject() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A4.js", false); } [Fact] [Trait("Category", "11.4.1")] public void AStrictDeleteShouldEitherSucceedReturningTrueOrItShouldFailByThrowingATypeerrorUnderNoCircumstancesShouldAStrictDeleteReturnFalse() { RunTest(@"TestCases/ch11/11.4/11.4.1/S11.4.1_A5.js", false); } } }
////////////////////////////////////////////////////////////////////////////////////// // Author : Shukri Adams // // Contact : shukri.adams@gmail.com // // // // vcFramework : A reuseable library of utility classes // // Copyright (C) // ////////////////////////////////////////////////////////////////////////////////////// using System; using vcFramework.Parsers; using vcFramework.Text; namespace vcFramework.Arrays { /// <summary> Summary description for ArrayHelper. </summary> public class StringArrayLib { /// <summary> Compares to string arrays </summary> /// <param name="arrFirst"></param> /// <param name="arrSecond"></param> /// <returns></returns> public static bool AreEqual( string[] arrFirst, string[] arrSecond, bool blnIgnoreOrder ) { // TODO ! blnIgnoreOrder is not emplemented yet // null test if (arrFirst == null && arrSecond == null) return true; // length test if (arrFirst.Length != arrSecond.Length) return false; // member test bool blnMemberTest = false; if (blnIgnoreOrder) { // in this test, only the contents of the two arrays // are compared, not the order. therefore each // item of one array will be compared with each item // of the other array, and only after if no match // for one can be found in another, will the test fail // Note that the blnMemberTest assignments are opposite // to those used in the !blnIgnoreOrder test further on. for (int i = 0 ; i < arrFirst.Length ; i ++) { // default - must be set for each i item blnMemberTest = true; for (int j = 0 ; j < arrSecond.Length ; j ++) { if (arrFirst[i] == arrSecond[j]) { // if reach here, test passed for the i-j combo blnMemberTest= false; break; } } // tests the results of i-j combo test if (blnMemberTest) break; } } else { // in this test, the content and content order // of both arrays must be identical. if any // discrepency is found, the test is aborted // and the result is failure // default blnMemberTest = false; for (int i = 0 ; i < arrFirst.Length ; i ++) { if (arrFirst[i] != arrSecond[i]) { // if reach here, test must fail - abort blnMemberTest= true; break; } } } if (blnMemberTest) return false; return true; } /// <summary> /// "Removes" all String.Empty and zero length strings from an array. /// </summary> /// <param name="input"></param> /// <returns></returns> public static string[] RemoveEmptyStrings( string[] input ) { string[] output = null; int outputSize = 0; for (int i = 0 ; i < input.Length ; i ++) if (input[i] != String.Empty && input[i] != "") outputSize ++; output = new string[outputSize]; int j = 0; for (int i = 0 ; i < input.Length ; i ++) if (input[i] != String.Empty && input[i] != "") { output[j] = input[i]; j++; } return output; } /// <summary> Returns a string array's contents as a /// single concatenated string </summary> /// <param name="arrStrItems"></param> /// <returns></returns> public static string ConcatStringArrayContents( string[] arrStrItems, string strDelimiter ) { string strOutput = ""; if (arrStrItems.Length == 0) return ""; for (int i = 0 ; i < arrStrItems.Length ; i ++) strOutput += arrStrItems[i] + strDelimiter; // removes last delimiter from string if (strOutput.Length > strDelimiter.Length) strOutput = ParserLib.ClipFromEnd( strOutput, strDelimiter.Length ); return strOutput; } /// <summary> Returns true if the string array contains /// the specified string </summary> /// <param name="arrStrHolder"></param> /// <param name="strItem"></param> /// <returns></returns> public static bool Contains( string[] arrStrHolder, string strItem ) { if (arrStrHolder == null) return false; for (int i = 0 ; i < arrStrHolder.Length ; i ++) { if (arrStrHolder[i] == strItem) return true; } return false; } /// <summary> Adds a new value to a string array - can /// be inserted in either top or bottom of array </summary> /// <param name="arrStrStrings"></param> /// <param name="strNewValue"></param> /// <param name="arrayPosition"></param> /// <returns></returns> public static string[] AppendString( string[] arrStrStrings, string strNewValue, ArrayPositions arrayPosition ) { string[] arrStrTemp = null; int intOffset = 0; // creates new temporary array, and transfers data from existing array to temp array if necessary if (arrStrStrings == null) arrStrTemp = new string[1]; else { arrStrTemp = new string[arrStrStrings.Length + 1]; // if new value will be inserted at top of array, need to shift all existing // values down one. use offset for this if (arrayPosition == ArrayPositions.Top) intOffset = 1; // copy array contents for (int i = 0 ; i < arrStrStrings.Length ; i ++) arrStrTemp[intOffset + i] = arrStrStrings[i]; } // add new string value at correct position if (arrayPosition == ArrayPositions.Top) arrStrTemp[0] = strNewValue; if (arrayPosition == ArrayPositions.Bottom) arrStrTemp[arrStrTemp.Length - 1] = strNewValue; // return temp array return arrStrTemp; } /// <summary> Implements bubble sort on string array </summary> /// <param name="arrStr"></param> /// <returns></returns> public static string[] SortStringArray( string[] arrStr, bool blnAscending ) { string strTempStringHolder = ""; for (int i = 0 ; i < arrStr.Length ; i ++) { for (int j = 0 ; j < arrStr.Length ; j ++) { if (blnAscending) { if (StringSortLib.IsAfter(arrStr[i], arrStr[j], true)) { strTempStringHolder = arrStr[j]; arrStr[j] = arrStr[i]; arrStr[i] = strTempStringHolder; } } else { if (StringSortLib.IsAfter(arrStr[j], arrStr[i], true)) { strTempStringHolder = arrStr[j]; arrStr[j] = arrStr[i]; arrStr[i] = strTempStringHolder; } } } } return arrStr; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net.Config; using NUnit.Framework; using OpenMetaverse; using OpenMetaverse.Assets; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.CoreModules.World.Land.Tests { [TestFixture] public class PrimCountModuleTests : OpenSimTestCase { protected UUID m_userId = new UUID("00000000-0000-0000-0000-100000000000"); protected UUID m_groupId = new UUID("00000000-0000-0000-8888-000000000000"); protected UUID m_otherUserId = new UUID("99999999-9999-9999-9999-999999999999"); protected TestScene m_scene; protected PrimCountModule m_pcm; /// <summary> /// A parcel that covers the entire sim except for a 1 unit wide strip on the eastern side. /// </summary> protected ILandObject m_lo; /// <summary> /// A parcel that covers just the eastern strip of the sim. /// </summary> protected ILandObject m_lo2; [SetUp] public override void SetUp() { base.SetUp(); m_pcm = new PrimCountModule(); LandManagementModule lmm = new LandManagementModule(); m_scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(m_scene, lmm, m_pcm); int xParcelDivider = (int)Constants.RegionSize - 1; ILandObject lo = new LandObject(m_userId, false, m_scene); lo.LandData.Name = "m_lo"; lo.SetLandBitmap( lo.GetSquareLandBitmap(0, 0, xParcelDivider, (int)Constants.RegionSize)); m_lo = lmm.AddLandObject(lo); ILandObject lo2 = new LandObject(m_userId, false, m_scene); lo2.SetLandBitmap( lo2.GetSquareLandBitmap(xParcelDivider, 0, (int)Constants.RegionSize, (int)Constants.RegionSize)); lo2.LandData.Name = "m_lo2"; m_lo2 = lmm.AddLandObject(lo2); } /// <summary> /// Test that counts before we do anything are correct. /// </summary> [Test] public void TestInitialCounts() { IPrimCounts pc = m_lo.PrimCounts; Assert.That(pc.Owner, Is.EqualTo(0)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(0)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(0)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(0)); } /// <summary> /// Test count after a parcel owner owned object is added. /// </summary> [Test] public void TestAddOwnerObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); IPrimCounts pc = m_lo.PrimCounts; SceneObjectGroup sog = SceneHelpers.CreateSceneObject(3, m_userId, "a", 0x01); m_scene.AddNewSceneObject(sog, false); Assert.That(pc.Owner, Is.EqualTo(3)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(3)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(3)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(3)); // Add a second object and retest SceneObjectGroup sog2 = SceneHelpers.CreateSceneObject(2, m_userId, "b", 0x10); m_scene.AddNewSceneObject(sog2, false); Assert.That(pc.Owner, Is.EqualTo(5)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(5)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(5)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(5)); } /// <summary> /// Test count after a parcel owner owned copied object is added. /// </summary> [Test] public void TestCopyOwnerObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); IPrimCounts pc = m_lo.PrimCounts; SceneObjectGroup sog = SceneHelpers.CreateSceneObject(3, m_userId, "a", 0x01); m_scene.AddNewSceneObject(sog, false); m_scene.SceneGraph.DuplicateObject(sog.LocalId, Vector3.Zero, 0, m_userId, UUID.Zero, Quaternion.Identity); Assert.That(pc.Owner, Is.EqualTo(6)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(6)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(6)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(6)); } /// <summary> /// Test that parcel counts update correctly when an object is moved between parcels, where that movement /// is not done directly by the user/ /// </summary> [Test] public void TestMoveOwnerObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SceneObjectGroup sog = SceneHelpers.CreateSceneObject(3, m_userId, "a", 0x01); m_scene.AddNewSceneObject(sog, false); SceneObjectGroup sog2 = SceneHelpers.CreateSceneObject(2, m_userId, "b", 0x10); m_scene.AddNewSceneObject(sog2, false); // Move the first scene object to the eastern strip parcel sog.AbsolutePosition = new Vector3(254, 2, 2); IPrimCounts pclo1 = m_lo.PrimCounts; Assert.That(pclo1.Owner, Is.EqualTo(2)); Assert.That(pclo1.Group, Is.EqualTo(0)); Assert.That(pclo1.Others, Is.EqualTo(0)); Assert.That(pclo1.Total, Is.EqualTo(2)); Assert.That(pclo1.Selected, Is.EqualTo(0)); Assert.That(pclo1.Users[m_userId], Is.EqualTo(2)); Assert.That(pclo1.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pclo1.Simulator, Is.EqualTo(5)); IPrimCounts pclo2 = m_lo2.PrimCounts; Assert.That(pclo2.Owner, Is.EqualTo(3)); Assert.That(pclo2.Group, Is.EqualTo(0)); Assert.That(pclo2.Others, Is.EqualTo(0)); Assert.That(pclo2.Total, Is.EqualTo(3)); Assert.That(pclo2.Selected, Is.EqualTo(0)); Assert.That(pclo2.Users[m_userId], Is.EqualTo(3)); Assert.That(pclo2.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pclo2.Simulator, Is.EqualTo(5)); // Now move it back again sog.AbsolutePosition = new Vector3(2, 2, 2); Assert.That(pclo1.Owner, Is.EqualTo(5)); Assert.That(pclo1.Group, Is.EqualTo(0)); Assert.That(pclo1.Others, Is.EqualTo(0)); Assert.That(pclo1.Total, Is.EqualTo(5)); Assert.That(pclo1.Selected, Is.EqualTo(0)); Assert.That(pclo1.Users[m_userId], Is.EqualTo(5)); Assert.That(pclo1.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pclo1.Simulator, Is.EqualTo(5)); Assert.That(pclo2.Owner, Is.EqualTo(0)); Assert.That(pclo2.Group, Is.EqualTo(0)); Assert.That(pclo2.Others, Is.EqualTo(0)); Assert.That(pclo2.Total, Is.EqualTo(0)); Assert.That(pclo2.Selected, Is.EqualTo(0)); Assert.That(pclo2.Users[m_userId], Is.EqualTo(0)); Assert.That(pclo2.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pclo2.Simulator, Is.EqualTo(5)); } /// <summary> /// Test count after a parcel owner owned object is removed. /// </summary> [Test] public void TestRemoveOwnerObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); IPrimCounts pc = m_lo.PrimCounts; m_scene.AddNewSceneObject(SceneHelpers.CreateSceneObject(1, m_userId, "a", 0x1), false); SceneObjectGroup sogToDelete = SceneHelpers.CreateSceneObject(3, m_userId, "b", 0x10); m_scene.AddNewSceneObject(sogToDelete, false); m_scene.DeleteSceneObject(sogToDelete, false); Assert.That(pc.Owner, Is.EqualTo(1)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(1)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(1)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(1)); } [Test] public void TestAddGroupObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); m_lo.DeedToGroup(m_groupId); IPrimCounts pc = m_lo.PrimCounts; SceneObjectGroup sog = SceneHelpers.CreateSceneObject(3, m_otherUserId, "a", 0x01); sog.GroupID = m_groupId; m_scene.AddNewSceneObject(sog, false); Assert.That(pc.Owner, Is.EqualTo(0)); Assert.That(pc.Group, Is.EqualTo(3)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(3)); Assert.That(pc.Selected, Is.EqualTo(0)); // Is this desired behaviour? Not totally sure. Assert.That(pc.Users[m_userId], Is.EqualTo(0)); Assert.That(pc.Users[m_groupId], Is.EqualTo(0)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(3)); Assert.That(pc.Simulator, Is.EqualTo(3)); } /// <summary> /// Test count after a parcel owner owned object is removed. /// </summary> [Test] public void TestRemoveGroupObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); m_lo.DeedToGroup(m_groupId); IPrimCounts pc = m_lo.PrimCounts; SceneObjectGroup sogToKeep = SceneHelpers.CreateSceneObject(1, m_userId, "a", 0x1); sogToKeep.GroupID = m_groupId; m_scene.AddNewSceneObject(sogToKeep, false); SceneObjectGroup sogToDelete = SceneHelpers.CreateSceneObject(3, m_userId, "b", 0x10); m_scene.AddNewSceneObject(sogToDelete, false); m_scene.DeleteSceneObject(sogToDelete, false); Assert.That(pc.Owner, Is.EqualTo(0)); Assert.That(pc.Group, Is.EqualTo(1)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(1)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(1)); Assert.That(pc.Users[m_groupId], Is.EqualTo(0)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(1)); } [Test] public void TestAddOthersObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); IPrimCounts pc = m_lo.PrimCounts; SceneObjectGroup sog = SceneHelpers.CreateSceneObject(3, m_otherUserId, "a", 0x01); m_scene.AddNewSceneObject(sog, false); Assert.That(pc.Owner, Is.EqualTo(0)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(3)); Assert.That(pc.Total, Is.EqualTo(3)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(0)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(3)); Assert.That(pc.Simulator, Is.EqualTo(3)); } [Test] public void TestRemoveOthersObject() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); IPrimCounts pc = m_lo.PrimCounts; m_scene.AddNewSceneObject(SceneHelpers.CreateSceneObject(1, m_otherUserId, "a", 0x1), false); SceneObjectGroup sogToDelete = SceneHelpers.CreateSceneObject(3, m_otherUserId, "b", 0x10); m_scene.AddNewSceneObject(sogToDelete, false); m_scene.DeleteSceneObject(sogToDelete, false); Assert.That(pc.Owner, Is.EqualTo(0)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(1)); Assert.That(pc.Total, Is.EqualTo(1)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(0)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(1)); Assert.That(pc.Simulator, Is.EqualTo(1)); } /// <summary> /// Test the count is correct after is has been tainted. /// </summary> [Test] public void TestTaint() { TestHelpers.InMethod(); IPrimCounts pc = m_lo.PrimCounts; SceneObjectGroup sog = SceneHelpers.CreateSceneObject(3, m_userId, "a", 0x01); m_scene.AddNewSceneObject(sog, false); m_pcm.TaintPrimCount(); Assert.That(pc.Owner, Is.EqualTo(3)); Assert.That(pc.Group, Is.EqualTo(0)); Assert.That(pc.Others, Is.EqualTo(0)); Assert.That(pc.Total, Is.EqualTo(3)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(3)); Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(3)); } } }
// The MIT License (MIT) // // Copyright (c) 2014-2016, Institute for Software & Systems Engineering // // 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 SafetySharp.Runtime { using System; using System.Collections.Generic; using Utilities; /// <summary> /// Represents a stack of <see cref="RuntimeModel" /> states that have yet to be checked. /// </summary> /// <remarks> /// When enumerating all states of a model in a depth-first fashion, we have to store the next states (that are computed all /// at once) somewhere while also being able to generate the counter example. When check a new state, a new frame is allocated /// on the stack and all unknown successor states are stored in that frame. We then take the topmost state, compute its /// successor states, and so on. When a formula violation is detected, the counter example consists of the last states of each /// frame on the stack. When a frame has been fully enumerated without detecting a formula violation, the stack frame is /// removed, the topmost state of the topmost frame is removed, and the new topmost state is checked. /// </remarks> internal sealed unsafe class StateStack : DisposableObject { /// <summary> /// The memory where the frames are stored. /// </summary> private readonly Frame* _frames; /// <summary> /// The buffer that stores the frames. /// </summary> private readonly MemoryBuffer _framesBuffer = new MemoryBuffer(); /// <summary> /// The memory where the states are stored. /// </summary> private readonly int* _states; /// <summary> /// The buffer that stores the states. /// </summary> private readonly MemoryBuffer _statesBuffer = new MemoryBuffer(); /// <summary> /// The maximum number of states that can be stored on the stack. /// </summary> private readonly int _capacity; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="capacity">The maximum number of states that can be stored on the stack.</param> public StateStack(int capacity) { Requires.InRange(capacity, nameof(capacity), 1024, Int32.MaxValue); _framesBuffer.Resize((long)capacity * sizeof(Frame), zeroMemory: false); _statesBuffer.Resize((long)capacity * sizeof(int), zeroMemory: false); _frames = (Frame*)_framesBuffer.Pointer; _states = (int*)_statesBuffer.Pointer; _capacity = capacity; } /// <summary> /// Gets the number of frames on the stack. /// </summary> public int FrameCount { get; private set; } /// <summary> /// Removes all states from the stack. /// </summary> public void Clear() { FrameCount = 0; } /// <summary> /// Pushes a new frame onto the stack. /// </summary> public void PushFrame() { if (FrameCount >= _capacity) { throw new InvalidOperationException( "Unable to allocate an additional depth first search frame. Try increasing the size of the state stack."); } var offset = FrameCount == 0 ? 0 : _frames[FrameCount - 1].Offset + _frames[FrameCount - 1].Count; _frames[FrameCount++] = new Frame { Offset = offset }; } /// <summary> /// Pushes the <paramref name="state" /> onto the stack for the current frame. /// </summary> /// <param name="state">The state that should be pushed onto the stack.</param> public void PushState(int state) { var frame = _frames[FrameCount - 1]; var offset = frame.Offset + frame.Count; if (offset >= _capacity) { throw new OutOfMemoryException( "Unable to allocate an additional depth first search state. Try increasing the size of the state stack."); } _states[offset] = state; _frames[FrameCount - 1].Count += 1; } /// <summary> /// Tries to get the topmost <paramref name="state" /> from the stack if there is one. Returns <c>false</c> to indicate that /// the stack was empty and no <paramref name="state" /> was returned. /// </summary> /// <param name="state">Returns the index of the topmost state on the stack.</param> public bool TryGetState(out int state) { while (FrameCount != 0) { if (_frames[FrameCount - 1].Count > 0) { // Return the frame's topmost state but do not yet remove the state as it might // be needed later when constructing the counter example state = _states[_frames[FrameCount - 1].Offset + _frames[FrameCount - 1].Count - 1]; return true; } // We're done with the frame and we can now remove the topmost state of the previous frame // as we no longer need it to construct a counter example --FrameCount; if (FrameCount > 0) _frames[FrameCount - 1].Count -= 1; } state = 0; return false; } /// <summary> /// Splits the work between this instance and the <paramref name="other" /> instance. Returns <c>true</c> to indicate that /// work has been split; <c>false</c>, otherwise. /// </summary> /// <param name="other">The other instance the work should be split with.</param> public bool SplitWork(StateStack other) { Requires.That(other.FrameCount == 0, nameof(other), "Expected an empty state stack."); // We go through each frame and split the first frame with more than two states in half for (var i = 0; i < FrameCount; ++i) { other.PushFrame(); switch (_frames[i].Count) { // The stack is in an invalid state; clear the other worker's stack and let this worker // continue; it will clean up its stack and try to split work later case 0: other.Clear(); return false; // We can't split work here, so just push the state to the other worker's stack case 1: other.PushState(_states[_frames[i].Offset]); break; // We've encountered a frame where we can actually split work; we always split work as early as possible, // that is, as low on the stack as possible, to hopefully maximize the amount of work passed to the other worker default: // Split the states of the frame var otherCount = _frames[i].Count / 2; var thisCount = _frames[i].Count - otherCount; // Add the first otherCount states to the other stack for (var j = 0; j < otherCount; ++j) other.PushState(_states[_frames[i].Offset + j]); // Adjust the count and offset of the frame _frames[i].Offset += otherCount; _frames[i].Count = thisCount; return true; } } // This stack could not be split, so we clear the other's stack and let some other worker try again other.Clear(); return false; } /// <summary> /// Gets the trace the stack currently represents, i.e., returns the sequence of topmost states of each frame, starting with /// the oldest one. /// </summary> public int[] GetTrace() { // We have to explicitly allocate and fill a list here, as pointers are not allowed in iterators var trace = new List<int>(FrameCount); for (var i = 0; i < FrameCount; ++i) { if (_frames[i].Count > 0) trace.Add(_states[_frames[i].Offset + _frames[i].Count - 1]); } return trace.ToArray(); } /// <summary> /// Disposes the object, releasing all managed and unmanaged resources. /// </summary> /// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param> protected override void OnDisposing(bool disposing) { if (!disposing) return; _framesBuffer.SafeDispose(); _statesBuffer.SafeDispose(); } /// <summary> /// Represents a frame of the state stack. /// </summary> private struct Frame { /// <summary> /// The offset into the <see cref="_states" /> array where the index of the frame's first state is stored. /// </summary> public int Offset; /// <summary> /// The number of states the frame consists of. /// </summary> public int Count; } } }
using System.Linq; namespace ModuleInject.Common.Linq { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq.Expressions; [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification="Externally created code.", Scope="method")] public abstract class ExpressionVisitor { protected ExpressionVisitor() { } protected virtual void OnVisiting(Expression expression) { } protected virtual Expression Visit(Expression expression) { if (expression == null) return expression; switch (expression.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: return this.VisitUnary((UnaryExpression)expression); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return this.VisitBinary((BinaryExpression)expression); case ExpressionType.TypeIs: return this.VisitTypeIs((TypeBinaryExpression)expression); case ExpressionType.Conditional: return this.VisitConditional((ConditionalExpression)expression); case ExpressionType.Constant: return this.VisitConstant((ConstantExpression)expression); case ExpressionType.Parameter: return this.VisitParameter((ParameterExpression)expression); case ExpressionType.MemberAccess: return this.VisitMemberAccess((MemberExpression)expression); case ExpressionType.Call: return this.VisitMethodCall((MethodCallExpression)expression); case ExpressionType.Lambda: return this.VisitLambda((LambdaExpression)expression); case ExpressionType.New: return this.VisitNew((NewExpression)expression); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return this.VisitNewArray((NewArrayExpression)expression); case ExpressionType.Invoke: return this.VisitInvocation((InvocationExpression)expression); case ExpressionType.MemberInit: return this.VisitMemberInit((MemberInitExpression)expression); case ExpressionType.ListInit: return this.VisitListInit((ListInitExpression)expression); default: throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unhandled expression type: '{0}'", expression.NodeType)); } } protected virtual MemberBinding VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return this.VisitMemberAssignment((MemberAssignment)binding); case MemberBindingType.MemberBinding: return this.VisitMemberMemberBinding((MemberMemberBinding)binding); case MemberBindingType.ListBinding: return this.VisitMemberListBinding((MemberListBinding)binding); default: throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unhandled binding type '{0}'", binding.BindingType)); } } protected virtual ElementInit VisitElementInitializer(ElementInit initializer) { ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments); if (arguments != initializer.Arguments) { return Expression.ElementInit(initializer.AddMethod, arguments); } return initializer; } protected virtual Expression VisitUnary(UnaryExpression unaryExpression) { OnVisiting(unaryExpression); Expression operand = this.Visit(unaryExpression.Operand); if (operand != unaryExpression.Operand) { return Expression.MakeUnary(unaryExpression.NodeType, operand, unaryExpression.Type, unaryExpression.Method); } return unaryExpression; } protected virtual Expression VisitBinary(BinaryExpression binaryExpression) { OnVisiting(binaryExpression); Expression left = this.Visit(binaryExpression.Left); Expression right = this.Visit(binaryExpression.Right); Expression conversion = this.Visit(binaryExpression.Conversion); if (left != binaryExpression.Left || right != binaryExpression.Right || conversion != binaryExpression.Conversion) { if (binaryExpression.NodeType == ExpressionType.Coalesce && binaryExpression.Conversion != null) return Expression.Coalesce(left, right, conversion as LambdaExpression); else return Expression.MakeBinary(binaryExpression.NodeType, left, right, binaryExpression.IsLiftedToNull, binaryExpression.Method); } return binaryExpression; } protected virtual Expression VisitTypeIs(TypeBinaryExpression typeBinaryExpression) { OnVisiting(typeBinaryExpression); Expression expr = this.Visit(typeBinaryExpression.Expression); if (expr != typeBinaryExpression.Expression) { return Expression.TypeIs(expr, typeBinaryExpression.TypeOperand); } return typeBinaryExpression; } protected virtual Expression VisitConstant(ConstantExpression constantExpression) { OnVisiting(constantExpression); return constantExpression; } protected virtual Expression VisitConditional(ConditionalExpression conditionalExpression) { OnVisiting(conditionalExpression); Expression test = this.Visit(conditionalExpression.Test); Expression ifTrue = this.Visit(conditionalExpression.IfTrue); Expression ifFalse = this.Visit(conditionalExpression.IfFalse); if (test != conditionalExpression.Test || ifTrue != conditionalExpression.IfTrue || ifFalse != conditionalExpression.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return conditionalExpression; } protected virtual Expression VisitParameter(ParameterExpression parameterExpression) { OnVisiting(parameterExpression); return parameterExpression; } protected virtual Expression VisitMemberAccess(MemberExpression memberExpression) { OnVisiting(memberExpression); Expression exp = this.Visit(memberExpression.Expression); if (exp != memberExpression.Expression) { return Expression.MakeMemberAccess(exp, memberExpression.Member); } return memberExpression; } protected virtual Expression VisitMethodCall(MethodCallExpression methodCallExpression) { OnVisiting(methodCallExpression); Expression obj = this.Visit(methodCallExpression.Object); IEnumerable<Expression> args = this.VisitExpressionList(methodCallExpression.Arguments); if (obj != methodCallExpression.Object || args != methodCallExpression.Arguments) { return Expression.Call(obj, methodCallExpression.Method, args); } return methodCallExpression; } protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original) { List<Expression> list = null; for (int i = 0, n = original.Count; i < n; i++) { Expression p = this.Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<Expression>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) { return list.AsReadOnly(); } return original; } protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { Expression e = this.Visit(assignment.Expression); if (e != assignment.Expression) { return Expression.Bind(assignment.Member, e); } return assignment; } protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings); if (bindings != binding.Bindings) { return Expression.MemberBind(binding.Member, bindings); } return binding; } protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) { IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers); if (initializers != binding.Initializers) { return Expression.ListBind(binding.Member, initializers); } return binding; } protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { List<MemberBinding> list = null; for (int i = 0, n = original.Count; i < n; i++) { MemberBinding b = this.VisitBinding(original[i]); if (list != null) { list.Add(b); } else if (b != original[i]) { list = new List<MemberBinding>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(b); } } if (list != null) return list; return original; } protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { List<ElementInit> list = null; for (int i = 0, n = original.Count; i < n; i++) { ElementInit init = this.VisitElementInitializer(original[i]); if (list != null) { list.Add(init); } else if (init != original[i]) { list = new List<ElementInit>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(init); } } if (list != null) return list; return original; } protected virtual Expression VisitLambda(LambdaExpression lambda) { OnVisiting(lambda); Expression body = this.Visit(lambda.Body); if (body != lambda.Body) { return Expression.Lambda(lambda.Type, body, lambda.Parameters); } return lambda; } protected virtual NewExpression VisitNew(NewExpression nex) { OnVisiting(nex); IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments); if (args != nex.Arguments) { if (nex.Members != null) return Expression.New(nex.Constructor, args, nex.Members); else return Expression.New(nex.Constructor, args); } return nex; } protected virtual Expression VisitMemberInit(MemberInitExpression init) { OnVisiting(init); NewExpression n = this.VisitNew(init.NewExpression); IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings); if (n != init.NewExpression || bindings != init.Bindings) { return Expression.MemberInit(n, bindings); } return init; } protected virtual Expression VisitListInit(ListInitExpression init) { OnVisiting(init); NewExpression n = this.VisitNew(init.NewExpression); IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || initializers != init.Initializers) { return Expression.ListInit(n, initializers); } return init; } protected virtual Expression VisitNewArray(NewArrayExpression newArrayExpression) { OnVisiting(newArrayExpression); IEnumerable<Expression> exprs = this.VisitExpressionList(newArrayExpression.Expressions); if (exprs != newArrayExpression.Expressions) { if (newArrayExpression.NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(newArrayExpression.Type.GetElementType(), exprs); } else { return Expression.NewArrayBounds(newArrayExpression.Type.GetElementType(), exprs); } } return newArrayExpression; } protected virtual Expression VisitInvocation(InvocationExpression invocationExpression) { OnVisiting(invocationExpression); IEnumerable<Expression> args = this.VisitExpressionList(invocationExpression.Arguments); Expression expr = this.Visit(invocationExpression.Expression); if (args != invocationExpression.Arguments || expr != invocationExpression.Expression) { return Expression.Invoke(expr, args); } return invocationExpression; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Wasm.Binary; using Wasm.Instructions; namespace Wasm { /// <summary> /// A type of section that declares the initialized data that is loaded into a table. /// </summary> public sealed class ElementSection : Section { /// <summary> /// Creates an empty element section. /// </summary> public ElementSection() { this.Segments = new List<ElementSegment>(); this.ExtraPayload = new byte[0]; } /// <summary> /// Creates an element section from a sequence of segments. /// </summary> /// <param name="segments">The segments to put in the elements section.</param> public ElementSection(IEnumerable<ElementSegment> segments) : this(segments, new byte[0]) { } /// <summary> /// Creates an element section from a sequence of segments and a trailing payload. /// </summary> /// <param name="segments">The segments to put in the elements section.</param> /// <param name="extraPayload"> /// A sequence of bytes that have no intrinsic meaning; they are part /// of the element section but are placed after the element section's actual contents. /// </param> public ElementSection(IEnumerable<ElementSegment> segments, byte[] extraPayload) { this.Segments = new List<ElementSegment>(segments); this.ExtraPayload = extraPayload; } /// <inheritdoc/> public override SectionName Name => new SectionName(SectionCode.Element); /// <summary> /// Gets the list of the element segments defined by this section. /// </summary> /// <returns>The element segments defined by this section.</returns> public List<ElementSegment> Segments { get; private set; } /// <summary> /// Gets this function section's additional payload. /// </summary> /// <returns>The additional payload, as an array of bytes.</returns> public byte[] ExtraPayload { get; set; } /// <inheritdoc/> public override void WritePayloadTo(BinaryWasmWriter writer) { writer.WriteVarUInt32((uint)Segments.Count); foreach (var segment in Segments) { segment.WriteTo(writer); } writer.Writer.Write(ExtraPayload); } /// <summary> /// Reads the element section with the given header. /// </summary> /// <param name="header">The section header.</param> /// <param name="reader">A reader for a binary WebAssembly file.</param> /// <returns>The parsed section.</returns> public static ElementSection ReadSectionPayload( SectionHeader header, BinaryWasmReader reader) { long startPos = reader.Position; // Read the element segments. uint count = reader.ReadVarUInt32(); var segments = new List<ElementSegment>(); for (uint i = 0; i < count; i++) { segments.Add(ElementSegment.ReadFrom(reader)); } // Skip any remaining bytes. var extraPayload = reader.ReadRemainingPayload(startPos, header); return new ElementSection(segments, extraPayload); } /// <inheritdoc/> public override void Dump(TextWriter writer) { writer.Write(Name.ToString()); writer.Write("; number of entries: "); writer.Write(Segments.Count); writer.WriteLine(); var indentedWriter = DumpHelpers.CreateIndentedTextWriter(writer); for (int i = 0; i < Segments.Count; i++) { writer.Write("#{0}:", i); indentedWriter.WriteLine(); Segments[i].Dump(indentedWriter); writer.WriteLine(); } if (ExtraPayload.Length > 0) { writer.Write("Extra payload size: "); writer.Write(ExtraPayload.Length); writer.WriteLine(); DumpHelpers.DumpBytes(ExtraPayload, writer); writer.WriteLine(); } } } /// <summary> /// An entry in the element section. /// </summary> public sealed class ElementSegment { /// <summary> /// Creates an element segment from the given table index, offset and data. /// </summary> /// <param name="tableIndex">The table index.</param> /// <param name="offset">An i32 initializer expression that computes the offset at which to place the data.</param> /// <param name="elements">A sequence of function indices to which a segment of the table is initialized.</param> public ElementSegment(uint tableIndex, InitializerExpression offset, IEnumerable<uint> elements) { this.TableIndex = tableIndex; this.Offset = offset; this.Elements = new List<uint>(elements); } /// <summary> /// Gets the table index. /// </summary> /// <returns>The table index.</returns> public uint TableIndex { get; set; } /// <summary> /// Gets an i32 initializer expression that computes the offset at which to place the data. /// </summary> /// <returns>An i32 initializer expression.</returns> public InitializerExpression Offset { get; set; } /// <summary> /// Gets a list of function indices to which this segment of the table is initialized. /// </summary> /// <returns>The list of function indices to which this segment of the table is initialized.</returns> public List<uint> Elements { get; private set; } /// <summary> /// Writes this element segment to the given WebAssembly file writer. /// </summary> /// <param name="writer">The WebAssembly file writer.</param> public void WriteTo(BinaryWasmWriter writer) { writer.WriteVarUInt32(TableIndex); Offset.WriteTo(writer); writer.WriteVarUInt32((uint)Elements.Count); foreach (var item in Elements) { writer.WriteVarUInt32(item); } } /// <summary> /// Reads an element segment from the given WebAssembly reader. /// </summary> /// <param name="reader">The WebAssembly reader.</param> /// <returns>The element segment that was read from the reader.</returns> public static ElementSegment ReadFrom(BinaryWasmReader reader) { var index = reader.ReadVarUInt32(); var offset = InitializerExpression.ReadFrom(reader); var dataLength = reader.ReadVarUInt32(); var elements = new List<uint>((int)dataLength); for (uint i = 0; i < dataLength; i++) { elements.Add(reader.ReadVarUInt32()); } return new ElementSegment(index, offset, elements); } /// <summary> /// Writes a textual representation of this element segment to the given writer. /// </summary> /// <param name="writer">The writer to which text is written.</param> public void Dump(TextWriter writer) { writer.Write("- Table index: "); writer.Write(TableIndex); writer.WriteLine(); writer.Write("- Offset:"); var indentedWriter = DumpHelpers.CreateIndentedTextWriter(writer); foreach (var instruction in Offset.BodyInstructions) { indentedWriter.WriteLine(); instruction.Dump(indentedWriter); } writer.WriteLine(); writer.Write("- Elements:"); for (int i = 0; i < Elements.Count; i++) { indentedWriter.WriteLine(); indentedWriter.Write("#{0} -> func #{1}", i, Elements[i]); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookChartSeriesFormatRequest. /// </summary> public partial class WorkbookChartSeriesFormatRequest : BaseRequest, IWorkbookChartSeriesFormatRequest { /// <summary> /// Constructs a new WorkbookChartSeriesFormatRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookChartSeriesFormatRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookChartSeriesFormat using POST. /// </summary> /// <param name="workbookChartSeriesFormatToCreate">The WorkbookChartSeriesFormat to create.</param> /// <returns>The created WorkbookChartSeriesFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartSeriesFormat> CreateAsync(WorkbookChartSeriesFormat workbookChartSeriesFormatToCreate) { return this.CreateAsync(workbookChartSeriesFormatToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookChartSeriesFormat using POST. /// </summary> /// <param name="workbookChartSeriesFormatToCreate">The WorkbookChartSeriesFormat to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookChartSeriesFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartSeriesFormat> CreateAsync(WorkbookChartSeriesFormat workbookChartSeriesFormatToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookChartSeriesFormat>(workbookChartSeriesFormatToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookChartSeriesFormat. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookChartSeriesFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookChartSeriesFormat>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookChartSeriesFormat. /// </summary> /// <returns>The WorkbookChartSeriesFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartSeriesFormat> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookChartSeriesFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookChartSeriesFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartSeriesFormat> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookChartSeriesFormat>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookChartSeriesFormat using PATCH. /// </summary> /// <param name="workbookChartSeriesFormatToUpdate">The WorkbookChartSeriesFormat to update.</param> /// <returns>The updated WorkbookChartSeriesFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartSeriesFormat> UpdateAsync(WorkbookChartSeriesFormat workbookChartSeriesFormatToUpdate) { return this.UpdateAsync(workbookChartSeriesFormatToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookChartSeriesFormat using PATCH. /// </summary> /// <param name="workbookChartSeriesFormatToUpdate">The WorkbookChartSeriesFormat to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookChartSeriesFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartSeriesFormat> UpdateAsync(WorkbookChartSeriesFormat workbookChartSeriesFormatToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookChartSeriesFormat>(workbookChartSeriesFormatToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesFormatRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesFormatRequest Expand(Expression<Func<WorkbookChartSeriesFormat, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesFormatRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesFormatRequest Select(Expression<Func<WorkbookChartSeriesFormat, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookChartSeriesFormatToInitialize">The <see cref="WorkbookChartSeriesFormat"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookChartSeriesFormat workbookChartSeriesFormatToInitialize) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Network.Fluent { using Microsoft.Azure.Management.Network.Fluent; using Microsoft.Azure.Management.Network.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System.Collections.Generic; /// <summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uTmljSVBDb25maWd1cmF0aW9uQmFzZUltcGw= /// Base class implementation for various network interface ip configurations. /// </summary> /// <typeparam name="ParentImplT">Parent implementation.</typeparam> /// <typeparam name="IParentT">Parent interface.</typeparam> internal partial class NicIPConfigurationBaseImpl<ParentImplT, ParentT> : ChildResource<NetworkInterfaceIPConfigurationInner, ParentImplT, ParentT>, INicIPConfigurationBase where ParentImplT : ParentT where ParentT : IHasManager<INetworkManager> { private INetworkManager networkManager; ///GENMHASH:23C49F051293E5877CB98C4B87F018C8:56B3D14E72AB91FEE453D95A27DD8E6C internal NicIPConfigurationBaseImpl( NetworkInterfaceIPConfigurationInner inner, ParentImplT parent, INetworkManager networkManager) : base(inner, parent) { this.networkManager = networkManager; } ///GENMHASH:492F1C99FDE7AED2307A308B9D148FE6:91EDC35A4F0FB7ED572A844DE6E566E8 internal bool IsPrimary() { if (Inner.Primary.HasValue) { return Inner.Primary.Value; } return false; } ///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:A4568D5A538C2116779423E74A62442B public override string Name() { return Inner.Name; } ///GENMHASH:F4EEE08685E447AE7D2A8F7252EC223A:516B6A004CB15A757AC222DE49CEC6EC internal string PrivateIPAddress() { return Inner.PrivateIPAddress; } ///GENMHASH:FCB784E90DCC27EAC6AD4B4C988E2752:925E8594616C741FD699EF2269B3D731 internal IPAllocationMethod PrivateIPAllocationMethod() { return Inner.PrivateIPAllocationMethod; } ///GENMHASH:572B5A1179A4B2EF64D68C0E25834020:D53CEB54EB83B4CD2AFB7B489DE5E4E6 internal IPVersion PrivateIPAddressVersion() { return Inner.PrivateIPAddressVersion; } ///GENMHASH:09E2C45F8481740F588302FB0C7A7C68:EEA5AE07BF27BC623913227E0050ECA2 internal INetwork GetNetwork() { string id = NetworkId(); return (id != null) ? networkManager.Networks.GetById(id) : null; } ///GENMHASH:C57133CD301470A479B3BA07CD283E86:1F748ABB2BF391EB5FEEFD3546A4C7A8 internal string SubnetName() { SubResource subnetRef = Inner.Subnet; return (subnetRef != null) ? ResourceUtils.NameFromResourceId(subnetRef.Id) : null; } ///GENMHASH:744A3724C9A3248553B33B2939CE091A:B91782240ED4E9E0E9CD0089AA8E08B6 internal IReadOnlyList<ILoadBalancerInboundNatRule> ListAssociatedLoadBalancerInboundNatRules() { var inboundNatPoolRefs = Inner.LoadBalancerInboundNatRules; if (inboundNatPoolRefs == null) { return new List<ILoadBalancerInboundNatRule>(); } var loadBalancers = new Dictionary<string, ILoadBalancer>(); var rules = new List<ILoadBalancerInboundNatRule>(); foreach (var reference in inboundNatPoolRefs) { string loadBalancerId = ResourceUtils.ParentResourcePathFromResourceId(reference.Id); ILoadBalancer loadBalancer; if (!loadBalancers.TryGetValue(loadBalancerId.ToLower(), out loadBalancer)) { loadBalancer = this.networkManager.LoadBalancers.GetById(loadBalancerId); loadBalancers[loadBalancerId.ToLower()] = loadBalancer; } string ruleName = ResourceUtils.NameFromResourceId(reference.Id); rules.Add(loadBalancer.InboundNatRules[ruleName]); } return rules; } ///GENMHASH:D5259819D030517B66106CDFA84D3219:52A28D2529D3E09774E3F4F8685E67EC internal IReadOnlyList<ILoadBalancerBackend> ListAssociatedLoadBalancerBackends() { var backendRefs = Inner.LoadBalancerBackendAddressPools; if (backendRefs == null) { return new List<ILoadBalancerBackend>(); } var loadBalancers = new Dictionary<string, ILoadBalancer>(); var backends = new List<ILoadBalancerBackend>(); foreach (BackendAddressPoolInner backendRef in backendRefs) { string loadBalancerId = ResourceUtils.ParentResourcePathFromResourceId(backendRef.Id); ILoadBalancer loadBalancer; if (!loadBalancers.TryGetValue(loadBalancerId.ToLower(), out loadBalancer)) { loadBalancer = networkManager.LoadBalancers.GetById(loadBalancerId); loadBalancers[loadBalancerId.ToLower()] = loadBalancer; } string backendName = ResourceUtils.NameFromResourceId(backendRef.Id); ILoadBalancerBackend backend; if (loadBalancer.Backends.TryGetValue(backendName, out backend)) backends.Add(backend); } return backends; } ///GENMHASH:1C444C90348D7064AB23705C542DDF18:AAA4FE3C44C931AA498D248FB062890E internal string NetworkId() { SubResource subnetRef = Inner.Subnet; return (subnetRef != null) ? ResourceUtils.ParentResourcePathFromResourceId(subnetRef.Id) : null; } ///GENMHASH:2E4015B29759BBD97527EBAE809B083C:91A166D41391DA35AAD7B2223B2992C5 public INetworkSecurityGroup GetNetworkSecurityGroup() { INetwork network = this.GetNetwork(); if (network == null) { return null; } string subnetName = SubnetName(); if (subnetName == null) { return null; } ISubnet subnet; if (network.Subnets.TryGetValue(subnetName, out subnet)) { return subnet.GetNetworkSecurityGroup(); } else { return null; } } ///GENMHASH:AB4065B8BA3CBEBBFE2194997931C513:9F5EC22819D02223DAAD78B94E1B5130 public IReadOnlyList<IApplicationGatewayBackend> ListAssociatedApplicationGatewayBackends() { //return ((NetworkManager)Parent.Manager).ListAssociatedApplicationGatewayBackends(Inner.ApplicationGatewayBackendAddressPools); IDictionary<string, IApplicationGateway> appGateways = new Dictionary<string, IApplicationGateway>(); List<IApplicationGatewayBackend> backends = new List<IApplicationGatewayBackend>(); var backendRefs = Inner.ApplicationGatewayBackendAddressPools; if (backendRefs != null) { foreach (var backendRef in backendRefs) { string appGatewayId = ResourceUtils.ParentResourcePathFromResourceId(backendRef.Id); IApplicationGateway appGateway; if (!appGateways.TryGetValue(appGatewayId.ToLower(), out appGateway)) { appGateway = Parent.Manager.ApplicationGateways.GetById(appGatewayId); appGateways[appGatewayId.ToLower()] = appGateway; } string backendName = ResourceUtils.NameFromResourceId(backendRef.Id); IApplicationGatewayBackend backend = null; if (appGateway.Backends.TryGetValue(backendName, out backend)) { backends.Add(backend); } } } return backends; } } }
/* * * (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.Collections.Specialized; using System.Globalization; using System.IO; using System.Net.Mail; using System.Runtime.Serialization; using System.Text; using ASC.Mail.Enums; using ASC.Mail.Extensions; using ASC.Mail.Utils; using ASC.Specific; namespace ASC.Mail.Data.Contracts { [DataContract(Namespace = "")] public class MailMessageData { public MailMessageData() { ToList = new List<MailAddress>(); CcList = new List<MailAddress>(); BccList = new List<MailAddress>(); } ~MailMessageData() { if (HtmlBodyStream != null) HtmlBodyStream.Dispose(); } [DataMember(EmitDefaultValue = false)] public List<MailAttachmentData> Attachments { get; set; } [DataMember(EmitDefaultValue = false)] public string Introduction { get; set; } private string _htmlBody; [DataMember(EmitDefaultValue = false)] public string HtmlBody { get { if (HtmlBodyStream == null || HtmlBodyStream.Length <= 0) return _htmlBody; HtmlBodyStream.Seek(0, SeekOrigin.Begin); _htmlBody = Encoding.UTF8.GetString(HtmlBodyStream.ReadToEnd()); HtmlBodyStream.Seek(0, SeekOrigin.Begin); return _htmlBody; } set { _htmlBody = value; } } [DataMember] public bool ContentIsBlocked { get; set; } [DataMember] public bool Important { get; set; } [DataMember] public string Subject { get; set; } [DataMember] public bool HasAttachments { get; set; } [DataMember(EmitDefaultValue = false)] public string Bcc { get; set; } [DataMember(EmitDefaultValue = false)] public string Cc { get; set; } [DataMember] public string To { get; set; } [DataMember] public string Address { get; set; } [DataMember] public string From { get; set; } public string FromEmail { get; set; } [DataMember(EmitDefaultValue = false)] public string ReplyTo { get; set; } [DataMember] public int Id { get; set; } [DataMember(EmitDefaultValue = false)] public string ChainId { get; set; } public DateTime ChainDate { get; set; } [DataMember(Name = "ChainDate")] public string ChainDateString { get { return ChainDate.ToString("G", CultureInfo.InvariantCulture); } set { DateTime date; if (DateTime.TryParseExact(value, "g", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out date)) { ChainDate = date; } } } public DateTime Date { get; set; } [DataMember(Name = "Date")] public string DateString { get { return Date.ToString("G", CultureInfo.InvariantCulture); } set { DateTime date; if (DateTime.TryParseExact(value, "g", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out date)) { Date = date; } } } [DataMember(Name = "DateDisplay")] public string DateDisplay { get { return Date.ToVerbString(); } } [DataMember(EmitDefaultValue = false)] public List<int> TagIds { get; set; } public string LabelsString { set { TagIds = new List<int>(MailUtil.GetLabelsFromString(value)); } } [DataMember(Name = "LabelsInString")] public string LabelsInString { get { return MailUtil.GetStringFromLabels(TagIds); } } [DataMember] public bool IsNew { get; set; } [DataMember] public bool IsAnswered { get; set; } [DataMember] public bool IsForwarded { get; set; } [DataMember] public bool TextBodyOnly { get; set; } [DataMember] public long Size { get; set; } [DataMember] // ReSharper disable once InconsistentNaming public string EMLLink { get; set; } [DataMember] public string StreamId { get; set; } [DataMember] public FolderType RestoreFolderId { get; set; } [DataMember] public FolderType Folder { get; set; } [DataMember] public uint? UserFolderId { get; set; } [DataMember] public int ChainLength { get; set; } [DataMember] public bool WasNew { get; set; } [DataMember] public bool IsToday { get; set; } [DataMember] public bool IsYesterday { get; set; } [DataMember] public ApiDateTime ReceivedDate { get { return (ApiDateTime)Date; } } public int MailboxId { get; set; } public List<CrmContactData> LinkedCrmEntityIds { get; set; } [DataMember] public bool IsBodyCorrupted { get; set; } [DataMember] public bool HasParseError { get; set; } [DataMember] public string MimeMessageId { get; set; } [DataMember] public string MimeReplyToId { get; set; } [DataMember] public string CalendarUid { get; set; } [IgnoreDataMember] public int CalendarId { get; set; } [IgnoreDataMember] public string CalendarEventCharset { get; set; } [IgnoreDataMember] public string CalendarEventMimeType { get; set; } [IgnoreDataMember] public string CalendarEventIcs { get; set; } [IgnoreDataMember] public List<MailAddress> ToList { get; set; } [IgnoreDataMember] public List<MailAddress> CcList { get; set; } [IgnoreDataMember] public List<MailAddress> BccList { get; set; } [IgnoreDataMember] public NameValueCollection HeaderFieldNames { get; set; } [IgnoreDataMember] public Stream HtmlBodyStream { get; set; } [IgnoreDataMember] public string Uidl { get; set; } public class Options { public Options() { OnlyUnremoved = true; NeedSanitizer = true; } public bool LoadImages { get; set; } public bool LoadBody { get; set; } public bool NeedProxyHttp { get; set; } public bool NeedSanitizer { get; set; } public bool OnlyUnremoved { get; set; } public bool LoadEmebbedAttachements { get; set; } public string ProxyHttpHandlerUrl { get; set; } } } }
using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; // To simplify the process of finding the toolbox bitmap resource: // #1 Create an internal class called "resfinder" outside of the root namespace. // #2 Use "resfinder" in the toolbox bitmap attribute instead of the control name. // #3 use the "<default namespace>.<resourcename>" string to locate the resource. // See: http://www.bobpowell.net/toolboxbitmap.htm internal class resfinder { } namespace WeifenLuo.WinFormsUI.Docking { /// <summary> /// Deserialization handler of layout file/stream. /// </summary> /// <param name="persistString">Strings stored in layout file/stream.</param> /// <returns>Dock content deserialized from layout/stream.</returns> /// <remarks> /// The deserialization handler method should handle all possible exceptions. /// /// If any exception happens during deserialization and is not handled, the program might crash or experience other issues. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")] public delegate IDockContent DeserializeDockContent(string persistString); [LocalizedDescription("DockPanel_Description")] [Designer("System.Windows.Forms.Design.ControlDesigner, System.Design")] [ToolboxBitmap(typeof(resfinder), "WeifenLuo.WinFormsUI.Docking.DockPanel.bmp")] [DefaultProperty("DocumentStyle")] [DefaultEvent("ActiveContentChanged")] public partial class DockPanel : Panel { private readonly FocusManagerImpl m_focusManager; private readonly DockPaneCollection m_panes; private readonly FloatWindowCollection m_floatWindows; private AutoHideWindowControl m_autoHideWindow; private DockWindowCollection m_dockWindows; private readonly DockContent m_dummyContent; private readonly Control m_dummyControl; public DockPanel() { ShowAutoHideContentOnHover = true; m_focusManager = new FocusManagerImpl(this); m_panes = new DockPaneCollection(); m_floatWindows = new FloatWindowCollection(); SuspendLayout(); m_dummyControl = new DummyControl(); m_dummyControl.Bounds = new Rectangle(0, 0, 1, 1); Controls.Add(m_dummyControl); Theme.ApplyTo(this); m_autoHideWindow = Theme.Extender.AutoHideWindowFactory.CreateAutoHideWindow(this); m_autoHideWindow.Visible = false; m_autoHideWindow.ActiveContentChanged += m_autoHideWindow_ActiveContentChanged; SetAutoHideWindowParent(); LoadDockWindows(); m_dummyContent = new DockContent(); ResumeLayout(); } internal void ResetDummy() { DummyControl.ResetBackColor(); } internal void SetDummy() { DummyControl.BackColor = DockBackColor; } private Color m_BackColor; /// <summary> /// Determines the color with which the client rectangle will be drawn. /// If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane). /// The BackColor property changes the borders of surrounding controls (DockPane). /// Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle). /// For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control) /// </summary> [Description("Determines the color with which the client rectangle will be drawn.\r\n" + "If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).\r\n" + "The BackColor property changes the borders of surrounding controls (DockPane).\r\n" + "Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).\r\n" + "For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control).")] public Color DockBackColor { get { return !m_BackColor.IsEmpty ? m_BackColor : base.BackColor; } set { if (m_BackColor != value) { m_BackColor = value; Refresh(); } } } private bool ShouldSerializeDockBackColor() { return !m_BackColor.IsEmpty; } private AutoHideStripBase m_autoHideStripControl; internal AutoHideStripBase AutoHideStripControl { get { if (m_autoHideStripControl == null) { m_autoHideStripControl = Theme.Extender.AutoHideStripFactory.CreateAutoHideStrip(this); Controls.Add(m_autoHideStripControl); } return m_autoHideStripControl; } } internal void ResetAutoHideStripControl() { if (m_autoHideStripControl != null) m_autoHideStripControl.Dispose(); m_autoHideStripControl = null; } private void MdiClientHandleAssigned(object sender, EventArgs e) { SetMdiClient(); PerformLayout(); } private void MdiClient_Layout(object sender, LayoutEventArgs e) { if (DocumentStyle != DocumentStyle.DockingMdi) return; foreach (DockPane pane in Panes) if (pane.DockState == DockState.Document) pane.SetContentBounds(); InvalidateWindowRegion(); } private bool m_disposed; protected override void Dispose(bool disposing) { if (!m_disposed && disposing) { m_focusManager.Dispose(); if (m_mdiClientController != null) { m_mdiClientController.HandleAssigned -= new EventHandler(MdiClientHandleAssigned); m_mdiClientController.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate); m_mdiClientController.Layout -= new LayoutEventHandler(MdiClient_Layout); m_mdiClientController.Dispose(); } FloatWindows.Dispose(); Panes.Dispose(); DummyContent.Dispose(); m_disposed = true; } base.Dispose(disposing); } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IDockContent ActiveAutoHideContent { get { return AutoHideWindow.ActiveContent; } set { AutoHideWindow.ActiveContent = value; } } private bool m_allowEndUserDocking = !Win32Helper.IsRunningOnMono; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_AllowEndUserDocking_Description")] [DefaultValue(true)] public bool AllowEndUserDocking { get { if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking) m_allowEndUserDocking = false; return m_allowEndUserDocking; } set { if (Win32Helper.IsRunningOnMono && value) throw new InvalidOperationException("AllowEndUserDocking can only be false if running on Mono"); m_allowEndUserDocking = value; } } private bool m_allowEndUserNestedDocking = !Win32Helper.IsRunningOnMono; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_AllowEndUserNestedDocking_Description")] [DefaultValue(true)] public bool AllowEndUserNestedDocking { get { if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking) m_allowEndUserDocking = false; return m_allowEndUserNestedDocking; } set { if (Win32Helper.IsRunningOnMono && value) throw new InvalidOperationException("AllowEndUserNestedDocking can only be false if running on Mono"); m_allowEndUserNestedDocking = value; } } private DockContentCollection m_contents = new DockContentCollection(); [Browsable(false)] public DockContentCollection Contents { get { return m_contents; } } internal DockContent DummyContent { get { return m_dummyContent; } } private bool m_rightToLeftLayout = false; [DefaultValue(false)] [LocalizedCategory("Appearance")] [LocalizedDescription("DockPanel_RightToLeftLayout_Description")] public bool RightToLeftLayout { get { return m_rightToLeftLayout; } set { if (m_rightToLeftLayout == value) return; m_rightToLeftLayout = value; foreach (FloatWindow floatWindow in FloatWindows) floatWindow.RightToLeftLayout = value; } } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); foreach (FloatWindow floatWindow in FloatWindows) floatWindow.RightToLeft = RightToLeft; } private bool m_showDocumentIcon = false; [DefaultValue(false)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_ShowDocumentIcon_Description")] public bool ShowDocumentIcon { get { return m_showDocumentIcon; } set { if (m_showDocumentIcon == value) return; m_showDocumentIcon = value; Refresh(); } } [DefaultValue(DocumentTabStripLocation.Top)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DocumentTabStripLocation")] public DocumentTabStripLocation DocumentTabStripLocation { get; set; } = DocumentTabStripLocation.Top; [Browsable(false)] [Obsolete("Use Theme.Extender instead.")] public DockPanelExtender Extender { get { return null; } } [Browsable(false)] [Obsolete("Use Theme.Extender instead.")] public DockPanelExtender.IDockPaneFactory DockPaneFactory { get { return null; } } [Browsable(false)] [Obsolete("Use Theme.Extender instead.")] public DockPanelExtender.IFloatWindowFactory FloatWindowFactory { get { return null; } } [Browsable(false)] [Obsolete("Use Theme.Extender instead.")] public DockPanelExtender.IDockWindowFactory DockWindowFactory { get { return null; } } [Browsable(false)] public DockPaneCollection Panes { get { return m_panes; } } /// <summary> /// Dock area. /// </summary> /// <remarks> /// This <see cref="Rectangle"/> is the center rectangle of <see cref="DockPanel"/> control. /// /// Excluded spaces are for the following visual elements, /// * Auto hide strips on four sides. /// * Necessary paddings defined in themes. /// /// Therefore, all dock contents mainly fall into this area (except auto hide window, which might slightly move beyond this area). /// </remarks> public Rectangle DockArea { get { return new Rectangle(DockPadding.Left, DockPadding.Top, ClientRectangle.Width - DockPadding.Left - DockPadding.Right, ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom); } } private double m_dockBottomPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockBottomPortion_Description")] [DefaultValue(0.25)] public double DockBottomPortion { get { return m_dockBottomPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); if (Math.Abs(value - m_dockBottomPortion) < double.Epsilon) return; m_dockBottomPortion = value; if (m_dockBottomPortion < 1 && m_dockTopPortion < 1) { if (m_dockTopPortion + m_dockBottomPortion > 1) m_dockTopPortion = 1 - m_dockBottomPortion; } PerformLayout(); } } private double m_dockLeftPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockLeftPortion_Description")] [DefaultValue(0.25)] public double DockLeftPortion { get { return m_dockLeftPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); if (Math.Abs(value - m_dockLeftPortion) < double.Epsilon) return; m_dockLeftPortion = value; if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) { if (m_dockLeftPortion + m_dockRightPortion > 1) m_dockRightPortion = 1 - m_dockLeftPortion; } PerformLayout(); } } private double m_dockRightPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockRightPortion_Description")] [DefaultValue(0.25)] public double DockRightPortion { get { return m_dockRightPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); if (Math.Abs(value - m_dockRightPortion) < double.Epsilon) return; m_dockRightPortion = value; if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) { if (m_dockLeftPortion + m_dockRightPortion > 1) m_dockLeftPortion = 1 - m_dockRightPortion; } PerformLayout(); } } private double m_dockTopPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockTopPortion_Description")] [DefaultValue(0.25)] public double DockTopPortion { get { return m_dockTopPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); if (Math.Abs(value - m_dockTopPortion) < double.Epsilon) return; m_dockTopPortion = value; if (m_dockTopPortion < 1 && m_dockBottomPortion < 1) { if (m_dockTopPortion + m_dockBottomPortion > 1) m_dockBottomPortion = 1 - m_dockTopPortion; } PerformLayout(); } } [Browsable(false)] public DockWindowCollection DockWindows { get { return m_dockWindows; } } public void UpdateDockWindowZOrder(DockStyle dockStyle, bool fullPanelEdge) { if (dockStyle == DockStyle.Left) { if (fullPanelEdge) DockWindows[DockState.DockLeft].SendToBack(); else DockWindows[DockState.DockLeft].BringToFront(); } else if (dockStyle == DockStyle.Right) { if (fullPanelEdge) DockWindows[DockState.DockRight].SendToBack(); else DockWindows[DockState.DockRight].BringToFront(); } else if (dockStyle == DockStyle.Top) { if (fullPanelEdge) DockWindows[DockState.DockTop].SendToBack(); else DockWindows[DockState.DockTop].BringToFront(); } else if (dockStyle == DockStyle.Bottom) { if (fullPanelEdge) DockWindows[DockState.DockBottom].SendToBack(); else DockWindows[DockState.DockBottom].BringToFront(); } } [Browsable(false)] public int DocumentsCount { get { int count = 0; foreach (IDockContent content in Documents) count++; return count; } } public IDockContent[] DocumentsToArray() { int count = DocumentsCount; IDockContent[] documents = new IDockContent[count]; int i = 0; foreach (IDockContent content in Documents) { documents[i] = content; i++; } return documents; } [Browsable(false)] public IEnumerable<IDockContent> Documents { get { foreach (IDockContent content in Contents) { if (content.DockHandler.DockState == DockState.Document) yield return content; } } } private Control DummyControl { get { return m_dummyControl; } } [Browsable(false)] public FloatWindowCollection FloatWindows { get { return m_floatWindows; } } [Category("Layout")] [LocalizedDescription("DockPanel_DefaultFloatWindowSize_Description")] public Size DefaultFloatWindowSize { get; set; } = new Size(300, 300); private bool ShouldSerializeDefaultFloatWindowSize() { return DefaultFloatWindowSize != new Size(300, 300); } private void ResetDefaultFloatWindowSize() { DefaultFloatWindowSize = new Size(300, 300); } private DocumentStyle m_documentStyle = DocumentStyle.DockingWindow; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DocumentStyle_Description")] [DefaultValue(DocumentStyle.DockingWindow)] public DocumentStyle DocumentStyle { get { return m_documentStyle; } set { if (value == m_documentStyle) return; if (!Enum.IsDefined(typeof(DocumentStyle), value)) throw new InvalidEnumArgumentException(); if (value == DocumentStyle.SystemMdi && DockWindows[DockState.Document].VisibleNestedPanes.Count > 0) throw new InvalidEnumArgumentException(); m_documentStyle = value; SuspendLayout(true); SetAutoHideWindowParent(); SetMdiClient(); InvalidateWindowRegion(); foreach (IDockContent content in Contents) { if (content.DockHandler.DockState == DockState.Document) content.DockHandler.SetPaneAndVisible(content.DockHandler.Pane); } PerformMdiClientLayout(); ResumeLayout(true, true); } } [LocalizedCategory("Category_Performance")] [LocalizedDescription("DockPanel_SupportDeeplyNestedContent_Description")] [DefaultValue(false)] public bool SupportDeeplyNestedContent { get; set; } /// <summary> /// Flag to show autohide content on mouse hover. Default value is <code>true</code>. /// </summary> /// <remarks> /// This flag is ignored in VS2012/2013 themes. Such themes assume it is always <code>false</code>. /// </remarks> [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_ShowAutoHideContentOnHover_Description")] [DefaultValue(true)] public bool ShowAutoHideContentOnHover { get; set; } public int GetDockWindowSize(DockState dockState) { if (dockState == DockState.DockLeft || dockState == DockState.DockRight) { int width = ClientRectangle.Width - DockPadding.Left - DockPadding.Right; int dockLeftSize = m_dockLeftPortion >= 1 ? (int)m_dockLeftPortion : (int)(width * m_dockLeftPortion); int dockRightSize = m_dockRightPortion >= 1 ? (int)m_dockRightPortion : (int)(width * m_dockRightPortion); if (dockLeftSize < MeasurePane.MinSize) dockLeftSize = MeasurePane.MinSize; if (dockRightSize < MeasurePane.MinSize) dockRightSize = MeasurePane.MinSize; if (dockLeftSize + dockRightSize > width - MeasurePane.MinSize) { int adjust = (dockLeftSize + dockRightSize) - (width - MeasurePane.MinSize); dockLeftSize -= adjust / 2; dockRightSize -= adjust / 2; } return dockState == DockState.DockLeft ? dockLeftSize : dockRightSize; } if (dockState == DockState.DockTop || dockState == DockState.DockBottom) { int height = ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom; int dockTopSize = m_dockTopPortion >= 1 ? (int)m_dockTopPortion : (int)(height * m_dockTopPortion); int dockBottomSize = m_dockBottomPortion >= 1 ? (int)m_dockBottomPortion : (int)(height * m_dockBottomPortion); if (dockTopSize < MeasurePane.MinSize) dockTopSize = MeasurePane.MinSize; if (dockBottomSize < MeasurePane.MinSize) dockBottomSize = MeasurePane.MinSize; if (dockTopSize + dockBottomSize > height - MeasurePane.MinSize) { int adjust = (dockTopSize + dockBottomSize) - (height - MeasurePane.MinSize); dockTopSize -= adjust / 2; dockBottomSize -= adjust / 2; } return dockState == DockState.DockTop ? dockTopSize : dockBottomSize; } return 0; } protected override void OnLayout(LayoutEventArgs levent) { SuspendLayout(true); AutoHideStripControl.Bounds = ClientRectangle; CalculateDockPadding(); DockWindows[DockState.DockLeft].Width = GetDockWindowSize(DockState.DockLeft); DockWindows[DockState.DockRight].Width = GetDockWindowSize(DockState.DockRight); DockWindows[DockState.DockTop].Height = GetDockWindowSize(DockState.DockTop); DockWindows[DockState.DockBottom].Height = GetDockWindowSize(DockState.DockBottom); AutoHideWindow.Bounds = GetAutoHideWindowBounds(AutoHideWindowRectangle); DockWindow documentDockWindow = DockWindows[DockState.Document]; if (ReferenceEquals(documentDockWindow.Parent, AutoHideWindow.Parent)) { AutoHideWindow.Parent.Controls.SetChildIndex(AutoHideWindow, 0); documentDockWindow.Parent.Controls.SetChildIndex(documentDockWindow, 1); } else { documentDockWindow.BringToFront(); AutoHideWindow.BringToFront(); } base.OnLayout(levent); if (DocumentStyle == DocumentStyle.SystemMdi && MdiClientExists) { SetMdiClientBounds(SystemMdiClientBounds); InvalidateWindowRegion(); } else if (DocumentStyle == DocumentStyle.DockingMdi) { InvalidateWindowRegion(); } ResumeLayout(true, true); } internal Rectangle GetTabStripRectangle(DockState dockState) { return AutoHideStripControl.GetTabStripRectangle(dockState); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (DockBackColor.ToArgb() == BackColor.ToArgb()) return; Graphics g = e.Graphics; SolidBrush bgBrush = new SolidBrush(DockBackColor); g.FillRectangle(bgBrush, ClientRectangle); } internal void AddContent(IDockContent content) { if (content == null) throw(new ArgumentNullException()); if (!Contents.Contains(content)) { Contents.Add(content); OnContentAdded(new DockContentEventArgs(content)); } } internal void AddPane(DockPane pane) { if (Panes.Contains(pane)) return; Panes.Add(pane); } internal void AddFloatWindow(FloatWindow floatWindow) { if (FloatWindows.Contains(floatWindow)) return; FloatWindows.Add(floatWindow); } private void CalculateDockPadding() { DockPadding.All = Theme.Measures.DockPadding; int standard = AutoHideStripControl.MeasureHeight(); if (AutoHideStripControl.GetNumberOfPanes(DockState.DockLeftAutoHide) > 0) DockPadding.Left = standard; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockRightAutoHide) > 0) DockPadding.Right = standard; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockTopAutoHide) > 0) DockPadding.Top = standard; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockBottomAutoHide) > 0) DockPadding.Bottom = standard; } internal void RemoveContent(IDockContent content) { if (content == null) throw(new ArgumentNullException()); if (Contents.Contains(content)) { Contents.Remove(content); OnContentRemoved(new DockContentEventArgs(content)); } } internal void RemovePane(DockPane pane) { if (!Panes.Contains(pane)) return; Panes.Remove(pane); } internal void RemoveFloatWindow(FloatWindow floatWindow) { if (!FloatWindows.Contains(floatWindow)) return; FloatWindows.Remove(floatWindow); if (FloatWindows.Count != 0) return; if (ParentForm == null) return; ParentForm.Focus(); } public void SetPaneIndex(DockPane pane, int index) { int oldIndex = Panes.IndexOf(pane); if (oldIndex == -1) throw(new ArgumentException(Strings.DockPanel_SetPaneIndex_InvalidPane)); if (index < 0 || index > Panes.Count - 1) if (index != -1) throw(new ArgumentOutOfRangeException(Strings.DockPanel_SetPaneIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Panes.Count - 1 && index == -1) return; Panes.Remove(pane); if (index == -1) Panes.Add(pane); else if (oldIndex < index) Panes.AddAt(pane, index - 1); else Panes.AddAt(pane, index); } public void SuspendLayout(bool allWindows) { FocusManager.SuspendFocusTracking(); SuspendLayout(); if (allWindows) SuspendMdiClientLayout(); } public void ResumeLayout(bool performLayout, bool allWindows) { FocusManager.ResumeFocusTracking(); ResumeLayout(performLayout); if (allWindows) ResumeMdiClientLayout(performLayout); } internal Form ParentForm { get { if (!IsParentFormValid()) throw new InvalidOperationException(Strings.DockPanel_ParentForm_Invalid); return GetMdiClientController().ParentForm; } } private bool IsParentFormValid() { if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow) return true; if (!MdiClientExists) GetMdiClientController().RenewMdiClient(); return (MdiClientExists); } protected override void OnParentChanged(EventArgs e) { SetAutoHideWindowParent(); GetMdiClientController().ParentForm = (this.Parent as Form); base.OnParentChanged (e); } private void SetAutoHideWindowParent() { Control parent; if (DocumentStyle == DocumentStyle.DockingMdi || DocumentStyle == DocumentStyle.SystemMdi) parent = this.Parent; else parent = this; if (AutoHideWindow.Parent != parent) { AutoHideWindow.Parent = parent; AutoHideWindow.BringToFront(); } } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged (e); if (Visible) SetMdiClient(); } private Rectangle SystemMdiClientBounds { get { if (!IsParentFormValid() || !Visible) return Rectangle.Empty; Rectangle rect = ParentForm.RectangleToClient(RectangleToScreen(DocumentWindowBounds)); return rect; } } public Rectangle DocumentWindowBounds { get { Rectangle rectDocumentBounds = DisplayRectangle; if (DockWindows[DockState.DockLeft].Visible) { rectDocumentBounds.X += DockWindows[DockState.DockLeft].Width; rectDocumentBounds.Width -= DockWindows[DockState.DockLeft].Width; } if (DockWindows[DockState.DockRight].Visible) rectDocumentBounds.Width -= DockWindows[DockState.DockRight].Width; if (DockWindows[DockState.DockTop].Visible) { rectDocumentBounds.Y += DockWindows[DockState.DockTop].Height; rectDocumentBounds.Height -= DockWindows[DockState.DockTop].Height; } if (DockWindows[DockState.DockBottom].Visible) rectDocumentBounds.Height -= DockWindows[DockState.DockBottom].Height; return rectDocumentBounds; } } private PaintEventHandler m_dummyControlPaintEventHandler = null; private void InvalidateWindowRegion() { if (DesignMode) return; if (m_dummyControlPaintEventHandler == null) m_dummyControlPaintEventHandler = new PaintEventHandler(DummyControl_Paint); DummyControl.Paint += m_dummyControlPaintEventHandler; DummyControl.Invalidate(); } void DummyControl_Paint(object sender, PaintEventArgs e) { DummyControl.Paint -= m_dummyControlPaintEventHandler; UpdateWindowRegion(); } private void UpdateWindowRegion() { if (this.DocumentStyle == DocumentStyle.DockingMdi) UpdateWindowRegion_ClipContent(); else if (this.DocumentStyle == DocumentStyle.DockingSdi || this.DocumentStyle == DocumentStyle.DockingWindow) UpdateWindowRegion_FullDocumentArea(); else if (this.DocumentStyle == DocumentStyle.SystemMdi) UpdateWindowRegion_EmptyDocumentArea(); } private void UpdateWindowRegion_FullDocumentArea() { SetRegion(null); } private void UpdateWindowRegion_EmptyDocumentArea() { Rectangle rect = DocumentWindowBounds; SetRegion(new Rectangle[] { rect }); } private void UpdateWindowRegion_ClipContent() { int count = 0; foreach (DockPane pane in this.Panes) { if (!pane.Visible || pane.DockState != DockState.Document) continue; count ++; } if (count == 0) { SetRegion(null); return; } Rectangle[] rects = new Rectangle[count]; int i = 0; foreach (DockPane pane in this.Panes) { if (!pane.Visible || pane.DockState != DockState.Document) continue; rects[i] = RectangleToClient(pane.RectangleToScreen(pane.ContentRectangle)); i++; } SetRegion(rects); } private Rectangle[] m_clipRects = null; private void SetRegion(Rectangle[] clipRects) { if (!IsClipRectsChanged(clipRects)) return; m_clipRects = clipRects; if (m_clipRects == null || m_clipRects.GetLength(0) == 0) Region = null; else { Region region = new Region(new Rectangle(0, 0, this.Width, this.Height)); foreach (Rectangle rect in m_clipRects) region.Exclude(rect); if (Region != null) { Region.Dispose(); } Region = region; } } private bool IsClipRectsChanged(Rectangle[] clipRects) { if (clipRects == null && m_clipRects == null) return false; else if ((clipRects == null) != (m_clipRects == null)) return true; foreach (Rectangle rect in clipRects) { bool matched = false; foreach (Rectangle rect2 in m_clipRects) { if (rect == rect2) { matched = true; break; } } if (!matched) return true; } foreach (Rectangle rect2 in m_clipRects) { bool matched = false; foreach (Rectangle rect in clipRects) { if (rect == rect2) { matched = true; break; } } if (!matched) return true; } return false; } private static readonly object ActiveAutoHideContentChangedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ActiveAutoHideContentChanged_Description")] public event EventHandler ActiveAutoHideContentChanged { add { Events.AddHandler(ActiveAutoHideContentChangedEvent, value); } remove { Events.RemoveHandler(ActiveAutoHideContentChangedEvent, value); } } protected virtual void OnActiveAutoHideContentChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActiveAutoHideContentChangedEvent]; if (handler != null) handler(this, e); } private void m_autoHideWindow_ActiveContentChanged(object sender, EventArgs e) { OnActiveAutoHideContentChanged(e); } private static readonly object ContentAddedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ContentAdded_Description")] public event EventHandler<DockContentEventArgs> ContentAdded { add { Events.AddHandler(ContentAddedEvent, value); } remove { Events.RemoveHandler(ContentAddedEvent, value); } } protected virtual void OnContentAdded(DockContentEventArgs e) { EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentAddedEvent]; if (handler != null) handler(this, e); } private static readonly object ContentRemovedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ContentRemoved_Description")] public event EventHandler<DockContentEventArgs> ContentRemoved { add { Events.AddHandler(ContentRemovedEvent, value); } remove { Events.RemoveHandler(ContentRemovedEvent, value); } } protected virtual void OnContentRemoved(DockContentEventArgs e) { EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentRemovedEvent]; if (handler != null) handler(this, e); } internal void ResetDockWindows() { if (m_autoHideWindow == null) { return; } var old = m_dockWindows; LoadDockWindows(); foreach (var dockWindow in old) { Controls.Remove(dockWindow); dockWindow.Dispose(); } } internal void LoadDockWindows() { m_dockWindows = new DockWindowCollection(this); foreach (var dockWindow in DockWindows) { Controls.Add(dockWindow); } } public void ResetAutoHideStripWindow() { var old = m_autoHideWindow; m_autoHideWindow = Theme.Extender.AutoHideWindowFactory.CreateAutoHideWindow(this); m_autoHideWindow.Visible = false; SetAutoHideWindowParent(); old.Visible = false; old.Parent = null; old.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace CppSharp.AST { /// <summary> /// Represents a declaration context. /// </summary> public abstract class DeclarationContext : Declaration { public bool IsAnonymous { get; set; } public List<Declaration> Declarations; public List<TypeReference> TypeReferences; public DeclIterator<Namespace> Namespaces { get { return new DeclIterator<Namespace>(Declarations); } } public DeclIterator<Enumeration> Enums { get { return new DeclIterator<Enumeration>(Declarations); } } public DeclIterator<Function> Functions { get { return new DeclIterator<Function>(Declarations); } } public DeclIterator<Class> Classes { get { return new DeclIterator<Class>(Declarations); } } public DeclIterator<Template> Templates { get { return new DeclIterator<Template>(Declarations); } } public DeclIterator<TypedefNameDecl> Typedefs { get { return new DeclIterator<TypedefNameDecl>(Declarations); } } public DeclIterator<Variable> Variables { get { return new DeclIterator<Variable>(Declarations); } } public DeclIterator<Event> Events { get { return new DeclIterator<Event>(Declarations); } } // Used to keep track of anonymous declarations. public Dictionary<ulong, Declaration> Anonymous; // True if the context is inside an extern "C" context. public bool IsExternCContext; public override string LogicalName { get { return IsAnonymous ? "<anonymous>" : base.Name; } } public override string LogicalOriginalName { get { return IsAnonymous ? "<anonymous>" : base.OriginalName; } } protected DeclarationContext() { Declarations = new List<Declaration>(); TypeReferences = new List<TypeReference>(); Anonymous = new Dictionary<ulong, Declaration>(); } protected DeclarationContext(DeclarationContext dc) : base(dc) { Declarations = dc.Declarations; TypeReferences = new List<TypeReference>(dc.TypeReferences); Anonymous = new Dictionary<ulong, Declaration>(dc.Anonymous); IsAnonymous = dc.IsAnonymous; } public IEnumerable<DeclarationContext> GatherParentNamespaces() { var children = new Stack<DeclarationContext>(); var currentNamespace = this; while (currentNamespace != null) { if (!(currentNamespace is TranslationUnit)) children.Push(currentNamespace); currentNamespace = currentNamespace.Namespace; } return children; } public Declaration FindAnonymous(ulong key) { return Anonymous.ContainsKey(key) ? Anonymous[key] : null; } public DeclarationContext FindDeclaration(IEnumerable<string> declarations) { DeclarationContext currentDeclaration = this; foreach (var declaration in declarations) { var subDeclaration = currentDeclaration.Namespaces .Concat<DeclarationContext>(currentDeclaration.Classes) .FirstOrDefault(e => e.Name.Equals(declaration)); if (subDeclaration == null) return null; currentDeclaration = subDeclaration; } return currentDeclaration as DeclarationContext; } public Namespace FindNamespace(string name) { var namespaces = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries); return FindNamespace(namespaces); } public Namespace FindNamespace(IEnumerable<string> namespaces) { DeclarationContext currentNamespace = this; foreach (var @namespace in namespaces) { var childNamespace = currentNamespace.Namespaces.Find( e => e.Name.Equals(@namespace)); if (childNamespace == null) return null; currentNamespace = childNamespace; } return currentNamespace as Namespace; } public Namespace FindCreateNamespace(string name) { var @namespace = FindNamespace(name); if (@namespace == null) { @namespace = new Namespace { Name = name, Namespace = this, }; Namespaces.Add(@namespace); } return @namespace; } public Enumeration FindEnum(string name, bool createDecl = false) { var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var @enum = Enums.Find(e => e.Name.Equals(name)); if (@enum == null && createDecl) { @enum = new Enumeration() { Name = name, Namespace = this }; Enums.Add(@enum); } return @enum; } var enumName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindEnum(enumName, createDecl); } public Enumeration FindEnum(IntPtr ptr) { return Enums.FirstOrDefault(f => f.OriginalPtr == ptr); } public Function FindFunction(string name, bool createDecl = false) { if (string.IsNullOrEmpty(name)) return null; var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var function = Functions.Find(e => e.Name.Equals(name)); if (function == null && createDecl) { function = new Function() { Name = name, Namespace = this }; Functions.Add(function); } return function; } var funcName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindFunction(funcName, createDecl); } public Function FindFunctionByUSR(string usr) { return Functions .Concat(Templates.OfType<FunctionTemplate>() .Select(t => t.TemplatedFunction)) .FirstOrDefault(f => f.USR == usr); } Class CreateClass(string name, bool isComplete) { var @class = new Class { Name = name, Namespace = this, IsIncomplete = !isComplete }; return @class; } public Class FindClass(string name, StringComparison stringComparison = StringComparison.Ordinal) { if (string.IsNullOrEmpty(name)) return null; var entries = name.Split(new[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var @class = Classes.Find(c => c.Name.Equals(name, stringComparison)) ?? Namespaces.Select(n => n.FindClass(name, stringComparison)).FirstOrDefault(c => c != null); if (@class != null) return @class.CompleteDeclaration == null ? @class : (Class) @class.CompleteDeclaration; return null; } var className = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); DeclarationContext declContext = FindDeclaration(namespaces); if (declContext == null) { declContext = FindClass(entries[0]); if (declContext == null) return null; } return declContext.FindClass(className); } public Class FindClass(string name, bool isComplete, bool createDecl = false) { var @class = FindClass(name); if (@class == null) { if (createDecl) { @class = CreateClass(name, isComplete); Classes.Add(@class); } return @class; } if (@class.IsIncomplete == !isComplete) return @class; if (!createDecl) return null; var newClass = CreateClass(name, isComplete); // Replace the incomplete declaration with the complete one. if (@class.IsIncomplete) { @class.CompleteDeclaration = newClass; Classes.Replace(@class, newClass); } return newClass; } public FunctionTemplate FindFunctionTemplate(string name) { return Templates.OfType<FunctionTemplate>() .FirstOrDefault(t => t.Name == name); } public FunctionTemplate FindFunctionTemplateByUSR(string usr) { return Templates.OfType<FunctionTemplate>() .FirstOrDefault(t => t.USR == usr); } public IEnumerable<ClassTemplate> FindClassTemplate(string name) { foreach (var template in Templates.OfType<ClassTemplate>().Where(t => t.Name == name)) yield return template; foreach (var @namespace in Namespaces) foreach (var template in @namespace.FindClassTemplate(name)) yield return template; } public ClassTemplate FindClassTemplateByUSR(string usr) { return Templates.OfType<ClassTemplate>() .FirstOrDefault(t => t.USR == usr); } public TypedefNameDecl FindTypedef(string name, bool createDecl = false) { var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var typeDef = Typedefs.Find(e => e.Name.Equals(name)); if (typeDef == null && createDecl) { typeDef = new TypedefDecl { Name = name, Namespace = this }; Typedefs.Add(typeDef); } return typeDef; } var typeDefName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindTypedef(typeDefName, createDecl); } public T FindType<T>(string name) where T : Declaration { var type = FindEnum(name) ?? FindFunction(name) ?? (Declaration)FindClass(name) ?? FindTypedef(name); return type as T; } public Enumeration FindEnumWithItem(string name) { var result = Enums.Find(e => e.ItemsByName.ContainsKey(name)); if (result == null) result = Namespaces.Select(ns => ns.FindEnumWithItem(name)).FirstOrDefault(); if (result == null) result = Classes.Select(c => c.FindEnumWithItem(name)).FirstOrDefault(); return result; } public virtual IEnumerable<Function> FindOperator(CXXOperatorKind kind) { return Functions.Where(fn => fn.OperatorKind == kind); } public virtual IEnumerable<Function> GetOverloads(Function function) { if (function.IsOperator) return FindOperator(function.OperatorKind); return Functions.Where(fn => fn.Name == function.Name); } public bool HasDeclarations { get { Func<Declaration, bool> pred = (t => t.IsGenerated); return Enums.Exists(pred) || HasFunctions || Typedefs.Exists(pred) || Classes.Any() || Namespaces.Exists(n => n.HasDeclarations) || Templates.Any(pred); } } public bool HasFunctions { get { Func<Declaration, bool> pred = (t => t.IsGenerated); return Functions.Exists(pred) || Namespaces.Exists(n => n.HasFunctions); } } public bool IsRoot { get { return Namespace == null; } } } /// <summary> /// Represents a C++ namespace. /// </summary> public class Namespace : DeclarationContext { public override string LogicalName { get { return IsInline ? string.Empty : base.Name; } } public override string LogicalOriginalName { get { return IsInline ? string.Empty : base.OriginalName; } } public bool IsInline; public override T Visit<T>(IDeclVisitor<T> visitor) { return visitor.VisitNamespace(this); } } }
// <copyright file="TracerProviderSdkTest.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using OpenTelemetry.Instrumentation; using OpenTelemetry.Resources; using OpenTelemetry.Tests; using Xunit; namespace OpenTelemetry.Trace.Tests { public class TracerProviderSdkTest : IDisposable { private const string ActivitySourceName = "TraceSdkTest"; public TracerProviderSdkTest() { Activity.DefaultIdFormat = ActivityIdFormat.W3C; } [Fact] public void TracerProviderSdkAddSource() { using var source1 = new ActivitySource($"{Utils.GetCurrentMethodName()}.1"); using var source2 = new ActivitySource($"{Utils.GetCurrentMethodName()}.2"); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(source1.Name) .Build(); using (var activity = source1.StartActivity("test")) { Assert.NotNull(activity); } using (var activity = source2.StartActivity("test")) { Assert.Null(activity); } } [Fact] public void TracerProviderSdkAddSourceWithWildcards() { using var source1 = new ActivitySource($"{Utils.GetCurrentMethodName()}.A"); using var source2 = new ActivitySource($"{Utils.GetCurrentMethodName()}.Ab"); using var source3 = new ActivitySource($"{Utils.GetCurrentMethodName()}.Abc"); using var source4 = new ActivitySource($"{Utils.GetCurrentMethodName()}.B"); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource($"{Utils.GetCurrentMethodName()}.*") .Build()) { using (var activity = source1.StartActivity("test")) { Assert.NotNull(activity); } using (var activity = source2.StartActivity("test")) { Assert.NotNull(activity); } using (var activity = source3.StartActivity("test")) { Assert.NotNull(activity); } using (var activity = source4.StartActivity("test")) { Assert.NotNull(activity); } } using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource($"{Utils.GetCurrentMethodName()}.?") .Build()) { using (var activity = source1.StartActivity("test")) { Assert.NotNull(activity); } using (var activity = source2.StartActivity("test")) { Assert.Null(activity); } using (var activity = source3.StartActivity("test")) { Assert.Null(activity); } using (var activity = source4.StartActivity("test")) { Assert.NotNull(activity); } } } [Fact] public void TracerProviderSdkInvokesSamplingWithCorrectParameters() { var testSampler = new TestSampler(); using var activitySource = new ActivitySource(ActivitySourceName); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(ActivitySourceName) .SetSampler(testSampler) .Build(); // OpenTelemetry Sdk is expected to set default to W3C. Assert.True(Activity.DefaultIdFormat == ActivityIdFormat.W3C); using (var rootActivity = activitySource.StartActivity("root")) { Assert.NotNull(rootActivity); Assert.True(rootActivity.ParentSpanId == default); // Validate that the TraceId seen by Sampler is same as the // Activity when it got created. Assert.Equal(rootActivity.TraceId, testSampler.LatestSamplingParameters.TraceId); } using (var parent = activitySource.StartActivity("parent", ActivityKind.Client)) { Assert.Equal(parent.TraceId, testSampler.LatestSamplingParameters.TraceId); using (var child = activitySource.StartActivity("child")) { Assert.Equal(child.TraceId, testSampler.LatestSamplingParameters.TraceId); Assert.Equal(parent.TraceId, child.TraceId); Assert.Equal(parent.SpanId, child.ParentSpanId); } } var customContext = new ActivityContext( ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None); using (var fromCustomContext = activitySource.StartActivity("customContext", ActivityKind.Client, customContext)) { Assert.Equal(fromCustomContext.TraceId, testSampler.LatestSamplingParameters.TraceId); Assert.Equal(customContext.TraceId, fromCustomContext.TraceId); Assert.Equal(customContext.SpanId, fromCustomContext.ParentSpanId); Assert.NotEqual(customContext.SpanId, fromCustomContext.SpanId); } // Validate that when StartActivity is called using Parent as string, // Sampling is called correctly. var act = new Activity("anything").Start(); act.Stop(); var customContextAsString = act.Id; var expectedTraceId = act.TraceId; var expectedParentSpanId = act.SpanId; using (var fromCustomContextAsString = activitySource.StartActivity("customContext", ActivityKind.Client, customContextAsString)) { Assert.Equal(fromCustomContextAsString.TraceId, testSampler.LatestSamplingParameters.TraceId); Assert.Equal(expectedTraceId, fromCustomContextAsString.TraceId); Assert.Equal(expectedParentSpanId, fromCustomContextAsString.ParentSpanId); } using (var fromInvalidW3CIdParent = activitySource.StartActivity("customContext", ActivityKind.Client, "InvalidW3CIdParent")) { // Verify that StartActivity returns an instance of Activity. Assert.NotNull(fromInvalidW3CIdParent); // Verify that the TestSampler was invoked and received the correct params. Assert.Equal(fromInvalidW3CIdParent.TraceId, testSampler.LatestSamplingParameters.TraceId); // OpenTelemetry ActivityContext does not support non W3C Ids. Assert.Null(fromInvalidW3CIdParent.ParentId); Assert.Equal(default(ActivitySpanId), fromInvalidW3CIdParent.ParentSpanId); } } [Theory] [InlineData(SamplingDecision.Drop)] [InlineData(SamplingDecision.RecordOnly)] [InlineData(SamplingDecision.RecordAndSample)] public void TracerProviderSdkSamplerAttributesAreAppliedToActivity(SamplingDecision sampling) { var testSampler = new TestSampler(); testSampler.SamplingAction = (samplingParams) => { var attributes = new Dictionary<string, object>(); attributes.Add("tagkeybysampler", "tagvalueaddedbysampler"); return new SamplingResult(sampling, attributes); }; using var activitySource = new ActivitySource(ActivitySourceName); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(ActivitySourceName) .SetSampler(testSampler) .Build(); using (var rootActivity = activitySource.StartActivity("root")) { Assert.NotNull(rootActivity); Assert.Equal(rootActivity.TraceId, testSampler.LatestSamplingParameters.TraceId); if (sampling != SamplingDecision.Drop) { Assert.Contains(new KeyValuePair<string, object>("tagkeybysampler", "tagvalueaddedbysampler"), rootActivity.TagObjects); } } } [Fact] public void TracerSdkSetsActivitySamplingResultBasedOnSamplingDecision() { var testSampler = new TestSampler(); using var activitySource = new ActivitySource(ActivitySourceName); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(ActivitySourceName) .SetSampler(testSampler) .Build(); testSampler.SamplingAction = (samplingParameters) => { return new SamplingResult(SamplingDecision.RecordAndSample); }; using (var activity = activitySource.StartActivity("root")) { Assert.NotNull(activity); Assert.True(activity.IsAllDataRequested); Assert.True(activity.Recorded); } testSampler.SamplingAction = (samplingParameters) => { return new SamplingResult(SamplingDecision.RecordOnly); }; using (var activity = activitySource.StartActivity("root")) { // Even if sampling returns false, for root activities, // activity is still created with PropagationOnly. Assert.NotNull(activity); Assert.True(activity.IsAllDataRequested); Assert.False(activity.Recorded); } testSampler.SamplingAction = (samplingParameters) => { return new SamplingResult(SamplingDecision.Drop); }; using (var activity = activitySource.StartActivity("root")) { // Even if sampling returns false, for root activities, // activity is still created with PropagationOnly. Assert.NotNull(activity); Assert.False(activity.IsAllDataRequested); Assert.False(activity.Recorded); using (var innerActivity = activitySource.StartActivity("inner")) { // This is not a root activity. // If sampling returns false, no activity is created at all. Assert.Null(innerActivity); } } } [Fact] public void TracerSdkSetsActivitySamplingResultToNoneWhenSuppressInstrumentationIsTrue() { using var scope = SuppressInstrumentationScope.Begin(); var testSampler = new TestSampler(); using var activitySource = new ActivitySource(ActivitySourceName); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(ActivitySourceName) .SetSampler(testSampler) .Build(); using (var activity = activitySource.StartActivity("root")) { Assert.Null(activity); } } [Fact] public void TracerSdkSetsActivityDataRequestedToFalseWhenSuppressInstrumentationIsTrueForLegacyActivity() { using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { startCalled = true; }; testActivityProcessor.EndAction = (a) => { endCalled = true; }; using var openTelemetry = Sdk.CreateTracerProviderBuilder() .AddLegacySource("random") .AddProcessor(testActivityProcessor) .SetSampler(new AlwaysOnSampler()) .Build(); using (SuppressInstrumentationScope.Begin(true)) { using var activity = new Activity("random").Start(); Assert.False(activity.IsAllDataRequested); } Assert.False(startCalled); Assert.False(endCalled); } [Fact] public void ProcessorDoesNotReceiveNotRecordDecisionSpan() { var testSampler = new TestSampler(); using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { startCalled = true; }; testActivityProcessor.EndAction = (a) => { endCalled = true; }; using var openTelemetry = Sdk.CreateTracerProviderBuilder() .AddSource("random") .AddProcessor(testActivityProcessor) .SetSampler(testSampler) .Build(); testSampler.SamplingAction = (samplingParameters) => { return new SamplingResult(SamplingDecision.Drop); }; using ActivitySource source = new ActivitySource("random"); var activity = source.StartActivity("somename"); activity.Stop(); Assert.False(activity.IsAllDataRequested); Assert.Equal(ActivityTraceFlags.None, activity.ActivityTraceFlags); Assert.False(activity.Recorded); Assert.False(startCalled); Assert.False(endCalled); } // Test to check that TracerProvider does not call Processor.OnStart or Processor.OnEnd for a legacy activity when no legacy OperationName is // provided to TracerProviderBuilder. [Fact] public void SdkDoesNotProcessLegacyActivityWithNoAdditionalConfig() { using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true startCalled = true; }; testActivityProcessor.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true endCalled = true; }; var emptyActivitySource = new ActivitySource(string.Empty); Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet // No AddLegacyOperationName chained to TracerProviderBuilder using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddProcessor(testActivityProcessor) .Build(); Assert.False(emptyActivitySource.HasListeners()); // No listener for empty ActivitySource even after build Activity activity = new Activity("Test"); activity.Start(); activity.Stop(); Assert.False(startCalled); // Processor.OnStart is not called since we did not add any legacy OperationName Assert.False(endCalled); // Processor.OnEnd is not called since we did not add any legacy OperationName } // Test to check that TracerProvider samples a legacy activity using a custom Sampler and calls Processor.OnStart and Processor.OnEnd for the // legacy activity when the correct legacy OperationName is provided to TracerProviderBuilder. [Fact] public void SdkSamplesAndProcessesLegacyActivityWithRightConfig() { bool samplerCalled = false; var sampler = new TestSampler { SamplingAction = (samplingParameters) => { samplerCalled = true; return new SamplingResult(SamplingDecision.RecordAndSample); }, }; using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { Assert.True(samplerCalled); Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true startCalled = true; }; testActivityProcessor.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true endCalled = true; }; var emptyActivitySource = new ActivitySource(string.Empty); Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet var operationNameForLegacyActivity = "TestOperationName"; // AddLegacyOperationName chained to TracerProviderBuilder using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) .AddProcessor(testActivityProcessor) .AddLegacySource(operationNameForLegacyActivity) .Build(); Assert.True(emptyActivitySource.HasListeners()); // Listener for empty ActivitySource added after TracerProvider build Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); activity.Stop(); Assert.True(startCalled); // Processor.OnStart is called since we added a legacy OperationName Assert.True(endCalled); // Processor.OnEnd is called since we added a legacy OperationName } // Test to check that TracerProvider samples a legacy activity using a custom Sampler and calls Processor.OnStart and Processor.OnEnd for the // legacy activity when the correct legacy OperationName is provided to TracerProviderBuilder and a wildcard Source is added [Fact] public void SdkSamplesAndProcessesLegacyActivityWithRightConfigOnWildCardMode() { bool samplerCalled = false; var sampler = new TestSampler { SamplingAction = (samplingParameters) => { samplerCalled = true; return new SamplingResult(SamplingDecision.RecordAndSample); }, }; using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { Assert.True(samplerCalled); Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true startCalled = true; }; testActivityProcessor.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true endCalled = true; }; var emptyActivitySource = new ActivitySource(string.Empty); Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet var operationNameForLegacyActivity = "TestOperationName"; // AddLegacyOperationName chained to TracerProviderBuilder using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) .AddSource("ABCCompany.XYZProduct.*") // Adding a wild card source .AddProcessor(testActivityProcessor) .AddLegacySource(operationNameForLegacyActivity) .Build(); Assert.True(emptyActivitySource.HasListeners()); // Listener for empty ActivitySource added after TracerProvider build Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); activity.Stop(); Assert.True(startCalled); // Processor.OnStart is called since we added a legacy OperationName Assert.True(endCalled); // Processor.OnEnd is called since we added a legacy OperationName } // Test to check that TracerProvider does not call Processor.OnEnd for a legacy activity whose ActivitySource got updated before Activity.Stop and // the updated source was not added to the Provider [Fact] public void SdkCallsOnlyProcessorOnStartForLegacyActivityWhenActivitySourceIsUpdatedWithoutAddSource() { using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true startCalled = true; }; testActivityProcessor.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true endCalled = true; }; var emptyActivitySource = new ActivitySource(string.Empty); Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet var operationNameForLegacyActivity = "TestOperationName"; var activitySourceForLegacyActvity = new ActivitySource("TestActivitySource", "1.0.0"); // AddLegacyOperationName chained to TracerProviderBuilder using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddLegacySource(operationNameForLegacyActivity) .AddProcessor(testActivityProcessor) .Build(); Assert.True(emptyActivitySource.HasListeners()); // Listener for empty ActivitySource added after TracerProvider build Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); ActivityInstrumentationHelper.SetActivitySourceProperty(activity, activitySourceForLegacyActvity); activity.Stop(); Assert.True(startCalled); // Processor.OnStart is called since we provided the legacy OperationName Assert.False(endCalled); // Processor.OnEnd is not called since the ActivitySource is updated and the updated source name is not added as a Source to the provider } // Test to check that TracerProvider calls Processor.OnStart and Processor.OnEnd for a legacy activity whose ActivitySource got updated before Activity.Stop and // the updated source was added to the Provider [Fact] public void SdkProcessesLegacyActivityWhenActivitySourceIsUpdatedWithAddSource() { using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true startCalled = true; }; testActivityProcessor.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true endCalled = true; }; var emptyActivitySource = new ActivitySource(string.Empty); Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet var operationNameForLegacyActivity = "TestOperationName"; var activitySourceForLegacyActvity = new ActivitySource("TestActivitySource", "1.0.0"); // AddLegacyOperationName chained to TracerProviderBuilder using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(activitySourceForLegacyActvity.Name) // Add the updated ActivitySource as a Source .AddLegacySource(operationNameForLegacyActivity) .AddProcessor(testActivityProcessor) .Build(); Assert.True(emptyActivitySource.HasListeners()); // Listener for empty ActivitySource added after TracerProvider build Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); ActivityInstrumentationHelper.SetActivitySourceProperty(activity, activitySourceForLegacyActvity); activity.Stop(); Assert.True(startCalled); // Processor.OnStart is called since we provided the legacy OperationName Assert.True(endCalled); // Processor.OnEnd is not called since the ActivitySource is updated and the updated source name is added as a Source to the provider } // Test to check that TracerProvider continues to process legacy activities even after a new Processor is added after the building the provider. [Fact] public void SdkProcessesLegacyActivityEvenAfterAddingNewProcessor() { using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); bool startCalled = false; bool endCalled = false; testActivityProcessor.StartAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true startCalled = true; }; testActivityProcessor.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true endCalled = true; }; var operationNameForLegacyActivity = "TestOperationName"; // AddLegacyOperationName chained to TracerProviderBuilder using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddProcessor(testActivityProcessor) .AddLegacySource(operationNameForLegacyActivity) .Build(); Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); activity.Stop(); Assert.True(startCalled); Assert.True(endCalled); // As Processors can be added anytime after Provider construction, the following validates // the following validates that updated processors are processing the legacy activities created from here on. TestActivityProcessor testActivityProcessorNew = new TestActivityProcessor(); bool startCalledNew = false; bool endCalledNew = false; testActivityProcessorNew.StartAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true startCalledNew = true; }; testActivityProcessorNew.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true endCalledNew = true; }; tracerProvider.AddProcessor(testActivityProcessorNew); Activity activityNew = new Activity(operationNameForLegacyActivity); // Create a new Activity with the same operation name activityNew.Start(); activityNew.Stop(); Assert.True(startCalledNew); Assert.True(endCalledNew); } [Fact] public void SdkSamplesLegacyActivityWithAlwaysOnSampler() { var operationNameForLegacyActivity = "TestOperationName"; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(new AlwaysOnSampler()) .AddLegacySource(operationNameForLegacyActivity) .Build(); Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); Assert.True(activity.IsAllDataRequested); Assert.True(activity.ActivityTraceFlags.HasFlag(ActivityTraceFlags.Recorded)); // Validating ActivityTraceFlags is not enough as it does not get reflected on // Id, If the Id is accessed before the sampler runs. // https://github.com/open-telemetry/opentelemetry-dotnet/issues/2700 Assert.EndsWith("-01", activity.Id); activity.Stop(); } [Fact] public void SdkSamplesLegacyActivityWithAlwaysOffSampler() { var operationNameForLegacyActivity = "TestOperationName"; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(new AlwaysOffSampler()) .AddLegacySource(operationNameForLegacyActivity) .Build(); Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); Assert.False(activity.IsAllDataRequested); Assert.False(activity.ActivityTraceFlags.HasFlag(ActivityTraceFlags.Recorded)); // Validating ActivityTraceFlags is not enough as it does not get reflected on // Id, If the Id is accessed before the sampler runs. // https://github.com/open-telemetry/opentelemetry-dotnet/issues/2700 Assert.EndsWith("-00", activity.Id); activity.Stop(); } [Theory] [InlineData(SamplingDecision.Drop, false, false)] [InlineData(SamplingDecision.RecordOnly, true, false)] [InlineData(SamplingDecision.RecordAndSample, true, true)] public void SdkSamplesLegacyActivityWithCustomSampler(SamplingDecision samplingDecision, bool isAllDataRequested, bool hasRecordedFlag) { var operationNameForLegacyActivity = "TestOperationName"; var sampler = new TestSampler() { SamplingAction = (samplingParameters) => new SamplingResult(samplingDecision) }; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) .AddLegacySource(operationNameForLegacyActivity) .Build(); Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); Assert.Equal(isAllDataRequested, activity.IsAllDataRequested); Assert.Equal(hasRecordedFlag, activity.ActivityTraceFlags.HasFlag(ActivityTraceFlags.Recorded)); // Validating ActivityTraceFlags is not enough as it does not get reflected on // Id, If the Id is accessed before the sampler runs. // https://github.com/open-telemetry/opentelemetry-dotnet/issues/2700 Assert.EndsWith(hasRecordedFlag ? "-01" : "-00", activity.Id); activity.Stop(); } [Fact] public void SdkPopulatesSamplingParamsCorrectlyForRootLegacyActivity() { var operationNameForLegacyActivity = "TestOperationName"; var sampler = new TestSampler() { SamplingAction = (samplingParameters) => { Assert.Equal(default, samplingParameters.ParentContext); return new SamplingResult(SamplingDecision.RecordAndSample); }, }; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) .AddLegacySource(operationNameForLegacyActivity) .Build(); // Start activity without setting parent. i.e it'll have null parent // and becomes root activity Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); activity.Stop(); } [Theory] [InlineData(SamplingDecision.Drop, ActivityTraceFlags.None, false, false)] [InlineData(SamplingDecision.Drop, ActivityTraceFlags.Recorded, false, false)] [InlineData(SamplingDecision.RecordOnly, ActivityTraceFlags.None, true, false)] [InlineData(SamplingDecision.RecordOnly, ActivityTraceFlags.Recorded, true, false)] [InlineData(SamplingDecision.RecordAndSample, ActivityTraceFlags.None, true, true)] [InlineData(SamplingDecision.RecordAndSample, ActivityTraceFlags.Recorded, true, true)] public void SdkSamplesLegacyActivityWithRemoteParentWithCustomSampler(SamplingDecision samplingDecision, ActivityTraceFlags parentTraceFlags, bool expectedIsAllDataRequested, bool hasRecordedFlag) { var parentTraceId = ActivityTraceId.CreateRandom(); var parentSpanId = ActivitySpanId.CreateRandom(); var parentTraceFlag = (parentTraceFlags == ActivityTraceFlags.Recorded) ? "01" : "00"; string remoteParentId = $"00-{parentTraceId}-{parentSpanId}-{parentTraceFlag}"; string tracestate = "a=b;c=d"; var operationNameForLegacyActivity = "TestOperationName"; var sampler = new TestSampler() { SamplingAction = (samplingParameters) => { // Ensure that SDK populates the sampling parameters correctly Assert.Equal(parentTraceId, samplingParameters.ParentContext.TraceId); Assert.Equal(parentSpanId, samplingParameters.ParentContext.SpanId); Assert.Equal(parentTraceFlags, samplingParameters.ParentContext.TraceFlags); Assert.Equal(tracestate, samplingParameters.ParentContext.TraceState); return new SamplingResult(samplingDecision); }, }; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) .AddLegacySource(operationNameForLegacyActivity) .Build(); // Create an activity with remote parent id. // The sampling parameters are expected to be that of the // parent context i.e the remote parent. Activity activity = new Activity(operationNameForLegacyActivity).SetParentId(remoteParentId); activity.TraceStateString = tracestate; // At this point SetParentId has set the ActivityTraceFlags to that of the parent activity. The activity is now passed to the sampler. activity.Start(); Assert.Equal(expectedIsAllDataRequested, activity.IsAllDataRequested); Assert.Equal(hasRecordedFlag, activity.ActivityTraceFlags.HasFlag(ActivityTraceFlags.Recorded)); // Validating ActivityTraceFlags is not enough as it does not get reflected on // Id, If the Id is accessed before the sampler runs. // https://github.com/open-telemetry/opentelemetry-dotnet/issues/2700 Assert.EndsWith(hasRecordedFlag ? "-01" : "-00", activity.Id); activity.Stop(); } [Theory] [InlineData(ActivityTraceFlags.None)] [InlineData(ActivityTraceFlags.Recorded)] public void SdkSamplesLegacyActivityWithRemoteParentWithAlwaysOnSampler(ActivityTraceFlags parentTraceFlags) { var parentTraceId = ActivityTraceId.CreateRandom(); var parentSpanId = ActivitySpanId.CreateRandom(); var parentTraceFlag = (parentTraceFlags == ActivityTraceFlags.Recorded) ? "01" : "00"; string remoteParentId = $"00-{parentTraceId}-{parentSpanId}-{parentTraceFlag}"; var operationNameForLegacyActivity = "TestOperationName"; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(new AlwaysOnSampler()) .AddLegacySource(operationNameForLegacyActivity) .Build(); // Create an activity with remote parent id. // The sampling parameters are expected to be that of the // parent context i.e the remote parent. Activity activity = new Activity(operationNameForLegacyActivity).SetParentId(remoteParentId); // At this point SetParentId has set the ActivityTraceFlags to that of the parent activity. The activity is now passed to the sampler. activity.Start(); Assert.True(activity.IsAllDataRequested); Assert.True(activity.ActivityTraceFlags.HasFlag(ActivityTraceFlags.Recorded)); // Validating ActivityTraceFlags is not enough as it does not get reflected on // Id, If the Id is accessed before the sampler runs. // https://github.com/open-telemetry/opentelemetry-dotnet/issues/2700 Assert.EndsWith("-01", activity.Id); activity.Stop(); } [Theory] [InlineData(ActivityTraceFlags.None)] [InlineData(ActivityTraceFlags.Recorded)] public void SdkSamplesLegacyActivityWithRemoteParentWithAlwaysOffSampler(ActivityTraceFlags parentTraceFlags) { var parentTraceId = ActivityTraceId.CreateRandom(); var parentSpanId = ActivitySpanId.CreateRandom(); var parentTraceFlag = (parentTraceFlags == ActivityTraceFlags.Recorded) ? "01" : "00"; string remoteParentId = $"00-{parentTraceId}-{parentSpanId}-{parentTraceFlag}"; var operationNameForLegacyActivity = "TestOperationName"; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(new AlwaysOffSampler()) .AddLegacySource(operationNameForLegacyActivity) .Build(); // Create an activity with remote parent id. // The sampling parameters are expected to be that of the // parent context i.e the remote parent. Activity activity = new Activity(operationNameForLegacyActivity).SetParentId(remoteParentId); // At this point SetParentId has set the ActivityTraceFlags to that of the parent activity. The activity is now passed to the sampler. activity.Start(); Assert.False(activity.IsAllDataRequested); Assert.False(activity.ActivityTraceFlags.HasFlag(ActivityTraceFlags.Recorded)); // Validating ActivityTraceFlags is not enough as it does not get reflected on // Id, If the Id is accessed before the sampler runs. // https://github.com/open-telemetry/opentelemetry-dotnet/issues/2700 Assert.EndsWith("-00", activity.Id); activity.Stop(); } [Theory] [InlineData(ActivityTraceFlags.None)] [InlineData(ActivityTraceFlags.Recorded)] public void SdkPopulatesSamplingParamsCorrectlyForLegacyActivityWithInProcParent(ActivityTraceFlags traceFlags) { // Create some parent activity. string tracestate = "a=b;c=d"; var activityLocalParent = new Activity("TestParent"); activityLocalParent.ActivityTraceFlags = traceFlags; activityLocalParent.TraceStateString = tracestate; activityLocalParent.Start(); var operationNameForLegacyActivity = "TestOperationName"; var sampler = new TestSampler() { SamplingAction = (samplingParameters) => { Assert.Equal(activityLocalParent.TraceId, samplingParameters.ParentContext.TraceId); Assert.Equal(activityLocalParent.SpanId, samplingParameters.ParentContext.SpanId); Assert.Equal(activityLocalParent.ActivityTraceFlags, samplingParameters.ParentContext.TraceFlags); Assert.Equal(tracestate, samplingParameters.ParentContext.TraceState); return new SamplingResult(SamplingDecision.RecordAndSample); }, }; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) .AddLegacySource(operationNameForLegacyActivity) .Build(); // This activity will have a inproc parent. // activity.Parent will be equal to the activity created at the beginning of this test. // Sampling parameters are expected to be that of the parentContext. // i.e of the parent Activity Activity activity = new Activity(operationNameForLegacyActivity); activity.Start(); activity.Stop(); } [Fact] public void TracerProvideSdkCreatesAndDiposesInstrumentation() { TestInstrumentation testInstrumentation = null; var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddInstrumentation(() => { testInstrumentation = new TestInstrumentation(); return testInstrumentation; }) .Build(); Assert.NotNull(testInstrumentation); Assert.False(testInstrumentation.IsDisposed); tracerProvider.Dispose(); Assert.True(testInstrumentation.IsDisposed); } [Fact] public void TracerProviderSdkBuildsWithDefaultResource() { var tracerProvider = Sdk.CreateTracerProviderBuilder().Build(); var resource = tracerProvider.GetResource(); var attributes = resource.Attributes; Assert.NotNull(resource); Assert.NotEqual(Resource.Empty, resource); Assert.Single(resource.Attributes); Assert.Equal(resource.Attributes.FirstOrDefault().Key, ResourceSemanticConventions.AttributeServiceName); Assert.Contains("unknown_service", (string)resource.Attributes.FirstOrDefault().Value); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void AddLegacyOperationName_BadArgs(string operationName) { var builder = Sdk.CreateTracerProviderBuilder(); Assert.Throws<ArgumentException>(() => builder.AddLegacySource(operationName)); } [Fact] public void AddLegacyOperationNameAddsActivityListenerForEmptyActivitySource() { var emptyActivitySource = new ActivitySource(string.Empty); var builder = Sdk.CreateTracerProviderBuilder(); builder.AddLegacySource("TestOperationName"); Assert.False(emptyActivitySource.HasListeners()); using var provider = builder.Build(); Assert.True(emptyActivitySource.HasListeners()); } [Fact] public void TracerProviderSdkBuildsWithSDKResource() { var tracerProvider = Sdk.CreateTracerProviderBuilder().SetResourceBuilder( ResourceBuilder.CreateDefault().AddTelemetrySdk()).Build(); var resource = tracerProvider.GetResource(); var attributes = resource.Attributes; Assert.NotNull(resource); Assert.NotEqual(Resource.Empty, resource); Assert.Contains(new KeyValuePair<string, object>("telemetry.sdk.name", "opentelemetry"), attributes); Assert.Contains(new KeyValuePair<string, object>("telemetry.sdk.language", "dotnet"), attributes); var versionAttribute = attributes.Where(pair => pair.Key.Equals("telemetry.sdk.version")); Assert.Single(versionAttribute); } [Fact] public void TracerProviderSdkFlushesProcessorForcibly() { using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddProcessor(testActivityProcessor) .Build(); var isFlushed = tracerProvider.ForceFlush(); Assert.True(isFlushed); Assert.True(testActivityProcessor.ForceFlushCalled); } [Fact] public void SdkSamplesAndProcessesLegacySourceWhenAddLegacySourceIsCalledWithWildcardValue() { var sampledActivities = new List<string>(); var sampler = new TestSampler { SamplingAction = (samplingParameters) => { sampledActivities.Add(samplingParameters.Name); return new SamplingResult(SamplingDecision.RecordAndSample); }, }; using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); var onStartProcessedActivities = new List<string>(); var onStopProcessedActivities = new List<string>(); testActivityProcessor.StartAction = (a) => { Assert.Contains(a.OperationName, sampledActivities); Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true onStartProcessedActivities.Add(a.OperationName); }; testActivityProcessor.EndAction = (a) => { Assert.False(Sdk.SuppressInstrumentation); Assert.True(a.IsAllDataRequested); // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true onStopProcessedActivities.Add(a.OperationName); }; var legacySourceNamespaces = new[] { "LegacyNamespace.*", "Namespace.*.Operation" }; using var activitySource = new ActivitySource(ActivitySourceName); // AddLegacyOperationName chained to TracerProviderBuilder using var tracerProvider = Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) .AddProcessor(testActivityProcessor) .AddLegacySource(legacySourceNamespaces[0]) .AddLegacySource(legacySourceNamespaces[1]) .AddSource(ActivitySourceName) .Build(); foreach (var ns in legacySourceNamespaces) { var startOpName = ns.Replace("*", "Start"); Activity startOperation = new Activity(startOpName); startOperation.Start(); startOperation.Stop(); Assert.Contains(startOpName, onStartProcessedActivities); // Processor.OnStart is called since we added a legacy OperationName Assert.Contains(startOpName, onStopProcessedActivities); // Processor.OnEnd is called since we added a legacy OperationName var stopOpName = ns.Replace("*", "Stop"); Activity stopOperation = new Activity(stopOpName); stopOperation.Start(); stopOperation.Stop(); Assert.Contains(stopOpName, onStartProcessedActivities); // Processor.OnStart is called since we added a legacy OperationName Assert.Contains(stopOpName, onStopProcessedActivities); // Processor.OnEnd is called since we added a legacy OperationName } // Ensure we can still process "normal" activities when in legacy wildcard mode. Activity nonLegacyActivity = activitySource.StartActivity("TestActivity"); nonLegacyActivity.Start(); nonLegacyActivity.Stop(); Assert.Contains(nonLegacyActivity.OperationName, onStartProcessedActivities); // Processor.OnStart is called since we added a legacy OperationName Assert.Contains(nonLegacyActivity.OperationName, onStopProcessedActivities); // Processor.OnEnd is called since we added a legacy OperationName } public void Dispose() { GC.SuppressFinalize(this); } private class TestInstrumentation : IDisposable { public bool IsDisposed; public TestInstrumentation() { this.IsDisposed = false; } public void Dispose() { this.IsDisposed = true; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CacheStorage.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Caching { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Policies; using Threading; /// <summary> /// The cache storage. /// </summary> /// <typeparam name="TKey">The key type.</typeparam> /// <typeparam name="TValue">The value type.</typeparam> public class CacheStorage<TKey, TValue> : ICacheStorage<TKey, TValue> { #region Fields private readonly Func<ExpirationPolicy> _defaultExpirationPolicyInitCode; /// <summary> /// Determines whether the cache storage can store null values. /// </summary> private readonly bool _storeNullValues; /// <summary> /// The dictionary. /// </summary> private readonly Dictionary<TKey, CacheStorageValueInfo<TValue>> _dictionary; /// <summary> /// The synchronization object. /// </summary> private readonly object _syncObj = new object(); /// <summary> /// The synchronization objects. /// </summary> private readonly Dictionary<TKey, object> _syncObjs = new Dictionary<TKey, object>(); /// <summary> /// The timer that is being executed to invalidate the cache. /// </summary> private Timer _expirationTimer; /// <summary> /// The expiration timer interval. /// </summary> private TimeSpan _expirationTimerInterval; /// <summary> /// Determines whether the cache storage can check for expired items. /// </summary> private bool _checkForExpiredItems; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CacheStorage{TKey,TValue}" /> class. /// </summary> /// <param name="defaultExpirationPolicyInitCode">The default expiration policy initialization code.</param> /// <param name="storeNullValues">Allow store null values on the cache.</param> [ObsoleteEx(Message = "Use other ctor, this is kept to not introduce breaking changes", ReplacementTypeOrMember = "ctor(Func<ExpirationPolicy>, bool, IEqualityComparer<TKey>)", TreatAsErrorFromVersion = "4.5", RemoveInVersion = "5.0")] public CacheStorage(Func<ExpirationPolicy> defaultExpirationPolicyInitCode, bool storeNullValues) : this(defaultExpirationPolicyInitCode, storeNullValues, null) { } /// <summary> /// Initializes a new instance of the <see cref="CacheStorage{TKey,TValue}" /> class. /// </summary> /// <param name="defaultExpirationPolicyInitCode">The default expiration policy initialization code.</param> /// <param name="storeNullValues">Allow store null values on the cache.</param> /// <param name="equalityComparer">The equality comparer.</param> public CacheStorage(Func<ExpirationPolicy> defaultExpirationPolicyInitCode = null, bool storeNullValues = false, IEqualityComparer<TKey> equalityComparer = null) { _dictionary = new Dictionary<TKey, CacheStorageValueInfo<TValue>>(equalityComparer); _storeNullValues = storeNullValues; _defaultExpirationPolicyInitCode = defaultExpirationPolicyInitCode; _expirationTimerInterval = TimeSpan.FromSeconds(1); } #endregion #region ICacheStorage<TKey,TValue> Members /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns>The value associated with the specified key, or default value for the type of the value if the key do not exists.</returns> /// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception> public TValue this[TKey key] { get { return Get(key); } } /// <summary> /// Gets the keys so it is possible to enumerate the cache. /// </summary> /// <value>The keys.</value> public IEnumerable<TKey> Keys { get { lock (_syncObj) { return _dictionary.Keys; } } } /// <summary> /// Gets or sets the expiration timer interval. /// <para /> /// The default value is <c>TimeSpan.FromSeconds(1)</c>. /// </summary> /// <value>The expiration timer interval.</value> public TimeSpan ExpirationTimerInterval { get { return _expirationTimerInterval; } set { _expirationTimerInterval = value; UpdateTimer(); } } private void UpdateTimer() { lock (_syncObj) { if (!_checkForExpiredItems) { if (_expirationTimer != null) { _expirationTimer.Dispose(); _expirationTimer = null; } } else { var timeSpan = _expirationTimerInterval; if (_expirationTimer == null) { _expirationTimer = new Timer(OnTimerElapsed, null, timeSpan, timeSpan); } else { _expirationTimer.Change(timeSpan, timeSpan); } } } } /// <summary> /// Gets the value associated with the specified key /// </summary> /// <param name="key">The key of the value to get.</param> /// <returns>The value associated with the specified key, or default value for the type of the value if the key do not exists.</returns> /// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception> public TValue Get(TKey key) { Argument.IsNotNull("key", key); CacheStorageValueInfo<TValue> valueInfo; lock (GetLockByKey(key)) { _dictionary.TryGetValue(key, out valueInfo); } return (valueInfo != null) ? valueInfo.Value : default(TValue); } /// <summary> /// Determines whether the cache contains a value associated with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns><c>true</c> if the cache contains an element with the specified key; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception> public bool Contains(TKey key) { Argument.IsNotNull("key", key); lock (GetLockByKey(key)) { return _dictionary.ContainsKey(key); } } /// <summary> /// Adds a value to the cache associated with to a key. /// </summary> /// <param name="key">The key.</param> /// <param name="code">The deferred initialization code of the value.</param> /// <param name="expirationPolicy">The expiration policy.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <returns>The instance initialized by the <paramref name="code" />.</returns> /// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception> [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed. Suppression is OK here.")] public TValue GetFromCacheOrFetch(TKey key, Func<TValue> code, ExpirationPolicy expirationPolicy, bool @override = false) { Argument.IsNotNull("key", key); Argument.IsNotNull("code", code); TValue value; lock (GetLockByKey(key)) { bool containsKey = _dictionary.ContainsKey(key); if (!containsKey || @override) { value = code.Invoke(); if (!ReferenceEquals(value, null) || _storeNullValues) { if (expirationPolicy == null && _defaultExpirationPolicyInitCode != null) { expirationPolicy = _defaultExpirationPolicyInitCode.Invoke(); } var valueInfo = new CacheStorageValueInfo<TValue>(value, expirationPolicy); lock (_syncObj) { _dictionary[key] = valueInfo; } if (valueInfo.CanExpire) { _checkForExpiredItems = true; } if (expirationPolicy != null) { if (_expirationTimer == null) { UpdateTimer(); } } } } else { value = _dictionary[key].Value; } } return value; } /// <summary> /// Adds a value to the cache associated with to a key. /// </summary> /// <param name="key">The key.</param> /// <param name="code">The deferred initialization code of the value.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <param name="expiration">The timespan in which the cache item should expire when added.</param> /// <returns>The instance initialized by the <paramref name="code" />.</returns> /// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception> public TValue GetFromCacheOrFetch(TKey key, Func<TValue> code, bool @override = false, TimeSpan expiration = default(TimeSpan)) { return GetFromCacheOrFetch(key, code, ExpirationPolicy.Duration(expiration), @override); } /// <summary> /// Adds a value to the cache associated with to a key asynchronously. /// <para /> /// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},ExpirationPolicy,bool)"/>. /// </summary> /// <param name="key">The key.</param> /// <param name="code">The deferred initialization code of the value.</param> /// <param name="expirationPolicy">The expiration policy.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <returns>The instance initialized by the <paramref name="code" />.</returns> /// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception> public async Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<Task<TValue>> code, ExpirationPolicy expirationPolicy, bool @override = false) { Argument.IsNotNull("key", key); Argument.IsNotNull("code", code); lock (GetLockByKey(key)) { var containsKey = _dictionary.ContainsKey(key); if (containsKey && !@override) { return _dictionary[key].Value; } } var value = await code.Invoke(); lock (GetLockByKey(key)) { if (!ReferenceEquals(value, null) || _storeNullValues) { if (expirationPolicy == null && _defaultExpirationPolicyInitCode != null) { expirationPolicy = _defaultExpirationPolicyInitCode.Invoke(); } var valueInfo = new CacheStorageValueInfo<TValue>(value, expirationPolicy); lock (_syncObj) { _dictionary[key] = valueInfo; } if (valueInfo.CanExpire) { _checkForExpiredItems = true; } if (expirationPolicy != null) { if (_expirationTimer == null) { UpdateTimer(); } } } } return value; } /// <summary> /// Adds a value to the cache associated with to a key asynchronously. /// <para /> /// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},bool,TimeSpan)"/>. /// </summary> /// <param name="key">The key.</param> /// <param name="code">The deferred initialization code of the value.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <param name="expiration">The timespan in which the cache item should expire when added.</param> /// <returns>The instance initialized by the <paramref name="code" />.</returns> /// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception> public Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<Task<TValue>> code, bool @override = false, TimeSpan expiration = default(TimeSpan)) { return GetFromCacheOrFetchAsync(key, code, ExpirationPolicy.Duration(expiration), @override); } /// <summary> /// Adds a value to the cache associated with to a key asynchronously. /// <para /> /// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},ExpirationPolicy,bool)"/>. /// </summary> /// <param name="key">The key.</param> /// <param name="code">The deferred initialization code of the value.</param> /// <param name="expirationPolicy">The expiration policy.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <returns>The instance initialized by the <paramref name="code" />.</returns> /// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception> [ObsoleteEx(Message = "Member will be removed because it's not truly asynchronous", TreatAsErrorFromVersion = "4.2", RemoveInVersion = "5.0")] public Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<TValue> code, ExpirationPolicy expirationPolicy, bool @override = false) { return TaskHelper.Run(() => GetFromCacheOrFetch(key, code, expirationPolicy, @override)); } /// <summary> /// Adds a value to the cache associated with to a key asynchronously. /// <para /> /// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},bool,TimeSpan)"/>. /// </summary> /// <param name="key">The key.</param> /// <param name="code">The deferred initialization code of the value.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <param name="expiration">The timespan in which the cache item should expire when added.</param> /// <returns>The instance initialized by the <paramref name="code" />.</returns> /// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception> [ObsoleteEx(Message = "Member will be removed because it's not truly asynchronous", TreatAsErrorFromVersion = "4.2", RemoveInVersion = "5.0")] public Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<TValue> code, bool @override = false, TimeSpan expiration = default(TimeSpan)) { return TaskHelper.Run(() => GetFromCacheOrFetch(key, code, @override, expiration)); } /// <summary> /// Adds a value to the cache associated with to a key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <param name="expiration">The timespan in which the cache item should expire when added.</param> /// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception> public void Add(TKey key, TValue @value, bool @override = false, TimeSpan expiration = default(TimeSpan)) { Add(key, value, ExpirationPolicy.Duration(expiration), @override); } /// <summary> /// Adds a value to the cache associated with to a key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="expirationPolicy">The expiration policy.</param> /// <param name="override">Indicates if the key exists the value will be overridden.</param> /// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception> public void Add(TKey key, TValue @value, ExpirationPolicy expirationPolicy, bool @override = false) { Argument.IsNotNull("key", key); if (!_storeNullValues) { Argument.IsNotNull("value", value); } GetFromCacheOrFetch(key, () => @value, expirationPolicy, @override); } /// <summary> /// Removes an item from the cache. /// </summary> /// <param name="key">The key.</param> /// <param name="action">The action that need to be executed in synchronization with the item cache removal.</param> /// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception> public void Remove(TKey key, Action action = null) { Argument.IsNotNull("key", key); lock (GetLockByKey(key)) { if (_dictionary.ContainsKey(key)) { if (action != null) { action.Invoke(); } _dictionary.Remove(key); } } } /// <summary> /// Clears all the items currently in the cache. /// </summary> public void Clear() { var keysToRemove = new List<TKey>(); lock (_syncObj) { keysToRemove.AddRange(_dictionary.Keys); foreach (var keyToRemove in keysToRemove) { lock (GetLockByKey(keyToRemove)) { _dictionary.Remove(keyToRemove); } } _checkForExpiredItems = false; UpdateTimer(); } } /// <summary> /// Removes the expired items from the cache. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1409:RemoveUnnecessaryCode", Justification = "Reviewed. Suppression is OK here.")] private void RemoveExpiredItems() { bool containsItemsThatCanExpire = false; var keysToRemove = new List<TKey>(); lock (_syncObj) { foreach (var cacheItem in _dictionary) { var valueInfo = cacheItem.Value; if (valueInfo.IsExpired) { keysToRemove.Add(cacheItem.Key); } else { if (!containsItemsThatCanExpire && valueInfo.CanExpire) { containsItemsThatCanExpire = true; } } } } foreach (var keyToRemove in keysToRemove) { lock (GetLockByKey(keyToRemove)) { _dictionary.Remove(keyToRemove); } } lock (_syncObj) { if (_checkForExpiredItems != containsItemsThatCanExpire) { _checkForExpiredItems = containsItemsThatCanExpire; UpdateTimer(); } } } /// <summary> /// Gets the lock by key. /// </summary> /// <param name="key">The key.</param> /// <returns>The lock object.</returns> private object GetLockByKey(TKey key) { lock (_syncObj) { var containsKey = _syncObjs.ContainsKey(key); if (!containsKey) { _syncObjs[key] = new object(); } } return _syncObjs[key]; } /// <summary> /// Called when the timer to clean up the cache elapsed. /// </summary> /// <param name="state">The timer state.</param> private void OnTimerElapsed(object state) { if (!_checkForExpiredItems) { return; } RemoveExpiredItems(); } #endregion } }
// // PlistCS Property List (plist) serialization and parsing library. // // https://github.com/animetrics/PlistCS // // Copyright (c) 2011 Animetrics Inc. (marc@animetrics.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace PlistCS { public static class Plist { private static List<int> offsetTable = new List<int>(); private static List<byte> objectTable = new List<byte>(); private static int refCount; private static int objRefSize; private static int offsetByteSize; private static long offsetTableOffset; #region Public Functions public static object readPlist(string path) { using (FileStream f = new FileStream(path, FileMode.Open, FileAccess.Read)) { return readPlist(f, plistType.Auto); } } public static object readPlistSource(string source) { return readPlist(System.Text.Encoding.UTF8.GetBytes(source)); } public static object readPlist(byte[] data) { return readPlist(new MemoryStream(data), plistType.Auto); } public static plistType getPlistType(Stream stream) { byte[] magicHeader = new byte[8]; stream.Read(magicHeader, 0, 8); if (BitConverter.ToInt64(magicHeader, 0) == 3472403351741427810) { return plistType.Binary; } else { return plistType.Xml; } } public static object readPlist(Stream stream, plistType type) { if (type == plistType.Auto) { type = getPlistType(stream); stream.Seek(0, SeekOrigin.Begin); } if (type == plistType.Binary) { using (BinaryReader reader = new BinaryReader(stream)) { byte[] data = reader.ReadBytes((int) reader.BaseStream.Length); return readBinary(data); } } else { XmlDocument xml = new XmlDocument(); xml.XmlResolver = null; xml.Load(stream); return readXml(xml); } } public static void writeXml(object value, string path) { using (StreamWriter writer = new StreamWriter(path)) { writer.Write(writeXml(value)); } } public static void writeXml(object value, Stream stream) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(writeXml(value)); } } public static string writeXml(object value) { using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Encoding = new System.Text.UTF8Encoding(false); xmlWriterSettings.ConformanceLevel = ConformanceLevel.Document; xmlWriterSettings.Indent = true; using (XmlWriter xmlWriter = XmlWriter.Create(ms, xmlWriterSettings)) { xmlWriter.WriteStartDocument(); //xmlWriter.WriteComment("DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" " + "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\""); xmlWriter.WriteDocType("plist", "-//Apple Computer//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null); xmlWriter.WriteStartElement("plist"); xmlWriter.WriteAttributeString("version", "1.0"); compose(value, xmlWriter); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Flush(); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } } } public static void writeBinary(object value, string path) { using (BinaryWriter writer = new BinaryWriter(new FileStream(path, FileMode.Create))) { writer.Write(writeBinary(value)); } } public static void writeBinary(object value, Stream stream) { using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(writeBinary(value)); } } public static byte[] writeBinary(object value) { offsetTable.Clear(); objectTable.Clear(); refCount = 0; objRefSize = 0; offsetByteSize = 0; offsetTableOffset = 0; //Do not count the root node, subtract by 1 int totalRefs = countObject(value) - 1; refCount = totalRefs; objRefSize = RegulateNullBytes(BitConverter.GetBytes(refCount)).Length; composeBinary(value); writeBinaryString("bplist00", false); offsetTableOffset = (long)objectTable.Count; offsetTable.Add(objectTable.Count - 8); offsetByteSize = RegulateNullBytes(BitConverter.GetBytes(offsetTable[offsetTable.Count-1])).Length; List<byte> offsetBytes = new List<byte>(); offsetTable.Reverse(); for (int i = 0; i < offsetTable.Count; i++) { offsetTable[i] = objectTable.Count - offsetTable[i]; byte[] buffer = RegulateNullBytes(BitConverter.GetBytes(offsetTable[i]), offsetByteSize); Array.Reverse(buffer); offsetBytes.AddRange(buffer); } objectTable.AddRange(offsetBytes); objectTable.AddRange(new byte[6]); objectTable.Add(Convert.ToByte(offsetByteSize)); objectTable.Add(Convert.ToByte(objRefSize)); var a = BitConverter.GetBytes((long) totalRefs + 1); Array.Reverse(a); objectTable.AddRange(a); objectTable.AddRange(BitConverter.GetBytes((long)0)); a = BitConverter.GetBytes(offsetTableOffset); Array.Reverse(a); objectTable.AddRange(a); return objectTable.ToArray(); } #endregion #region Private Functions private static object readXml(XmlDocument xml) { XmlNode rootNode = xml.DocumentElement.ChildNodes[0]; return parse(rootNode); } private static object readBinary(byte[] data) { offsetTable.Clear(); List<byte> offsetTableBytes = new List<byte>(); objectTable.Clear(); refCount = 0; objRefSize = 0; offsetByteSize = 0; offsetTableOffset = 0; List<byte> bList = new List<byte>(data); List<byte> trailer = bList.GetRange(bList.Count - 32, 32); parseTrailer(trailer); objectTable = bList.GetRange(0, (int)offsetTableOffset); offsetTableBytes = bList.GetRange((int)offsetTableOffset, bList.Count - (int)offsetTableOffset - 32); parseOffsetTable(offsetTableBytes); return parseBinary(0); } private static Dictionary<string, object> parseDictionary(XmlNode node) { XmlNodeList children = node.ChildNodes; if (children.Count % 2 != 0) { throw new DataMisalignedException("Dictionary elements must have an even number of child nodes"); } Dictionary<string, object> dict = new Dictionary<string, object>(); for (int i = 0; i < children.Count; i += 2) { XmlNode keynode = children[i]; XmlNode valnode = children[i + 1]; if (keynode.Name != "key") { throw new ApplicationException("expected a key node"); } object result = parse(valnode); if (result != null) { dict.Add(keynode.InnerText, result); } } return dict; } private static List<object> parseArray(XmlNode node) { List<object> array = new List<object>(); foreach (XmlNode child in node.ChildNodes) { object result = parse(child); if (result != null) { array.Add(result); } } return array; } private static void composeArray(List<object> value, XmlWriter writer) { writer.WriteStartElement("array"); foreach (object obj in value) { compose(obj, writer); } writer.WriteEndElement(); } private static object parse(XmlNode node) { switch (node.Name) { case "dict": return parseDictionary(node); case "array": return parseArray(node); case "string": return node.InnerText; case "integer": // int result; //int.TryParse(node.InnerText, System.Globalization.NumberFormatInfo.InvariantInfo, out result); return Convert.ToInt32(node.InnerText, System.Globalization.NumberFormatInfo.InvariantInfo); case "real": return Convert.ToDouble(node.InnerText,System.Globalization.NumberFormatInfo.InvariantInfo); case "false": return false; case "true": return true; case "null": return null; case "date": return XmlConvert.ToDateTime(node.InnerText, XmlDateTimeSerializationMode.Utc); case "data": return Convert.FromBase64String(node.InnerText); } throw new ApplicationException(String.Format("Plist Node `{0}' is not supported", node.Name)); } private static void compose(object value, XmlWriter writer) { if (value == null || value is string) { writer.WriteElementString("string", value as string); } else if (value is int || value is long) { writer.WriteElementString("integer", ((int)value).ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } else if (value is System.Collections.Generic.Dictionary<string, object> || value.GetType().ToString().StartsWith("System.Collections.Generic.Dictionary`2[System.String")) { //Convert to Dictionary<string, object> Dictionary<string, object> dic = value as Dictionary<string, object>; if (dic == null) { dic = new Dictionary<string, object>(); IDictionary idic = (IDictionary)value; foreach (var key in idic.Keys) { dic.Add(key.ToString(), idic[key]); } } writeDictionaryValues(dic, writer); } else if (value is List<object>) { composeArray((List<object>)value, writer); } else if (value is byte[]) { writer.WriteElementString("data", Convert.ToBase64String((Byte[])value)); } else if (value is float || value is double) { writer.WriteElementString("real", ((double)value).ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } else if (value is DateTime) { DateTime time = (DateTime)value; string theString = XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc); writer.WriteElementString("date", theString);//, "yyyy-MM-ddTHH:mm:ssZ")); } else if (value is bool) { writer.WriteElementString(value.ToString().ToLower(), ""); } else { throw new Exception(String.Format("Value type '{0}' is unhandled", value.GetType().ToString())); } } private static void writeDictionaryValues(Dictionary<string, object> dictionary, XmlWriter writer) { writer.WriteStartElement("dict"); foreach (string key in dictionary.Keys) { object value = dictionary[key]; writer.WriteElementString("key", key); compose(value, writer); } writer.WriteEndElement(); } private static int countObject(object value) { int count = 0; switch (value.GetType().ToString()) { case "System.Collections.Generic.Dictionary`2[System.String,System.Object]": Dictionary<string, object> dict = (Dictionary<string, object>)value; foreach (string key in dict.Keys) { count += countObject(dict[key]); } count += dict.Keys.Count; count++; break; case "System.Collections.Generic.List`1[System.Object]": List<object> list = (List<object>)value; foreach (object obj in list) { count += countObject(obj); } count++; break; default: count++; break; } return count; } private static byte[] writeBinaryDictionary(Dictionary<string, object> dictionary) { List<byte> buffer = new List<byte>(); List<byte> header = new List<byte>(); List<int> refs = new List<int>(); for (int i = dictionary.Count - 1; i >= 0; i--) { var o = new object[dictionary.Count]; dictionary.Values.CopyTo(o, 0); composeBinary(o[i]); offsetTable.Add(objectTable.Count); refs.Add(refCount); refCount--; } for (int i = dictionary.Count - 1; i >= 0; i--) { var o = new string[dictionary.Count]; dictionary.Keys.CopyTo(o, 0); composeBinary(o[i]);//); offsetTable.Add(objectTable.Count); refs.Add(refCount); refCount--; } if (dictionary.Count < 15) { header.Add(Convert.ToByte(0xD0 | Convert.ToByte(dictionary.Count))); } else { header.Add(0xD0 | 0xf); header.AddRange(writeBinaryInteger(dictionary.Count, false)); } foreach (int val in refs) { byte[] refBuffer = RegulateNullBytes(BitConverter.GetBytes(val), objRefSize); Array.Reverse(refBuffer); buffer.InsertRange(0, refBuffer); } buffer.InsertRange(0, header); objectTable.InsertRange(0, buffer); return buffer.ToArray(); } private static byte[] composeBinaryArray(List<object> objects) { List<byte> buffer = new List<byte>(); List<byte> header = new List<byte>(); List<int> refs = new List<int>(); for (int i = objects.Count - 1; i >= 0; i--) { composeBinary(objects[i]); offsetTable.Add(objectTable.Count); refs.Add(refCount); refCount--; } if (objects.Count < 15) { header.Add(Convert.ToByte(0xA0 | Convert.ToByte(objects.Count))); } else { header.Add(0xA0 | 0xf); header.AddRange(writeBinaryInteger(objects.Count, false)); } foreach (int val in refs) { byte[] refBuffer = RegulateNullBytes(BitConverter.GetBytes(val), objRefSize); Array.Reverse(refBuffer); buffer.InsertRange(0, refBuffer); } buffer.InsertRange(0, header); objectTable.InsertRange(0, buffer); return buffer.ToArray(); } private static byte[] composeBinary(object obj) { byte[] value; switch (obj.GetType().ToString()) { case "System.Collections.Generic.Dictionary`2[System.String,System.Object]": value = writeBinaryDictionary((Dictionary<string, object>)obj); return value; case "System.Collections.Generic.List`1[System.Object]": value = composeBinaryArray((List<object>)obj); return value; case "System.Byte[]": value = writeBinaryByteArray((byte[])obj); return value; case "System.Double": value = writeBinaryDouble((double)obj); return value; case "System.Int32": value = writeBinaryInteger((int)obj, true); return value; case "System.String": value = writeBinaryString((string)obj, true); return value; case "System.DateTime": value = writeBinaryDate((DateTime)obj); return value; case "System.Boolean": value = writeBinaryBool((bool)obj); return value; default: return new byte[0]; } } public static byte[] writeBinaryDate(DateTime obj) { List<byte> buffer =new List<byte>(RegulateNullBytes(BitConverter.GetBytes(PlistDateConverter.ConvertToAppleTimeStamp(obj)), 8)); buffer.Reverse(); buffer.Insert(0, 0x33); objectTable.InsertRange(0, buffer); return buffer.ToArray(); } public static byte[] writeBinaryBool(bool obj) { List<byte> buffer = new List<byte>(new byte[1] { (bool)obj ? (byte)9 : (byte)8 }); objectTable.InsertRange(0, buffer); return buffer.ToArray(); } private static byte[] writeBinaryInteger(int value, bool write) { List<byte> buffer = new List<byte>(BitConverter.GetBytes((long) value)); buffer =new List<byte>(RegulateNullBytes(buffer.ToArray())); while (buffer.Count != Math.Pow(2, Math.Log(buffer.Count) / Math.Log(2))) buffer.Add(0); int header = 0x10 | (int)(Math.Log(buffer.Count) / Math.Log(2)); buffer.Reverse(); buffer.Insert(0, Convert.ToByte(header)); if (write) objectTable.InsertRange(0, buffer); return buffer.ToArray(); } private static byte[] writeBinaryDouble(double value) { List<byte> buffer =new List<byte>(RegulateNullBytes(BitConverter.GetBytes(value), 4)); while (buffer.Count != Math.Pow(2, Math.Log(buffer.Count) / Math.Log(2))) buffer.Add(0); int header = 0x20 | (int)(Math.Log(buffer.Count) / Math.Log(2)); buffer.Reverse(); buffer.Insert(0, Convert.ToByte(header)); objectTable.InsertRange(0, buffer); return buffer.ToArray(); } private static byte[] writeBinaryByteArray(byte[] value) { List<byte> buffer = new List<byte>(value); List<byte> header = new List<byte>(); if (value.Length < 15) { header.Add(Convert.ToByte(0x40 | Convert.ToByte(value.Length))); } else { header.Add(0x40 | 0xf); header.AddRange(writeBinaryInteger(buffer.Count, false)); } buffer.InsertRange(0, header); objectTable.InsertRange(0, buffer); return buffer.ToArray(); } private static byte[] writeBinaryString(string value, bool head) { List<byte> buffer = new List<byte>(); List<byte> header = new List<byte>(); foreach (char chr in value.ToCharArray()) buffer.Add(Convert.ToByte(chr)); if (head) { if (value.Length < 15) { header.Add(Convert.ToByte(0x50 | Convert.ToByte(value.Length))); } else { header.Add(0x50 | 0xf); header.AddRange(writeBinaryInteger(buffer.Count, false)); } } buffer.InsertRange(0, header); objectTable.InsertRange(0, buffer); return buffer.ToArray(); } private static byte[] RegulateNullBytes(byte[] value) { return RegulateNullBytes(value, 1); } private static byte[] RegulateNullBytes(byte[] value, int minBytes) { Array.Reverse(value); List<byte> bytes = new List<byte>(value); for (int i = 0; i < bytes.Count; i++) { if (bytes[i] == 0 && bytes.Count > minBytes) { bytes.Remove(bytes[i]); i--; } else break; } if (bytes.Count < minBytes) { int dist = minBytes - bytes.Count; for (int i = 0; i < dist; i++) bytes.Insert(0, 0); } value = bytes.ToArray(); Array.Reverse(value); return value; } private static void parseTrailer(List<byte> trailer) { offsetByteSize = BitConverter.ToInt32(RegulateNullBytes(trailer.GetRange(6, 1).ToArray(), 4), 0); objRefSize = BitConverter.ToInt32(RegulateNullBytes(trailer.GetRange(7, 1).ToArray(), 4), 0); byte[] refCountBytes = trailer.GetRange(12, 4).ToArray(); Array.Reverse(refCountBytes); refCount = BitConverter.ToInt32(refCountBytes, 0); byte[] offsetTableOffsetBytes = trailer.GetRange(24, 8).ToArray(); Array.Reverse(offsetTableOffsetBytes); offsetTableOffset = BitConverter.ToInt64(offsetTableOffsetBytes, 0); } private static void parseOffsetTable(List<byte> offsetTableBytes) { for (int i = 0; i < offsetTableBytes.Count; i += offsetByteSize) { byte[] buffer = offsetTableBytes.GetRange(i, offsetByteSize).ToArray(); Array.Reverse(buffer); offsetTable.Add(BitConverter.ToInt32(RegulateNullBytes(buffer, 4), 0)); } } private static object parseBinaryDictionary(int objRef) { Dictionary<string, object> buffer = new Dictionary<string, object>(); List<int> refs = new List<int>(); int refCount = 0; int refStartPosition; refCount = getCount(offsetTable[objRef], out refStartPosition); if (refCount < 15) refStartPosition = offsetTable[objRef] + 1; else refStartPosition = offsetTable[objRef] + 2 + RegulateNullBytes(BitConverter.GetBytes(refCount), 1).Length; for (int i = refStartPosition; i < refStartPosition + refCount * 2 * objRefSize; i += objRefSize) { byte[] refBuffer = objectTable.GetRange(i, objRefSize).ToArray(); Array.Reverse(refBuffer); refs.Add(BitConverter.ToInt32(RegulateNullBytes(refBuffer, 4), 0)); } for (int i = 0; i < refCount; i++) { buffer.Add((string)parseBinary(refs[i]), parseBinary(refs[i + refCount])); } return buffer; } private static object parseBinaryArray(int objRef) { List<object> buffer = new List<object>(); List<int> refs = new List<int>(); int refCount = 0; int refStartPosition; refCount = getCount(offsetTable[objRef], out refStartPosition); if (refCount < 15) refStartPosition = offsetTable[objRef] + 1; else //The following integer has a header aswell so we increase the refStartPosition by two to account for that. refStartPosition = offsetTable[objRef] + 2 + RegulateNullBytes(BitConverter.GetBytes(refCount), 1).Length; for (int i = refStartPosition; i < refStartPosition + refCount * objRefSize; i += objRefSize) { byte[] refBuffer = objectTable.GetRange(i, objRefSize).ToArray(); Array.Reverse(refBuffer); refs.Add(BitConverter.ToInt32(RegulateNullBytes(refBuffer, 4), 0)); } for (int i = 0; i < refCount; i++) { buffer.Add(parseBinary(refs[i])); } return buffer; } private static int getCount(int bytePosition, out int newBytePosition) { byte headerByte = objectTable[bytePosition]; byte headerByteTrail = Convert.ToByte(headerByte & 0xf); int count; if (headerByteTrail < 15) { count = headerByteTrail; newBytePosition = bytePosition + 1; } else count = (int)parseBinaryInt(bytePosition + 1, out newBytePosition); return count; } private static object parseBinary(int objRef) { byte header = objectTable[offsetTable[objRef]]; switch (header & 0xF0) { case 0: { //If the byte is //0 return null //9 return true //8 return false return (objectTable[offsetTable[objRef]] == 0) ? (object)null : ((objectTable[offsetTable[objRef]] == 9) ? true : false); } case 0x10: { return parseBinaryInt(offsetTable[objRef]); } case 0x20: { return parseBinaryReal(offsetTable[objRef]); } case 0x30: { return parseBinaryDate(offsetTable[objRef]); } case 0x40: { return parseBinaryByteArray(offsetTable[objRef]); } case 0x50://String ASCII { return parseBinaryAsciiString(offsetTable[objRef]); } case 0x60://String Unicode { return parseBinaryUnicodeString(offsetTable[objRef]); } case 0xD0: { return parseBinaryDictionary(objRef); } case 0xA0: { return parseBinaryArray(objRef); } } throw new Exception("This type is not supported"); } public static object parseBinaryDate(int headerPosition) { byte[] buffer = objectTable.GetRange(headerPosition + 1, 8).ToArray(); Array.Reverse(buffer); double appleTime = BitConverter.ToDouble(buffer, 0); DateTime result = PlistDateConverter.ConvertFromAppleTimeStamp(appleTime); return result; } private static object parseBinaryInt(int headerPosition) { int output; return parseBinaryInt(headerPosition, out output); } private static object parseBinaryInt(int headerPosition, out int newHeaderPosition) { byte header = objectTable[headerPosition]; int byteCount = (int)Math.Pow(2, header & 0xf); byte[] buffer = objectTable.GetRange(headerPosition + 1, byteCount).ToArray(); Array.Reverse(buffer); //Add one to account for the header byte newHeaderPosition = headerPosition + byteCount + 1; return BitConverter.ToInt32(RegulateNullBytes(buffer, 4), 0); } private static object parseBinaryReal(int headerPosition) { byte header = objectTable[headerPosition]; int byteCount = (int)Math.Pow(2, header & 0xf); byte[] buffer = objectTable.GetRange(headerPosition + 1, byteCount).ToArray(); Array.Reverse(buffer); return BitConverter.ToDouble(RegulateNullBytes(buffer, 8), 0); } private static object parseBinaryAsciiString(int headerPosition) { int charStartPosition; int charCount = getCount(headerPosition, out charStartPosition); var buffer = objectTable.GetRange(charStartPosition, charCount); return buffer.Count > 0 ? Encoding.ASCII.GetString(buffer.ToArray()) : string.Empty; } private static object parseBinaryUnicodeString(int headerPosition) { int charStartPosition; int charCount = getCount(headerPosition, out charStartPosition); charCount = charCount * 2; byte[] buffer = new byte[charCount]; byte one, two; for (int i = 0; i < charCount; i+=2) { one = objectTable.GetRange(charStartPosition+i,1)[0]; two = objectTable.GetRange(charStartPosition + i+1, 1)[0]; if (BitConverter.IsLittleEndian) { buffer[i] = two; buffer[i + 1] = one; } else { buffer[i] = one; buffer[i + 1] = two; } } return Encoding.Unicode.GetString(buffer); } private static object parseBinaryByteArray(int headerPosition) { int byteStartPosition; int byteCount = getCount(headerPosition, out byteStartPosition); return objectTable.GetRange(byteStartPosition, byteCount).ToArray(); } #endregion } public enum plistType { Auto, Binary, Xml } public static class PlistDateConverter { public static long timeDifference = 978307200; public static long GetAppleTime(long unixTime) { return unixTime - timeDifference; } public static long GetUnixTime(long appleTime) { return appleTime + timeDifference; } public static DateTime ConvertFromAppleTimeStamp(double timestamp) { DateTime origin = new DateTime(2001, 1, 1, 0, 0, 0, 0); return origin.AddSeconds(timestamp); } public static double ConvertToAppleTimeStamp(DateTime date) { DateTime begin = new DateTime(2001, 1, 1, 0, 0, 0, 0); TimeSpan diff = date - begin; return Math.Floor(diff.TotalSeconds); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.CoreFunctionLibrary { /// <summary> /// Core Function Library - String Functions /// </summary> public static partial class StringFunctionsTests { /// <summary> /// Verify result. /// string()="context node data" /// </summary> [Fact] public static void StringFunctionsTest241() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1/Para[1]"; var testExpression = @"string()"; var expected = @"Test"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// string(1) = "1" /// </summary> [Fact] public static void StringFunctionsTest242() { var xml = "dummy.xml"; var testExpression = @"string(1)"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(-0) = "0" /// </summary> [Fact] public static void StringFunctionsTest243() { var xml = "dummy.xml"; var testExpression = @"string(-0)"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(+0) = "0" /// </summary> [Fact] public static void StringFunctionsTest244() { var xml = "dummy.xml"; var testExpression = @"string(+0)"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Verify result. /// string(number("NotANumber")) = "NaN" /// </summary> [Fact] public static void StringFunctionsTest245() { var xml = "dummy.xml"; var testExpression = @"string(number(""NotANumber""))"; var expected = Double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(true()) = "true" /// </summary> [Fact] public static void StringFunctionsTest246() { var xml = "dummy.xml"; var testExpression = @"string(true())"; var expected = @"true"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(false()) = "false" /// </summary> [Fact] public static void StringFunctionsTest247() { var xml = "dummy.xml"; var testExpression = @"string(false())"; var expected = @"false"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(child::para) = "1st child node data" /// </summary> [Fact] public static void StringFunctionsTest248() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"string(child::Para)"; var expected = @"Test"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// concat("AA", "BB") = "AABB" /// </summary> [Fact] public static void StringFunctionsTest249() { var xml = "dummy.xml"; var testExpression = @"concat(""AA"", ""BB"")"; var expected = @"AABB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// concat("AA", "BB", "CC") = "AABBCC" /// </summary> [Fact] public static void StringFunctionsTest2410() { var xml = "dummy.xml"; var testExpression = @"concat(""AA"", ""BB"", ""CC"")"; var expected = @"AABBCC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// concat(string(child::*), "BB") = "AABB" /// </summary> [Fact] public static void StringFunctionsTest2411() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"concat(string(child::*), ""BB"")"; var expected = @"TestBB"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// starts-with("AABB", "AA") = true /// </summary> [Fact] public static void StringFunctionsTest2412() { var xml = "dummy.xml"; var testExpression = @"starts-with(""AABB"", ""AA"")"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// starts-with("AABB", "BB") = false /// </summary> [Fact] public static void StringFunctionsTest2413() { var xml = "dummy.xml"; var testExpression = @"starts-with(""AABB"", ""BB"")"; var expected = false; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// starts-with("AABB", string(child::*)) = true /// </summary> [Fact] public static void StringFunctionsTest2414() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"starts-with(""TestBB"", string(child::*))"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// contains("AABBCC", "BB") = true /// </summary> [Fact] public static void StringFunctionsTest2415() { var xml = "dummy.xml"; var testExpression = @"contains(""AABBCC"", ""BB"")"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// contains("AABBCC", "DD") = false /// </summary> [Fact] public static void StringFunctionsTest2416() { var xml = "dummy.xml"; var testExpression = @"contains(""AABBCC"", ""DD"")"; var expected = false; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// contains("AABBCC", string(child::*)) = true /// </summary> [Fact] public static void StringFunctionsTest2417() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"contains(""AATestBB"", string(child::*))"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// substring-before("AA/BB", "/") = "AA" /// </summary> [Fact] public static void StringFunctionsTest2418() { var xml = "dummy.xml"; var testExpression = @"substring-before(""AA/BB"", ""/"")"; var expected = @"AA"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-before("AA/BB", "D") = "" /// </summary> [Fact] public static void StringFunctionsTest2419() { var xml = "dummy.xml"; var testExpression = @"substring-before(""AA/BB"", ""D"")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-before(string(child::*), "/") = "AA" /// </summary> [Fact] public static void StringFunctionsTest2420() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"substring-before(string(child::*), ""t"")"; var expected = @"Tes"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// substring-after("AA/BB", "/") = "BB" /// </summary> [Fact] public static void StringFunctionsTest2421() { var xml = "dummy.xml"; var testExpression = @"substring-after(""AA/BB"", ""/"")"; var expected = @"BB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-after("AA/BB", "D") != "" /// </summary> [Fact] public static void StringFunctionsTest2422() { var xml = "dummy.xml"; var testExpression = @"substring-after(""AA/BB"", ""D"")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-after(string(child::*), "/") = "BB" /// </summary> [Fact] public static void StringFunctionsTest2423() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"substring-after(string(child::*), ""T"")"; var expected = @"est"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// substring("ABC", 2) = "BC" /// </summary> [Fact] public static void StringFunctionsTest2424() { var xml = "dummy.xml"; var testExpression = @"substring(""ABC"", 2)"; var expected = @"BC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCD", 2, 2) = "BC" /// </summary> [Fact] public static void StringFunctionsTest2425() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCD"", 2, 2)"; var expected = @"BC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 1.5, 2.6) = "BCD" /// </summary> [Fact] public static void StringFunctionsTest2426() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1.5, 2.6)"; var expected = @"BCD"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 0, 3) = "AB" /// </summary> [Fact] public static void StringFunctionsTest2427() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 0, 3)"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 0 div 0, 3) = "" /// </summary> [Fact] public static void StringFunctionsTest2428() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 0 div 0, 3)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 1, 0 div 0) = "" /// </summary> [Fact] public static void StringFunctionsTest2429() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1, 0 div 0)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", -42, 1 div 0) = "ABCDE" /// </summary> [Fact] public static void StringFunctionsTest2430() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", -42, 1 div 0)"; var expected = @"ABCDE"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", -1 div 0, 1 div 0) = "" /// </summary> [Fact] public static void StringFunctionsTest2431() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", -1 div 0, 1 div 0)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring(string(child::*), 2) = "BC" /// </summary> [Fact] public static void StringFunctionsTest2432() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"substring(string(child::*), 2)"; var expected = @"est"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// string-length("ABCDE") = 5 /// </summary> [Fact] public static void StringFunctionsTest2433() { var xml = "dummy.xml"; var testExpression = @"string-length(""ABCDE"")"; var expected = 5d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result ( assuming the string-value of the context node has 5 characters). /// string-length() = 5 /// </summary> [Fact] public static void StringFunctionsTest2434() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1/Para[1]"; var testExpression = @"string-length()"; var expected = 4d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// string-length("") = 0 /// </summary> [Fact] public static void StringFunctionsTest2435() { var xml = "dummy.xml"; var testExpression = @"string-length("""")"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string-length(string(child::*)) = 2 /// </summary> [Fact] public static void StringFunctionsTest2436() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"string-length(string(child::*))"; var expected = 4d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// normalize-space("") = "" /// </summary> [Fact] public static void StringFunctionsTest2473() { var xml = "dummy.xml"; var testExpression = @"normalize-space("""")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" \t\n\r") = "" /// </summary> [Fact] public static void StringFunctionsTest2474() { var xml = "dummy.xml"; var testExpression = "normalize-space(\" \t\n\r\")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" Surrogate-Pair-String ") = "" /// </summary> [Fact] public static void StringFunctionsTest2475() { var xml = "dummy.xml"; var fourCircles = char.ConvertFromUtf32(0x1F01C); var testExpression = "normalize-space(\" " + fourCircles + " \")"; var expected = fourCircles; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" AB") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2437() { var xml = "dummy.xml"; var testExpression = @"normalize-space("" AB"")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("AB ") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2438() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""AB "")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("A B") = "A B" /// </summary> [Fact] public static void StringFunctionsTest2439() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""A B"")"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" AB") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2440() { var xml = "dummy.xml"; var testExpression = @"normalize-space("" AB"")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("AB ") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2441() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""AB "")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("A B") = "A B" /// </summary> [Fact] public static void StringFunctionsTest2442() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""A B"")"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" A B ") = "A B" /// </summary> [Fact] public static void StringFunctionsTest2443() { var xml = "dummy.xml"; var testExpression = @"normalize-space("" A B "")"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space() = "A B" /// </summary> [Fact] public static void StringFunctionsTest2444() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test4/Para[1]"; var testExpression = @"normalize-space()"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Checks for preceding and trailing whitespaces /// normalize-space(' abc ') /// </summary> [Fact] public static void StringFunctionsTest2445() { var xml = "books.xml"; var testExpression = @"normalize-space(' abc ')"; var expected = @"abc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Checks for preceding and trailing whitespaces (characters other than space) /// normalize-space(' abc ') /// </summary> [Fact] public static void StringFunctionsTest2446() { var xml = "books.xml"; var testExpression = @"normalize-space(' abc ')"; var expected = @"abc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Checks for a sequence of whitespaces between characters /// normalize-space('a bc') /// </summary> [Fact] public static void StringFunctionsTest2447() { var xml = "books.xml"; var testExpression = @"normalize-space('a bc')"; var expected = @"a bc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Checks for a sequence of whitespaces between characters (characters other than space) /// normalize-space('a bc') /// </summary> [Fact] public static void StringFunctionsTest2448() { var xml = "books.xml"; var testExpression = @"normalize-space('a bc')"; var expected = @"a bc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// A single tab should be replaced with a space /// normalize-space('a bc') /// </summary> [Fact] public static void StringFunctionsTest2449() { var xml = "books.xml"; var testExpression = @"normalize-space('a bc')"; var expected = @"a bc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(string(child::*)) = "A B" /// </summary> [Fact] public static void StringFunctionsTest2450() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test4"; var testExpression = @"normalize-space(string(child::*))"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// translate("", "abc", "ABC") = "" /// </summary> [Fact] public static void StringFunctionsTest2472() { var xml = "dummy.xml"; var testExpression = @"translate("""", ""abc"", ""ABC"")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("unicode", "unicode", "uppercase-unicode") = "uppercase -unicode" /// </summary> [Fact] public static void StringFunctionsTest2476() { var xml = "dummy.xml"; var testExpression = "translate(\"\0x03B1\0x03B2\0x03B3\", \"\0x03B1\0x03B2\0x03B3\", \"\0x0391\0x0392\0x0393\")"; var expected = "\0x0391\0x0392\0x0393"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("surrogate-pairs", "ABC", "") = "surrogate-pairs" /// </summary> [Fact] public static void StringFunctionsTest2477() { var xml = "dummy.xml"; var fourOClock = char.ConvertFromUtf32(0x1F553); var fiveOClock = char.ConvertFromUtf32(0x1F554); var testExpression = @"translate(""" + fourOClock + fiveOClock + @""", ""ABC"", """")"; var expected = fourOClock + fiveOClock; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("abc", "abca", "ABCZ") = "ABC" /// </summary> [Fact] public static void StringFunctionsTest2478() { var xml = "dummy.xml"; var testExpression = @"translate(""abc"", ""abca"", ""ABCZ"")"; var expected = "ABC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("abc", "abc", "ABC") = "ABC" /// </summary> [Fact] public static void StringFunctionsTest2451() { var xml = "dummy.xml"; var testExpression = @"translate(""abc"", ""abc"", ""ABC"")"; var expected = @"ABC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("aba", "b", "B") = "aBa" /// </summary> [Fact] public static void StringFunctionsTest2452() { var xml = "dummy.xml"; var testExpression = @"translate(""aba"", ""b"", ""B"")"; var expected = @"aBa"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("--aaa--", "abc-", "ABC") = "AAA" /// </summary> [Fact] public static void StringFunctionsTest2453() { var xml = "dummy.xml"; var testExpression = @"translate(""-aaa-"", ""abc-"", ""ABC"")"; var expected = @"AAA"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate(string(child::*), "AB", "ab") = "aa" /// </summary> [Fact] public static void StringFunctionsTest2454() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"translate(string(child::*), ""est"", ""EST"")"; var expected = @"TEST"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// string(NaN) /// </summary> [Fact] public static void StringFunctionsTest2455() { var xml = "dummy.xml"; var testExpression = @"string(number(0 div 0))"; var expected = Double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(-0) /// </summary> [Fact] public static void StringFunctionsTest2456() { var xml = "dummy.xml"; var testExpression = @"string(-0)"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(infinity) /// </summary> [Fact] public static void StringFunctionsTest2457() { var xml = "dummy.xml"; var testExpression = @"string(number(1 div 0))"; var expected = Double.PositiveInfinity; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(-Infinity) /// </summary> [Fact] public static void StringFunctionsTest2458() { var xml = "dummy.xml"; var testExpression = @"string(number(-1 div 0))"; var expected = Double.NegativeInfinity; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// for integers, leading zeros and decimal should be removed /// string(007.00) /// </summary> [Fact] public static void StringFunctionsTest2459() { var xml = "dummy.xml"; var testExpression = @"string(007.00)"; var expected = 7d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(-007.00) /// </summary> [Fact] public static void StringFunctionsTest2460() { var xml = "dummy.xml"; var testExpression = @"string(-007.00)"; var expected = -7d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Code coverage: covers the substring() function with in a query /// child::*[substring(name(),0,1)="b"] /// </summary> [Fact] public static void StringFunctionsTest2461() { var xml = "books.xml"; var testExpression = @"child::*[substring(name(),0,1)=""b""]"; var expected = new XPathResult(0); ; Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Code coverage: covers the substring-after() function with in a query /// child::*[substring-after(name(),"b")="ook"] /// </summary> [Fact] public static void StringFunctionsTest2462() { var xml = "books.xml"; var testExpression = @"child::*[substring-after(name(),""b"")=""ook""]"; var expected = new XPathResult(0); ; Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Code coverage: covers the normalize-space() function with in a query /// child::*[normalize-space(" book")=name()] /// </summary> [Fact] public static void StringFunctionsTest2463() { var xml = "books.xml"; var testExpression = @"child::*[normalize-space("" book"")=name()]"; var expected = new XPathResult(0); ; Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Expected: namespace uri /// string() (namespace node) /// </summary> [Fact] public static void StringFunctionsTest2464() { var xml = "name2.xml"; var startingNodePath = "/ns:store/ns:booksection/namespace::NSbook"; var testExpression = @"string()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://book.htm"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: xml namespace uri /// string() (namespace node = xml) /// </summary> [Fact] public static void StringFunctionsTest2465() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[last()]"; var testExpression = @"string()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://www.w3.org/XML/1998/namespace"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: default namespace uri /// string() (namespace node = default ns) /// </summary> [Fact] public static void StringFunctionsTest2466() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[1]"; var testExpression = @"string()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://default.htm"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: uri of namespace /// string() (namespace node) /// </summary> [Fact] public static void StringFunctionsTest2467() { var xml = "name2.xml"; var testExpression = @"string(ns:store/ns:booksection/namespace::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://book.htm"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager); } /// <summary> /// substring("ABCDE", 1, -1) /// </summary> [Fact] public static void StringFunctionsTest2468() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1, -1)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// substring("ABCDE", 1, -1 div 0) /// </summary> [Fact] public static void StringFunctionsTest2469() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1, -1 div 0)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// string(/bookstore/book/title) /// </summary> [Fact] public static void StringFunctionsTest2471() { var xml = "books.xml"; var testExpression = @"string(/bookstore/book/title)"; var expected = @"Seven Years in Trenton"; Utils.XPathStringTest(xml, testExpression, expected); } } }
/* * BitArray.cs - Implementation of the "System.Collections.BitArray" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Collections { #if !ECMA_COMPAT using System; using System.Runtime.CompilerServices; public sealed class BitArray : ICollection, IEnumerable, ICloneable { // Internal state. private int[] bitArray; private int numBits; private int generation; // Constructors. public BitArray(BitArray bits) { if(bits == null) { throw new ArgumentNullException("bits"); } bitArray = (int[])(bits.bitArray.Clone()); numBits = bits.numBits; generation = 0; } public BitArray(bool[] values) { if(values == null) { throw new ArgumentNullException("values"); } numBits = values.Length; bitArray = new int [(numBits + 31) / 32]; int posn; for(posn = 0; posn < numBits; ++posn) { if(values[posn]) { bitArray[posn >> 5] |= (1 << (posn & 31)); } } generation = 0; } public BitArray(byte[] values) { if(values == null) { throw new ArgumentNullException("values"); } numBits = values.Length * 8; bitArray = new int [(numBits + 31) / 32]; int posn; for(posn = 0; posn < values.Length; ++posn) { bitArray[posn >> 2] |= (values[posn] << (8 * (posn & 3))); } generation = 0; } public BitArray(int length) { if(length < 0) { throw new ArgumentOutOfRangeException (_("ArgRange_NonNegative")); } numBits = length; bitArray = new int [(numBits + 31) / 32]; generation = 0; } public BitArray(int[] values) { if(values == null) { throw new ArgumentNullException("values"); } numBits = values.Length * 32; bitArray = (int[])(values.Clone()); generation = 0; } public BitArray(int length, bool defaultValue) { if(length < 0) { throw new ArgumentOutOfRangeException (_("ArgRange_NonNegative")); } numBits = length; bitArray = new int [(numBits + 31) / 32]; if(defaultValue) { int posn; for(posn = 0; posn < bitArray.Length; ++posn) { bitArray[posn] = -1; } } generation = 0; } // Implement the ICollection interface. public int Count { get { return numBits; } } public bool IsReadOnly { get { return false; } } public bool IsSynchronized { get { return false; } } public bool this[int index] { get { return Get(index); } set { Set(index, value); } } public Object SyncRoot { get { return this; } } public void CopyTo(Array array, int index) { if(array == null) { throw new ArgumentNullException("array"); } else if(array.Rank != 1) { throw new ArgumentException(_("Arg_RankMustBe1")); } else if(index < array.GetLowerBound(0)) { throw new ArgumentOutOfRangeException ("index", _("Arg_InvalidArrayIndex")); } else if(index > (array.GetLength(0) - numBits)) { throw new ArgumentException(_("Arg_InvalidArrayRange")); } else { int posn; for(posn = 0; posn < numBits; ++posn) { array.SetValue (((bitArray[posn >> 5] & (1 << (posn & 31))) != 0), index++); } } } // Get or set the length of the bit array. public int Length { get { return numBits; } set { if(value < 0) { throw new ArgumentOutOfRangeException (_("ArgRange_NonNegative")); } else if(value == numBits) { // No change to the current array size. return; } ++generation; if(value < numBits) { // We are making the array smaller, which // means we can keep the same bit buffer. numBits = value; } else if(((value + 31) / 32) <= bitArray.Length) { // The array will still fit within the current buffer, // so just clear any additional bits that we need. ClearBits(numBits, value - numBits); } else { // We need to extend the current buffer. ClearBits(numBits, bitArray.Length * 32 - numBits); int[] newArray = new int [(value + 31) / 32]; Array.Copy(bitArray, newArray, (numBits + 31) / 32); bitArray = newArray; numBits = value; } } } // Clear a range of bits. private void ClearBits(int start, int num) { int posn = (start >> 5); int leftOver; while(num > 0) { leftOver = 32 - (start & 31); if(leftOver > num) { leftOver = num; } if(leftOver == 32) { bitArray[posn] = 0; } else { bitArray[posn] &= ~(((1 << leftOver) - 1) << (start & 31)); } start += leftOver; num -= leftOver; ++posn; } } // And two bit arrays together. public BitArray And(BitArray value) { if(value == null) { throw new ArgumentNullException("value"); } if(numBits != value.numBits) { throw new ArgumentException(_("Arg_BitArrayLengths")); } BitArray result = new BitArray(numBits); int posn = ((numBits + 31) / 32); while(posn > 0) { --posn; result.bitArray[posn] = (bitArray[posn] & value.bitArray[posn]); } return result; } // Or two bit arrays together. public BitArray Or(BitArray value) { if(value == null) { throw new ArgumentNullException("value"); } if(numBits != value.numBits) { throw new ArgumentException(_("Arg_BitArrayLengths")); } BitArray result = new BitArray(numBits); int posn = ((numBits + 31) / 32); while(posn > 0) { --posn; result.bitArray[posn] = (bitArray[posn] | value.bitArray[posn]); } return result; } // Xor two bit arrays together. public BitArray Xor(BitArray value) { if(value == null) { throw new ArgumentNullException("value"); } if(numBits != value.numBits) { throw new ArgumentException(_("Arg_BitArrayLengths")); } BitArray result = new BitArray(numBits); int posn = ((numBits + 31) / 32); while(posn > 0) { --posn; result.bitArray[posn] = (bitArray[posn] ^ value.bitArray[posn]); } return result; } // Implement the ICloneable interface. public Object Clone() { BitArray array = (BitArray)MemberwiseClone(); array.bitArray = (int[])(bitArray.Clone()); return array; } // Get an element from this bit array. public bool Get(int index) { if(index < 0 || index >= numBits) { throw new ArgumentOutOfRangeException ("index", _("Arg_InvalidArrayIndex")); } return ((bitArray[index >> 5] & (1 << (index & 31))) != 0); } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return new BitArrayEnumerator(this); } // Invert all of the bits in this bit array. public BitArray Not() { BitArray result = new BitArray(numBits); int posn = ((numBits + 31) / 32); while(posn > 0) { --posn; result.bitArray[posn] = ~(bitArray[posn]); } return result; } // Set a particular bit in this bit array. public void Set(int index, bool value) { if(index < 0 || index >= numBits) { throw new ArgumentOutOfRangeException ("index", _("Arg_InvalidArrayIndex")); } if(value) { bitArray[index >> 5] |= (1 << (index & 31)); } else { bitArray[index >> 5] &= ~(1 << (index & 31)); } ++generation; } // Set all bits in this bit array to a specific value. public void SetAll(bool value) { int posn = ((numBits + 31) / 32); if(value) { while(posn > 0) { --posn; bitArray[posn] = -1; } } else { while(posn > 0) { --posn; bitArray[posn] = 0; } } ++generation; } // Bit array enumerator class. private sealed class BitArrayEnumerator : IEnumerator { // Internal state. private BitArray array; private int generation; private int posn; // Constructor. public BitArrayEnumerator(BitArray array) { this.array = array; generation = array.generation; posn = -1; } // Implement the IEnumerator interface. public bool MoveNext() { if(array.generation != generation) { throw new InvalidOperationException (_("Invalid_CollectionModified")); } if(++posn < array.numBits) { return true; } posn = array.numBits; return false; } public void Reset() { if(array.generation != generation) { throw new InvalidOperationException (_("Invalid_CollectionModified")); } posn = -1; } public Object Current { get { if(array.generation != generation) { throw new InvalidOperationException (_("Invalid_CollectionModified")); } if(posn < 0 || posn >= array.numBits) { throw new InvalidOperationException (_("Invalid_BadEnumeratorPosition")); } return ((array.bitArray[posn >> 5] & (1 << (posn & 31))) != 0); } } }; // BitArrayEnumerator }; // class BitArray #endif // !ECMA_COMPAT }; // namespace System.Collections
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.IO; using System.Globalization; #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE) using System.Numerics; #endif #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40) using System.Threading.Tasks; #endif using uWebshop.Newtonsoft.Json.Linq; using uWebshop.Newtonsoft.Json.Utilities; using System.Xml; using uWebshop.Newtonsoft.Json.Converters; using uWebshop.Newtonsoft.Json.Serialization; using System.Text; #if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE) && !PORTABLE40 using System.Xml.Linq; #endif namespace uWebshop.Newtonsoft.Json { /// <summary> /// Provides methods for converting between common language runtime types and JSON types. /// </summary> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" /> /// </example> public static class JsonConvert { /// <summary> /// Gets or sets a function that creates default <see cref="JsonSerializerSettings"/>. /// Default settings are automatically used by serialization methods on <see cref="JsonConvert"/>, /// and <see cref="JToken.ToObject{T}()"/> and <see cref="JToken.FromObject(object)"/> on <see cref="JToken"/>. /// To serialize without using any default settings create a <see cref="JsonSerializer"/> with /// <see cref="JsonSerializer.Create()"/>. /// </summary> public static Func<JsonSerializerSettings> DefaultSettings { get; set; } /// <summary> /// Represents JavaScript's boolean value true as a string. This field is read-only. /// </summary> public static readonly string True = "true"; /// <summary> /// Represents JavaScript's boolean value false as a string. This field is read-only. /// </summary> public static readonly string False = "false"; /// <summary> /// Represents JavaScript's null as a string. This field is read-only. /// </summary> public static readonly string Null = "null"; /// <summary> /// Represents JavaScript's undefined as a string. This field is read-only. /// </summary> public static readonly string Undefined = "undefined"; /// <summary> /// Represents JavaScript's positive infinity as a string. This field is read-only. /// </summary> public static readonly string PositiveInfinity = "Infinity"; /// <summary> /// Represents JavaScript's negative infinity as a string. This field is read-only. /// </summary> public static readonly string NegativeInfinity = "-Infinity"; /// <summary> /// Represents JavaScript's NaN as a string. This field is read-only. /// </summary> public static readonly string NaN = "NaN"; /// <summary> /// Converts the <see cref="DateTime"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns> public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } /// <summary> /// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="format">The format the date will be converted to.</param> /// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param> /// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns> public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using (StringWriter writer = StringUtils.CreateStringWriter(64)) { writer.Write('"'); DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture); writer.Write('"'); return writer.ToString(); } } #if !NET20 /// <summary> /// Converts the <see cref="DateTimeOffset"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns> public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } /// <summary> /// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="format">The format the date will be converted to.</param> /// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns> public static string ToString(DateTimeOffset value, DateFormatHandling format) { using (StringWriter writer = StringUtils.CreateStringWriter(64)) { writer.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture); writer.Write('"'); return writer.ToString(); } } #endif /// <summary> /// Converts the <see cref="Boolean"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns> public static string ToString(bool value) { return (value) ? True : False; } /// <summary> /// Converts the <see cref="Char"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Char"/>.</returns> public static string ToString(char value) { return ToString(char.ToString(value)); } /// <summary> /// Converts the <see cref="Enum"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Enum"/>.</returns> public static string ToString(Enum value) { return value.ToString("D"); } /// <summary> /// Converts the <see cref="Int32"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Int32"/>.</returns> public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="Int16"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Int16"/>.</returns> public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="UInt16"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns> public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="UInt32"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns> public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="Int64"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Int64"/>.</returns> public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="UInt64"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns> public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="Single"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Single"/>.</returns> public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value))) return text; if (floatFormatHandling == FloatFormatHandling.DefaultValue) return (!nullable) ? "0.0" : Null; return quoteChar + text + quoteChar; } /// <summary> /// Converts the <see cref="Double"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Double"/>.</returns> public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) return text; return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1) return text; return text + ".0"; } /// <summary> /// Converts the <see cref="Byte"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Byte"/>.</returns> public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="SByte"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="SByte"/>.</returns> public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } /// <summary> /// Converts the <see cref="Decimal"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="SByte"/>.</returns> public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } /// <summary> /// Converts the <see cref="Guid"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Guid"/>.</returns> public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = null; #if !(NETFX_CORE || PORTABLE40 || PORTABLE) text = value.ToString("D", CultureInfo.InvariantCulture); #else text = value.ToString("D"); #endif return quoteChar + text + quoteChar; } /// <summary> /// Converts the <see cref="TimeSpan"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns> public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } /// <summary> /// Converts the <see cref="Uri"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Uri"/>.</returns> public static string ToString(Uri value) { if (value == null) return Null; return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.ToString(), quoteChar); } /// <summary> /// Converts the <see cref="String"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="String"/>.</returns> public static string ToString(string value) { return ToString(value, '"'); } /// <summary> /// Converts the <see cref="String"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="delimiter">The string delimiter character.</param> /// <returns>A JSON string representation of the <see cref="String"/>.</returns> public static string ToString(string value, char delimiter) { if (delimiter != '"' && delimiter != '\'') throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true); } /// <summary> /// Converts the <see cref="Object"/> to its JSON string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A JSON string representation of the <see cref="Object"/>.</returns> public static string ToString(object value) { if (value == null) return Null; PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value); switch (typeCode) { case PrimitiveTypeCode.String: return ToString((string) value); case PrimitiveTypeCode.Char: return ToString((char) value); case PrimitiveTypeCode.Boolean: return ToString((bool) value); case PrimitiveTypeCode.SByte: return ToString((sbyte) value); case PrimitiveTypeCode.Int16: return ToString((short) value); case PrimitiveTypeCode.UInt16: return ToString((ushort) value); case PrimitiveTypeCode.Int32: return ToString((int) value); case PrimitiveTypeCode.Byte: return ToString((byte) value); case PrimitiveTypeCode.UInt32: return ToString((uint) value); case PrimitiveTypeCode.Int64: return ToString((long) value); case PrimitiveTypeCode.UInt64: return ToString((ulong) value); case PrimitiveTypeCode.Single: return ToString((float) value); case PrimitiveTypeCode.Double: return ToString((double) value); case PrimitiveTypeCode.DateTime: return ToString((DateTime) value); case PrimitiveTypeCode.Decimal: return ToString((decimal) value); #if !(NETFX_CORE || PORTABLE) case PrimitiveTypeCode.DBNull: return Null; #endif #if !NET20 case PrimitiveTypeCode.DateTimeOffset: return ToString((DateTimeOffset) value); #endif case PrimitiveTypeCode.Guid: return ToString((Guid) value); case PrimitiveTypeCode.Uri: return ToString((Uri) value); case PrimitiveTypeCode.TimeSpan: return ToString((TimeSpan) value); } throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } #region Serialize /// <summary> /// Serializes the specified object to a JSON string. /// </summary> /// <param name="value">The object to serialize.</param> /// <returns>A JSON string representation of the object.</returns> public static string SerializeObject(object value) { return SerializeObject(value, Formatting.None, (JsonSerializerSettings) null); } /// <summary> /// Serializes the specified object to a JSON string using formatting. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <returns> /// A JSON string representation of the object. /// </returns> public static string SerializeObject(object value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings) null); } /// <summary> /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="converters">A collection converters used while serializing.</param> /// <returns>A JSON string representation of the object.</returns> public static string SerializeObject(object value, params JsonConverter[] converters) { return SerializeObject(value, Formatting.None, converters); } /// <summary> /// Serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <param name="converters">A collection converters used while serializing.</param> /// <returns>A JSON string representation of the object.</returns> public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings {Converters = converters} : null; return SerializeObject(value, formatting, settings); } /// <summary> /// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object. /// If this is null, default serialization settings will be is used.</param> /// <returns> /// A JSON string representation of the object. /// </returns> public static string SerializeObject(object value, JsonSerializerSettings settings) { return SerializeObject(value, Formatting.None, settings); } /// <summary> /// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object. /// If this is null, default serialization settings will be is used.</param> /// <returns> /// A JSON string representation of the object. /// </returns> public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) { return SerializeObject(value, null, formatting, settings); } /// <summary> /// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object. /// If this is null, default serialization settings will be is used.</param> /// <param name="type"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> /// <returns> /// A JSON string representation of the object. /// </returns> public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); var sb = new StringBuilder(256); var sw = new StringWriter(sb, CultureInfo.InvariantCulture); using (var jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = formatting; jsonSerializer.Serialize(jsonWriter, value, type); } return sw.ToString(); } #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40) /// <summary> /// Asynchronously serializes the specified object to a JSON string. /// Serialization will happen on a new thread. /// </summary> /// <param name="value">The object to serialize.</param> /// <returns> /// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object. /// </returns> public static Task<string> SerializeObjectAsync(object value) { return SerializeObjectAsync(value, Formatting.None, null); } /// <summary> /// Asynchronously serializes the specified object to a JSON string using formatting. /// Serialization will happen on a new thread. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <returns> /// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object. /// </returns> public static Task<string> SerializeObjectAsync(object value, Formatting formatting) { return SerializeObjectAsync(value, formatting, null); } /// <summary> /// Asynchronously serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>. /// Serialization will happen on a new thread. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object. /// If this is null, default serialization settings will be is used.</param> /// <returns> /// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object. /// </returns> public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings) { return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings)); } #endif #endregion #region Deserialize /// <summary> /// Deserializes the JSON to a .NET object. /// </summary> /// <param name="value">The JSON to deserialize.</param> /// <returns>The deserialized object from the Json string.</returns> public static object DeserializeObject(string value) { return DeserializeObject(value, null, (JsonSerializerSettings) null); } /// <summary> /// Deserializes the JSON to a .NET object using <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="value">The JSON to deserialize.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> /// <returns>The deserialized object from the JSON string.</returns> public static object DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } /// <summary> /// Deserializes the JSON to the specified .NET type. /// </summary> /// <param name="value">The JSON to deserialize.</param> /// <param name="type">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The deserialized object from the Json string.</returns> public static object DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings) null); } /// <summary> /// Deserializes the JSON to the specified .NET type. /// </summary> /// <typeparam name="T">The type of the object to deserialize to.</typeparam> /// <param name="value">The JSON to deserialize.</param> /// <returns>The deserialized object from the Json string.</returns> public static T DeserializeObject<T>(string value) { return DeserializeObject<T>(value, (JsonSerializerSettings) null); } /// <summary> /// Deserializes the JSON to the given anonymous type. /// </summary> /// <typeparam name="T"> /// The anonymous type to deserialize to. This can't be specified /// traditionally and must be infered from the anonymous type passed /// as a parameter. /// </typeparam> /// <param name="value">The JSON to deserialize.</param> /// <param name="anonymousTypeObject">The anonymous type object.</param> /// <returns>The deserialized anonymous type from the JSON string.</returns> public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } /// <summary> /// Deserializes the JSON to the given anonymous type using <see cref="JsonSerializerSettings"/>. /// </summary> /// <typeparam name="T"> /// The anonymous type to deserialize to. This can't be specified /// traditionally and must be infered from the anonymous type passed /// as a parameter. /// </typeparam> /// <param name="value">The JSON to deserialize.</param> /// <param name="anonymousTypeObject">The anonymous type object.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> /// <returns>The deserialized anonymous type from the JSON string.</returns> public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } /// <summary> /// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>. /// </summary> /// <typeparam name="T">The type of the object to deserialize to.</typeparam> /// <param name="value">The JSON to deserialize.</param> /// <param name="converters">Converters to use while deserializing.</param> /// <returns>The deserialized object from the JSON string.</returns> public static T DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T) DeserializeObject(value, typeof (T), converters); } /// <summary> /// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>. /// </summary> /// <typeparam name="T">The type of the object to deserialize to.</typeparam> /// <param name="value">The object to deserialize.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> /// <returns>The deserialized object from the JSON string.</returns> public static T DeserializeObject<T>(string value, JsonSerializerSettings settings) { return (T) DeserializeObject(value, typeof (T), settings); } /// <summary> /// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>. /// </summary> /// <param name="value">The JSON to deserialize.</param> /// <param name="type">The type of the object to deserialize.</param> /// <param name="converters">Converters to use while deserializing.</param> /// <returns>The deserialized object from the JSON string.</returns> public static object DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings {Converters = converters} : null; return DeserializeObject(value, type, settings); } /// <summary> /// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="value">The JSON to deserialize.</param> /// <param name="type">The type of the object to deserialize to.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> /// <returns>The deserialized object from the JSON string.</returns> public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings) { ValidationUtils.ArgumentNotNull(value, "value"); var sr = new StringReader(value); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); // by default DeserializeObject should check for additional content if (!jsonSerializer.IsCheckAdditionalContentSet()) jsonSerializer.CheckAdditionalContent = true; return jsonSerializer.Deserialize(new JsonTextReader(sr), type); } #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40) /// <summary> /// Asynchronously deserializes the JSON to the specified .NET type. /// Deserialization will happen on a new thread. /// </summary> /// <typeparam name="T">The type of the object to deserialize to.</typeparam> /// <param name="value">The JSON to deserialize.</param> /// <returns> /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string. /// </returns> public static Task<T> DeserializeObjectAsync<T>(string value) { return DeserializeObjectAsync<T>(value, null); } /// <summary> /// Asynchronously deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>. /// Deserialization will happen on a new thread. /// </summary> /// <typeparam name="T">The type of the object to deserialize to.</typeparam> /// <param name="value">The JSON to deserialize.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> /// <returns> /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string. /// </returns> public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings) { return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings)); } /// <summary> /// Asynchronously deserializes the JSON to the specified .NET type. /// Deserialization will happen on a new thread. /// </summary> /// <param name="value">The JSON to deserialize.</param> /// <returns> /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string. /// </returns> public static Task<object> DeserializeObjectAsync(string value) { return DeserializeObjectAsync(value, null, null); } /// <summary> /// Asynchronously deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>. /// Deserialization will happen on a new thread. /// </summary> /// <param name="value">The JSON to deserialize.</param> /// <param name="type">The type of the object to deserialize to.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> /// <returns> /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string. /// </returns> public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings) { return Task.Factory.StartNew(() => DeserializeObject(value, type, settings)); } #endif #endregion /// <summary> /// Populates the object with values from the JSON string. /// </summary> /// <param name="value">The JSON to populate values from.</param> /// <param name="target">The target object to populate values onto.</param> public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } /// <summary> /// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="value">The JSON to populate values from.</param> /// <param name="target">The target object to populate values onto.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> public static void PopulateObject(string value, object target, JsonSerializerSettings settings) { var sr = new StringReader(value); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using (JsonReader jsonReader = new JsonTextReader(sr)) { jsonSerializer.Populate(jsonReader, target); if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); } } #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40) /// <summary> /// Asynchronously populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="value">The JSON to populate values from.</param> /// <param name="target">The target object to populate values onto.</param> /// <param name="settings"> /// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// If this is null, default serialization settings will be is used. /// </param> /// <returns> /// A task that represents the asynchronous populate operation. /// </returns> public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings) { return Task.Factory.StartNew(() => PopulateObject(value, target, settings)); } #endif #if !(SILVERLIGHT || PORTABLE40 || PORTABLE || NETFX_CORE) /// <summary> /// Serializes the XML node to a JSON string. /// </summary> /// <param name="node">The node to serialize.</param> /// <returns>A JSON string of the XmlNode.</returns> public static string SerializeXmlNode(XmlNode node) { return SerializeXmlNode(node, Formatting.None); } /// <summary> /// Serializes the XML node to a JSON string using formatting. /// </summary> /// <param name="node">The node to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <returns>A JSON string of the XmlNode.</returns> public static string SerializeXmlNode(XmlNode node, Formatting formatting) { var converter = new XmlNodeConverter(); return SerializeObject(node, formatting, converter); } /// <summary> /// Serializes the XML node to a JSON string using formatting and omits the root object if <see cref="omitRootObject"/> is <c>true</c>. /// </summary> /// <param name="node">The node to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <param name="omitRootObject">Omits writing the root object.</param> /// <returns>A JSON string of the XmlNode.</returns> public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject) { var converter = new XmlNodeConverter {OmitRootObject = omitRootObject}; return SerializeObject(node, formatting, converter); } /// <summary> /// Deserializes the XmlNode from a JSON string. /// </summary> /// <param name="value">The JSON string.</param> /// <returns>The deserialized XmlNode</returns> public static XmlDocument DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } /// <summary> /// Deserializes the XmlNode from a JSON string nested in a root elment specified by <see cref="deserializeRootElementName"/>. /// </summary> /// <param name="value">The JSON string.</param> /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param> /// <returns>The deserialized XmlNode</returns> public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, false); } /// <summary> /// Deserializes the XmlNode from a JSON string nested in a root elment specified by <see cref="deserializeRootElementName"/> /// and writes a .NET array attribute for collections. /// </summary> /// <param name="value">The JSON string.</param> /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param> /// <param name="writeArrayAttribute"> /// A flag to indicate whether to write the Json.NET array attribute. /// This attribute helps preserve arrays when converting the written XML back to JSON. /// </param> /// <returns>The deserialized XmlNode</returns> public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute) { var converter = new XmlNodeConverter(); converter.DeserializeRootElementName = deserializeRootElementName; converter.WriteArrayAttribute = writeArrayAttribute; return (XmlDocument) DeserializeObject(value, typeof (XmlDocument), converter); } #endif #if !NET20 && (!(SILVERLIGHT) || WINDOWS_PHONE) && !PORTABLE40 /// <summary> /// Serializes the <see cref="XNode"/> to a JSON string. /// </summary> /// <param name="node">The node to convert to JSON.</param> /// <returns>A JSON string of the XNode.</returns> public static string SerializeXNode(XObject node) { return SerializeXNode(node, Formatting.None); } /// <summary> /// Serializes the <see cref="XNode"/> to a JSON string using formatting. /// </summary> /// <param name="node">The node to convert to JSON.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <returns>A JSON string of the XNode.</returns> public static string SerializeXNode(XObject node, Formatting formatting) { return SerializeXNode(node, formatting, false); } /// <summary> /// Serializes the <see cref="XNode"/> to a JSON string using formatting and omits the root object if <see cref="omitRootObject"/> is <c>true</c>. /// </summary> /// <param name="node">The node to serialize.</param> /// <param name="formatting">Indicates how the output is formatted.</param> /// <param name="omitRootObject">Omits writing the root object.</param> /// <returns>A JSON string of the XNode.</returns> public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject) { var converter = new XmlNodeConverter {OmitRootObject = omitRootObject}; return SerializeObject(node, formatting, converter); } /// <summary> /// Deserializes the <see cref="XNode"/> from a JSON string. /// </summary> /// <param name="value">The JSON string.</param> /// <returns>The deserialized XNode</returns> public static XDocument DeserializeXNode(string value) { return DeserializeXNode(value, null); } /// <summary> /// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment specified by <see cref="deserializeRootElementName"/>. /// </summary> /// <param name="value">The JSON string.</param> /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param> /// <returns>The deserialized XNode</returns> public static XDocument DeserializeXNode(string value, string deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, false); } /// <summary> /// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment specified by <see cref="deserializeRootElementName"/> /// and writes a .NET array attribute for collections. /// </summary> /// <param name="value">The JSON string.</param> /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param> /// <param name="writeArrayAttribute"> /// A flag to indicate whether to write the Json.NET array attribute. /// This attribute helps preserve arrays when converting the written XML back to JSON. /// </param> /// <returns>The deserialized XNode</returns> public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute) { var converter = new XmlNodeConverter(); converter.DeserializeRootElementName = deserializeRootElementName; converter.WriteArrayAttribute = writeArrayAttribute; return (XDocument) DeserializeObject(value, typeof (XDocument), converter); } #endif } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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.Xml; using System.Text; using System.IO; using System.Drawing.Imaging; using System.Globalization; using System.Threading; using System.Net; namespace Reporting.Rdl { ///<summary> /// Represents the background image information in a Style. ///</summary> [Serializable] internal class StyleBackgroundImage : ReportLink { StyleBackgroundImageSourceEnum _Source; // Identifies the source of the image: Expression _Value; // (string) See Source. Expected datatype is string or // binary, depending on Source. If the Value is // null, no background image is displayed. Expression _MIMEType; // (string) The MIMEType for the image. // Valid values are: image/bmp, image/jpeg, // image/gif, image/png, image/x-png // Required if Source = Database. Ignored otherwise. Expression _BackgroundRepeat; // (Enum BackgroundRepeat) Indicates how the background image should // repeat to fill the available space: Default: Repeat bool _ConstantImage; // true if constant image internal StyleBackgroundImage(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p) { _Source=StyleBackgroundImageSourceEnum.Unknown; _Value=null; _MIMEType=null; _BackgroundRepeat=null; _ConstantImage=false; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "Source": _Source = StyleBackgroundImageSource.GetStyle(xNodeLoop.InnerText); break; case "Value": _Value = new Expression(r, this, xNodeLoop, ExpressionType.String); break; case "MIMEType": _MIMEType = new Expression(r, this, xNodeLoop, ExpressionType.String); break; case "BackgroundRepeat": _BackgroundRepeat = new Expression(r, this, xNodeLoop, ExpressionType.Enum); break; default: // don't know this element - log it OwnerReport.rl.LogError(4, "Unknown BackgroundImage element '" + xNodeLoop.Name + "' ignored."); break; } } if (_Source == StyleBackgroundImageSourceEnum.Unknown) OwnerReport.rl.LogError(8, "BackgroundImage requires the Source element."); if (_Value == null) OwnerReport.rl.LogError(8, "BackgroundImage requires the Value element."); } // Handle parsing of function in final pass override internal void FinalPass() { if (_Value != null) _Value.FinalPass(); if (_MIMEType != null) _MIMEType.FinalPass(); if (_BackgroundRepeat != null) _BackgroundRepeat.FinalPass(); _ConstantImage = this.IsConstant(); return; } // Generate a CSS string from the specified styles internal string GetCSS(Report rpt, Row row, bool bDefaults) { StringBuilder sb = new StringBuilder(); // TODO: need to handle other types of sources if (_Value != null && _Source==StyleBackgroundImageSourceEnum.External) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "background-image:url(\"{0}\");",_Value.EvaluateString(rpt, row)); else if (bDefaults) return "background-image:none;"; if (_BackgroundRepeat != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "background-repeat:{0};",_BackgroundRepeat.EvaluateString(rpt, row)); else if (bDefaults) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "background-repeat:repeat;"); return sb.ToString(); } internal bool IsConstant() { if (_Source == StyleBackgroundImageSourceEnum.Database) return false; bool rc = true; if (_Value != null) rc = _Value.IsConstant(); if (!rc) return false; if (_BackgroundRepeat != null) rc = _BackgroundRepeat.IsConstant(); return rc; } internal PageImage GetPageImage(Report rpt, Row row) { string mtype=null; Stream strm=null; System.Drawing.Image im=null; PageImage pi=null; WorkClass wc = GetWC(rpt); if (wc.PgImage != null) { // have we already generated this one // reuse most of the work; only position will likely change pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH); pi.Name = wc.PgImage.Name; // this is name it will be shared under return pi; } try { strm = GetImageStream(rpt, row, out mtype); if (strm == null) { rpt.rl.LogError(4, string.Format("Unable to load image {0}.", this._Value==null?"": this._Value.EvaluateString(rpt, row))); return null; } im = System.Drawing.Image.FromStream(strm); int height = im.Height; int width = im.Width; MemoryStream ostrm = new MemoryStream(); ImageFormat imf; // if (mtype.ToLower() == "image/jpeg") //TODO: how do we get png to work // imf = ImageFormat.Jpeg; // else imf = ImageFormat.Jpeg; System.Drawing.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQualityManager.EmbeddedImageQuality); System.Drawing.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); byte[] ba = ostrm.ToArray(); ostrm.Close(); pi = new PageImage(imf, ba, width, height); pi.SI = new StyleInfo(); // this will just default everything if (_BackgroundRepeat != null) { string r = _BackgroundRepeat.EvaluateString(rpt, row).ToLower(); switch (r) { case "repeat": pi.Repeat = ImageRepeat.Repeat; break; case "repeatx": pi.Repeat = ImageRepeat.RepeatX; break; case "repeaty": pi.Repeat = ImageRepeat.RepeatY; break; case "norepeat": default: pi.Repeat = ImageRepeat.NoRepeat; break; } } else pi.Repeat = ImageRepeat.Repeat; if (_ConstantImage) { wc.PgImage = pi; // create unique name; PDF generation uses this to optimize the saving of the image only once pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name } } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } return pi; } Stream GetImageStream(Report rpt, Row row, out string mtype) { mtype=null; Stream strm=null; try { switch (this._Source) { case StyleBackgroundImageSourceEnum.Database: if (_MIMEType == null) return null; mtype = _MIMEType.EvaluateString(rpt, row); object o = _Value.Evaluate(rpt, row); strm = new MemoryStream((byte[]) o); break; case StyleBackgroundImageSourceEnum.Embedded: string name = _Value.EvaluateString(rpt, row); EmbeddedImage ei = (EmbeddedImage) OwnerReport.LUEmbeddedImages[name]; mtype = ei.MIMEType; byte[] ba = Convert.FromBase64String(ei.ImageData); strm = new MemoryStream(ba); break; case StyleBackgroundImageSourceEnum.External: string fname = _Value.EvaluateString(rpt, row); mtype = Image.GetMimeType(fname); if (fname.StartsWith("http:") || fname.StartsWith("file:") || fname.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(fname); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read); break; default: return null; } } catch { if (strm != null) { strm.Close(); strm = null; } } return strm; } static internal string GetCSSDefaults() { return "background-image:none;"; } internal StyleBackgroundImageSourceEnum Source { get { return _Source; } set { _Source = value; } } internal Expression Value { get { return _Value; } set { _Value = value; } } internal Expression MIMEType { get { return _MIMEType; } set { _MIMEType = value; } } internal Expression BackgroundRepeat { get { return _BackgroundRepeat; } set { _BackgroundRepeat = value; } } private WorkClass GetWC(Report rpt) { WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass; if (wc == null) { wc = new WorkClass(); rpt.Cache.Add(this, "wc", wc); } return wc; } private void RemoveWC(Report rpt) { rpt.Cache.Remove(this, "wc"); } class WorkClass { internal PageImage PgImage; // When ConstantImage is true this will save the PageImage for reuse internal WorkClass() { PgImage=null; } } } internal enum BackgroundRepeat { Repeat, // repeat image in both x and y directions NoRepeat, // don't repeat RepeatX, // repeat image in x direction RepeatY // repeat image in y direction } }
using System; using System.Collections.Generic; using MonoBrickFirmware.Display; using MonoBrickFirmware.UserInput; namespace MonoBrickFirmware.Display.Dialogs { public class CharacterDialog : Dialog { private const int maxNumberOfHorizontalCharacters = 10; private const int maxNumberOfLines = 4; private const int maxNumberOfButtomCharacters = maxNumberOfHorizontalCharacters -4; private const int charactersInSet = maxNumberOfHorizontalCharacters*2 + maxNumberOfButtomCharacters; private const int characterSize = 14; private const int characterEdge = 1; private const int characterOffset = 4; private const int lineThreeCharacterIndexStart = 2; private const int lineThreeCharacterIndexEnd = 8; private const int lineFourSpaceStart = 2; private const int lineFourSpaceEnd = 8; private const int yPrintOffset = 3; Point characterInnerBox; Point characterOutherBox; private Point characterSpace = new Point(1,0); internal enum Selection {LeftArrow = 1, RightArrow = 2, Character = 3, Ok = 4, Delete = 5, Space = 6, Change = 7}; private int selectedLine = 0; private int selectedIndex = 0; private Selection selection = Selection.Character; private ICharacterSet[] alfabetSet; private ICharacterSet[] symboleSet; private bool showAlfabet = true; private int selectedSetIndex = 0; private ICharacterSet selectedSet; private const string alfabetSetString = "abc"; private const string symboleSetString = "123"; private string setTypeString; private Rectangle resultRect; private Rectangle resultRectSmall; private Rectangle lineRect; private string resultString; private Font resultFont = Font.MediumFont; private bool useSmallFont = false; private string selectedCharacter = ""; private bool showLine = false; private List<string> inputLines = new List<string>(); public CharacterDialog(string title) : base(Font.MediumFont, title, Lcd.Width, Lcd.Height-22) { characterInnerBox = new Point(characterSize, characterSize); characterOutherBox = new Point(characterInnerBox.X + 2* characterEdge, characterInnerBox.Y + 2* characterEdge); alfabetSet = new ICharacterSet[]{new SmallLetters(), new BigLetters()}; symboleSet = new ICharacterSet[]{new NumbersAndSymbols(), new NumbersAndSymbols2()}; selectedSet = alfabetSet[selectedSetIndex]; setTypeString = symboleSetString; resultRect = new Rectangle(new Point(innerWindow.P1.X+characterEdge, innerWindow.P2.Y - (int)Font.MediumFont.maxHeight -1 ), new Point(innerWindow.P2.X-characterEdge, innerWindow.P2.Y -1)); resultRectSmall = new Rectangle(new Point(innerWindow.P1.X+characterEdge, innerWindow.P2.Y - (int)Font.SmallFont.maxHeight -1 ), new Point(innerWindow.P2.X-characterEdge, innerWindow.P2.Y -1)); lineRect = new Rectangle(new Point(innerWindow.P1.X+characterEdge, innerWindow.P2.Y - 2*((int)Font.SmallFont.maxHeight -1 )), new Point(innerWindow.P2.X-characterEdge, innerWindow.P2.Y -((int)Font.SmallFont.maxHeight -1 ))); resultString = ""; } public string GetUserInput () { string userString= ""; foreach(var s in inputLines) userString+= s; return userString+=resultString; } private bool ChangeSetType () { selectedSetIndex = 0; if (showAlfabet) { selectedSet = symboleSet [selectedSetIndex]; showAlfabet = false; setTypeString = alfabetSetString; } else { selectedSet = alfabetSet [selectedSetIndex]; showAlfabet = true; setTypeString = symboleSetString; } return false; } private bool AddCharacter (string characterToAdd) { resultString = resultString + characterToAdd; int charSize; if (useSmallFont) { charSize = characterSize/2; } else { charSize = characterSize; } bool tooBig = resultFont.TextSize (resultString).X >= (resultRect.P2.X - resultRect.P1.X) - charSize; if (tooBig) {//to big if (!useSmallFont) { useSmallFont = true; resultFont = Font.SmallFont; } else { if (tooBig) {//add using small font showLine = true; inputLines.Add (resultString); resultString = ""; } } } return false; } private bool DeleteCharacter () { if (resultString.Length != 0) { resultString = resultString.Substring (0, resultString.Length - 1); if (useSmallFont) { if (inputLines.Count == 0) { if (Font.MediumFont.TextSize (resultString).X < (resultRect.P2.X - resultRect.P1.X) - characterSize) { useSmallFont = false; resultFont = Font.MediumFont; } } } } else if (useSmallFont && inputLines.Count != 0) { resultString = inputLines[inputLines.Count-1]; inputLines.RemoveAt(inputLines.Count-1); resultString = resultString.Substring (0, resultString.Length - 1); if(inputLines.Count == 0) showLine = false; } return false; } private bool NextSet () { if (showAlfabet) { selectedSetIndex++; if(selectedSetIndex >= alfabetSet.Length) selectedSetIndex = 0; selectedSet = alfabetSet[selectedSetIndex]; } else { selectedSetIndex++; if(selectedSetIndex >= symboleSet.Length) selectedSetIndex = 0; selectedSet = symboleSet[selectedSetIndex]; } return false; } private bool PreviousSet () { if (showAlfabet) { selectedSetIndex--; if(selectedSetIndex < 0) selectedSetIndex = alfabetSet.Length-1; selectedSet = alfabetSet[selectedSetIndex]; } else { selectedSetIndex--; if(selectedSetIndex < 0) selectedSetIndex = symboleSet.Length-1; selectedSet = symboleSet[selectedSetIndex]; } return false; } private bool Done(){ return true; } protected override bool OnEnterAction () { bool end = false; switch (selection) { case Selection.Change: end = ChangeSetType(); break; case Selection.Character: end = AddCharacter(selectedCharacter); break; case Selection.Delete: end = DeleteCharacter(); break; case Selection.LeftArrow: end = PreviousSet(); break; case Selection.Ok: end = Done(); break; case Selection.RightArrow: end = NextSet(); break; case Selection.Space: end = AddCharacter(" "); break; } return end; } protected override bool OnLeftAction () { switch (selection) { case Selection.Delete: selectedIndex = lineThreeCharacterIndexEnd-1; break; case Selection.Ok: selectedIndex = lineFourSpaceEnd-1; break; case Selection.Space: selectedIndex = lineFourSpaceStart-1; break; default: selectedIndex--; if(selectedIndex < 0) selectedIndex = 0; break; } return false; } protected override bool OnRightAction () { switch (selection) { case Selection.Change: selectedIndex = lineFourSpaceStart; break; case Selection.Delete: selectedIndex = lineFourSpaceStart; break; case Selection.Space: selectedIndex = lineFourSpaceEnd+1; break; default : selectedIndex++; if(selectedIndex > maxNumberOfHorizontalCharacters-1) selectedIndex = maxNumberOfHorizontalCharacters-1; break; } return false; } protected override bool OnUpAction () { switch (selection) { case Selection.Change: selectedIndex = 0; break; case Selection.Delete: selectedIndex = maxNumberOfHorizontalCharacters-1; break; case Selection.Space: selectedIndex = (maxNumberOfHorizontalCharacters-1)/2; break; } selectedLine--; if(selectedLine < 0) selectedLine = 0; return false; } protected override bool OnDownAction () { selectedLine++; if(selectedLine > maxNumberOfLines-1) selectedLine = maxNumberOfLines-1; return false; } protected override void OnDrawContent () { bool rightArrowSelected = false; bool leftArrowSelected = false; bool deleteSelected = false; bool okSelected = false; bool spaceSelected = false; bool changeSelected = false; bool charactersSelected = false; int characterIndex = 0; Point start; Rectangle outherRect; Rectangle innerRect; int line; for (line = 0; line < 2; line++) { start = new Point (innerWindow.P1.X, innerWindow.P1.Y + (int)font.maxHeight / 2 - yPrintOffset + line * characterOutherBox.Y); outherRect = new Rectangle (start, start + characterOutherBox); for (int character = 0; character < maxNumberOfHorizontalCharacters; character++) { bool selected = (selectedLine == line && selectedIndex == character); if (selected) { selection = Selection.Character; charactersSelected = true; selectedCharacter = selectedSet.Characters [characterIndex].ToString (); } Lcd.Instance.DrawRectangle(outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle (innerRect, selected, true); Lcd.Instance.WriteText (Font.MediumFont, new Point (innerRect.P1.X + characterOffset, innerRect.P1.Y - characterOffset), selectedSet.Characters [characterIndex].ToString (), !selected); outherRect = outherRect + new Point (characterOutherBox.X, 0) + characterSpace; characterIndex++; } } if (selectedLine == line && selectedIndex < lineThreeCharacterIndexStart) { if (selectedIndex == 0) { selection = Selection.LeftArrow; leftArrowSelected = true; } else { selection = Selection.RightArrow; rightArrowSelected = true; } } start = new Point (innerWindow.P1.X, innerWindow.P1.Y + (int)font.maxHeight / 2 - yPrintOffset + line * characterOutherBox.Y); outherRect = new Rectangle (start, start + characterOutherBox); Lcd.Instance.DrawRectangle(outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle(innerRect, leftArrowSelected, true); innerRect = new Rectangle (new Point (outherRect.P1.X + 3 * characterEdge, outherRect.P1.Y + 3 * characterEdge), new Point (outherRect.P2.X - 3 * characterEdge, outherRect.P2.Y - 3 * characterEdge)); Lcd.Instance.DrawArrow (innerRect, Lcd.ArrowOrientation.Left, !leftArrowSelected); outherRect = outherRect + new Point (characterOutherBox.X, 0) + characterSpace; Lcd.Instance.DrawRectangle (outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle(innerRect, rightArrowSelected, true); innerRect = new Rectangle (new Point (outherRect.P1.X + 3 * characterEdge, outherRect.P1.Y + 3 * characterEdge), new Point (outherRect.P2.X - 3 * characterEdge, outherRect.P2.Y - 3 * characterEdge)); Lcd.Instance.DrawArrow (innerRect, Lcd.ArrowOrientation.Right, !rightArrowSelected); for (int character = 0; character < maxNumberOfButtomCharacters; character++) { bool selected = false; if (selectedLine == line) { if (selectedIndex >= lineThreeCharacterIndexStart && selectedIndex < lineThreeCharacterIndexEnd && (selectedIndex - lineThreeCharacterIndexStart) == character) { selected = true; selection = Selection.Character; charactersSelected = true; selectedCharacter = selectedSet.Characters [characterIndex].ToString (); } } outherRect = outherRect + new Point (characterOutherBox.X, 0) + characterSpace; Lcd.Instance.DrawRectangle (outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle (innerRect, selected, true); Lcd.Instance.WriteText (Font.MediumFont, new Point (innerRect.P1.X + characterOffset, innerRect.P1.Y - characterOffset), selectedSet.Characters [characterIndex].ToString (), !selected); characterIndex++; } if (selectedLine == line && selectedIndex >= lineThreeCharacterIndexEnd) { selection = Selection.Delete; deleteSelected = true; } outherRect = new Rectangle (new Point (outherRect.P1.X, outherRect.P1.Y), new Point (outherRect.P2.X + characterOutherBox.X + characterSpace.X, outherRect.P2.Y)) + new Point (characterOutherBox.X, 0) + new Point (characterSpace.X, characterSpace.Y); Lcd.Instance.DrawRectangle (outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle (innerRect, deleteSelected, true); Lcd.Instance.WriteText (Font.MediumFont, new Point (innerRect.P1.X + characterOffset + 1, innerRect.P1.Y - characterOffset + 1), "Del", !deleteSelected); line++; if (selectedLine == line && selectedIndex >= lineFourSpaceEnd) { selection = Selection.Ok; okSelected = true; } if (selectedLine == line && selectedIndex < lineFourSpaceStart) { selection = Selection.Change; changeSelected = true; } if (selectedLine == line && selectedIndex >= lineFourSpaceStart && selectedIndex < lineFourSpaceEnd) { selection = Selection.Space; spaceSelected = true; } start = new Point (innerWindow.P1.X, innerWindow.P1.Y + (int)font.maxHeight / 2 - yPrintOffset + line * characterOutherBox.Y); outherRect = new Rectangle (new Point (start.X, start.Y), new Point (start.X + 2 * characterOutherBox.X + characterSpace.X, start.Y + characterOutherBox.Y)); Lcd.Instance.DrawRectangle (outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle (innerRect, changeSelected, true); Lcd.Instance.WriteText (Font.MediumFont, new Point (innerRect.P1.X + characterOffset - 3, innerRect.P1.Y - characterOffset), setTypeString, !changeSelected); outherRect = new Rectangle (new Point (start.X + 2 * characterSpace.X + 2 * characterOutherBox.X, start.Y), new Point (start.X + 2 * characterSpace.X + 2 * characterOutherBox.X + 6 * characterOutherBox.X + 5 * characterSpace.X, start.Y + characterOutherBox.Y)); Lcd.Instance.DrawRectangle (outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle (innerRect, spaceSelected, true); Lcd.Instance.WriteText (Font.MediumFont, new Point (innerRect.P1.X + characterOffset + 3, innerRect.P1.Y - characterOffset + 1), " SPACE", !spaceSelected); outherRect = new Rectangle (new Point (outherRect.P2.X + characterSpace.X, outherRect.P1.Y), new Point (outherRect.P2.X + 2 * characterSpace.X + 2 * characterOutherBox.X, outherRect.P2.Y)); Lcd.Instance.DrawRectangle (outherRect, true, true); innerRect = new Rectangle (new Point (outherRect.P1.X + characterEdge, outherRect.P1.Y + characterEdge), new Point (outherRect.P2.X - characterEdge, outherRect.P2.Y - characterEdge)); Lcd.Instance.DrawRectangle (innerRect, okSelected, true); Lcd.Instance.WriteText (Font.MediumFont, new Point (innerRect.P1.X + characterOffset + 2, innerRect.P1.Y - characterOffset + 1), "OK", !okSelected); int xUnderLine = innerWindow.P1.X + characterEdge + resultFont.TextSize (resultString).X; int yUnderLine = innerWindow.P2.Y - 1; if (charactersSelected) { if (!useSmallFont) { Lcd.Instance.WriteTextBox (resultFont, resultRect, resultString + selectedCharacter, true, Lcd.Alignment.Left); Lcd.Instance.DrawHLine (new Point (xUnderLine, yUnderLine), resultFont.TextSize(selectedCharacter).X, true); } else { Lcd.Instance.WriteTextBox (resultFont, resultRectSmall, resultString + selectedCharacter, true, Lcd.Alignment.Left); Lcd.Instance.DrawHLine (new Point (xUnderLine, yUnderLine), resultFont.TextSize(selectedCharacter).X, true); if (showLine) { Lcd.Instance.WriteTextBox (resultFont, lineRect,inputLines[inputLines.Count-1], true, Lcd.Alignment.Left); } } } else { if (!useSmallFont) { Lcd.Instance.WriteTextBox (resultFont, resultRect, resultString + " ", true, Lcd.Alignment.Left); Lcd.Instance.DrawHLine (new Point (xUnderLine, yUnderLine), resultFont.TextSize(selectedCharacter).X, true); } else { Lcd.Instance.WriteTextBox (resultFont, resultRectSmall, resultString + " ", true, Lcd.Alignment.Left); Lcd.Instance.DrawHLine (new Point (xUnderLine, yUnderLine), resultFont.TextSize(selectedCharacter).X, true); if (showLine) { Lcd.Instance.WriteTextBox (resultFont, lineRect, inputLines[inputLines.Count-1], true, Lcd.Alignment.Left); } } } } } internal interface ICharacterSet { char[] Characters{ get;} } internal class BigLetters : ICharacterSet { public BigLetters () { Characters = new char[26]; char start = 'A'; for (int i = 0; i < 26; i++) { Characters[i] = start; start = (char)((int)start +1); } } public char[] Characters{ get; private set;} } internal class SmallLetters : ICharacterSet { public SmallLetters () { Characters = new char[26]; char start = 'a'; for (int i = 0; i < 26; i++) { Characters[i] = start; start = (char)((int)start +1); } } public char[] Characters{ get; private set;} } internal class NumbersAndSymbols: ICharacterSet { public NumbersAndSymbols() { Characters = new char[26]; Characters[0] = '1'; Characters[1] = '2'; Characters[2] = '3'; Characters[3] = '4'; Characters[4] = '5'; Characters[5] = '6'; Characters[6] = '7'; Characters[7] = '8'; Characters[8] = '9'; Characters[9] = '0'; Characters[10] = '-'; Characters[11] = '/'; Characters[12] = '.'; Characters[13] = ':'; Characters[14] = ';'; Characters[15] = '('; Characters[16] = ')'; Characters[17] = '&'; Characters[18] = '@'; Characters[19] = '"'; Characters[20] = '!'; Characters[21] = '+'; Characters[22] = '*'; Characters[23] = ','; Characters[24] = '#'; Characters[25] = '%'; } public char[] Characters{ get; private set;} } internal class NumbersAndSymbols2: ICharacterSet { public NumbersAndSymbols2() { Characters = new char[26]; Characters[0] = '1'; Characters[1] = '2'; Characters[2] = '3'; Characters[3] = '4'; Characters[4] = '5'; Characters[5] = '6'; Characters[6] = '7'; Characters[7] = '8'; Characters[8] = '9'; Characters[9] = '0'; Characters[10] = '$'; Characters[11] = (char) 39; //Single quote ' Characters[12] = '<'; Characters[13] = '='; Characters[14] = '>'; Characters[15] = '?'; Characters[16] = (char)92; //Backslash \ Characters[17] = ']'; Characters[18] = '^'; Characters[19] = '_'; Characters[20] = '`'; Characters[21] = '{'; Characters[22] = '|'; Characters[23] = '}'; Characters[24] = '~'; Characters[25] = (char)0; } public char[] Characters{ get; private set;} } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // AsynchronousOneToOneChannel.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// This is a bounded channel meant for single-producer/single-consumer scenarios. /// </summary> /// <typeparam name="T">Specifies the type of data in the channel.</typeparam> internal sealed class AsynchronousChannel<T> : IDisposable { // The producer will be blocked once the channel reaches a capacity, and unblocked // as soon as a consumer makes room. A consumer can block waiting until a producer // enqueues a new element. We use a chunking scheme to adjust the granularity and // frequency of synchronization, e.g. by enqueueing/dequeueing N elements at a time. // Because there is only ever a single producer and consumer, we are able to acheive // efficient and low-overhead synchronization. // // In general, the buffer has four logical states: // FULL <--> OPEN <--> EMPTY <--> DONE // // Here is a summary of the state transitions and what they mean: // * OPEN: // A buffer starts in the OPEN state. When the buffer is in the READY state, // a consumer and producer can dequeue and enqueue new elements. // * OPEN->FULL: // A producer transitions the buffer from OPEN->FULL when it enqueues a chunk // that causes the buffer to reach capacity; a producer can no longer enqueue // new chunks when this happens, causing it to block. // * FULL->OPEN: // When the consumer takes a chunk from a FULL buffer, it transitions back from // FULL->OPEN and the producer is woken up. // * OPEN->EMPTY: // When the consumer takes the last chunk from a buffer, the buffer is // transitioned from OPEN->EMPTY; a consumer can no longer take new chunks, // causing it to block. // * EMPTY->OPEN: // Lastly, when the producer enqueues an item into an EMPTY buffer, it // transitions to the OPEN state. This causes any waiting consumers to wake up. // * EMPTY->DONE: // If the buffer is empty, and the producer is done enqueueing new // items, the buffer is DONE. There will be no more consumption or production. // // Assumptions: // There is only ever one producer and one consumer operating on this channel // concurrently. The internal synchronization cannot handle anything else. // // ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** // VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV // // There... got your attention now... just in case you didn't read the comments // very carefully above, this channel will deadlock, become corrupt, and generally // make you an unhappy camper if you try to use more than 1 producer or more than // 1 consumer thread to access this thing concurrently. It's been carefully designed // to avoid locking, but only because of this restriction... private T[][] _buffer; // The buffer of chunks. private readonly int _index; // Index of this channel private volatile int _producerBufferIndex; // Producer's current index, i.e. where to put the next chunk. private volatile int _consumerBufferIndex; // Consumer's current index, i.e. where to get the next chunk. private volatile bool _done; // Set to true once the producer is done. private T[] _producerChunk; // The temporary chunk being generated by the producer. private int _producerChunkIndex; // A producer's index into its temporary chunk. private T[] _consumerChunk; // The temporary chunk being enumerated by the consumer. private int _consumerChunkIndex; // A consumer's index into its temporary chunk. private int _chunkSize; // The number of elements that comprise a chunk. // These events are used to signal a waiting producer when the consumer dequeues, and to signal a // waiting consumer when the producer enqueues. private ManualResetEventSlim _producerEvent; private IntValueEvent _consumerEvent; // These two-valued ints track whether a producer or consumer _might_ be waiting. They are marked // volatile because they are used in synchronization critical regions of code (see usage below). private volatile int _producerIsWaiting; private volatile int _consumerIsWaiting; private CancellationToken _cancellationToken; //----------------------------------------------------------------------------------- // Initializes a new channel with the specific capacity and chunk size. // // Arguments: // orderingHelper - the ordering helper to use for order preservation // capacity - the maximum number of elements before a producer blocks // chunkSize - the granularity of chunking on enqueue/dequeue. 0 means default size. // // Notes: // The capacity represents the maximum number of chunks a channel can hold. That // means producers will actually block after enqueueing capacity*chunkSize // individual elements. // internal AsynchronousChannel(int index, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) : this(index, Scheduling.DEFAULT_BOUNDED_BUFFER_CAPACITY, chunkSize, cancellationToken, consumerEvent) { } internal AsynchronousChannel(int index, int capacity, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) { if (chunkSize == 0) chunkSize = Scheduling.GetDefaultChunkSize<T>(); Debug.Assert(chunkSize > 0, "chunk size must be greater than 0"); Debug.Assert(capacity > 1, "this impl doesn't support capacity of 1 or 0"); // Initialize a buffer with enough space to hold 'capacity' elements. // We need one extra unused element as a sentinel to detect a full buffer, // thus we add one to the capacity requested. _index = index; _buffer = new T[capacity + 1][]; _producerBufferIndex = 0; _consumerBufferIndex = 0; _producerEvent = new ManualResetEventSlim(); _consumerEvent = consumerEvent; _chunkSize = chunkSize; _producerChunk = new T[chunkSize]; _producerChunkIndex = 0; _cancellationToken = cancellationToken; } //----------------------------------------------------------------------------------- // Checks whether the buffer is full. If the consumer is calling this, they can be // assured that a true value won't change before the consumer has a chance to dequeue // elements. That's because only one consumer can run at once. A producer might see // a true value, however, and then a consumer might transition to non-full, so it's // not stable for them. Lastly, it's of course possible to see a false value when // there really is a full queue, it's all dependent on small race conditions. // internal bool IsFull { get { // Read the fields once. One of these is always stable, since the only threads // that call this are the 1 producer/1 consumer threads. int producerIndex = _producerBufferIndex; int consumerIndex = _consumerBufferIndex; // Two cases: // 1) Is the producer index one less than the consumer? // 2) The producer is at the end of the buffer and the consumer at the beginning. return (producerIndex == consumerIndex - 1) || (consumerIndex == 0 && producerIndex == _buffer.Length - 1); // Note to readers: you might have expected us to consider the case where // _producerBufferIndex == _buffer.Length && _consumerBufferIndex == 1. // That is, a producer has gone off the end of the array, but is about to // wrap around to the 0th element again. We don't need this for a subtle // reason. It is SAFE for a consumer to think we are non-full when we // actually are full; it is NOT for a producer; but thankfully, there is // only one producer, and hence the producer will never see this seemingly // invalid state. Hence, we're fine producing a false negative. It's all // based on a race condition we have to deal with anyway. } } //----------------------------------------------------------------------------------- // Checks whether the buffer is empty. If the producer is calling this, they can be // assured that a true value won't change before the producer has a chance to enqueue // an item. That's because only one producer can run at once. A consumer might see // a true value, however, and then a producer might transition to non-empty. // internal bool IsChunkBufferEmpty { get { // The queue is empty when the producer and consumer are at the same index. return _producerBufferIndex == _consumerBufferIndex; } } //----------------------------------------------------------------------------------- // Checks whether the producer is done enqueueing new elements. // internal bool IsDone { get { return _done; } } //----------------------------------------------------------------------------------- // Used by a producer to flush out any internal buffers that have been accumulating // data, but which hasn't yet been published to the consumer. internal void FlushBuffers() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::FlushBuffers() called", Environment.CurrentManagedThreadId); // Ensure that a partially filled chunk is made available to the consumer. FlushCachedChunk(); } //----------------------------------------------------------------------------------- // Used by a producer to signal that it is done producing new elements. This will // also wake up any consumers that have gone to sleep. // internal void SetDone() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::SetDone() called", Environment.CurrentManagedThreadId); // This is set with a volatile write to ensure that, after the consumer // sees done, they can re-read the enqueued chunks and see the last one we // enqueued just above. _done = true; // We set the event to ensure consumers that may have waited or are // considering waiting will notice that the producer is done. This is done // after setting the done flag to facilitate a Dekker-style check/recheck. // // Because we can race with threads trying to Dispose of the event, we must // acquire a lock around our setting, and double-check that the event isn't null. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { if (_consumerEvent != null) { _consumerEvent.Set(_index); } } } //----------------------------------------------------------------------------------- // Enqueues a new element to the buffer, possibly blocking in the process. // // Arguments: // item - the new element to enqueue // timeoutMilliseconds - a timeout (or -1 for no timeout) used in case the buffer // is full; we return false if it expires // // Notes: // This API will block until the buffer is non-full. This internally buffers // elements up into chunks, so elements are not immediately available to consumers. // internal void Enqueue(T item) { // Store the element into our current chunk. int producerChunkIndex = _producerChunkIndex; _producerChunk[producerChunkIndex] = item; // And lastly, if we have filled a chunk, make it visible to consumers. if (producerChunkIndex == _chunkSize - 1) { EnqueueChunk(_producerChunk); _producerChunk = new T[_chunkSize]; } _producerChunkIndex = (producerChunkIndex + 1) % _chunkSize; } //----------------------------------------------------------------------------------- // Internal helper to queue a real chunk, not just an element. // // Arguments: // chunk - the chunk to make visible to consumers // timeoutMilliseconds - an optional timeout; we return false if it expires // // Notes: // This API will block if the buffer is full. A chunk must contain only valid // elements; if the chunk wasn't filled, it should be trimmed to size before // enqueueing it for consumers to observe. // private void EnqueueChunk(T[] chunk) { Debug.Assert(chunk != null); Debug.Assert(!_done, "can't continue producing after the production is over"); if (IsFull) WaitUntilNonFull(); Debug.Assert(!IsFull, "expected a non-full buffer"); // We can safely store into the current producer index because we know no consumers // will be reading from it concurrently. int bufferIndex = _producerBufferIndex; _buffer[bufferIndex] = chunk; // Increment the producer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. #pragma warning disable 0420 Interlocked.Exchange(ref _producerBufferIndex, (bufferIndex + 1) % _buffer.Length); #pragma warning restore 0420 // (If there is a consumer waiting, we have to ensure to signal the event. Unfortunately, // this requires that we issue a memory barrier: We need to guarantee that the write to // our producer index doesn't pass the read of the consumer waiting flags; the CLR memory // model unfortunately permits this reordering. That is handled by using a CAS above.) if (_consumerIsWaiting == 1 && !IsChunkBufferEmpty) { TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waking consumer"); _consumerIsWaiting = 0; _consumerEvent.Set(_index); } } //----------------------------------------------------------------------------------- // Just waits until the queue is non-full. // private void WaitUntilNonFull() { // We must loop; sometimes the producer event will have been set // prematurely due to the way waiting flags are managed. By looping, // we will only return from this method when space is truly available. do { // If the queue is full, we have to wait for a consumer to make room. // Reset the event to unsignaled state before waiting. _producerEvent.Reset(); // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a producer might see a full queue (by // reading IsFull just above), but meanwhile a consumer might drain the queue // very quickly, suddenly seeing an empty queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. #pragma warning disable 0420 Interlocked.Exchange(ref _producerIsWaiting, 1); #pragma warning restore 0420 // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a consumer that is transitioning the // buffer from full to non-full, we must check that the queue is full once // more. Otherwise, we might decide to wait and never be woken up (since // we just reset the event). if (IsFull) { // Assuming a consumer didn't make room for us, we can wait on the event. TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waiting, buffer full"); _producerEvent.Wait(_cancellationToken); } else { // Reset the flags, we don't actually have to wait after all. _producerIsWaiting = 0; } } while (IsFull); } //----------------------------------------------------------------------------------- // Flushes any built up elements that haven't been made available to a consumer yet. // Only safe to be called by a producer. // // Notes: // This API can block if the channel is currently full. // private void FlushCachedChunk() { // If the producer didn't fill their temporary working chunk, flushing forces an enqueue // so that a consumer will see the partially filled chunk of elements. if (_producerChunk != null && _producerChunkIndex != 0) { // Trim the partially-full chunk to an array just big enough to hold it. Debug.Assert(1 <= _producerChunkIndex && _producerChunkIndex <= _chunkSize); T[] leftOverChunk = new T[_producerChunkIndex]; Array.Copy(_producerChunk, leftOverChunk, _producerChunkIndex); // And enqueue the right-sized temporary chunk, possibly blocking if it's full. EnqueueChunk(leftOverChunk); _producerChunk = null; } } //----------------------------------------------------------------------------------- // Dequeues the next element in the queue. // // Arguments: // item - a byref to the location into which we'll store the dequeued element // // Return Value: // True if an item was found, false otherwise. // internal bool TryDequeue(ref T item) { // Ensure we have a chunk to work with. if (_consumerChunk == null) { if (!TryDequeueChunk(ref _consumerChunk)) { Debug.Assert(_consumerChunk == null); return false; } _consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Debug.Assert(_consumerChunk != null, "consumer chunk is null"); Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds"); item = _consumerChunk[_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out so we'll get the // next one when dequeue is called again. ++_consumerChunkIndex; if (_consumerChunkIndex == _consumerChunk.Length) { _consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. // // Arguments: // chunk - a byref to the location into which we'll store the chunk // // Return Value: // True if a chunk was found, false otherwise. // private bool TryDequeueChunk(ref T[] chunk) { // This is the non-blocking version of dequeue. We first check to see // if the queue is empty. If the caller chooses to wait later, they can // call the overload with an event. if (IsChunkBufferEmpty) { return false; } chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Blocking dequeue for the next element. This version of the API is used when the // caller will possibly wait for a new chunk to be enqueued. // // Arguments: // item - a byref for the returned element // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if an element was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // internal bool TryDequeue(ref T item, ref bool isDone) { isDone = false; // Ensure we have a buffer to work with. if (_consumerChunk == null) { if (!TryDequeueChunk(ref _consumerChunk, ref isDone)) { Debug.Assert(_consumerChunk == null); return false; } _consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Debug.Assert(_consumerChunk != null, "consumer chunk is null"); Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds"); item = _consumerChunk[_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out. ++_consumerChunkIndex; if (_consumerChunkIndex == _consumerChunk.Length) { _consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. This version of the API is used // when the caller will wait for a new chunk to be enqueued. // // Arguments: // chunk - a byref for the dequeued chunk // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if a chunk was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // private bool TryDequeueChunk(ref T[] chunk, ref bool isDone) { isDone = false; // We will register our interest in waiting, and then return an event // that the caller can use to wait. while (IsChunkBufferEmpty) { // If the producer is done and we've drained the queue, we can bail right away. if (IsDone) { // We have to see if the buffer is empty AFTER we've seen that it's done. // Otherwise, we would possibly miss the elements enqueued before the // producer signaled that it's done. This is done with a volatile load so // that the read of empty doesn't move before the read of done. if (IsChunkBufferEmpty) { // Return isDone=true so callers know not to wait isDone = true; return false; } } // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a consumer might see an empty queue (by // reading IsChunkBufferEmpty just above), but meanwhile a producer might fill the queue // very quickly, suddenly seeing a full queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. #pragma warning disable 0420 Interlocked.Exchange(ref _consumerIsWaiting, 1); #pragma warning restore 0420 // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a producer that is transitioning the // buffer from empty to non-full, we must check that the queue is empty once // more. Similarly, if the queue has been marked as done, we must not wait // because we just reset the event, possibly losing as signal. In both cases, // we would otherwise decide to wait and never be woken up (i.e. deadlock). if (IsChunkBufferEmpty && !IsDone) { // Note that the caller must eventually call DequeueEndAfterWait to set the // flags back to a state where no consumer is waiting, whether they choose // to wait or not. TraceHelpers.TraceInfo("AsynchronousChannel::DequeueChunk - consumer possibly waiting"); return false; } else { // Reset the wait flags, we don't need to wait after all. We loop back around // and recheck that the queue isn't empty, done, etc. _consumerIsWaiting = 0; } } Debug.Assert(!IsChunkBufferEmpty, "single-consumer should never witness an empty queue here"); chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Internal helper method that dequeues a chunk after we've verified that there is // a chunk available to dequeue. // // Return Value: // The dequeued chunk. // // Assumptions: // The caller has verified that a chunk is available, i.e. the queue is non-empty. // private T[] InternalDequeueChunk() { Debug.Assert(!IsChunkBufferEmpty); // We can safely read from the consumer index because we know no producers // will write concurrently. int consumerBufferIndex = _consumerBufferIndex; T[] chunk = _buffer[consumerBufferIndex]; // Zero out contents to avoid holding on to memory for longer than necessary. This // ensures the entire chunk is eligible for GC sooner. (More important for big chunks.) _buffer[consumerBufferIndex] = null; // Increment the consumer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. #pragma warning disable 0420 Interlocked.Exchange(ref _consumerBufferIndex, (consumerBufferIndex + 1) % _buffer.Length); #pragma warning restore 0420 // (Unfortunately, this whole sequence requires a memory barrier: We need to guarantee // that the write to _consumerBufferIndex doesn't pass the read of the wait-flags; the CLR memory // model sadly permits this reordering. Hence the CAS above.) if (_producerIsWaiting == 1 && !IsFull) { TraceHelpers.TraceInfo("BoundedSingleLockFreeChannel::DequeueChunk - consumer waking producer"); _producerIsWaiting = 0; _producerEvent.Set(); } return chunk; } //----------------------------------------------------------------------------------- // Clears the flag set when a blocking Dequeue is called, letting producers know // the consumer is no longer waiting. // internal void DoneWithDequeueWait() { // On our way out, be sure to reset the flags. _consumerIsWaiting = 0; } //----------------------------------------------------------------------------------- // Closes Win32 events possibly allocated during execution. // public void Dispose() { // We need to take a lock to deal with consumer threads racing to call Dispose // and producer threads racing inside of SetDone. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { Debug.Assert(_done, "Expected channel to be done before disposing"); Debug.Assert(_producerEvent != null); Debug.Assert(_consumerEvent != null); _producerEvent.Dispose(); _producerEvent = null; _consumerEvent = null; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Xml.Serialization; namespace Wyam.Feeds.Syndication.Atom { /// <summary> /// Adapter for Atom 0.3 compatibility /// </summary> [Serializable] [XmlRoot(RootElement, Namespace=Namespace)] public class AtomFeedOld : AtomSource, IFeed { public const string SpecificationUrl = "http://www.mnot.net/drafts/draft-nottingham-atom-format-02.html"; protected internal const string Prefix = ""; protected internal const string Namespace = "http://purl.org/atom/ns#"; protected internal const string RootElement = "feed"; protected internal const string MimeType = "application/atom+xml"; private Version _version = new Version(0, 3); /// <summary> /// Ctor /// </summary> [Obsolete("Atom 0.3 is for backwards compatibility and should only be used for deserialization", true)] public AtomFeedOld() { } [DefaultValue(null)] [XmlAttribute("version")] public string Version { get { return (_version == null) ? null : _version.ToString(); } set { _version = string.IsNullOrEmpty(value) ? null : new Version(value); } } [DefaultValue(null)] [XmlElement("tagline")] public AtomText TagLine { get { return SubTitle; } set { SubTitle = value; } } [DefaultValue(null)] [XmlElement("copyright")] public AtomText Copyright { get { return Rights; } set { Rights = value; } } [DefaultValue(null)] [XmlElement("modified")] public AtomDate Modified { get { return base.Updated; } set { base.Updated = value; } } [DefaultValue(0)] [XmlElement("fullcount")] public int FullCount { get { if (Entries == null) { return 0; } return Entries.Count; } set { } } [XmlElement("entry")] public readonly List<AtomEntryOld> Entries = new List<AtomEntryOld>(); [XmlIgnore] public bool EntriesSpecified { get { return (Entries.Count > 0); } set { } } [XmlIgnore] public override bool SubTitleSpecified { get { return false; } set { } } [XmlIgnore] public override bool UpdatedSpecified { get { return false; } set { } } [XmlIgnore] FeedType IFeed.FeedType => FeedType.Atom; string IFeed.MimeType => MimeType; string IFeed.Copyright => Rights?.StringValue; IList<IFeedItem> IFeed.Items => Entries.ToArray(); Uri IFeedMetadata.ID => ((IUriProvider)this).Uri; string IFeedMetadata.Title { get { if (Title == null) { return null; } return Title.StringValue; } } string IFeedMetadata.Description { get { if (SubTitle == null) { return null; } return SubTitle.StringValue; } } string IFeedMetadata.Author { get { if (!AuthorsSpecified) { if (!ContributorsSpecified) { return null; } foreach (AtomPerson person in Contributors) { if (!string.IsNullOrEmpty(person.Name)) { return person.Name; } if (!string.IsNullOrEmpty(person.Email)) { return person.Name; } } } foreach (AtomPerson person in Authors) { if (!string.IsNullOrEmpty(person.Name)) { return person.Name; } if (!string.IsNullOrEmpty(person.Email)) { return person.Name; } } return null; } } DateTime? IFeedMetadata.Published => ((IFeedMetadata)this).Updated; DateTime? IFeedMetadata.Updated { get { if (!Updated.HasValue) { return null; } return Updated.Value; } } Uri IFeedMetadata.Link { get { if (!LinksSpecified) { return null; } Uri alternate = null; foreach (AtomLink link in Links) { switch (link.Relation) { case AtomLinkRelation.Alternate: { return ((IUriProvider)link).Uri; } case AtomLinkRelation.Related: case AtomLinkRelation.Enclosure: { if (alternate == null) { alternate = ((IUriProvider)link).Uri; } break; } default: { continue; } } } return alternate; } } Uri IFeedMetadata.ImageLink { get { if (LogoUri == null) { return IconUri; } return LogoUri; } } public override void AddNamespaces(XmlSerializerNamespaces namespaces) { namespaces.Add(Prefix, Namespace); namespaces.Add(XmlPrefix, XmlNamespace); foreach (AtomEntry entry in Entries) { entry.AddNamespaces(namespaces); } base.AddNamespaces(namespaces); } } }
using System; using System.Collections.Generic; using System.Linq; using EnvDTE; using EnvDTE80; using Typewriter.Metadata.Interfaces; namespace Typewriter.Metadata.CodeDom { public class CodeDomTypeMetadata : ITypeMetadata { protected CodeType codeType; private readonly bool isNullable; private readonly bool isTask; private readonly CodeDomFileMetadata file; protected virtual CodeType CodeType => codeType; protected CodeDomTypeMetadata(CodeType codeType, bool isNullable, bool isTask, CodeDomFileMetadata file) { this.codeType = codeType; this.isNullable = isNullable; this.isTask = isTask; this.file = file; } public string DocComment => CodeType.DocComment; public virtual string Name => GetName(CodeType.Name); public virtual string FullName => GetFullName(CodeType.FullName); public virtual string Namespace => GetNamespace(); public ITypeMetadata Type => this; public bool IsAbstract => (codeType as CodeClass2)?.IsAbstract ?? false; public bool IsEnum => CodeType.Kind == vsCMElement.vsCMElementEnum; public bool IsEnumerable => IsCollection(FullName); public bool IsGeneric => FullName.IndexOf("<", StringComparison.Ordinal) > -1 && IsNullable == false; public bool IsNullable => isNullable; public bool IsTask => isTask; public bool IsDefined => CodeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject; public bool IsValueTuple => false; public IEnumerable<IFieldMetadata> TupleElements => new IFieldMetadata[0]; public IEnumerable<IAttributeMetadata> Attributes => CodeDomAttributeMetadata.FromCodeElements(CodeType.Attributes); public IEnumerable<ITypeMetadata> TypeArguments => LoadGenericTypeArguments(IsGeneric, FullName, file); public IEnumerable<ITypeParameterMetadata> TypeParameters => CodeDomTypeParameterMetadata.FromFullName(FullName); public IClassMetadata BaseClass => CodeDomClassMetadata.FromCodeElements(CodeType.Bases, file).FirstOrDefault(); public IClassMetadata ContainingClass => CodeDomClassMetadata.FromCodeClass(CodeType.Parent as CodeClass2, file); public IEnumerable<IConstantMetadata> Constants => CodeDomConstantMetadata.FromCodeElements(CodeType.Children, file); public IEnumerable<IDelegateMetadata> Delegates => CodeDomDelegateMetadata.FromCodeElements(CodeType.Children, file); public IEnumerable<IEventMetadata> Events => CodeDomEventMetadata.FromCodeElements(CodeType.Children, file); public IEnumerable<IFieldMetadata> Fields => CodeDomFieldMetadata.FromCodeElements(CodeType.Children, file); public IEnumerable<IInterfaceMetadata> Interfaces => CodeDomInterfaceMetadata.FromCodeElements(CodeType.Bases, file); public IEnumerable<IMethodMetadata> Methods => CodeDomMethodMetadata.FromCodeElements(CodeType.Children, file); public IEnumerable<IPropertyMetadata> Properties => CodeDomPropertyMetadata.FromCodeElements(CodeType.Children, file); public IEnumerable<IClassMetadata> NestedClasses => CodeDomClassMetadata.FromCodeElements(CodeType.Members, file); public IEnumerable<IEnumMetadata> NestedEnums => CodeDomEnumMetadata.FromCodeElements(CodeType.Members, file); public IEnumerable<IInterfaceMetadata> NestedInterfaces => CodeDomInterfaceMetadata.FromCodeElements(CodeType.Members, file); private string GetNamespace() { var parent = CodeType.Parent as CodeClass2; return parent != null ? parent.FullName : (CodeType.Namespace?.FullName ?? string.Empty); } protected string GetName(string name) { return name + (IsNullable ? "?" : string.Empty); } protected string GetFullName(string fullName) { return fullName + (IsNullable ? "?" : string.Empty); } public static IEnumerable<ITypeMetadata> LoadGenericTypeArguments(bool isGeneric, string typeFullName, CodeDomFileMetadata file) { if (isGeneric == false) return new ITypeMetadata[0]; return LazyCodeDomTypeMetadata.ExtractGenericTypeNames(typeFullName).Select(fullName => { if (fullName.EndsWith("[]")) fullName = $"System.Collections.Generic.ICollection<{fullName.TrimEnd('[', ']')}>"; var isNullable = fullName.EndsWith("?") || fullName.StartsWith("System.Nullable<"); if (isNullable) { fullName = fullName.EndsWith("?") ? fullName.TrimEnd('?') : fullName.Substring(16, fullName.Length - 17); return new LazyCodeDomTypeMetadata(fullName, true, false, file); } var isTask = fullName.StartsWith("System.Threading.Tasks.Task"); if (isTask) { fullName = fullName.Contains("<") ? fullName.Substring(28, fullName.Length - 29) : "System.Void"; isNullable = fullName.EndsWith("?") || fullName.StartsWith("System.Nullable<"); if (isNullable) { fullName = fullName.EndsWith("?") ? fullName.TrimEnd('?') : fullName.Substring(16, fullName.Length - 17); return new LazyCodeDomTypeMetadata(fullName, true, true, file); } return new LazyCodeDomTypeMetadata(fullName, false, true, file); } return new LazyCodeDomTypeMetadata(fullName, false, false, file); }); } private static ITypeMetadata GetType(dynamic element, CodeDomFileMetadata file) { var isGenericTypeArgument = element.Type.TypeKind == (int)vsCMTypeRef.vsCMTypeRefOther && element.Type.AsFullName.Split('.').Length == 1; if (isGenericTypeArgument) { return new GenericTypeMetadata(element.Type.AsFullName); } var isArray = element.Type.TypeKind == (int)vsCMTypeRef.vsCMTypeRefArray; if (isArray) { var name = element.Type.ElementType.AsFullName; return new LazyCodeDomTypeMetadata($"System.Collections.Generic.ICollection<{name}>", false, false, file); } CodeType codeType = element.Type.CodeType; var isNullable = codeType.FullName.EndsWith("?") || codeType.FullName.StartsWith("System.Nullable<"); if (isNullable) { var name = codeType.FullName; name = name.EndsWith("?") ? name.TrimEnd('?') : name.Substring(16, name.Length - 17); return new LazyCodeDomTypeMetadata(name, true, false, file); } var isTask = codeType.FullName.StartsWith("System.Threading.Tasks.Task"); if (isTask) { var name = codeType.FullName; name = name.Contains("<") ? name.Substring(28, name.Length - 29) : "System.Void"; isNullable = name.EndsWith("?") || name.StartsWith("System.Nullable<"); if (isNullable) { name = name.EndsWith("?") ? name.TrimEnd('?') : name.Substring(16, name.Length - 17); return new LazyCodeDomTypeMetadata(name, true, true, file); } return new LazyCodeDomTypeMetadata(name, false, true, file); } return new CodeDomTypeMetadata(codeType, false, false, file); } private static bool IsCollection(string fullName) { if (fullName == "System.Array") return true; if (fullName.StartsWith("System.Collections.") == false) return false; fullName = fullName.Split('<')[0]; if (fullName.Contains("Comparer")) return false; if (fullName.Contains("Enumerator")) return false; if (fullName.Contains("Provider")) return false; if (fullName.Contains("Partitioner")) return false; if (fullName.Contains("Structural")) return false; if (fullName.Contains("KeyNotFoundException")) return false; if (fullName.Contains("KeyValuePair")) return false; return true; } public static ITypeMetadata FromCodeElement(CodeVariable2 codeVariable, CodeDomFileMetadata file) { return GetType(codeVariable, file); } public static ITypeMetadata FromCodeElement(CodeFunction2 codeVariable, CodeDomFileMetadata file) { return GetType(codeVariable, file); } public static ITypeMetadata FromCodeElement(CodeDelegate2 codeVariable, CodeDomFileMetadata file) { return GetType(codeVariable, file); } public static ITypeMetadata FromCodeElement(CodeEvent codeVariable, CodeDomFileMetadata file) { return GetType(codeVariable, file); } public static ITypeMetadata FromCodeElement(CodeProperty2 codeVariable, CodeDomFileMetadata file) { return GetType(codeVariable, file); } public static ITypeMetadata FromCodeElement(CodeParameter2 codeVariable, CodeDomFileMetadata file) { return GetType(codeVariable, file); } } }
using System; using System.ComponentModel; using Mercurial.Attributes; namespace Mercurial { /// <summary> /// This class implements the "hg archive" command (<see href="http://www.selenic.com/mercurial/hg.1.html#archive"/>): /// create an unversioned archive of a repository revision. /// </summary> public sealed class ArchiveCommand : IncludeExcludeCommandBase<ArchiveCommand> { /// <summary> /// This is the backing field for the <see cref="DirectoryPrefix"/> property. /// </summary> private string _DirectoryPrefix = string.Empty; /// <summary> /// This is the backing field for the <see cref="PassThroughDecoders"/> property. /// </summary> private bool _PassThroughDecoders = true; /// <summary> /// This is the backing field for the <see cref="ArchiveType"/> property. /// </summary> private ArchiveType _ArchiveType = ArchiveType.Automatic; /// <summary> /// This is the backing field for the <see cref="Destination"/> property. /// </summary> private string _Destination = string.Empty; /// <summary> /// This is the backing field for the <see cref="RecurseSubRepositories"/> property. /// </summary> private bool _RecurseSubRepositories; /// <summary> /// Initializes a new instance of the <see cref="ArchiveCommand"/> class. /// </summary> public ArchiveCommand() : base("archive") { } /// <summary> /// Gets or sets a value indicating whether to pass files through decoders before archival. /// Default is <c>true</c>. /// </summary> [BooleanArgument(FalseOption = "--no-decode")] [DefaultValue(true)] public bool PassThroughDecoders { get { return _PassThroughDecoders; } set { _PassThroughDecoders = value; } } /// <summary> /// Gets or sets a directory prefix for files in the archive. /// Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument(NonNullOption = "--prefix")] [DefaultValue("")] public string DirectoryPrefix { get { return _DirectoryPrefix; } set { _DirectoryPrefix = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the <see cref="RevSpec"/> to archive. /// </summary> [NullableArgument] [DefaultValue(null)] public RevSpec Revision { get; set; } /// <summary> /// Gets or sets the type of archive to produce. /// Default is <see cref="Mercurial.ArchiveType.Automatic"/>. /// </summary> [EnumArgument(ArchiveType.Automatic, "")] [EnumArgument(ArchiveType.DirectoryWithFiles, "--type", "files")] [EnumArgument(ArchiveType.TarUncompressed, "--type", "tar")] [EnumArgument(ArchiveType.TarBZip2Compressed, "--type", "tbz2")] [EnumArgument(ArchiveType.TarGZipCompressed, "--type", "tgz")] [EnumArgument(ArchiveType.ZipUncompressed, "--type", "uzip")] [EnumArgument(ArchiveType.ZipDeflateCompressed, "--type", "zip")] [DefaultValue(ArchiveType.Automatic)] public ArchiveType ArchiveType { get { return _ArchiveType; } set { _ArchiveType = value; } } /// <summary> /// Gets or sets a value indicating whether to recurse into subrepositories. /// Default is <c>false</c>. /// </summary> /// <remarks> /// This property requires Mercurial 1.7 or newer. /// </remarks> [BooleanArgument(TrueOption = "--subrepos")] [DefaultValue(false)] public bool RecurseSubRepositories { get { return _RecurseSubRepositories; } set { RequiresVersion(new Version(1, 7, 0), "RecurseSubRepositories property of the ArchiveCommand class"); _RecurseSubRepositories = value; } } /// <summary> /// Gets or sets the destination to archive typ, either the directory (if <see cref="ArchiveType"/> is /// <see cref="Mercurial.ArchiveType.DirectoryWithFiles"/>) or the full path to and name of the archive file /// (for all other <see cref="ArchiveType"/>s of archives.) /// Default value is <see cref="string.Empty"/>. /// </summary> [NullableArgument] [DefaultValue("")] public string Destination { get { return _Destination; } set { _Destination = (value ?? string.Empty).Trim(); } } /// <summary> /// Sets the <see cref="PassThroughDecoders"/> property to the specified value and /// returns this <see cref="ArchiveCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="PassThroughDecoders"/> property. /// </param> /// <returns> /// This <see cref="ArchiveCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public ArchiveCommand WithPassThroughDecoders(bool value) { PassThroughDecoders = value; return this; } /// <summary> /// Sets the <see cref="DirectoryPrefix"/> property to the specified value and /// returns this <see cref="ArchiveCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="DirectoryPrefix"/> property. /// </param> /// <returns> /// This <see cref="ArchiveCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public ArchiveCommand WithDirectoryPrefix(string value) { DirectoryPrefix = value; return this; } /// <summary> /// Sets the <see cref="Revision"/> property to the specified value and /// returns this <see cref="ArchiveCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Revision"/> property. /// </param> /// <returns> /// This <see cref="ArchiveCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public ArchiveCommand WithRevision(RevSpec value) { Revision = value; return this; } /// <summary> /// Sets the <see cref="ArchiveType"/> property to the specified value and /// returns this <see cref="ArchiveCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="ArchiveType"/> property. /// </param> /// <returns> /// This <see cref="ArchiveCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public ArchiveCommand WithArchiveType(ArchiveType value) { ArchiveType = value; return this; } /// <summary> /// Sets the <see cref="RecurseSubRepositories"/> property to the specified value and /// returns this <see cref="ArchiveCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="RecurseSubRepositories"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="ArchiveCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public ArchiveCommand WithRecurseSubRepositories(bool value) { RecurseSubRepositories = value; return this; } /// <summary> /// Sets the <see cref="Destination"/> property to the specified value and /// returns this <see cref="ArchiveCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Destination"/> property. /// </param> /// <returns> /// This <see cref="ArchiveCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public ArchiveCommand WithDestination(string value) { Destination = value; return this; } /// <summary> /// Validates the command configuration. This method should throw the necessary /// exceptions to signal missing or incorrect configuration (like attempting to /// add files to the repository without specifying which files to add.) /// </summary> /// <exception cref="InvalidOperationException"> /// <para><see cref="Destination"/> is <c>null</c> or empty.</para> /// </exception> public override void Validate() { base.Validate(); if (StringEx.IsNullOrWhiteSpace(Destination)) throw new InvalidOperationException("Must specify the destination for the archive"); } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERLevel; namespace SelfLoad.Business.ERLevel { /// <summary> /// C05_SubContinent_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="C05_SubContinent_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="C04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class C05_SubContinent_ReChild : BusinessBase<C05_SubContinent_ReChild> { #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Countries Child Name"); /// <summary> /// Gets or sets the Countries Child Name. /// </summary> /// <value>The Countries Child Name.</value> public string SubContinent_Child_Name { get { return GetProperty(SubContinent_Child_NameProperty); } set { SetProperty(SubContinent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C05_SubContinent_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="C05_SubContinent_ReChild"/> object.</returns> internal static C05_SubContinent_ReChild NewC05_SubContinent_ReChild() { return DataPortal.CreateChild<C05_SubContinent_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="C05_SubContinent_ReChild"/> object, based on given parameters. /// </summary> /// <param name="subContinent_ID2">The SubContinent_ID2 parameter of the C05_SubContinent_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="C05_SubContinent_ReChild"/> object.</returns> internal static C05_SubContinent_ReChild GetC05_SubContinent_ReChild(int subContinent_ID2) { return DataPortal.FetchChild<C05_SubContinent_ReChild>(subContinent_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C05_SubContinent_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C05_SubContinent_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C05_SubContinent_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C05_SubContinent_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="subContinent_ID2">The Sub Continent ID2.</param> protected void Child_Fetch(int subContinent_ID2) { var args = new DataPortalHookArgs(subContinent_ID2); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<IC05_SubContinent_ReChildDal>(); var data = dal.Fetch(subContinent_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C05_SubContinent_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name")); _rowVersion = dr.GetValue("RowVersion") as byte[]; var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="C05_SubContinent_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C04_SubContinent parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IC05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { _rowVersion = dal.Insert( parent.SubContinent_ID, SubContinent_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="C05_SubContinent_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(C04_SubContinent parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IC05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { _rowVersion = dal.Update( parent.SubContinent_ID, SubContinent_Child_Name, _rowVersion ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="C05_SubContinent_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(C04_SubContinent parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IC05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.SubContinent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.IO; using System.Net; using System.Security.Cryptography.X509Certificates; using OpenADK.Library.Infra; using OpenADK.Util; using Org.Mentalis.Security.Certificates; namespace OpenADK.Library.Impl { /// <summary> /// Summary description for BaseHttpProtocolHandler. /// </summary> internal abstract class BaseHttpProtocolHandler : IProtocolHandler { #region Private Members private string fHttpUserAgent; private bool fKeepAliveOnSend; private Uri fZoneUrl; private ZoneImpl fZone; protected readonly HttpTransport fTransport; private X509Certificate fClientAuthCertificate; private bool fSSLInitialized; protected BaseHttpProtocolHandler(HttpTransport transport) { fTransport = transport; } #endregion #region IProtocolHandler Members public virtual string Name { get { return fZone.Agent.Id + "@" + fZone.ZoneId + ".HttpProtocolHandler"; } } /// <summary> Initialize the protocol handler for a zone</summary> public virtual void Open( ZoneImpl zone ) { fZone = zone; fKeepAliveOnSend = ((HttpProperties) fTransport.Properties).KeepAliveOnSend; try { // Ensure the ZIS URL is http/https fZoneUrl = fZone.ZoneUrl; string check = fZoneUrl.Scheme.ToLower(); if ( !check.Equals( "http" ) && !check.Equals( "https" ) ) { throw new AdkException ( "HttpProtocolHandler cannot handle URL: " + fZone.ZoneUrl, fZone ); } // Prepare headers later used to send messages fHttpUserAgent = fZone.Agent.Id + " (Adk/" + Adk.AdkVersion + ")"; } catch ( Exception thr ) { throw new AdkException ( "HttpProtocolHandler could not parse URL \"" + fZone.ZoneUrl + "\": " + thr, fZone ); } } public abstract void Close( IZone zone ); public abstract void Start(); public abstract void Shutdown(); /// <summary> Sends a SIF infrastructure message and returns the response.</summary> /// <remarks> /// The message content should consist of a complete <SIF_Message> element. /// This method sends whatever content is passed to it without any checking /// or validation of any kind. /// </remarks> /// <param name="msg">The message content</param> /// <returns> The response from the ZIS (expected to be a <SIF_Ack> message) /// </returns> /// <exception cref="AdkMessagingException"> is thrown if there is an error sending /// the message to the Zone Integration Server /// </exception> public IMessageInputStream Send( IMessageOutputStream msg ) { try { return TrySend( msg ); } catch ( WebException webEx ) { if ( webEx.Status == WebExceptionStatus.ConnectionClosed ) { // Try one more time, the underlying keep-alive connection must have // been closed by the ZIS. Trying again will start with a fresh, // new connection try { return TrySend( msg ); } catch ( AdkException ) { throw; } catch ( Exception ex ) { throw new AdkMessagingException ( "HttpProtocolHandler: Unexpected error sending message retry: " + ex, fZone ); } } else { // This code should never be hit because TrySend() should never emit this exception // Leaving the code here for defensive purposes throw new AdkMessagingException ( "HttpProtocolHandler: Unexpected error sending message: " + webEx, fZone ); } } } /// <summary> /// Returns true if the protocol and underlying transport are currently active /// for this zone /// </summary> /// <param name="zone"></param> /// <returns>True if the protocol handler and transport are active</returns> public abstract bool IsActive( ZoneImpl zone ); /// <summary> /// Creates the SIF_Protocol object that will be included with a SIF_Register /// message sent to the zone associated with this Transport.</Summary> /// <remarks> /// The base class implementation creates an empty SIF_Protocol with zero /// or more SIF_Property elements according to the parameters that have been /// defined by the client via setParameter. Derived classes should therefore /// call the superclass implementation first, then add to the resulting /// SIF_Protocol element as needed. /// </remarks> /// <param name="zone"></param> /// <returns></returns> public abstract SIF_Protocol MakeSIF_Protocol( IZone zone ); private IMessageInputStream TrySend( IMessageOutputStream msg ) { MessageStreamImpl returnStream; Stream reqStream; HttpWebRequest conn = GetConnection( fZoneUrl ); conn.ContentLength = msg.Length; try { reqStream = conn.GetRequestStream(); } catch ( WebException webEx ) { if ( webEx.Status == WebExceptionStatus.ConnectionClosed ) { // This could be a keep-alive connection that was closed unexpectedly // rethrow so that retry handling can take affect throw; } else { throw new AdkTransportException ( "Could not establish a connection to the ZIS (" + fZoneUrl.AbsoluteUri + "): " + webEx, fZone, webEx ); } } catch ( Exception thr ) { throw new AdkTransportException ( "Could not establish a connection to the ZIS (" + fZoneUrl.AbsoluteUri + "): " + thr, fZone, thr ); } try { if ( (Adk.Debug & AdkDebugFlags.Transport) != 0 ) { fZone.Log.Debug( "Sending message (" + msg.Length + " bytes)" ); } if ( (Adk.Debug & AdkDebugFlags.Message_Content) != 0 ) { fZone.Log.Debug( msg.Decode() ); } try { msg.CopyTo( reqStream ); reqStream.Flush(); reqStream.Close(); } catch ( Exception thr ) { throw new AdkMessagingException ( "HttpProtocolHandler: Unexpected error sending message: " + thr, fZone ); } try { using ( WebResponse response = conn.GetResponse() ) { if ( (Adk.Debug & AdkDebugFlags.Transport) != 0 ) { fZone.Log.Debug ( "Expecting reply (" + response.ContentLength + " bytes)" ); } returnStream = new MessageStreamImpl( response.GetResponseStream() ); response.Close(); if ( (Adk.Debug & AdkDebugFlags.Transport) != 0 ) { fZone.Log.Debug( "Received reply (" + returnStream.Length + " bytes)" ); } if ( (Adk.Debug & AdkDebugFlags.Message_Content) != 0 ) { fZone.Log.Debug( returnStream.Decode() ); } } } catch ( Exception thr ) { throw new AdkTransportException ( "An unexpected error occurred while receiving data from the ZIS: " + thr, fZone ); } } catch ( AdkException ) { // rethrow anything that's already wrapped in an AdkException throw; } catch ( Exception thr ) { throw new AdkMessagingException ( "HttpProtocolHandler: Error receiving response to sent message: " + thr, fZone ); } return returnStream; } #endregion #region Protected Members protected internal ZoneImpl Zone { get { return fZone; } } /// <summary> Get an outbound connection to the ZIS</summary> /// <returns> Either an HttpsURLConnection or an HttpURLConnection depending /// on whether the associated transport protocol is secure or not /// </returns> protected HttpWebRequest GetConnection( Uri uri ) { try { HttpWebRequest conn = (HttpWebRequest) WebRequest.Create( uri ); conn.Method = "POST"; conn.ContentType = SifIOFormatter.CONTENTTYPE; conn.UserAgent = fHttpUserAgent; conn.KeepAlive = fKeepAliveOnSend; // If the transport is an HTTPS transport, attempt to set an SSL // client certificate if ( fTransport.Secure ) { ApplySSLAttributes( conn ); } return conn; } catch ( WebException webEx ) { throw new AdkTransportException ( "Failed to create HttpWebRequest " + fZoneUrl.AbsoluteUri + ": " + webEx, fZone, webEx ); } } /// <summary> /// Retrieves a certificate to use for client authentication, if available and /// adds it to the client certificate collection of the HttpWebRequest. /// </summary> /// <param name="conn"></param> protected void ApplySSLAttributes( HttpWebRequest conn ) { if ( !fSSLInitialized ) { fSSLInitialized = true; Certificate cert = fTransport.GetClientAuthenticationCertificate(); if ( cert == null ) { fTransport.DebugTransport ( "No certificate found for client authentication", new object[0] ); } else { fClientAuthCertificate = cert.ToX509(); ServicePointManager.CertificatePolicy = fTransport.GetServerCertificatePolicy(); } } if ( fClientAuthCertificate != null ) { conn.ClientCertificates.Add( fClientAuthCertificate ); } } protected SifParser CreateParser() { return SifParser.NewInstance(); } #endregion } } // Synchronized with Library-ADK-1.5.0.Version_5.SIFPrimitives.java
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editor.SignatureHelp; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp { [ExportSignatureHelpProvider("ElementAccessExpressionSignatureHelpProvider", LanguageNames.CSharp)] internal sealed class ElementAccessExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) { return IsTriggerCharacterInternal(ch); } private static bool IsTriggerCharacterInternal(char ch) { return ch == '[' || ch == ','; } public override bool IsRetriggerCharacter(char ch) { return ch == ']'; } private static bool TryGetElementAccessExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { return CompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || IncompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || ConditionalAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace); } protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); ExpressionSyntax expression; SyntaxToken openBrace; if (!TryGetElementAccessExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out expression, out openBrace)) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (expressionSymbol is INamedTypeSymbol) { // foo?[$$] var namedType = (INamedTypeSymbol)expressionSymbol; if (namedType.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T && expression.IsKind(SyntaxKind.NullableType) && expression.IsChildNode<ArrayTypeSyntax>(a => a.ElementType)) { // Speculatively bind the type part of the nullable as an expression var nullableTypeSyntax = (NullableTypeSyntax)expression; var speculativeBinding = semanticModel.GetSpeculativeSymbolInfo(position, nullableTypeSyntax.ElementType, SpeculativeBindingOption.BindAsExpression); expressionSymbol = speculativeBinding.GetAnySymbol(); expression = nullableTypeSyntax.ElementType; } } if (expressionSymbol != null && expressionSymbol is INamedTypeSymbol) { return null; } IEnumerable<IPropertySymbol> indexers; ITypeSymbol expressionType; if (!TryGetIndexers(position, semanticModel, expression, cancellationToken, out indexers, out expressionType) && !TryGetComIndexers(semanticModel, expression, cancellationToken, out indexers, out expressionType)) { return null; } var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } var accessibleIndexers = indexers.Where(m => m.IsAccessibleWithin(within, throughTypeOpt: expressionType)); if (!accessibleIndexers.Any()) { return null; } var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>(); accessibleIndexers = accessibleIndexers.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(symbolDisplayService, semanticModel, expression.SpanStart); var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); var textSpan = GetTextSpan(expression, openBrace); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); return CreateSignatureHelpItems(accessibleIndexers.Select(p => Convert(p, openBrace, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken)), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } private TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken openBracket) { if (openBracket.Parent is BracketedArgumentListSyntax) { var conditional = expression.Parent as ConditionalAccessExpressionSyntax; if (conditional != null) { return TextSpan.FromBounds(conditional.Span.Start, openBracket.FullSpan.End); } else { return CompleteElementAccessExpression.GetTextSpan(expression, openBracket); } } else if (openBracket.Parent is ArrayRankSpecifierSyntax) { return IncompleteElementAccessExpression.GetTextSpan(expression, openBracket); } throw ExceptionUtilities.Unreachable; } public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { ExpressionSyntax expression; SyntaxToken openBracket; if (!TryGetElementAccessExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out expression, out openBracket) || currentSpan.Start != expression.SpanStart) { return null; } // If the user is actively typing, it's likely that we're in a broken state and the // syntax tree will be incorrect. Because of this we need to synthesize a new // bracketed argument list so we can correctly map the cursor to the current argument // and then we need to account for this and offset the position check accordingly. int offset; BracketedArgumentListSyntax argumentList; var newBracketedArgumentList = SyntaxFactory.ParseBracketedArgumentList(openBracket.Parent.ToString()); if (expression.Parent is ConditionalAccessExpressionSyntax) { // The typed code looks like: <expression>?[ var conditional = (ConditionalAccessExpressionSyntax)expression.Parent; var elementBinding = SyntaxFactory.ElementBindingExpression(newBracketedArgumentList); var conditionalAccessExpression = SyntaxFactory.ConditionalAccessExpression(expression, elementBinding); offset = expression.SpanStart - conditionalAccessExpression.SpanStart; argumentList = ((ElementBindingExpressionSyntax)conditionalAccessExpression.WhenNotNull).ArgumentList; } else { // The typed code looks like: // <expression>[ // or // <identifier>?[ ElementAccessExpressionSyntax elementAccessExpression = SyntaxFactory.ElementAccessExpression(expression, newBracketedArgumentList); offset = expression.SpanStart - elementAccessExpression.SpanStart; argumentList = elementAccessExpression.ArgumentList; } position -= offset; return SignatureHelpUtilities.GetSignatureHelpState(argumentList, position); } private bool TryGetComIndexers(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType) { indexers = semanticModel.GetMemberGroup(expression, cancellationToken).OfType<IPropertySymbol>(); if (indexers.Any() && expression is MemberAccessExpressionSyntax) { expressionType = semanticModel.GetTypeInfo(((MemberAccessExpressionSyntax)expression).Expression, cancellationToken).Type; return true; } expressionType = null; return false; } private bool TryGetIndexers(int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType) { expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType == null) { indexers = null; return false; } if (expressionType is IErrorTypeSymbol) { // If `expression` is a QualifiedNameSyntax then GetTypeInfo().Type won't have any CandidateSymbols, so // we should then fall back to getting the actual symbol for the expression. expressionType = (expressionType as IErrorTypeSymbol).CandidateSymbols.FirstOrDefault().GetSymbolType() ?? semanticModel.GetSymbolInfo(expression).GetAnySymbol().GetSymbolType(); } indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer).OfType<IPropertySymbol>(); return true; } private SignatureHelpItem Convert( IPropertySymbol indexer, SyntaxToken openToken, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, CancellationToken cancellationToken) { var position = openToken.SpanStart; var item = CreateItem(indexer, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, indexer.IsParams(), indexer.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(indexer, position, semanticModel), GetSeparatorParts(), GetPostambleParts(indexer), indexer.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken))); return item; } private IEnumerable<SymbolDisplayPart> GetPreambleParts( IPropertySymbol indexer, int position, SemanticModel semanticModel) { var result = new List<SymbolDisplayPart>(); result.AddRange(indexer.Type.ToMinimalDisplayParts(semanticModel, position)); result.Add(Space()); result.AddRange(indexer.ContainingType.ToMinimalDisplayParts(semanticModel, position)); if (indexer.Name != WellKnownMemberNames.Indexer) { result.Add(Punctuation(SyntaxKind.DotToken)); result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, indexer, indexer.Name)); } result.Add(Punctuation(SyntaxKind.OpenBracketToken)); return result; } private IEnumerable<SymbolDisplayPart> GetPostambleParts(IPropertySymbol indexer) { yield return Punctuation(SyntaxKind.CloseBracketToken); } private static class CompleteElementAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementAccessExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is BracketedArgumentListSyntax && (openBracket.Parent.Parent is ElementAccessExpressionSyntax || openBracket.Parent.Parent is ElementBindingExpressionSyntax)); return SignatureHelpUtilities.GetSignatureHelpSpan((BracketedArgumentListSyntax)openBracket.Parent); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ElementAccessExpressionSyntax elementAccessExpression; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out elementAccessExpression)) { identifier = elementAccessExpression.Expression; openBrace = elementAccessExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } /// Error tolerance case for /// "foo[$$]" or "foo?[$$]" /// which is parsed as an ArrayTypeSyntax variable declaration instead of an ElementAccessExpression private static class IncompleteElementAccessExpression { internal static bool IsArgumentListToken(ArrayTypeSyntax node, SyntaxToken token) { return node.RankSpecifiers.Span.Contains(token.SpanStart) && token != node.RankSpecifiers.First().CloseBracketToken; } internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is ArrayRankSpecifierSyntax; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is ArrayRankSpecifierSyntax && openBracket.Parent.Parent is ArrayTypeSyntax); return TextSpan.FromBounds(expression.SpanStart, openBracket.Parent.Span.End); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ArrayTypeSyntax arrayTypeSyntax; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out arrayTypeSyntax)) { identifier = arrayTypeSyntax.ElementType; openBrace = arrayTypeSyntax.RankSpecifiers.First().OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } /// Error tolerance case for /// "new String()?[$$]" /// which is parsed as a BracketedArgumentListSyntax parented by an ElementBindingExpressionSyntax parented by a ConditionalAccessExpressionSyntax private static class ConditionalAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementBindingExpressionSyntax && token.Parent.Parent.Parent is ConditionalAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementBindingExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ElementBindingExpressionSyntax elementBindingExpression; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out elementBindingExpression)) { identifier = ((ConditionalAccessExpressionSyntax)elementBindingExpression.Parent).Expression; openBrace = elementBindingExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } } }
// 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.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.EnterpriseServer; using WebsitePanel.Providers.Web; namespace WebsitePanel.Portal { public partial class WebSitesEditVirtualDir : WebsitePanelModuleBase { class Tab { int index; string id; string name; public Tab(int index, string id, string name) { this.index = index; this.id = id; this.name = name; } public int Index { get { return this.index; } set { this.index = value; } } public string Id { get { return this.id; } set { this.id = value; } } public string Name { get { return this.name; } set { this.name = value; } } } private int PackageId { get { return (int)ViewState["PackageId"]; } set { ViewState["PackageId"] = value; } } private bool IIs7 { get { return (bool)ViewState["IIs7"]; } set { ViewState["IIs7"] = value; } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindVirtualDir(); BindTabs(); } } private void BindTabs() { List<Tab> tabsList = new List<Tab>(); tabsList.Add(new Tab(0, "home", GetLocalizedString("Tab.HomeFolder"))); tabsList.Add(new Tab(1, "extensions", GetLocalizedString("Tab.Extensions"))); if (PackagesHelper.CheckGroupQuotaEnabled(PackageId, ResourceGroups.Web, Quotas.WEB_ERRORS)) tabsList.Add(new Tab(2, "errors", GetLocalizedString("Tab.CustomErrors"))); if (PackagesHelper.CheckGroupQuotaEnabled(PackageId, ResourceGroups.Web, Quotas.WEB_HEADERS)) tabsList.Add(new Tab(3, "headers", GetLocalizedString("Tab.CustomHeaders"))); if (PackagesHelper.CheckGroupQuotaEnabled(PackageId, ResourceGroups.Web, Quotas.WEB_MIME)) tabsList.Add(new Tab(4, "mime", GetLocalizedString("Tab.MIMETypes"))); if (dlTabs.SelectedIndex == -1) dlTabs.SelectedIndex = 0; dlTabs.DataSource = tabsList.ToArray(); dlTabs.DataBind(); tabs.ActiveViewIndex = tabsList[dlTabs.SelectedIndex].Index; } protected void dlTabs_SelectedIndexChanged(object sender, EventArgs e) { BindTabs(); } private void BindVirtualDir() { WebVirtualDirectory vdir = null; try { vdir = ES.Services.WebServers.GetVirtualDirectory(PanelRequest.ItemID, PanelRequest.VirtDir); } catch (Exception ex) { ShowErrorMessage("WEB_GET_VDIR", ex); return; } if (vdir == null) RedirectToBrowsePage(); // IIS 7.0 mode IIs7 = vdir.IIs7; PackageId = vdir.PackageId; // bind site string fullName = vdir.ParentSiteName + "/" + vdir.Name; lnkSiteName.Text = fullName; lnkSiteName.NavigateUrl = "http://" + fullName; // bind controls webSitesHomeFolderControl.BindWebItem(PackageId, vdir); webSitesExtensionsControl.BindWebItem(PackageId, vdir); webSitesMimeTypesControl.BindWebItem(vdir); webSitesCustomHeadersControl.BindWebItem(vdir); webSitesCustomErrorsControl.BindWebItem(vdir); } private void SaveVirtualDir() { if (!Page.IsValid) return; // load original web site item WebVirtualDirectory vdir = ES.Services.WebServers.GetVirtualDirectory(PanelRequest.ItemID, PanelRequest.VirtDir); // other controls webSitesExtensionsControl.SaveWebItem(vdir); webSitesHomeFolderControl.SaveWebItem(vdir); webSitesMimeTypesControl.SaveWebItem(vdir); webSitesCustomHeadersControl.SaveWebItem(vdir); webSitesCustomErrorsControl.SaveWebItem(vdir); // update web site try { int result = ES.Services.WebServers.UpdateVirtualDirectory(PanelRequest.ItemID, vdir); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("WEB_UPDATE_VDIR", ex); return; } ReturnBack(); } private void DeleteVirtualDir() { try { int result = ES.Services.WebServers.DeleteVirtualDirectory(PanelRequest.ItemID, PanelRequest.VirtDir); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("WEB_DELETE_VDIR", ex); return; } ReturnBack(); } protected void btnUpdate_Click(object sender, EventArgs e) { SaveVirtualDir(); } protected void btnCancel_Click(object sender, EventArgs e) { ReturnBack(); } protected void btnDelete_Click(object sender, EventArgs e) { DeleteVirtualDir(); } private void ReturnBack() { Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "edit_item", "MenuID=vdirs", PortalUtils.SPACE_ID_PARAM + "=" + PanelSecurity.PackageId.ToString())); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.DisposableTypesShouldDeclareFinalizerAnalyzer, Microsoft.NetCore.CSharp.Analyzers.Runtime.CSharpDisposableTypesShouldDeclareFinalizerFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.DisposableTypesShouldDeclareFinalizerAnalyzer, Microsoft.NetCore.VisualBasic.Analyzers.Runtime.BasicDisposableTypesShouldDeclareFinalizerFixer>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class DisposableTypesShouldDeclareFinalizerTests { [Fact] public async Task CSharpDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndNoFinalizerExists() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public class A : IDisposable { private readonly IntPtr _pi; public A() { _pi = NativeMethods.AllocateResource(); } public void Dispose() { } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpDiagnostic(11, 14)); } [Fact] public async Task BasicDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndNoFinalizerExists() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Class A Implements IDisposable Private ReadOnly _pi As IntPtr Public Sub New() _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicDiagnostic(11, 14)); } [Fact] public async Task CSharpNoDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndFinalizerExists() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public class A : IDisposable { private readonly IntPtr _pi; public A() { _pi = NativeMethods.AllocateResource(); } public void Dispose() { } ~A() { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndFinalizerExists() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Class A Implements IDisposable Private ReadOnly _pi As IntPtr Public Sub New() _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticIfIntPtrFieldInValueTypeIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public struct A : IDisposable // Although disposable structs are evil { private readonly IntPtr _pi; public A(int i) { _pi = NativeMethods.AllocateResource(); } public void Dispose() { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticIfIntPtrFieldInValueTypeIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Structure A Implements IDisposable ' Although disposable structs are evil Private ReadOnly _pi As IntPtr Public Sub New(i As Integer) _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticIfIntPtrFieldInNonDisposableTypeIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public class A { private readonly IntPtr _pi; public A() { _pi = NativeMethods.AllocateResource(); } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticIfIntPtrFieldInNonDisposableTypeIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Class A Private ReadOnly _pi As IntPtr Public Sub New() _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticIfIntPtrFieldIsAssignedFromManagedCode() { var code = @" using System; internal static class ManagedMethods { internal static IntPtr AllocateResource() { return IntPtr.Zero; } } public class A : IDisposable { private readonly IntPtr _pi; public A() { _pi = ManagedMethods.AllocateResource(); } public void Dispose() { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticIfIntPtrFieldIsAssignedFromManagedCode() { var code = @" Imports System Friend NotInheritable Class ManagedMethods Friend Shared Function AllocateResource() As IntPtr Return IntPtr.Zero End Function End Class Public Class A Implements IDisposable Private ReadOnly _pi As IntPtr Public Sub New() _pi = ManagedMethods.AllocateResource() End Sub Public Overloads Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpDiagnosticIfUIntPtrFieldIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern UIntPtr AllocateResource(); } public class A : IDisposable { private readonly UIntPtr _pu; public A() { _pu = NativeMethods.AllocateResource(); } public void Dispose() { } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpDiagnostic(11, 14)); } [Fact] public async Task BasicDiagnosticIfUIntPtrFieldIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As UIntPtr End Function End Class Public Class A Implements IDisposable Private ReadOnly _pu As UIntPtr Public Sub New() _pu = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicDiagnostic(11, 14)); } [Fact] public async Task CSharpDiagnosticIfHandleRefFieldIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern HandleRef AllocateResource(); } public class A : IDisposable { private readonly HandleRef _hr; public A() { _hr = NativeMethods.AllocateResource(); } public void Dispose() { } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpDiagnostic(11, 14)); } [Fact] public async Task BasicDiagnosticIfHandleRefFieldIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As HandleRef End Function End Class Public Class A Implements IDisposable Private ReadOnly _hr As HandleRef Public Sub New() _hr = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicDiagnostic(11, 14)); } [Fact] public async Task CSharpNoDiagnosticIfNonNativeResourceFieldIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern int AllocateResource(); } public class A : IDisposable { private readonly int _i; public A() { _i = NativeMethods.AllocateResource(); } public void Dispose() { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticIfNonNativeResourceFieldIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As Integer End Function End Class Public Class A Implements IDisposable Private ReadOnly _i As Integer Public Sub New() _i = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } private static DiagnosticResult GetCSharpDiagnostic(int line, int column) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic().WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetBasicDiagnostic(int line, int column) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic().WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; namespace Cytoid.Storyboard { public abstract class StateParser { public abstract void Parse(ObjectState state, JObject json, ObjectState baseState); } public abstract class GenericStateParser<TS> : StateParser where TS : ObjectState { public Storyboard Storyboard { get; } public GenericStateParser(Storyboard storyboard) { Storyboard = storyboard; } public abstract void Parse(TS state, JObject json, TS baseState); public override void Parse(ObjectState state, JObject json, ObjectState baseState) { Parse((TS) state, json, (TS) baseState); } protected void ParseObjectState(ObjectState state, JObject json, ObjectState baseState) { var token = json.SelectToken("time"); state.Time = Storyboard.ParseTime(json, token) ?? state.Time; state.Easing = json["easing"] != null ? (EasingFunction.Ease) Enum.Parse(typeof(EasingFunction.Ease), (string) json["easing"], true) : EasingFunction.Ease.Linear; state.Destroy = (bool?) json.SelectToken("destroy") ?? state.Destroy; } protected void ParseStageObjectState(StageObjectState state, JObject json, StageObjectState baseState) { ParseObjectState(state, json, baseState); state.X = ParseUnitFloat(json.SelectToken("x"), ReferenceUnit.StageX, true, false) ?? state.X; state.Y = ParseUnitFloat(json.SelectToken("y"), ReferenceUnit.StageY, true, false) ?? state.Y; state.Z = ParseUnitFloat(json.SelectToken("z"), ReferenceUnit.World, true, false) ?? state.Z; if (baseState != null) { var baseX = baseState.X?.Value ?? 0; var baseY = baseState.Y?.Value ?? 0; var dx = ParseUnitFloat(json.SelectToken("dx"), ReferenceUnit.StageX, true, true); var dy = ParseUnitFloat(json.SelectToken("dy"), ReferenceUnit.StageY, true, true); if (dx != null) state.X = dx.WithValue(dx.Value + baseX); if (dy != null) state.Y = dy.WithValue(dy.Value + baseY); } state.RotX = (float?) json.SelectToken("rot_x") ?? state.RotX; state.RotY = (float?) json.SelectToken("rot_y") ?? state.RotY; state.RotZ = (float?) json.SelectToken("rot_z") ?? state.RotZ; state.ScaleX = (float?) json.SelectToken("scale_x") ?? state.ScaleX; state.ScaleY = (float?) json.SelectToken("scale_y") ?? state.ScaleY; if (json["scale"] != null) { var scale = (float) json.SelectToken("scale"); state.ScaleX = scale; state.ScaleY = scale; } state.Opacity = (float?) json.SelectToken("opacity") ?? state.Opacity; state.Width = ParseUnitFloat(json.SelectToken("width"), ReferenceUnit.StageX, true, true) ?? state.Width; state.Height = ParseUnitFloat(json.SelectToken("height"), ReferenceUnit.StageY, true, true) ?? state.Height; state.FillWidth = (bool?) json.SelectToken("fill_width") ?? state.FillWidth; state.Layer = (int?) json.SelectToken("layer") ?? state.Layer; state.Order = (int?) json.SelectToken("order") ?? state.Order; } protected UnitFloat ParseUnitFloat(JToken token, ReferenceUnit defaultUnit, bool scaleToCanvas, bool span, float? defaultValue = null) { if (token == null) { if (defaultValue == null) return null; return new UnitFloat(defaultValue.Value, defaultUnit, scaleToCanvas, span); } switch (token.Type) { case JTokenType.Integer: return new UnitFloat((int) token, defaultUnit, scaleToCanvas, span); case JTokenType.Float: return new UnitFloat((float) token, defaultUnit, scaleToCanvas, span); case JTokenType.String: { var split = ((string) token).Split(':'); if (split.Length == 1) return new UnitFloat(float.Parse(split[0]), defaultUnit, scaleToCanvas, span); var type = split[0].ToLower(); var value = float.Parse(split[1]); return new UnitFloat(value, (ReferenceUnit) Enum.Parse(typeof(ReferenceUnit), type, true), scaleToCanvas, span); } default: throw new ArgumentException(); } } } public enum ReferenceUnit { World, StageX, StageY, // Canvas: 800 x 600 NoteX, NoteY, // Notes: 1 x 1 CameraX, CameraY, // Orthographic } [Serializable] public class UnitFloat { [JsonIgnore] public static Storyboard Storyboard; public float Value; public ReferenceUnit Unit; public bool ScaleToCanvas; public bool Span; [JsonIgnore] public float ConvertedValue { get { if (convertedValue != null) return convertedValue.Value; convertedValue = Convert(); return convertedValue.Value; } } [JsonIgnore] private float? convertedValue; public UnitFloat(float value, ReferenceUnit unit, bool scaleToCanvas, bool span) { Value = value; Unit = unit; ScaleToCanvas = scaleToCanvas; Span = span; } public UnitFloat WithValue(float value) { return new UnitFloat(value, Unit, ScaleToCanvas, Span); } public float Convert() { float res; switch (Unit) { case ReferenceUnit.World: res = Value; break; case ReferenceUnit.StageX: res = Value / StoryboardRenderer.ReferenceWidth * Storyboard.Game.camera.orthographicSize / UnityEngine.Screen.height * UnityEngine.Screen.width; break; case ReferenceUnit.StageY: res = Value / StoryboardRenderer.ReferenceHeight * Storyboard.Game.camera.orthographicSize; break; case ReferenceUnit.NoteX: res = Storyboard.Game.Chart.Let(it => it.ConvertChartXToScreenX(Value) - (Span ? it.ConvertChartXToScreenX(0) : 0)); break; case ReferenceUnit.NoteY: res = Storyboard.Game.Chart.Let(it => it.ConvertChartYToScreenY(Value) - (Span ? it.ConvertChartYToScreenY(0) : 0)); break; case ReferenceUnit.CameraX: res = Value * Storyboard.Game.camera.orthographicSize / UnityEngine.Screen.height * UnityEngine.Screen.width; break; case ReferenceUnit.CameraY: res = Value * Storyboard.Game.camera.orthographicSize; break; default: throw new ArgumentOutOfRangeException(); } if (ScaleToCanvas) { switch (Unit) { case ReferenceUnit.NoteX: res = res / (Storyboard.Game.camera.orthographicSize * 2 / UnityEngine.Screen.height * UnityEngine.Screen.width) * Storyboard.Renderer.Provider.CanvasRect.width; break; case ReferenceUnit.StageX: case ReferenceUnit.CameraX: res = res / (Storyboard.Game.camera.orthographicSize / UnityEngine.Screen.height * UnityEngine.Screen.width) * Storyboard.Renderer.Provider.CanvasRect.width; break; case ReferenceUnit.NoteY: res = res / (Storyboard.Game.camera.orthographicSize * 2) * Storyboard.Renderer.Provider.CanvasRect.height; break; case ReferenceUnit.StageY: case ReferenceUnit.CameraY: res = res / Storyboard.Game.camera.orthographicSize * Storyboard.Renderer.Provider.CanvasRect.height; break; } } return res; } public override string ToString() { return JsonConvert.SerializeObject(this); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides access to configuration variables for a repository. /// </summary> public class Configuration : IDisposable, IEnumerable<ConfigurationEntry<string>> { private readonly FilePath repoConfigPath; private readonly FilePath globalConfigPath; private readonly FilePath xdgConfigPath; private readonly FilePath systemConfigPath; private readonly FilePath programDataConfigPath; private ConfigurationHandle configHandle; /// <summary> /// Needed for mocking purposes. /// </summary> protected Configuration() { } internal Configuration( Repository repository, string repositoryConfigurationFileLocation, string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation) { if (repositoryConfigurationFileLocation != null) { repoConfigPath = NormalizeConfigPath(repositoryConfigurationFileLocation); } globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global(); xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg(); systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system(); programDataConfigPath = Proxy.git_config_find_programdata(); Init(repository); } private void Init(Repository repository) { configHandle = Proxy.git_config_new(); RepositoryHandle repoHandle = (repository != null) ? repository.Handle : null; if (repoHandle != null) { //TODO: push back this logic into libgit2. // As stated by @carlosmn "having a helper function to load the defaults and then allowing you // to modify it before giving it to git_repository_open_ext() would be a good addition, I think." // -- Agreed :) string repoConfigLocation = Path.Combine(repository.Info.Path, "config"); Proxy.git_config_add_file_ondisk(configHandle, repoConfigLocation, ConfigurationLevel.Local, repoHandle); Proxy.git_repository_set_config(repoHandle, configHandle); } else if (repoConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, repoConfigPath, ConfigurationLevel.Local, repoHandle); } if (globalConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, globalConfigPath, ConfigurationLevel.Global, repoHandle); } if (xdgConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, xdgConfigPath, ConfigurationLevel.Xdg, repoHandle); } if (systemConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System, repoHandle); } if (programDataConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, programDataConfigPath, ConfigurationLevel.ProgramData, repoHandle); } } private FilePath NormalizeConfigPath(FilePath path) { if (File.Exists(path.Native)) { return path; } if (!Directory.Exists(path.Native)) { throw new FileNotFoundException("Cannot find repository configuration file", path.Native); } var configPath = Path.Combine(path.Native, "config"); if (File.Exists(configPath)) { return configPath; } var gitConfigPath = Path.Combine(path.Native, ".git", "config"); if (File.Exists(gitConfigPath)) { return gitConfigPath; } throw new FileNotFoundException("Cannot find repository configuration file", path.Native); } /// <summary> /// Access configuration values without a repository. /// <para> /// Generally you want to access configuration via an instance of <see cref="Repository"/> instead. /// </para> /// <para> /// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case, /// this can be the working directory, the .git directory or the directory containing a bare repository. /// </para> /// </summary> /// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param> /// <returns>An instance of <see cref="Configuration"/>.</returns> public static Configuration BuildFrom(string repositoryConfigurationFileLocation) { return BuildFrom(repositoryConfigurationFileLocation, null, null, null); } /// <summary> /// Access configuration values without a repository. /// <para> /// Generally you want to access configuration via an instance of <see cref="Repository"/> instead. /// </para> /// <para> /// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case, /// this can be the working directory, the .git directory or the directory containing a bare repository. /// </para> /// </summary> /// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param> /// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param> /// <returns>An instance of <see cref="Configuration"/>.</returns> public static Configuration BuildFrom( string repositoryConfigurationFileLocation, string globalConfigurationFileLocation) { return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, null, null); } /// <summary> /// Access configuration values without a repository. /// <para> /// Generally you want to access configuration via an instance of <see cref="Repository"/> instead. /// </para> /// <para> /// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case, /// this can be the working directory, the .git directory or the directory containing a bare repository. /// </para> /// </summary> /// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param> /// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param> /// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param> /// <returns>An instance of <see cref="Configuration"/>.</returns> public static Configuration BuildFrom( string repositoryConfigurationFileLocation, string globalConfigurationFileLocation, string xdgConfigurationFileLocation) { return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, null); } /// <summary> /// Access configuration values without a repository. /// <para> /// Generally you want to access configuration via an instance of <see cref="Repository"/> instead. /// </para> /// <para> /// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case, /// this can be the working directory, the .git directory or the directory containing a bare repository. /// </para> /// </summary> /// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param> /// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param> /// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param> /// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a System configuration file will be probed.</param> /// <returns>An instance of <see cref="Configuration"/>.</returns> public static Configuration BuildFrom( string repositoryConfigurationFileLocation, string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation) { return new Configuration(null, repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation); } /// <summary> /// Determines which configuration file has been found. /// </summary> public virtual bool HasConfig(ConfigurationLevel level) { using (ConfigurationHandle snapshot = Snapshot()) using (ConfigurationHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { return handle != null; } } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// Saves any open configuration files. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Unset a configuration variable (key and value) in the local configuration. /// </summary> /// <param name="key">The key to unset.</param> public virtual void Unset(string key) { Unset(key, ConfigurationLevel.Local); } /// <summary> /// Unset a configuration variable (key and value). /// </summary> /// <param name="key">The key to unset.</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Unset(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_delete(h, key); } } internal void UnsetMultivar(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_delete_multivar(h, key); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> protected virtual void Dispose(bool disposing) { configHandle.SafeDispose(); } /// <summary> /// Get a configuration value for the given key parts. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;(new []{ "core", "bare" }).Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="keyParts">The key parts</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string[] keyParts) { Ensure.ArgumentNotNull(keyParts, "keyParts"); return Get<T>(string.Join(".", keyParts)); } /// <summary> /// Get a configuration value for the given key parts. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [difftool "kdiff3"] /// path = c:/Program Files/KDiff3/kdiff3.exe /// </code> /// /// You would call: /// /// <code> /// string where = repo.Config.Get&lt;string&gt;("difftool", "kdiff3", "path").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="firstKeyPart">The first key part</param> /// <param name="secondKeyPart">The second key part</param> /// <param name="thirdKeyPart">The third key part</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart) { Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart"); Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart"); Ensure.ArgumentNotNullOrEmptyString(thirdKeyPart, "thirdKeyPart"); return Get<T>(new[] { firstKeyPart, secondKeyPart, thirdKeyPart }); } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// The same escalation logic than in git.git will be used when looking for the key in the config files: /// - local: the Git file in the current repository /// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`) /// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`) /// - system: the system-wide Git file /// /// The first occurence of the key will be returned. /// </para> /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core.bare").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string key) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle snapshot = Snapshot()) { return Proxy.git_config_get_entry<T>(snapshot, key); } } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core.bare").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key</param> /// <param name="level">The configuration file into which the key should be searched for</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle snapshot = Snapshot()) using (ConfigurationHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { if (handle == null) { return null; } return Proxy.git_config_get_entry<T>(handle, key); } } /// <summary> /// Get a configuration value for the given key. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="key">The key</param> /// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/>if not found</returns> public virtual T GetValueOrDefault<T>(string key) { return ValueOrDefault(Get<T>(key), default(T)); } /// <summary> /// Get a configuration value for the given key, /// or <paramref name="defaultValue" /> if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="key">The key</param> /// <param name="defaultValue">The default value if the key is not set.</param> /// <returns>The configuration value, or the default value</returns> public virtual T GetValueOrDefault<T>(string key, T defaultValue) { return ValueOrDefault(Get<T>(key), defaultValue); } /// <summary> /// Get a configuration value for the given key /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="key">The key.</param> /// <param name="level">The configuration file into which the key should be searched for.</param> /// <returns>The configuration value, or the default value for <see typeparamref="T"/> if not found</returns> public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level) { return ValueOrDefault(Get<T>(key, level), default(T)); } /// <summary> /// Get a configuration value for the given key, /// or <paramref name="defaultValue" /> if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="key">The key.</param> /// <param name="level">The configuration file into which the key should be searched for.</param> /// <param name="defaultValue">The selector used to generate a default value if the key is not set.</param> /// <returns>The configuration value, or the default value.</returns> public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, T defaultValue) { return ValueOrDefault(Get<T>(key, level), defaultValue); } /// <summary> /// Get a configuration value for the given key parts /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="keyParts">The key parts.</param> /// <returns>The configuration value, or the default value for<see typeparamref="T"/> if not found</returns> public virtual T GetValueOrDefault<T>(string[] keyParts) { return ValueOrDefault(Get<T>(keyParts), default(T)); } /// <summary> /// Get a configuration value for the given key parts, /// or <paramref name="defaultValue" /> if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="keyParts">The key parts.</param> /// <param name="defaultValue">The default value if the key is not set.</param> /// <returns>The configuration value, or the default value.</returns> public virtual T GetValueOrDefault<T>(string[] keyParts, T defaultValue) { return ValueOrDefault(Get<T>(keyParts), defaultValue); } /// <summary> /// Get a configuration value for the given key parts. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="firstKeyPart">The first key part.</param> /// <param name="secondKeyPart">The second key part.</param> /// <param name="thirdKeyPart">The third key part.</param> /// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/> if not found</returns> public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart) { return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), default(T)); } /// <summary> /// Get a configuration value for the given key parts, /// or <paramref name="defaultValue" /> if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="firstKeyPart">The first key part.</param> /// <param name="secondKeyPart">The second key part.</param> /// <param name="thirdKeyPart">The third key part.</param> /// <param name="defaultValue">The default value if the key is not set.</param> /// <returns>The configuration value, or the default.</returns> public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, T defaultValue) { return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValue); } /// <summary> /// Get a configuration value for the given key, /// or a value generated by <paramref name="defaultValueSelector" /> /// if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="key">The key</param> /// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param> /// <returns>The configuration value, or a generated default.</returns> public virtual T GetValueOrDefault<T>(string key, Func<T> defaultValueSelector) { return ValueOrDefault(Get<T>(key), defaultValueSelector); } /// <summary> /// Get a configuration value for the given key, /// or a value generated by <paramref name="defaultValueSelector" /> /// if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="key">The key.</param> /// <param name="level">The configuration file into which the key should be searched for.</param> /// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param> /// <returns>The configuration value, or a generated default.</returns> public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, Func<T> defaultValueSelector) { return ValueOrDefault(Get<T>(key, level), defaultValueSelector); } /// <summary> /// Get a configuration value for the given key parts, /// or a value generated by <paramref name="defaultValueSelector" /> /// if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="keyParts">The key parts.</param> /// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param> /// <returns>The configuration value, or a generated default.</returns> public virtual T GetValueOrDefault<T>(string[] keyParts, Func<T> defaultValueSelector) { return ValueOrDefault(Get<T>(keyParts), defaultValueSelector); } /// <summary> /// Get a configuration value for the given key parts, /// or a value generated by <paramref name="defaultValueSelector" /> /// if the key is not set. /// </summary> /// <typeparam name="T">The configuration value type.</typeparam> /// <param name="firstKeyPart">The first key part.</param> /// <param name="secondKeyPart">The second key part.</param> /// <param name="thirdKeyPart">The third key part.</param> /// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param> /// <returns>The configuration value, or a generated default.</returns> public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, Func<T> defaultValueSelector) { return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValueSelector); } private static T ValueOrDefault<T>(ConfigurationEntry<T> value, T defaultValue) { return value == null ? defaultValue : value.Value; } private static T ValueOrDefault<T>(ConfigurationEntry<T> value, Func<T> defaultValueSelector) { Ensure.ArgumentNotNull(defaultValueSelector, "defaultValueSelector"); return value == null ? defaultValueSelector() : value.Value; } /// <summary> /// Set a configuration value for a key in the local configuration. Keys are in the form 'section.name'. /// <para> /// For example in order to set the value for this in a .git\config file: /// /// [test] /// boolsetting = true /// /// You would call: /// /// repo.Config.Set("test.boolsetting", true); /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key parts</param> /// <param name="value">The value</param> public virtual void Set<T>(string key, T value) { Set(key, value, ConfigurationLevel.Local); } /// <summary> /// Set a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to set the value for this in a .git\config file: /// /// [test] /// boolsetting = true /// /// You would call: /// /// repo.Config.Set("test.boolsetting", true); /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key parts</param> /// <param name="value">The value</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Set<T>(string key, T value, ConfigurationLevel level) { Ensure.ArgumentNotNull(value, "value"); Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { if (!configurationTypedUpdater.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } configurationTypedUpdater[typeof(T)](key, value, h); } } /// <summary> /// Find configuration entries matching <paramref name="regexp"/>. /// </summary> /// <param name="regexp">A regular expression.</param> /// <returns>Matching entries.</returns> public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp) { return Find(regexp, ConfigurationLevel.Local); } /// <summary> /// Find configuration entries matching <paramref name="regexp"/>. /// </summary> /// <param name="regexp">A regular expression.</param> /// <param name="level">The configuration file into which the key should be searched for.</param> /// <returns>Matching entries.</returns> public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp"); using (ConfigurationHandle snapshot = Snapshot()) using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, snapshot)) { return Proxy.git_config_iterator_glob(h, regexp).ToList(); } } private ConfigurationHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationHandle fromHandle) { ConfigurationHandle handle = null; if (fromHandle != null) { handle = Proxy.git_config_open_level(fromHandle, level); } if (handle == null && throwIfStoreHasNotBeenFound) { throw new LibGit2SharpException("No {0} configuration file has been found.", Enum.GetName(typeof(ConfigurationLevel), level)); } return handle; } private static Action<string, object, ConfigurationHandle> GetUpdater<T>(Action<ConfigurationHandle, string, T> setter) { return (key, val, handle) => setter(handle, key, (T)val); } private readonly static IDictionary<Type, Action<string, object, ConfigurationHandle>> configurationTypedUpdater = new Dictionary<Type, Action<string, object, ConfigurationHandle>> { { typeof(int), GetUpdater<int>(Proxy.git_config_set_int32) }, { typeof(long), GetUpdater<long>(Proxy.git_config_set_int64) }, { typeof(bool), GetUpdater<bool>(Proxy.git_config_set_bool) }, { typeof(string), GetUpdater<string>(Proxy.git_config_set_string) }, }; /// <summary> /// Returns an enumerator that iterates through the configuration entries. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the configuration entries.</returns> public virtual IEnumerator<ConfigurationEntry<string>> GetEnumerator() { return BuildConfigEntries().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<ConfigurationEntry<string>>)this).GetEnumerator(); } private IEnumerable<ConfigurationEntry<string>> BuildConfigEntries() { return Proxy.git_config_foreach(configHandle, BuildConfigEntry); } internal static unsafe ConfigurationEntry<string> BuildConfigEntry(IntPtr entryPtr) { var entry = (GitConfigEntry*)entryPtr.ToPointer(); return new ConfigurationEntry<string>(LaxUtf8Marshaler.FromNative(entry->namePtr), LaxUtf8Marshaler.FromNative(entry->valuePtr), (ConfigurationLevel)entry->level); } /// <summary> /// Builds a <see cref="Signature"/> based on current configuration. If it is not found or /// some configuration is missing, <code>null</code> is returned. /// <para> /// The same escalation logic than in git.git will be used when looking for the key in the config files: /// - local: the Git file in the current repository /// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`) /// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`) /// - system: the system-wide Git file /// </para> /// </summary> /// <param name="now">The timestamp to use for the <see cref="Signature"/>.</param> /// <returns>The signature or null if no user identity can be found in the configuration.</returns> public virtual Signature BuildSignature(DateTimeOffset now) { var name = this.GetValueOrDefault<string>("user.name"); var email = this.GetValueOrDefault<string>("user.email"); if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email)) { return null; } return new Signature(name, email, now); } internal Signature BuildSignatureOrThrow(DateTimeOffset now) { var signature = BuildSignature(now); if (signature == null) { throw new LibGit2SharpException("This overload requires 'user.name' and 'user.email' to be set. " + "Use a different overload or set those variables in the configuation"); } return signature; } private ConfigurationHandle Snapshot() { return Proxy.git_config_snapshot(configHandle); } /// <summary> /// Perform a series of actions within a transaction. /// /// The configuration will be locked during this function and the changes will be committed at the end. These /// changes will not be visible in the configuration until the end of this method. /// /// If the action throws an exception, the changes will be rolled back. /// </summary> /// <param name="action">The code to run under the transaction</param> public virtual unsafe void WithinTransaction(Action action) { IntPtr txn = IntPtr.Zero; try { txn = Proxy.git_config_lock(configHandle); action(); Proxy.git_transaction_commit(txn); } finally { Proxy.git_transaction_free(txn); } } } }
// 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.Win32.SafeHandles; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { /// <devdoc> /// <para> /// Provides access to local and remote /// processes. Enables you to start and stop system processes. /// </para> /// </devdoc> public partial class Process : IDisposable { private bool _haveProcessId; private int _processId; private bool _haveProcessHandle; private SafeProcessHandle _processHandle; private bool _isRemoteMachine; private string _machineName; private ProcessInfo _processInfo; private ProcessThreadCollection _threads; private ProcessModuleCollection _modules; private bool _haveWorkingSetLimits; private IntPtr _minWorkingSet; private IntPtr _maxWorkingSet; private bool _haveProcessorAffinity; private IntPtr _processorAffinity; private bool _havePriorityClass; private ProcessPriorityClass _priorityClass; private ProcessStartInfo _startInfo; private bool _watchForExit; private bool _watchingForExit; private EventHandler _onExited; private bool _exited; private int _exitCode; private DateTime _exitTime; private bool _haveExitTime; private bool _priorityBoostEnabled; private bool _havePriorityBoostEnabled; private bool _raisedOnExited; private RegisteredWaitHandle _registeredWaitHandle; private WaitHandle _waitHandle; private StreamReader _standardOutput; private StreamWriter _standardInput; private StreamReader _standardError; private bool _disposed; private static object s_createProcessLock = new object(); private StreamReadMode _outputStreamReadMode; private StreamReadMode _errorStreamReadMode; // Support for asynchronously reading streams public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; // Abstract the stream details internal AsyncStreamReader _output; internal AsyncStreamReader _error; internal bool _pendingOutputRead; internal bool _pendingErrorRead; #if FEATURE_TRACESWITCH internal static TraceSwitch _processTracing = #if DEBUG new TraceSwitch("processTracing", "Controls debug output from Process component"); #else null; #endif #endif /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class. /// </para> /// </devdoc> public Process() { // This class once inherited a finalizer. For backward compatibility it has one so that // any derived class that depends on it will see the behaviour expected. Since it is // not used by this class itself, suppress it immediately if this is not an instance // of a derived class it doesn't suffer the GC burden of finalization. if (GetType() == typeof(Process)) { GC.SuppressFinalize(this); } _machineName = "."; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo) { GC.SuppressFinalize(this); _processInfo = processInfo; _machineName = machineName; _isRemoteMachine = isRemoteMachine; _processId = processId; _haveProcessId = true; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } ~Process() { Dispose(false); } public SafeProcessHandle SafeHandle { get { EnsureState(State.Associated); return OpenProcessHandle(); } } /// <devdoc> /// Returns whether this process component is associated with a real process. /// </devdoc> /// <internalonly/> bool Associated { get { return _haveProcessId || _haveProcessHandle; } } /// <devdoc> /// <para> /// Gets the base priority of /// the associated process. /// </para> /// </devdoc> public int BasePriority { get { EnsureState(State.HaveProcessInfo); return _processInfo.BasePriority; } } /// <devdoc> /// <para> /// Gets /// the /// value that was specified by the associated process when it was terminated. /// </para> /// </devdoc> public int ExitCode { get { EnsureState(State.Exited); return _exitCode; } } /// <devdoc> /// <para> /// Gets a /// value indicating whether the associated process has been terminated. /// </para> /// </devdoc> public bool HasExited { get { if (!_exited) { EnsureState(State.Associated); UpdateHasExited(); if (_exited) { RaiseOnExited(); } } return _exited; } } /// <devdoc> /// <para> /// Gets the time that the associated process exited. /// </para> /// </devdoc> public DateTime ExitTime { get { if (!_haveExitTime) { EnsureState(State.Exited); _exitTime = ExitTimeCore; _haveExitTime = true; } return _exitTime; } } /// <devdoc> /// <para> /// Gets /// the unique identifier for the associated process. /// </para> /// </devdoc> public int Id { get { EnsureState(State.HaveId); return _processId; } } /// <devdoc> /// <para> /// Gets /// the name of the computer on which the associated process is running. /// </para> /// </devdoc> public string MachineName { get { EnsureState(State.Associated); return _machineName; } } /// <devdoc> /// <para> /// Gets or sets the maximum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MaxWorkingSet { get { EnsureWorkingSetLimits(); return _maxWorkingSet; } set { SetWorkingSetLimits(null, value); } } /// <devdoc> /// <para> /// Gets or sets the minimum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MinWorkingSet { get { EnsureWorkingSetLimits(); return _minWorkingSet; } set { SetWorkingSetLimits(value, null); } } public ProcessModuleCollection Modules { get { if (_modules == null) { EnsureState(State.HaveId | State.IsLocal); ModuleInfo[] moduleInfos = ProcessManager.GetModuleInfos(_processId); ProcessModule[] newModulesArray = new ProcessModule[moduleInfos.Length]; for (int i = 0; i < moduleInfos.Length; i++) { newModulesArray[i] = new ProcessModule(moduleInfos[i]); } ProcessModuleCollection newModules = new ProcessModuleCollection(newModulesArray); _modules = newModules; } return _modules; } } public long NonpagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolNonPagedBytes; } } public long PagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytes; } } public long PagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolPagedBytes; } } public long PeakPagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytesPeak; } } public long PeakWorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSetPeak; } } public long PeakVirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytesPeak; } } /// <devdoc> /// <para> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </para> /// </devdoc> public bool PriorityBoostEnabled { get { if (!_havePriorityBoostEnabled) { _priorityBoostEnabled = PriorityBoostEnabledCore; _havePriorityBoostEnabled = true; } return _priorityBoostEnabled; } set { PriorityBoostEnabledCore = value; _priorityBoostEnabled = value; _havePriorityBoostEnabled = true; } } /// <devdoc> /// <para> /// Gets or sets the overall priority category for the /// associated process. /// </para> /// </devdoc> public ProcessPriorityClass PriorityClass { get { if (!_havePriorityClass) { _priorityClass = PriorityClassCore; _havePriorityClass = true; } return _priorityClass; } set { if (!Enum.IsDefined(typeof(ProcessPriorityClass), value)) { throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "value", (int)value, typeof(ProcessPriorityClass))); } PriorityClassCore = value; _priorityClass = value; _havePriorityClass = true; } } public long PrivateMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PrivateBytes; } } /// <devdoc> /// <para> /// Gets /// the friendly name of the process. /// </para> /// </devdoc> public string ProcessName { get { EnsureState(State.HaveProcessInfo); return _processInfo.ProcessName; } } /// <devdoc> /// <para> /// Gets /// or sets which processors the threads in this process can be scheduled to run on. /// </para> /// </devdoc> public IntPtr ProcessorAffinity { get { if (!_haveProcessorAffinity) { _processorAffinity = ProcessorAffinityCore; _haveProcessorAffinity = true; } return _processorAffinity; } set { ProcessorAffinityCore = value; _processorAffinity = value; _haveProcessorAffinity = true; } } public int SessionId { get { EnsureState(State.HaveProcessInfo); return _processInfo.SessionId; } } /// <devdoc> /// <para> /// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/> /// . /// </para> /// </devdoc> public ProcessStartInfo StartInfo { get { if (_startInfo == null) { if (Associated) { throw new InvalidOperationException(SR.CantGetProcessStartInfo); } _startInfo = new ProcessStartInfo(); } return _startInfo; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (Associated) { throw new InvalidOperationException(SR.CantSetProcessStartInfo); } _startInfo = value; } } /// <devdoc> /// <para> /// Gets the set of threads that are running in the associated /// process. /// </para> /// </devdoc> public ProcessThreadCollection Threads { get { if (_threads == null) { EnsureState(State.HaveProcessInfo); int count = _processInfo._threadInfoList.Count; ProcessThread[] newThreadsArray = new ProcessThread[count]; for (int i = 0; i < count; i++) { newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]); } ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray); _threads = newThreads; } return _threads; } } public long VirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytes; } } /// <devdoc> /// <para> /// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/> /// event is fired /// when the process terminates. /// </para> /// </devdoc> public bool EnableRaisingEvents { get { return _watchForExit; } set { if (value != _watchForExit) { if (Associated) { if (value) { OpenProcessHandle(); EnsureWatchingForExit(); } else { StopWatchingForExit(); } } _watchForExit = value; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamWriter StandardInput { get { if (_standardInput == null) { throw new InvalidOperationException(SR.CantGetStandardIn); } return _standardInput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardOutput { get { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.SyncMode; } else if (_outputStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardOutput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardError { get { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.SyncMode; } else if (_errorStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardError; } } public long WorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSet; } } public event EventHandler Exited { add { _onExited += value; } remove { _onExited -= value; } } /// <devdoc> /// Release the temporary handle we used to get process information. /// If we used the process handle stored in the process object (we have all access to the handle,) don't release it. /// </devdoc> /// <internalonly/> private void ReleaseProcessHandle(SafeProcessHandle handle) { if (handle == null) { return; } if (_haveProcessHandle && handle == _processHandle) { return; } #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif handle.Dispose(); } /// <devdoc> /// This is called from the threadpool when a process exits. /// </devdoc> /// <internalonly/> private void CompletionCallback(object context, bool wasSignaled) { StopWatchingForExit(); RaiseOnExited(); } /// <internalonly/> /// <devdoc> /// <para> /// Free any resources associated with this component. /// </para> /// </devdoc> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //Dispose managed and unmanaged resources Close(); } _disposed = true; } } /// <devdoc> /// <para> /// Frees any resources associated with this component. /// </para> /// </devdoc> internal void Close() { if (Associated) { if (_haveProcessHandle) { StopWatchingForExit(); #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()"); #endif _processHandle.Dispose(); _processHandle = null; _haveProcessHandle = false; } _haveProcessId = false; _isRemoteMachine = false; _machineName = "."; _raisedOnExited = false; //Don't call close on the Readers and writers //since they might be referenced by somebody else while the //process is still alive but this method called. _standardOutput = null; _standardInput = null; _standardError = null; _output = null; _error = null; CloseCore(); Refresh(); } } /// <devdoc> /// Helper method for checking preconditions when accessing properties. /// </devdoc> /// <internalonly/> private void EnsureState(State state) { if ((state & State.Associated) != (State)0) if (!Associated) throw new InvalidOperationException(SR.NoAssociatedProcess); if ((state & State.HaveId) != (State)0) { if (!_haveProcessId) { if (_haveProcessHandle) { SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle)); } else { EnsureState(State.Associated); throw new InvalidOperationException(SR.ProcessIdRequired); } } } if ((state & State.IsLocal) != (State)0 && _isRemoteMachine) { throw new NotSupportedException(SR.NotSupportedRemote); } if ((state & State.HaveProcessInfo) != (State)0) { if (_processInfo == null) { if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId); _processInfo = ProcessManager.GetProcessInfo(_processId, _machineName); if (_processInfo == null) { throw new InvalidOperationException(SR.NoProcessInfo); } } } if ((state & State.Exited) != (State)0) { if (!HasExited) { throw new InvalidOperationException(SR.WaitTillExit); } if (!_haveProcessHandle) { throw new InvalidOperationException(SR.NoProcessHandle); } } } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new ProcessWaitHandle(_processHandle); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), null, -1, true); } catch { _watchingForExit = false; throw; } } } } } /// <devdoc> /// Make sure we have obtained the min and max working set limits. /// </devdoc> /// <internalonly/> private void EnsureWorkingSetLimits() { if (!_haveWorkingSetLimits) { GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } } /// <devdoc> /// Helper to set minimum or maximum working set limits. /// </devdoc> /// <internalonly/> private void SetWorkingSetLimits(IntPtr? min, IntPtr? max) { SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and /// the name of a computer in the network. /// </para> /// </devdoc> public static Process GetProcessById(int processId, string machineName) { if (!ProcessManager.IsProcessRunning(processId, machineName)) { throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture))); } return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null); } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given the /// identifier of a process on the local computer. /// </para> /// </devdoc> public static Process GetProcessById(int processId) { return GetProcessById(processId, "."); } /// <devdoc> /// <para> /// Creates an array of <see cref='System.Diagnostics.Process'/> components that are /// associated /// with process resources on the /// local computer. These process resources share the specified process name. /// </para> /// </devdoc> public static Process[] GetProcessesByName(string processName) { return GetProcessesByName(processName, "."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each process resource on the local computer. /// </para> /// </devdoc> public static Process[] GetProcesses() { return GetProcesses("."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each /// process resource on the specified computer. /// </para> /// </devdoc> public static Process[] GetProcesses(string machineName) { bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName); ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); Process[] processes = new Process[processInfos.Length]; for (int i = 0; i < processInfos.Length; i++) { ProcessInfo processInfo = processInfos[i]; processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo); } #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")"); #if DEBUG if (_processTracing.TraceVerbose) { Debug.Indent(); for (int i = 0; i < processInfos.Length; i++) { Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName); } Debug.Unindent(); } #endif #endif return processes; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> /// component and associates it with the current active process. /// </para> /// </devdoc> public static Process GetCurrentProcess() { return new Process(".", false, GetCurrentProcessId(), null); } /// <devdoc> /// <para> /// Raises the <see cref='System.Diagnostics.Process.Exited'/> event. /// </para> /// </devdoc> protected void OnExited() { EventHandler exited = _onExited; if (exited != null) { exited(this, EventArgs.Empty); } } /// <devdoc> /// Raise the Exited event, but make sure we don't do it more than once. /// </devdoc> /// <internalonly/> private void RaiseOnExited() { if (!_raisedOnExited) { lock (this) { if (!_raisedOnExited) { _raisedOnExited = true; OnExited(); } } } } /// <devdoc> /// <para> /// Discards any information about the associated process /// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the /// first request for information for each property causes the process component /// to obtain a new value from the associated process. /// </para> /// </devdoc> public void Refresh() { _processInfo = null; _threads = null; _modules = null; _exited = false; _haveWorkingSetLimits = false; _haveProcessorAffinity = false; _havePriorityClass = false; _haveExitTime = false; _havePriorityBoostEnabled = false; RefreshCore(); } /// <summary> /// Opens a long-term handle to the process, with all access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle OpenProcessHandle() { if (!_haveProcessHandle) { //Cannot open a new process handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } SetProcessHandle(GetProcessHandle()); } return _processHandle; } /// <devdoc> /// Helper to associate a process handle with this component. /// </devdoc> /// <internalonly/> private void SetProcessHandle(SafeProcessHandle processHandle) { _processHandle = processHandle; _haveProcessHandle = true; if (_watchForExit) { EnsureWatchingForExit(); } } /// <devdoc> /// Helper to associate a process id with this component. /// </devdoc> /// <internalonly/> private void SetProcessId(int processId) { _processId = processId; _haveProcessId = true; } /// <devdoc> /// <para> /// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/> /// component and associates it with the /// <see cref='System.Diagnostics.Process'/> . If a process resource is reused /// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public bool Start() { Close(); ProcessStartInfo startInfo = StartInfo; if (startInfo.FileName.Length == 0) { throw new InvalidOperationException(SR.FileNameMissing); } if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); } if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); } //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } return StartCore(startInfo); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of a /// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName) { return Start(new ProcessStartInfo(fileName)); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of an /// application and a set of command line arguments. Associates the process resource /// with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName, string arguments) { return Start(new ProcessStartInfo(fileName, arguments)); } /// <devdoc> /// <para> /// Starts a process resource specified by the process start /// information passed in, for example the file name of the process to start. /// Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(ProcessStartInfo startInfo) { Process process = new Process(); if (startInfo == null) throw new ArgumentNullException(nameof(startInfo)); process.StartInfo = startInfo; return process.Start() ? process : null; } /// <devdoc> /// Make sure we are not watching for process exit. /// </devdoc> /// <internalonly/> private void StopWatchingForExit() { if (_watchingForExit) { RegisteredWaitHandle rwh = null; WaitHandle wh = null; lock (this) { if (_watchingForExit) { _watchingForExit = false; wh = _waitHandle; _waitHandle = null; rwh = _registeredWaitHandle; _registeredWaitHandle = null; } } if (rwh != null) { rwh.Unregister(null); } if (wh != null) { wh.Dispose(); } } } public override string ToString() { if (Associated) { string processName = ProcessName; if (processName.Length != 0) { return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName); } } return base.ToString(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to wait /// indefinitely for the associated process to exit. /// </para> /// </devdoc> public void WaitForExit() { WaitForExit(Timeout.Infinite); } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for /// the associated process to exit. /// </summary> public bool WaitForExit(int milliseconds) { bool exited = WaitForExitCore(milliseconds); if (exited && _watchForExit) { RaiseOnExited(); } return exited; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardOutput stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to OutputDataReceived. /// </para> /// </devdoc> public void BeginOutputReadLine() { if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.AsyncMode; } else if (_outputStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingOutputRead) throw new InvalidOperationException(SR.PendingAsyncOperation); _pendingOutputRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_output == null) { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } Stream s = _standardOutput.BaseStream; _output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding); } _output.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardError stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to ErrorDataReceived. /// </para> /// </devdoc> public void BeginErrorReadLine() { if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.AsyncMode; } else if (_errorStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingErrorRead) { throw new InvalidOperationException(SR.PendingAsyncOperation); } _pendingErrorRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_error == null) { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } Stream s = _standardError.BaseStream; _error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding); } _error.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginOutputReadLine(). /// </para> /// </devdoc> public void CancelOutputRead() { if (_output != null) { _output.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingOutputRead = false; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginErrorReadLine(). /// </para> /// </devdoc> public void CancelErrorRead() { if (_error != null) { _error.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingErrorRead = false; } internal void OutputReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler outputDataReceived = OutputDataReceived; if (outputDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); outputDataReceived(this, e); // Call back to user informing data is available } } internal void ErrorReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler errorDataReceived = ErrorDataReceived; if (errorDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); errorDataReceived(this, e); // Call back to user informing data is available. } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// This enum defines the operation mode for redirected process stream. /// We don't support switching between synchronous mode and asynchronous mode. /// </summary> private enum StreamReadMode { Undefined, SyncMode, AsyncMode } /// <summary>A desired internal state.</summary> private enum State { HaveId = 0x1, IsLocal = 0x2, HaveProcessInfo = 0x8, Exited = 0x10, Associated = 0x20, } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Threading; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Management.Automation.Runspaces.Internal; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// This class is designed to contains the pertinent information about a Remote Connection, /// such as remote computer name, remote user name etc. /// It is also used to access remote connection capability and configuration information. /// Currently the session is identified by the InstanceId of the runspacePool associated with it /// This can change in future if we start supporting multiple runspacePools per session. /// </summary> internal class ClientRemoteSessionContext { #region properties /// <summary> /// Remote computer address in URI format. /// </summary> internal Uri RemoteAddress { get; set; } /// <summary> /// User credential to be used on the remote computer. /// </summary> internal PSCredential UserCredential { get; set; } /// <summary> /// Capability information for the client side. /// </summary> internal RemoteSessionCapability ClientCapability { get; set; } /// <summary> /// Capability information received from the server side. /// </summary> internal RemoteSessionCapability ServerCapability { get; set; } /// <summary> /// This is the shellName which identifies the PowerShell configuration to launch /// on remote machine. /// </summary> internal string ShellName { get; set; } #endregion Public_Properties } /// <summary> /// This abstract class defines the client view of the remote connection. /// </summary> internal abstract class ClientRemoteSession : RemoteSession { [TraceSourceAttribute("CRSession", "ClientRemoteSession")] private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSession", "ClientRemoteSession"); #region Public_Method_API /// <summary> /// Client side user calls this function to create a new remote session. /// User needs to register event handler to ConnectionEstablished and ConnectionClosed to /// monitor the actual connection state. /// </summary> public abstract void CreateAsync(); /// <summary> /// This event handler is raised when the state of session changes /// </summary> public abstract event EventHandler<RemoteSessionStateEventArgs> StateChanged; /// <summary> /// Close the connection to the remote computer in an asynchronous manner. /// Client side user can register an event handler with ConnectionClosed to monitor /// the connection state. /// </summary> public abstract void CloseAsync(); /// <summary> /// Disconnects the remote session in an asynchronous manner /// </summary> public abstract void DisconnectAsync(); /// <summary> /// Reconnects the remote session in an asynchronous manner /// </summary> public abstract void ReconnectAsync(); /// <summary> /// Connects to an existing remote session /// User needs to register event handler to ConnectionEstablished and ConnectionClosed to /// monitor the actual connection state. /// </summary> public abstract void ConnectAsync(); #endregion Public_Method_API #region Public_Properties internal ClientRemoteSessionContext Context { get; } = new ClientRemoteSessionContext(); #endregion Public_Properties #region URI Redirection /// <summary> /// Delegate used to report connection URI redirections to the application /// </summary> /// <param name="newURI"> /// New URI to which the connection is being redirected to. /// </param> internal delegate void URIDirectionReported(Uri newURI); #endregion /// <summary> /// ServerRemoteSessionDataStructureHandler instance for this session /// </summary> internal ClientRemoteSessionDataStructureHandler SessionDataStructureHandler { get; set; } protected Version _serverProtocolVersion; /// <summary> /// Protocol version negotiated by the server /// </summary> internal Version ServerProtocolVersion { get { return _serverProtocolVersion; } } private RemoteRunspacePoolInternal _remoteRunspacePool; /// <summary> /// remote runspace pool if used, for this session /// </summary> internal RemoteRunspacePoolInternal RemoteRunspacePoolInternal { get { return _remoteRunspacePool; } set { Dbg.Assert(_remoteRunspacePool == null, @"RunspacePool should be attached only once to the session"); _remoteRunspacePool = value; } } /// <summary> /// Get the runspace pool with the matching id /// </summary> /// <param name="clientRunspacePoolId"> /// Id of the runspace to get /// </param> /// <returns></returns> internal RemoteRunspacePoolInternal GetRunspacePool(Guid clientRunspacePoolId) { if (_remoteRunspacePool != null) { if (_remoteRunspacePool.InstanceId.Equals(clientRunspacePoolId)) return _remoteRunspacePool; } return null; } } /// <summary> /// Remote Session Implementation /// </summary> internal class ClientRemoteSessionImpl : ClientRemoteSession, IDisposable { [TraceSourceAttribute("CRSessionImpl", "ClientRemoteSessionImpl")] private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionImpl", "ClientRemoteSessionImpl"); private PSRemotingCryptoHelperClient _cryptoHelper = null; #region Constructors /// <summary> /// Creates a new instance of ClientRemoteSessionImpl /// </summary> /// <param name="rsPool"> /// The RunspacePool object this session should map to. /// </param> /// <param name="uriRedirectionHandler"> /// </param> internal ClientRemoteSessionImpl(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler) { Dbg.Assert(null != rsPool, "RunspacePool cannot be null"); base.RemoteRunspacePoolInternal = rsPool; Context.RemoteAddress = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(rsPool.ConnectionInfo, "ConnectionUri", null); _cryptoHelper = new PSRemotingCryptoHelperClient(); _cryptoHelper.Session = this; Context.ClientCapability = RemoteSessionCapability.CreateClientCapability(); Context.UserCredential = rsPool.ConnectionInfo.Credential; // shellName validation is not performed on the client side. // This is recommended by the WinRS team: for the reason that the rules may change in the future. Context.ShellName = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<string>(rsPool.ConnectionInfo, "ShellUri", string.Empty); MySelf = RemotingDestination.Client; //Create session data structure handler for this session SessionDataStructureHandler = new ClientRemoteSessionDSHandlerImpl(this, _cryptoHelper, rsPool.ConnectionInfo, uriRedirectionHandler); BaseSessionDataStructureHandler = SessionDataStructureHandler; _waitHandleForConfigurationReceived = new ManualResetEvent(false); //Register handlers for various ClientSessiondata structure handler events SessionDataStructureHandler.NegotiationReceived += HandleNegotiationReceived; SessionDataStructureHandler.ConnectionStateChanged += HandleConnectionStateChanged; SessionDataStructureHandler.EncryptedSessionKeyReceived += new EventHandler<RemoteDataEventArgs<string>>(HandleEncryptedSessionKeyReceived); SessionDataStructureHandler.PublicKeyRequestReceived += new EventHandler<RemoteDataEventArgs<string>>(HandlePublicKeyRequestReceived); } #endregion Constructors #region connect/close /// <summary> /// Creates a Remote Session Asynchronously. /// </summary> public override void CreateAsync() { //Raise a CreateSession event in StateMachine. This start the process of connection and negotiation to a new remote session RemoteSessionStateMachineEventArgs startArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CreateSession); SessionDataStructureHandler.StateMachine.RaiseEvent(startArg); } /// <summary> /// Connects to a existing Remote Session Asynchronously by executing a Connect negotiation algorithm /// </summary> public override void ConnectAsync() { //Raise the connectsession event in statemachine. This start the process of connection and negotiation to an existing remote session RemoteSessionStateMachineEventArgs startArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.ConnectSession); SessionDataStructureHandler.StateMachine.RaiseEvent(startArg); } /// <summary> /// Closes Session Connection Asynchronously. /// </summary> /// <remarks> /// Caller should register for ConnectionClosed event to get notified /// </remarks> public override void CloseAsync() { RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); SessionDataStructureHandler.StateMachine.RaiseEvent(closeArg); } /// <summary> /// Temporarily suspends connection to a connected remote session /// </summary> public override void DisconnectAsync() { RemoteSessionStateMachineEventArgs startDisconnectArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.DisconnectStart); SessionDataStructureHandler.StateMachine.RaiseEvent(startDisconnectArg); } /// <summary> /// Restores connection to a disconnected remote session. Negotiation has already been performed before /// </summary> public override void ReconnectAsync() { RemoteSessionStateMachineEventArgs startReconnectArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.ReconnectStart); SessionDataStructureHandler.StateMachine.RaiseEvent(startReconnectArg); } /// <summary> /// This event handler is raised when the state of session changes /// </summary> public override event EventHandler<RemoteSessionStateEventArgs> StateChanged; /// <summary> /// Handles changes in data structure handler state /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// Event argument which contains the new state /// </param> private void HandleConnectionStateChanged(object sender, RemoteSessionStateEventArgs arg) { using (s_trace.TraceEventHandlers()) { if (arg == null) { throw PSTraceSource.NewArgumentNullException("arg"); } if (arg.SessionStateInfo.State == RemoteSessionState.EstablishedAndKeyReceived) //TODO - Client session would never get into this state... to be removed { // send the public key StartKeyExchange(); } if (arg.SessionStateInfo.State == RemoteSessionState.ClosingConnection) { // when the connection is being closed we need to // complete the key exchange process to release // the lock under which the key exchange is happening // if we fail to release the lock, then when // transport manager is closing it will try to // acquire the lock again leading to a deadlock CompleteKeyExchange(); } StateChanged.SafeInvoke(this, arg); } } #endregion connect/closed #region KeyExchange /// <summary> /// Start the key exchange process /// </summary> internal override void StartKeyExchange() { if (SessionDataStructureHandler.StateMachine.State == RemoteSessionState.Established || SessionDataStructureHandler.StateMachine.State == RemoteSessionState.EstablishedAndKeyRequested) { // Start the key sending process string localPublicKey = null; bool ret = false; RemoteSessionStateMachineEventArgs eventArgs = null; Exception exception = null; try { ret = _cryptoHelper.ExportLocalPublicKey(out localPublicKey); } catch (PSCryptoException cryptoException) { ret = false; exception = cryptoException; } if (!ret) { // we need to complete the key exchange // since the crypto helper will be waiting on it CompleteKeyExchange(); // exporting local public key failed // set state to Closed eventArgs = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeySendFailed, exception); SessionDataStructureHandler.StateMachine.RaiseEvent(eventArgs); } // send using data structure handler eventArgs = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeySent); SessionDataStructureHandler.StateMachine.RaiseEvent(eventArgs); SessionDataStructureHandler.SendPublicKeyAsync(localPublicKey); } } /// <summary> /// Complete the key exchange process /// </summary> internal override void CompleteKeyExchange() { _cryptoHelper.CompleteKeyExchange(); } /// <summary> /// Handles an encrypted session key received from the other side /// </summary> /// <param name="sender">sender of this event</param> /// <param name="eventArgs">arguments that contain the remote /// public key</param> private void HandleEncryptedSessionKeyReceived(object sender, RemoteDataEventArgs<string> eventArgs) { if (SessionDataStructureHandler.StateMachine.State == RemoteSessionState.EstablishedAndKeySent) { string encryptedSessionKey = eventArgs.Data; bool ret = _cryptoHelper.ImportEncryptedSessionKey(encryptedSessionKey); RemoteSessionStateMachineEventArgs args = null; if (!ret) { // importing remote public key failed // set state to closed args = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed); SessionDataStructureHandler.StateMachine.RaiseEvent(args); } // complete the key exchange process CompleteKeyExchange(); args = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceived); SessionDataStructureHandler.StateMachine.RaiseEvent(args); } } /// <summary> /// Handles a request for public key from the server /// </summary> /// <param name="sender">send of this event, unused</param> /// <param name="eventArgs">arguments describing this event, unused</param> private void HandlePublicKeyRequestReceived(object sender, RemoteDataEventArgs<string> eventArgs) { if (SessionDataStructureHandler.StateMachine.State == RemoteSessionState.Established) { RemoteSessionStateMachineEventArgs args = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyRequested); SessionDataStructureHandler.StateMachine.RaiseEvent(args); StartKeyExchange(); } } #endregion KeyExchange //TODO:Review Configuration Story #region configuration private ManualResetEvent _waitHandleForConfigurationReceived; #endregion configuration #region negotiation /// <summary> /// Examines the negotiation packet received from the server /// </summary> /// <param name="sender"></param> /// <param name="arg"></param> private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEventArgs arg) { using (s_trace.TraceEventHandlers()) { if (arg == null) { throw PSTraceSource.NewArgumentNullException("arg"); } if (arg.RemoteSessionCapability == null) { throw PSTraceSource.NewArgumentException("arg"); } Context.ServerCapability = arg.RemoteSessionCapability; try { // This will throw if there is an error running the algorithm RunClientNegotiationAlgorithm(Context.ServerCapability); RemoteSessionStateMachineEventArgs negotiationCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationCompleted); SessionDataStructureHandler.StateMachine.RaiseEvent(negotiationCompletedArg); } catch (PSRemotingDataStructureException dse) { RemoteSessionStateMachineEventArgs negotiationFailedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationFailed, dse); SessionDataStructureHandler.StateMachine.RaiseEvent(negotiationFailedArg); } } } /// <summary> /// Verifies the negotiation packet received from the server /// </summary> /// <param name="serverRemoteSessionCapability"> /// Capabilities of remote session /// </param> /// <returns> /// The method returns true if the capability negotiation is successful. /// Otherwise, it returns false. /// </returns> /// <exception cref="PSRemotingDataStructureException"> /// 1. PowerShell client does not support the PSVersion {1} negotiated by the server. /// Make sure the server is compatible with the build {2} of PowerShell. /// 2. PowerShell client does not support the SerializationVersion {1} negotiated by the server. /// Make sure the server is compatible with the build {2} of PowerShell. /// </exception> private bool RunClientNegotiationAlgorithm(RemoteSessionCapability serverRemoteSessionCapability) { Dbg.Assert(serverRemoteSessionCapability != null, "server capability cache must be non-null"); // ProtocolVersion check Version serverProtocolVersion = serverRemoteSessionCapability.ProtocolVersion; _serverProtocolVersion = serverProtocolVersion; Version clientProtocolVersion = Context.ClientCapability.ProtocolVersion; if ( clientProtocolVersion.Equals(serverProtocolVersion) || (clientProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM && serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RC) || (clientProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM && (serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RC || serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM )) || (clientProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM && (serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RC || serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM || serverProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM )) ) { //passed negotiation check } else { PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientNegotiationFailed, RemoteDataNameStrings.PS_STARTUP_PROTOCOL_VERSION_NAME, serverProtocolVersion, PSVersionInfo.BuildVersion, RemotingConstants.ProtocolVersion); throw reasonOfFailure; } // PSVersion check Version serverPSVersion = serverRemoteSessionCapability.PSVersion; Version clientPSVersion = Context.ClientCapability.PSVersion; if (!clientPSVersion.Equals(serverPSVersion)) { PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientNegotiationFailed, RemoteDataNameStrings.PSVersion, serverPSVersion.ToString(), PSVersionInfo.BuildVersion, RemotingConstants.ProtocolVersion); throw reasonOfFailure; } // Serialization Version check Version serverSerVersion = serverRemoteSessionCapability.SerializationVersion; Version clientSerVersion = Context.ClientCapability.SerializationVersion; if (!clientSerVersion.Equals(serverSerVersion)) { PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientNegotiationFailed, RemoteDataNameStrings.SerializationVersion, serverSerVersion.ToString(), PSVersionInfo.BuildVersion, RemotingConstants.ProtocolVersion); throw reasonOfFailure; } return true; } #endregion negotiation internal override RemotingDestination MySelf { get; } #region IDisposable /// <summary> /// Public method for dispose /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Release all resources /// </summary> /// <param name="disposing">if true, release all managed resources</param> public void Dispose(bool disposing) { if (disposing) { if (_waitHandleForConfigurationReceived != null) { _waitHandleForConfigurationReceived.Dispose(); _waitHandleForConfigurationReceived = null; } ((ClientRemoteSessionDSHandlerImpl)SessionDataStructureHandler).Dispose(); SessionDataStructureHandler = null; _cryptoHelper.Dispose(); _cryptoHelper = null; } } #endregion IDisposable } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using NServiceKit.Text; using NServiceKit.Text.Common; namespace NServiceKit.Common.Tests.Perf { /// <summary>to string performance.</summary> [Ignore("Bencharks for serializing basic .NET types")] [TestFixture] public class ToStringPerf : PerfTestBase { /// <summary>Initializes a new instance of the NServiceKit.Common.Tests.Perf.ToStringPerf class.</summary> public ToStringPerf() { this.MultipleIterations = new List<int> { 10000 }; } /// <summary>Compare string.</summary> [Test] public void Compare_string() { CompareMultipleRuns( "'test'.ToCsvField()", () => "test".ToCsvField(), "SCU.ToString('test')", () => TypeSerializer.SerializeToString("test") ); } /// <summary>Compare escaped string.</summary> [Test] public void Compare_escaped_string() { CompareMultipleRuns( "'t,e:st'.ToCsvField()", () => "t,e:st".ToCsvField(), "SCU.ToString('t,e:st')", () => TypeSerializer.SerializeToString("t,e:st") ); } /// <summary>Compare ints.</summary> [Test] public void Compare_ints() { CompareMultipleRuns( "1.ToString()", () => 1.ToString(), "SCU.ToString(1)", () => TypeSerializer.SerializeToString(1) ); } /// <summary>Compare longs.</summary> [Test] public void Compare_longs() { CompareMultipleRuns( "1L.ToString()", () => 1L.ToString(), "SCU.ToString(1L)", () => TypeSerializer.SerializeToString(1L) ); } /// <summary>Compare guids.</summary> [Test] public void Compare_Guids() { var guid = new Guid("AC800C9C-B8BE-4829-868A-B43CFF7B2AFD"); CompareMultipleRuns( "guid.ToString()", () => guid.ToString(), "SCU.ToString(guid)", () => TypeSerializer.SerializeToString(guid) ); } /// <summary>Compare date time.</summary> [Test] public void Compare_DateTime() { var now = DateTime.Now; CompareMultipleRuns( "now.ToString()", () => now.ToString(), "SCU.ToString(now)", () => TypeSerializer.SerializeToString(now) ); } /// <summary>Compare int list.</summary> [Test] public void Compare_IntList() { var intList = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; CompareMultipleRuns( "intList.ForEach(x => sb.Append(x.ToString()))", () => { var sb = new StringBuilder(); intList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); }); sb.ToString(); }, "SCU.ToString(intList)", () => TypeSerializer.SerializeToString(intList) ); } /// <summary>Compare long list.</summary> [Test] public void Compare_LongList() { var longList = new List<long> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; CompareMultipleRuns( "longList.ForEach(x => sb.Append(x.ToString()))", () => { var sb = new StringBuilder(); longList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); }); sb.ToString(); }, "SCU.ToString(longList)", () => TypeSerializer.SerializeToString(longList) ); } /// <summary>Compare string array.</summary> [Test] public void Compare_StringArray() { var stringArray = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; CompareMultipleRuns( "sb.Append(s.ToCsvField());", () => { var sb = new StringBuilder(); foreach (var s in stringArray) { if (sb.Length > 0) sb.Append(","); sb.Append(s.ToCsvField()); } sb.ToString(); }, "SCU.ToString(stringArray)", () => TypeSerializer.SerializeToString(stringArray) ); } /// <summary>Compare string list.</summary> [Test] public void Compare_StringList() { var stringList = new List<string> { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; CompareMultipleRuns( "sb.Append(s.ToCsvField());", () => { var sb = new StringBuilder(); stringList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); }); sb.ToString(); }, "SCU.ToString(stringList)", () => TypeSerializer.SerializeToString(stringList) ); } /// <summary>Compare double list.</summary> [Test] public void Compare_DoubleList() { var doubleList = new List<double> { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 0.1 }; CompareMultipleRuns( "doubleList.ForEach(x => sb.Append(x.ToString()))", () => { var sb = new StringBuilder(); doubleList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); }); sb.ToString(); }, "SCU.ToString(doubleList)", () => TypeSerializer.SerializeToString(doubleList) ); } /// <summary>Compare unique identifier list.</summary> [Test] public void Compare_GuidList() { var guidList = new List<Guid> { new Guid("8F403A5E-CDFC-4C6F-B0EB-C055C1C8BA60"), new Guid("5673BAC7-BAC5-4B3F-9B69-4180E6227508"), new Guid("B0CA730F-14C9-4D00-AC7F-07E7DE8D566E"), new Guid("4E26AF94-6B13-4F89-B192-36C6ABE73DAE"), new Guid("08491B16-2270-4DF9-8AEE-A8861A791C50"), }; CompareMultipleRuns( "guidList.ForEach(x => sb.Append(x.ToString()))", () => { var sb = new StringBuilder(); guidList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); }); sb.ToString(); }, "SCU.ToString(guidList)", () => TypeSerializer.SerializeToString(guidList) ); } /// <summary>Compare string hash set.</summary> [Test] public void Compare_StringHashSet() { var stringHashSet = new HashSet<string> { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; CompareMultipleRuns( "sb.Append(s.ToCsvField());", () => { var sb = new StringBuilder(); foreach (var s in stringHashSet) { if (sb.Length > 0) sb.Append(","); sb.Append(s.ToCsvField()); } sb.ToString(); }, "SCU.ToString(stringHashSet)", () => TypeSerializer.SerializeToString(stringHashSet) ); } /// <summary>Compare int hash set.</summary> [Test] public void Compare_IntHashSet() { var intHashSet = new HashSet<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; CompareMultipleRuns( "intList.ForEach(x => sb.Append(x.ToString()))", () => { var sb = new StringBuilder(); foreach (var s in intHashSet) { if (sb.Length > 0) sb.Append(","); sb.Append(s.ToString()); } sb.ToString(); }, "SCU.ToString(intHashSet)", () => TypeSerializer.SerializeToString(intHashSet) ); } /// <summary>Compare double hash set.</summary> [Test] public void Compare_DoubleHashSet() { var doubleHashSet = new HashSet<double> { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 0.1 }; CompareMultipleRuns( "doubleList.ForEach(x => sb.Append(x.ToString()))", () => { var sb = new StringBuilder(); foreach (var s in doubleHashSet) { if (sb.Length > 0) sb.Append(","); sb.Append(s.ToString()); } sb.ToString(); }, "SCU.ToString(doubleHashSet)", () => TypeSerializer.SerializeToString(doubleHashSet) ); } /// <summary>Compare string map.</summary> [Test] public void Compare_StringStringMap() { var map = new Dictionary<string, string> { {"A", "1"},{"B", "2"},{"C", "3"},{"D", "4"},{"E", "5"}, {"F", "6"},{"G", "7"},{"H", "8"},{"I", "9"},{"j", "10"}, }; CompareMultipleRuns( "sb.Append(kv.Key.ToCsvField()).Append(ParseStringMethods.KeyValueSeperator).", () => { var sb = new StringBuilder(); foreach (var kv in map) { if (sb.Length > 0) sb.Append(","); sb.Append(kv.Key.ToCsvField()) .Append(JsWriter.MapKeySeperator) .Append(kv.Value.ToCsvField()); } sb.ToString(); }, "SCU.ToString(map)", () => TypeSerializer.SerializeToString(map) ); } /// <summary>Compare string int map.</summary> [Test] public void Compare_StringIntMap() { var map = new Dictionary<string, int> { {"A", 1},{"B", 2},{"C", 3},{"D", 4},{"E", 5}, {"F", 6},{"G", 7},{"H", 8},{"I", 9},{"j", 10}, }; CompareMultipleRuns( ".Append(ParseStringMethods.KeyValueSeperator).Append(kv.Value.ToString())", () => { var sb = new StringBuilder(); foreach (var kv in map) { if (sb.Length > 0) sb.Append(","); sb.Append(kv.Key.ToCsvField()) .Append(JsWriter.MapKeySeperator) .Append(kv.Value.ToString()); } sb.ToString(); }, "SCU.ToString(map)", () => TypeSerializer.SerializeToString(map) ); } /// <summary>Compare string int sorted dictionary.</summary> [Test] public void Compare_StringInt_SortedDictionary() { var map = new SortedDictionary<string, int>{ {"A", 1},{"B", 2},{"C", 3},{"D", 4},{"E", 5}, {"F", 6},{"G", 7},{"H", 8},{"I", 9},{"j", 10}, }; CompareMultipleRuns( ".Append(ParseStringMethods.KeyValueSeperator).Append(kv.Value.ToString())", () => { var sb = new StringBuilder(); foreach (var kv in map) { if (sb.Length > 0) sb.Append(","); sb.Append(kv.Key.ToCsvField()) .Append(JsWriter.MapKeySeperator) .Append(kv.Value.ToString()); } sb.ToString(); }, "SCU.ToString(map)", () => TypeSerializer.SerializeToString(map) ); } /// <summary>Compare byte array.</summary> [Test] public void Compare_ByteArray() { var byteArrayValue = new byte[] { 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, }; CompareMultipleRuns( "Encoding.Default.GetString(byteArrayValue)", () => Encoding.Default.GetString(byteArrayValue), "SCU.ToString(byteArrayValue)", () => TypeSerializer.SerializeToString(byteArrayValue) ); } } }
// ZipHelperStream.cs // // Copyright 2006, 2007 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. #if ZIPLIB using System; using System.IO; using System.Text; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// Holds data pertinent to a data descriptor. /// </summary> internal class DescriptorData { /// <summary> /// Get /set the compressed size of data. /// </summary> public long CompressedSize { get { return compressedSize; } set { compressedSize = value; } } /// <summary> /// Get / set the uncompressed size of data /// </summary> public long Size { get { return size; } set { size = value; } } /// <summary> /// Get /set the crc value. /// </summary> public long Crc { get { return crc; } set { crc = (value & 0xffffffff); } } #region Instance Fields long size; long compressedSize; long crc; #endregion } class EntryPatchData { public long SizePatchOffset { get { return sizePatchOffset_; } set { sizePatchOffset_ = value; } } public long CrcPatchOffset { get { return crcPatchOffset_; } set { crcPatchOffset_ = value; } } #region Instance Fields long sizePatchOffset_; long crcPatchOffset_; #endregion } /// <summary> /// This class assists with writing/reading from Zip files. /// </summary> internal class ZipHelperStream : Stream { #region Constructors /// <summary> /// Initialise an instance of this class. /// </summary> /// <param name="name">The name of the file to open.</param> public ZipHelperStream(string name) { stream_ = new FileStream(name, FileMode.Open, FileAccess.ReadWrite); isOwner_ = true; } /// <summary> /// Initialise a new instance of <see cref="ZipHelperStream"/>. /// </summary> /// <param name="stream">The stream to use.</param> public ZipHelperStream(Stream stream) { stream_ = stream; } #endregion /// <summary> /// Get / set a value indicating wether the the underlying stream is owned or not. /// </summary> /// <remarks>If the stream is owned it is closed when this instance is closed.</remarks> public bool IsStreamOwner { get { return isOwner_; } set { isOwner_ = value; } } #region Base Stream Methods public override bool CanRead { get { return stream_.CanRead; } } public override bool CanSeek { get { return stream_.CanSeek; } } #if !NET_1_0 && !NET_1_1 && !NETCF_1_0 public override bool CanTimeout { get { return stream_.CanTimeout; } } #endif public override long Length { get { return stream_.Length; } } public override long Position { get { return stream_.Position; } set { stream_.Position = value; } } public override bool CanWrite { get { return stream_.CanWrite; } } public override void Flush() { stream_.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return stream_.Seek(offset, origin); } public override void SetLength(long value) { stream_.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return stream_.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { stream_.Write(buffer, offset, count); } /// <summary> /// Close the stream. /// </summary> /// <remarks> /// The underlying stream is closed only if <see cref="IsStreamOwner"/> is true. /// </remarks> override public void Close() { Stream toClose = stream_; stream_ = null; if (isOwner_ && (toClose != null)) { isOwner_ = false; toClose.Close(); } } #endregion // Write the local file header // TODO: ZipHelperStream.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage void WriteLocalHeader(ZipEntry entry, EntryPatchData patchData) { CompressionMethod method = entry.CompressionMethod; bool headerInfoAvailable = true; // How to get this? bool patchEntryHeader = false; WriteLEInt(ZipConstants.LocalHeaderSignature); WriteLEShort(entry.Version); WriteLEShort(entry.Flags); WriteLEShort((byte)method); WriteLEInt((int)entry.DosTime); if (headerInfoAvailable == true) { WriteLEInt((int)entry.Crc); if ( entry.LocalHeaderRequiresZip64 ) { WriteLEInt(-1); WriteLEInt(-1); } else { WriteLEInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); WriteLEInt((int)entry.Size); } } else { if (patchData != null) { patchData.CrcPatchOffset = stream_.Position; } WriteLEInt(0); // Crc if ( patchData != null ) { patchData.SizePatchOffset = stream_.Position; } // For local header both sizes appear in Zip64 Extended Information if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { WriteLEInt(-1); WriteLEInt(-1); } else { WriteLEInt(0); // Compressed size WriteLEInt(0); // Uncompressed size } } byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); if (name.Length > 0xFFFF) { throw new ZipException("Entry name too long."); } ZipExtraData ed = new ZipExtraData(entry.ExtraData); if (entry.LocalHeaderRequiresZip64 && (headerInfoAvailable || patchEntryHeader)) { ed.StartNewEntry(); if (headerInfoAvailable) { ed.AddLeLong(entry.Size); ed.AddLeLong(entry.CompressedSize); } else { ed.AddLeLong(-1); ed.AddLeLong(-1); } ed.AddNewEntry(1); if ( !ed.Find(1) ) { throw new ZipException("Internal error cant find extra data"); } if ( patchData != null ) { patchData.SizePatchOffset = ed.CurrentReadIndex; } } else { ed.Delete(1); } byte[] extra = ed.GetEntryData(); WriteLEShort(name.Length); WriteLEShort(extra.Length); if ( name.Length > 0 ) { stream_.Write(name, 0, name.Length); } if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { patchData.SizePatchOffset += stream_.Position; } if ( extra.Length > 0 ) { stream_.Write(extra, 0, extra.Length); } } /// <summary> /// Locates a block with the desired <paramref name="signature"/>. /// </summary> /// <param name="signature">The signature to find.</param> /// <param name="endLocation">Location, marking the end of block.</param> /// <param name="minimumBlockSize">Minimum size of the block.</param> /// <param name="maximumVariableData">The maximum variable data.</param> /// <returns>Eeturns the offset of the first byte after the signature; -1 if not found</returns> public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) { long pos = endLocation - minimumBlockSize; if ( pos < 0 ) { return -1; } long giveUpMarker = Math.Max(pos - maximumVariableData, 0); // TODO: This loop could be optimised for speed. do { if ( pos < giveUpMarker ) { return -1; } Seek(pos--, SeekOrigin.Begin); } while ( ReadLEInt() != signature ); return Position; } /// <summary> /// Write Zip64 end of central directory records (File header and locator). /// </summary> /// <param name="noOfEntries">The number of entries in the central directory.</param> /// <param name="sizeEntries">The size of entries in the central directory.</param> /// <param name="centralDirOffset">The offset of the dentral directory.</param> public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset) { long centralSignatureOffset = stream_.Position; WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature); WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12) WriteLEShort(ZipConstants.VersionMadeBy); // Version made by WriteLEShort(ZipConstants.VersionZip64); // Version to extract WriteLEInt(0); // Number of this disk WriteLEInt(0); // number of the disk with the start of the central directory WriteLELong(noOfEntries); // No of entries on this disk WriteLELong(noOfEntries); // Total No of entries in central directory WriteLELong(sizeEntries); // Size of the central directory WriteLELong(centralDirOffset); // offset of start of central directory // zip64 extensible data sector not catered for here (variable size) // Write the Zip64 end of central directory locator WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature); // no of the disk with the start of the zip64 end of central directory WriteLEInt(0); // relative offset of the zip64 end of central directory record WriteLELong(centralSignatureOffset); // total number of disks WriteLEInt(1); } /// <summary> /// Write the required records to end the central directory. /// </summary> /// <param name="noOfEntries">The number of entries in the directory.</param> /// <param name="sizeEntries">The size of the entries in the directory.</param> /// <param name="startOfCentralDirectory">The start of the central directory.</param> /// <param name="comment">The archive comment. (This can be null).</param> public void WriteEndOfCentralDirectory(long noOfEntries, long sizeEntries, long startOfCentralDirectory, byte[] comment) { if ( (noOfEntries >= 0xffff) || (startOfCentralDirectory >= 0xffffffff) || (sizeEntries >= 0xffffffff) ) { WriteZip64EndOfCentralDirectory(noOfEntries, sizeEntries, startOfCentralDirectory); } WriteLEInt(ZipConstants.EndOfCentralDirectorySignature); // TODO: ZipFile Multi disk handling not done WriteLEShort(0); // number of this disk WriteLEShort(0); // no of disk with start of central dir // Number of entries if ( noOfEntries >= 0xffff ) { WriteLEUshort(0xffff); // Zip64 marker WriteLEUshort(0xffff); } else { WriteLEShort(( short )noOfEntries); // entries in central dir for this disk WriteLEShort(( short )noOfEntries); // total entries in central directory } // Size of the central directory if ( sizeEntries >= 0xffffffff ) { WriteLEUint(0xffffffff); // Zip64 marker } else { WriteLEInt(( int )sizeEntries); } // offset of start of central directory if ( startOfCentralDirectory >= 0xffffffff ) { WriteLEUint(0xffffffff); // Zip64 marker } else { WriteLEInt(( int )startOfCentralDirectory); } int commentLength = (comment != null) ? comment.Length : 0; if ( commentLength > 0xffff ) { throw new ZipException(string.Format("Comment length({0}) is too long can only be 64K", commentLength)); } WriteLEShort(commentLength); if ( commentLength > 0 ) { Write(comment, 0, comment.Length); } } #region LE value reading/writing /// <summary> /// Read an unsigned short in little endian byte order. /// </summary> /// <returns>Returns the value read.</returns> /// <exception cref="IOException"> /// An i/o error occurs. /// </exception> /// <exception cref="EndOfStreamException"> /// The file ends prematurely /// </exception> public int ReadLEShort() { int byteValue1 = stream_.ReadByte(); if (byteValue1 < 0) { throw new EndOfStreamException(); } int byteValue2 = stream_.ReadByte(); if (byteValue2 < 0) { throw new EndOfStreamException(); } return byteValue1 | (byteValue2 << 8); } /// <summary> /// Read an int in little endian byte order. /// </summary> /// <returns>Returns the value read.</returns> /// <exception cref="IOException"> /// An i/o error occurs. /// </exception> /// <exception cref="System.IO.EndOfStreamException"> /// The file ends prematurely /// </exception> public int ReadLEInt() { return ReadLEShort() | (ReadLEShort() << 16); } /// <summary> /// Read a long in little endian byte order. /// </summary> /// <returns>The value read.</returns> public long ReadLELong() { return (uint)ReadLEInt() | ((long)ReadLEInt() << 32); } /// <summary> /// Write an unsigned short in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEShort(int value) { stream_.WriteByte(( byte )(value & 0xff)); stream_.WriteByte(( byte )((value >> 8) & 0xff)); } /// <summary> /// Write a ushort in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUshort(ushort value) { stream_.WriteByte(( byte )(value & 0xff)); stream_.WriteByte(( byte )(value >> 8)); } /// <summary> /// Write an int in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEInt(int value) { WriteLEShort(value); WriteLEShort(value >> 16); } /// <summary> /// Write a uint in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUint(uint value) { WriteLEUshort(( ushort )(value & 0xffff)); WriteLEUshort(( ushort )(value >> 16)); } /// <summary> /// Write a long in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLELong(long value) { WriteLEInt(( int )value); WriteLEInt(( int )(value >> 32)); } /// <summary> /// Write a ulong in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUlong(ulong value) { WriteLEUint(( uint )(value & 0xffffffff)); WriteLEUint(( uint )(value >> 32)); } #endregion /// <summary> /// Write a data descriptor. /// </summary> /// <param name="entry">The entry to write a descriptor for.</param> /// <returns>Returns the number of descriptor bytes written.</returns> public int WriteDataDescriptor(ZipEntry entry) { if (entry == null) { throw new ArgumentNullException("entry"); } int result=0; // Add data descriptor if flagged as required if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) { // The signature is not PKZIP originally but is now described as optional // in the PKZIP Appnote documenting trhe format. WriteLEInt(ZipConstants.DataDescriptorSignature); WriteLEInt(unchecked((int)(entry.Crc))); result+=8; if (entry.LocalHeaderRequiresZip64) { WriteLELong(entry.CompressedSize); WriteLELong(entry.Size); result+=16; } else { WriteLEInt((int)entry.CompressedSize); WriteLEInt((int)entry.Size); result+=8; } } return result; } /// <summary> /// Read data descriptor at the end of compressed data. /// </summary> /// <param name="zip64">if set to <c>true</c> [zip64].</param> /// <param name="data">The data to fill in.</param> /// <returns>Returns the number of bytes read in the descriptor.</returns> public void ReadDataDescriptor(bool zip64, DescriptorData data) { int intValue = ReadLEInt(); // In theory this may not be a descriptor according to PKZIP appnote. // In practise its always there. if (intValue != ZipConstants.DataDescriptorSignature) { throw new ZipException("Data descriptor signature not found"); } data.Crc = ReadLEInt(); if (zip64) { data.CompressedSize = ReadLELong(); data.Size = ReadLELong(); } else { data.CompressedSize = ReadLEInt(); data.Size = ReadLEInt(); } } #region Instance Fields bool isOwner_; Stream stream_; #endregion } } #endif
/* Copyright (c) 2014, Lars Brubaker 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.PolygonMesh.Processors; using MatterHackers.RenderOpenGl; using MatterHackers.VectorMath; using System; using System.Diagnostics; using System.IO; namespace MatterHackers.MeshVisualizer { public class MeshViewerApplication : SystemWindow { protected MeshViewerWidget meshViewerWidget; private Button openFileButton; private CheckBox bedCheckBox; private CheckBox wireframeCheckBox; private GuiWidget viewArea; public MeshViewerWidget MeshViewerWidget { get { return meshViewerWidget; } } public MeshViewerApplication(string meshFileToLoad = "") : base(800, 600) { BackgroundColor = RGBA_Bytes.White; MinimumSize = new VectorMath.Vector2(200, 200); Title = "MatterHackers MeshViewr"; UseOpenGL = true; FlowLayoutWidget mainContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); mainContainer.AnchorAll(); viewArea = new GuiWidget(); viewArea.AnchorAll(); Vector3 viewerVolume = new Vector3(200, 200, 200); meshViewerWidget = new MeshViewerWidget(viewerVolume, new Vector2(100, 100), MeshViewerWidget.BedShape.Rectangular, "No Part Loaded"); meshViewerWidget.AnchorAll(); viewArea.AddChild(meshViewerWidget); mainContainer.AddChild(viewArea); FlowLayoutWidget buttonPanel = new FlowLayoutWidget(FlowDirection.LeftToRight); buttonPanel.HAnchor = HAnchor.ParentLeftRight; buttonPanel.Padding = new BorderDouble(3, 3); buttonPanel.BackgroundColor = RGBA_Bytes.DarkGray; if (meshFileToLoad != "") { meshViewerWidget.LoadMesh(meshFileToLoad, MeshViewerWidget.CenterPartAfterLoad.DO); } else { openFileButton = new Button("Open 3D File", 0, 0); openFileButton.Click += new EventHandler(openFileButton_ButtonClick); buttonPanel.AddChild(openFileButton); } bedCheckBox = new CheckBox("Bed"); bedCheckBox.Checked = true; buttonPanel.AddChild(bedCheckBox); wireframeCheckBox = new CheckBox("Wireframe"); buttonPanel.AddChild(wireframeCheckBox); GuiWidget leftRightSpacer = new GuiWidget(); leftRightSpacer.HAnchor = HAnchor.ParentLeftRight; buttonPanel.AddChild(leftRightSpacer); mainContainer.AddChild(buttonPanel); this.AddChild(mainContainer); this.AnchorAll(); AddHandlers(); } private void AddHandlers() { bedCheckBox.CheckedStateChanged += bedCheckBox_CheckedStateChanged; wireframeCheckBox.CheckedStateChanged += wireframeCheckBox_CheckedStateChanged; } private void wireframeCheckBox_CheckedStateChanged(object sender, EventArgs e) { if (wireframeCheckBox.Checked) { meshViewerWidget.RenderType = RenderTypes.Polygons; } else { meshViewerWidget.RenderType = RenderTypes.Shaded; } } private void bedCheckBox_CheckedStateChanged(object sender, EventArgs e) { meshViewerWidget.RenderBed = bedCheckBox.Checked; } private void openFileButton_ButtonClick(object sender, EventArgs mouseEvent) { UiThread.RunOnIdle(DoOpenFileButton_ButtonClick); } private void DoOpenFileButton_ButtonClick() { FileDialog.OpenFileDialog( new OpenFileDialogParams("3D Mesh Files|*.stl;*.amf"), (openParams) => { meshViewerWidget.LoadMesh(openParams.FileName, MeshViewerWidget.CenterPartAfterLoad.DO); }); Invalidate(); } public override void OnDragEnter(FileDropEventArgs fileDropEventArgs) { foreach (string file in fileDropEventArgs.DroppedFiles) { string extension = Path.GetExtension(file).ToUpper(); if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension))) { fileDropEventArgs.AcceptDrop = true; } } base.OnDragEnter(fileDropEventArgs); } public override void OnDragOver(FileDropEventArgs fileDropEventArgs) { foreach (string file in fileDropEventArgs.DroppedFiles) { string extension = Path.GetExtension(file).ToUpper(); if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension))) { fileDropEventArgs.AcceptDrop = true; } } base.OnDragOver(fileDropEventArgs); } public override void OnDragDrop(FileDropEventArgs fileDropEventArgs) { foreach (string droppedFileName in fileDropEventArgs.DroppedFiles) { string extension = Path.GetExtension(droppedFileName).ToUpper(); if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension))) { meshViewerWidget.LoadMesh(droppedFileName, MeshViewerWidget.CenterPartAfterLoad.DO); break; } } base.OnDragDrop(fileDropEventArgs); } private Stopwatch totalDrawTime = new Stopwatch(); private int drawCount = 0; public override void OnDraw(Graphics2D graphics2D) { totalDrawTime.Restart(); base.OnDraw(graphics2D); totalDrawTime.Stop(); if (true) { long memory = GC.GetTotalMemory(false); this.Title = string.Format("Allocated = {0:n0} : {1}ms, d{2} Size = {3}x{4}", memory, totalDrawTime.ElapsedMilliseconds, drawCount++, this.Width, this.Height); //GC.Collect(); } } [STAThread] public static void Main(string[] args) { MeshViewerApplication app = new MeshViewerApplication(); app.ShowAsSystemWindow(); } } }
using System; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using TreeGecko.Library.Geospatial.Geoframeworks.Interfaces; namespace TreeGecko.Library.Geospatial.Geoframeworks.Objects { /// <summary> /// Represents a position on Earth marked by latitude, longitude, and altitude. /// </summary> /// <remarks> /// <para>Instances of this class are guaranteed to be thread-safe because the class is /// immutable (its properties can only be changed via constructors).</para> /// </remarks> public struct Position3D : IFormattable, IEquatable<Position3D>, ICloneable<Position3D>, IXmlSerializable { private Position _Position; private Distance _Altitude; #region Constructors public Position3D(Distance altitude, Position location) { _Position = location; _Altitude = altitude; } public Position3D(Distance altitude, Longitude longitude, Latitude latitude) { _Position = new Position(longitude, latitude); _Altitude = altitude; } /// <overloads>Creates a new instance.</overloads> public Position3D(Distance altitude, Latitude latitude, Longitude longitude) { _Position = new Position(latitude, longitude); _Altitude = altitude; } public Position3D(Longitude longitude, Latitude latitude, Distance altitude) { _Position = new Position(latitude, longitude); _Altitude = altitude; } public Position3D(Latitude latitude, Longitude longitude, Distance altitude) { _Position = new Position(latitude, longitude); _Altitude = altitude; } /// <summary> /// Creates a new instance by parsing latitude and longitude from a single string. /// </summary> /// <param name="value">A <strong>String</strong> containing both a latitude and longitude to parse.</param> public Position3D(string altitude, string location) : this(altitude, location, CultureInfo.CurrentCulture) { } /// <summary> /// Creates a new instance by interpreting the specified latitude and longitude. /// </summary> /// <param name="latitude">A <strong>String</strong> describing a latitude in the current culture.</param> /// <param name="longitude">A <strong>String</strong> describing a longitude in the current culture.</param> /// <remarks>Latitude and longitude values are parsed using the current local culture. For better support /// of international cultures, add a CultureInfo parameter.</remarks> public Position3D(string altitude, string latitude, string longitude) : this(altitude, latitude, longitude, CultureInfo.CurrentCulture) { } /// <summary> /// Creates a new instance by interpreting the specified latitude and longitude. /// </summary> /// <param name="latitude">A <strong>String</strong> describing a latitude in the current culture.</param> /// <param name="longitude">A <strong>String</strong> describing a longitude in the current culture.</param> /// <remarks>Latitude and longitude values are parsed using the current local culture. For better support /// of international cultures, a CultureInfo parameter should be specified to indicate how numbers should /// be parsed.</remarks> public Position3D(string altitude, string latitude, string longitude, CultureInfo culture) { _Position = new Position(latitude, longitude, culture); _Altitude = new Distance(altitude, culture); } /// <summary> /// Creates a new instance by converting the specified string using the specific culture. /// </summary> /// <param name="value"></param> /// <param name="culture"></param> public Position3D(string altitude, string location, CultureInfo culture) { _Position = new Position(location, culture); _Altitude = new Distance(altitude, culture); } /// <summary> /// Upgrades a Position object to a Position3D object. /// </summary> /// <param name="position"></param> public Position3D(Position position) { _Position = position; _Altitude = Distance.Empty; } public Position3D(XmlReader reader) { // Initialize all fields _Position = Position.Invalid; _Altitude = Distance.Invalid; // Deserialize the object from XML ReadXml(reader); } #endregion #region Public Properties /// <summary>Returns the location's distance above sea level.</summary> public Distance Altitude { get { return _Altitude; } } public Latitude Latitude { get { return _Position.Latitude; } } public Longitude Longitude { get { return _Position.Longitude; } } #endregion #region Public Methods public CartesianPoint ToCartesianPoint() { return ToCartesianPoint(Ellipsoid.Default); } public CartesianPoint ToCartesianPoint(Ellipsoid ellipsoid) { return _Position.ToCartesianPoint(ellipsoid, _Altitude); } #endregion #region Operators public static bool operator ==(Position3D left, Position3D right) { return left.Equals(right); } public static bool operator !=(Position3D left, Position3D right) { return !left.Equals(right); } public static Position3D operator +(Position3D left, Position3D right) { return left.Add(right); } public static Position3D operator -(Position3D left, Position3D right) { return left.Subtract(right); } public static Position3D operator *(Position3D left, Position3D right) { return left.Multiply(right); } public static Position3D operator /(Position3D left, Position3D right) { return left.Divide(right); } public Position3D Add(Position3D position) { return new Position3D(this.Latitude.Add(position.Latitude.DecimalDegrees), this.Longitude.Add(position.Longitude.DecimalDegrees), this._Altitude.Add(position.Altitude)); } public Position3D Subtract(Position3D position) { return new Position3D(this.Latitude.Subtract(position.Latitude.DecimalDegrees), this.Longitude.Subtract(position.Longitude.DecimalDegrees), this._Altitude.Subtract(position.Altitude)); } public Position3D Multiply(Position3D position) { return new Position3D(this.Latitude.Multiply(position.Latitude.DecimalDegrees), this.Longitude.Multiply(position.Longitude.DecimalDegrees), this._Altitude.Multiply(position.Altitude)); } public Position3D Divide(Position3D position) { return new Position3D(this.Latitude.Divide(position.Latitude.DecimalDegrees), this.Longitude.Divide(position.Longitude.DecimalDegrees), this._Altitude.Divide(position.Altitude)); } #endregion /// <summary> /// Returns whether the latitude, longitude and altitude are zero. /// </summary> public bool IsEmpty { get { return _Altitude.IsEmpty && _Position.IsEmpty; } } #region Overrides public override int GetHashCode() { return _Position.GetHashCode() ^ _Altitude.GetHashCode(); } public override bool Equals(object obj) { if (obj is Position3D) return Equals((Position3D) obj); return false; } #endregion #region Conversions public static explicit operator Position3D(CartesianPoint value) { return value.ToPosition3D(); } public static explicit operator string(Position3D value) { return value.ToString(); } #endregion #region IXmlSerializable XmlSchema IXmlSerializable.GetSchema() { return null; } public void WriteXml(XmlWriter writer) { /* The position class uses the GML 3.0 specification for XML. * * <gml:pos>X Y</gml:pos> * */ writer.WriteStartElement(Xml.GmlXmlPrefix, "pos", Xml.GmlXmlNamespace); writer.WriteString(Longitude.DecimalDegrees.ToString("G17", CultureInfo.InvariantCulture)); writer.WriteString(" "); writer.WriteString(Latitude.DecimalDegrees.ToString("G17", CultureInfo.InvariantCulture)); writer.WriteString(" "); writer.WriteString(Altitude.ToMeters().Value.ToString("G17", CultureInfo.InvariantCulture)); writer.WriteEndElement(); } public void ReadXml(XmlReader reader) { /* The position class uses the GML 3.0 specification for XML. * * <gml:pos>X Y</gml:pos> * * ... but it is also helpful to be able to READ older versions * of GML, such as this one for GML 2.0: * * <gml:coord> * <gml:X>double</gml:X> * <gml:Y>double</gml:Y> // optional * <gml:Z>double</gml:Z> // optional * </gml:coord> * */ // .NET Complains if we don't assign values _Position = Position.Empty; _Altitude = Distance.Empty; Longitude longitude = Longitude.Empty; Latitude latitude = Latitude.Empty; // Move to the <gml:pos> or <gml:coord> element if (!reader.IsStartElement("pos", Xml.GmlXmlNamespace) && !reader.IsStartElement("coord", Xml.GmlXmlNamespace)) reader.ReadStartElement(); switch (reader.LocalName.ToLower(CultureInfo.InvariantCulture)) { case "pos": // Read the "X Y" string, then split by the space between them string[] Values = reader.ReadElementContentAsString().Split(' '); // Deserialize the longitude longitude = new Longitude(Values[0], CultureInfo.InvariantCulture); // Deserialize the latitude if (Values.Length >= 2) latitude = new Latitude(Values[1], CultureInfo.InvariantCulture); // Deserialize the altitude if (Values.Length == 3) _Altitude = Distance.FromMeters(double.Parse(Values[2], CultureInfo.InvariantCulture)); // Make the position _Position = new Position(latitude, longitude); break; case "coord": // Read the <gml:coord> start tag reader.ReadStartElement(); // Now read up to 3 elements: X, and optionally Y or Z for (int index = 0; index < 3; index++) { switch (reader.LocalName.ToLower(CultureInfo.InvariantCulture)) { case "x": longitude = new Longitude(reader.ReadElementContentAsDouble()); break; case "y": latitude = new Latitude(reader.ReadElementContentAsDouble()); break; case "z": // Read Z as meters (there's no unit type in the spec :P morons) _Altitude = Distance.FromMeters(reader.ReadElementContentAsDouble()); break; } // If we're at an end element, stop if (reader.NodeType == XmlNodeType.EndElement) break; } // Make the position _Position = new Position(latitude, longitude); // Read the </gml:coord> end tag reader.ReadEndElement(); break; } } #endregion #region IEquatable<Position3D> /// <summary> /// Compares the current instance to the specified position. /// </summary> /// <param name="value">A <strong>Position</strong> object to compare with.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> /// <remarks>The two objects are compared at up to four digits of precision.</remarks> public bool Equals(Position3D other) { return Latitude.Equals(other.Latitude) && Longitude.Equals(other.Longitude) && _Altitude.Equals(other.Altitude); } /// <summary> /// Compares the current instance to the specified position using the specified numeric precision. /// </summary> /// <param name="value">A <strong>Position</strong> object to compare with.</param> /// <param name="decimals">An <strong>Integer</strong> specifying the number of fractional digits to compare.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> /// <remarks>This method is typically used when positions do not mark the same location unless they are /// extremely close to one another. Conversely, a low or even negative value for <strong>Precision</strong> /// allows positions to be considered equal even when they do not precisely match.</remarks> public bool Equals(Position3D other, int decimals) { return Latitude.Equals(other.Latitude, decimals) && Longitude.Equals(other.Longitude, decimals) && _Altitude.Equals(other.Altitude, decimals); } #endregion #region IFormattable Members /// <summary> /// Outputs the current instance as a string using the specified format and culture information. /// </summary> /// <returns></returns> public string ToString(string format, IFormatProvider formatProvider) { CultureInfo culture = (CultureInfo) formatProvider; if (culture == null) culture = CultureInfo.CurrentCulture; if (format == null || format.Length == 0) format = "G"; // Output as latitude and longitude return _Position.ToString(format, culture) + culture.TextInfo.ListSeparator + _Altitude.ToString(format, culture); } /// <summary> /// Returns a coordinate which has been shifted the specified bearing and distance. /// </summary> /// <param name="bearing"></param> /// <param name="distance"></param> /// <param name="ellipsoid"></param> /// <returns></returns> public Position3D TranslateTo(Azimuth bearing, Distance distance, Ellipsoid ellipsoid) { return new Position3D(_Altitude, _Position.TranslateTo(bearing, distance, ellipsoid)); } #endregion #region ICloneable<Position3D> Members public Position3D Clone() { return new Position3D(_Position); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Xml; using System.IO; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Threading; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes.Scripting; namespace OpenSim.Region.Framework.Scenes { public class SceneObjectPartInventory : IEntityInventory { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_inventoryFileName = String.Empty; private int m_inventoryFileNameSerial = 0; /// <value> /// The part to which the inventory belongs. /// </value> private SceneObjectPart m_part; /// <summary> /// Serial count for inventory file , used to tell if inventory has changed /// no need for this to be part of Database backup /// </summary> protected uint m_inventorySerial = 0; /// <summary> /// Holds in memory prim inventory /// </summary> protected TaskInventoryDictionary m_items = new TaskInventoryDictionary(); /// <summary> /// Tracks whether inventory has changed since the last persistent backup /// </summary> internal bool HasInventoryChanged; /// <value> /// Inventory serial number /// </value> protected internal uint Serial { get { return m_inventorySerial; } set { m_inventorySerial = value; } } /// <value> /// Raw inventory data /// </value> protected internal TaskInventoryDictionary Items { get { return m_items; } set { m_items = value; m_inventorySerial++; } } /// <summary> /// Constructor /// </summary> /// <param name="part"> /// A <see cref="SceneObjectPart"/> /// </param> public SceneObjectPartInventory(SceneObjectPart part) { m_part = part; } /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> public void ForceInventoryPersistence() { HasInventoryChanged = true; } /// <summary> /// Reset UUIDs for all the items in the prim's inventory. This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// </summary> /// <param name="linkNum">Link number for the part</param> public void ResetInventoryIDs() { lock (Items) { if (0 == Items.Count) return; HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); Items.Clear(); foreach (TaskInventoryItem item in items) { item.ResetIDs(m_part.UUID); Items.Add(item.ItemID, item); } } } /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> public void ChangeInventoryOwner(UUID ownerId) { lock (Items) { if (0 == Items.Count) { return; } HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); foreach (TaskInventoryItem item in items) { if (ownerId != item.OwnerID) { item.LastOwnerID = item.OwnerID; item.OwnerID = ownerId; } } } } /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> public void ChangeInventoryGroup(UUID groupID) { lock (Items) { if (0 == Items.Count) { return; } HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); foreach (TaskInventoryItem item in items) { if (groupID != item.GroupID) { item.GroupID = groupID; } } } } /// <summary> /// Start all the scripts contained in this prim's inventory /// </summary> public void CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource) { lock (m_items) { foreach (TaskInventoryItem item in Items.Values) { if ((int)InventoryType.LSL == item.InvType) { CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); Thread.Sleep(10); // workaround for Mono cpu utilization > 100% bug } } } } public ArrayList GetScriptErrors(UUID itemID) { ArrayList ret = new ArrayList(); IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) // No engine at all return ret; foreach (IScriptModule e in engines) { if (e != null) { ArrayList errors = e.GetScriptErrors(itemID); foreach (Object line in errors) ret.Add(line); } } return ret; } /// <summary> /// Stop all the scripts in this prim. /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { lock (Items) { foreach (TaskInventoryItem item in Items.Values) { if ((int)InventoryType.LSL == item.InvType) { RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); } } } } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <returns></returns> public void CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource) { // m_log.InfoFormat( // "[PRIM INVENTORY]: " + // "Starting script {0}, {1} in prim {2}, {3}", // item.Name, item.ItemID, m_part.Name, m_part.UUID); if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return; m_part.AddFlag(PrimFlags.Scripted); if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) { if (stateSource == 1 && // Prim crossing m_part.ParentGroup.Scene.m_trustBinaries) { lock (m_items) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); return; } m_part.ParentGroup.Scene.AssetService.Get( item.AssetID.ToString(), this, delegate(string id, object sender, AssetBase asset) { if (null == asset) { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", item.Name, item.ItemID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID); } else { lock (m_items) { if (m_part.ParentGroup.m_savedScriptState != null) RestoreSavedScriptState(item.OldItemID, item.ItemID); m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; string script = Utils.BytesToString(asset.Data); m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); } } } ); } } private void RestoreSavedScriptState(UUID oldID, UUID newID) { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) // No engine at all return; if (m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(m_part.ParentGroup.m_savedScriptState[oldID]); ////////// CRUFT WARNING /////////////////////////////////// // // Old objects will have <ScriptState><State> ... // This format is XEngine ONLY // // New objects have <State Engine="...." ...><ScriptState>... // This can be passed to any engine // XmlNode n = doc.SelectSingleNode("ScriptState"); if (n != null) // Old format data { XmlDocument newDoc = new XmlDocument(); XmlElement rootN = newDoc.CreateElement("", "State", ""); XmlAttribute uuidA = newDoc.CreateAttribute("", "UUID", ""); uuidA.Value = oldID.ToString(); rootN.Attributes.Append(uuidA); XmlAttribute engineA = newDoc.CreateAttribute("", "Engine", ""); engineA.Value = "XEngine"; rootN.Attributes.Append(engineA); newDoc.AppendChild(rootN); XmlNode stateN = newDoc.ImportNode(n, true); rootN.AppendChild(stateN); // This created document has only the minimun data // necessary for XEngine to parse it successfully m_part.ParentGroup.m_savedScriptState[oldID] = newDoc.OuterXml; } foreach (IScriptModule e in engines) { if (e != null) { if (e.SetXMLState(newID, m_part.ParentGroup.m_savedScriptState[oldID])) break; } } m_part.ParentGroup.m_savedScriptState.Remove(oldID); } } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="itemId"> /// A <see cref="UUID"/> /// </param> public void CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) { lock (m_items) { if (m_items.ContainsKey(itemId)) { CreateScriptInstance(m_items[itemId], startParam, postOnRez, engine, stateSource); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } } /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if this script is being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) { bool scriptPresent = false; lock (m_items) { if (m_items.ContainsKey(itemId)) scriptPresent = true; } if (scriptPresent) { if (!sceneObjectBeingDeleted) m_part.RemoveScriptEvents(itemId); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId); m_part.ParentGroup.AddActiveScriptCount(-1); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } /// <summary> /// Check if the inventory holds an item with a given name. /// This method assumes that the task inventory is already locked. /// </summary> /// <param name="name"></param> /// <returns></returns> private bool InventoryContainsName(string name) { foreach (TaskInventoryItem item in Items.Values) { if (item.Name == name) return true; } return false; } /// <summary> /// For a given item name, return that name if it is available. Otherwise, return the next available /// similar name (which is currently the original name with the next available numeric suffix). /// </summary> /// <param name="name"></param> /// <returns></returns> private string FindAvailableInventoryName(string name) { if (!InventoryContainsName(name)) return name; int suffix=1; while (suffix < 256) { string tryName=String.Format("{0} {1}", name, suffix); if (!InventoryContainsName(tryName)) return tryName; suffix++; } return String.Empty; } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop) { AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced. /// </summary> /// <param name="item"></param> public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) { List<TaskInventoryItem> il; lock (m_items) { il = new List<TaskInventoryItem>(m_items.Values); } foreach (TaskInventoryItem i in il) { if (i.Name == item.Name) { if (i.InvType == (int)InventoryType.LSL) RemoveScriptInstance(i.ItemID, false); RemoveInventoryItem(i.ItemID); break; } } AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. /// </summary> /// <param name="name">The name that the new item should have.</param> /// <param name="item"> /// The item itself. The name within this structure is ignored in favour of the name /// given in this method's arguments /// </param> /// <param name="allowedDrop"> /// Item was only added to inventory because AllowedDrop is set /// </param> protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop) { name = FindAvailableInventoryName(name); if (name == String.Empty) return; item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Name = name; item.GroupID = m_part.GroupID; lock (m_items) { m_items.Add(item.ItemID, item); if (allowedDrop) m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); else m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } m_inventorySerial++; //m_inventorySerial += 2; HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } /// <summary> /// Restore a whole collection of items to the prim's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) { lock (m_items) { foreach (TaskInventoryItem item in items) { m_items.Add(item.ItemID, item); m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } } m_inventorySerial++; } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(UUID itemId) { TaskInventoryItem item; lock (m_items) m_items.TryGetValue(itemId, out item); return item; } /// <summary> /// Get inventory items by name. /// </summary> /// <param name="name"></param> /// <returns> /// A list of inventory items with that name. /// If no inventory item has that name then an empty list is returned. /// </returns> public IList<TaskInventoryItem> GetInventoryItems(string name) { IList<TaskInventoryItem> items = new List<TaskInventoryItem>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) items.Add(item); } } return items; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { lock (m_items) { if (m_items.ContainsKey(item.ItemID)) { item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Flags = m_items[item.ItemID].Flags; // If group permissions have been set on, check that the groupID is up to date in case it has // changed since permissions were last set. if (item.GroupPermissions != (uint)PermissionMask.None) item.GroupID = m_part.GroupID; if (item.AssetID == UUID.Zero) { item.AssetID = m_items[item.ItemID].AssetID; } else if ((InventoryType)item.Type == InventoryType.Notecard) { ScenePresence presence = m_part.ParentGroup.Scene.GetScenePresence(item.OwnerID); if (presence != null) { presence.ControllingClient.SendAgentAlertMessage( "Notecard saved", false); } } m_items[item.ItemID] = item; m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", item.ItemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } return false; } /// <summary> /// Remove an item from this prim's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> public int RemoveInventoryItem(UUID itemID) { lock (m_items) { if (m_items.ContainsKey(itemID)) { int type = m_items[itemID].InvType; if (type == 10) // Script { m_part.RemoveScriptEvents(itemID); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); } m_items.Remove(itemID); m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; int scriptcount = 0; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Type == 10) { scriptcount++; } } } if (scriptcount <= 0) { m_part.RemFlag(PrimFlags.Scripted); } m_part.ScheduleFullUpdate(); return type; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", itemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } return -1; } public string GetInventoryFileName() { if (m_inventoryFileName == String.Empty) m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; if (m_inventoryFileNameSerial < m_inventorySerial) { m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; } return m_inventoryFileName; } /// <summary> /// Return the name with which a client can request a xfer of this prim's inventory metadata /// </summary> /// <param name="client"></param> /// <param name="localID"></param> public bool GetInventoryFileName(IClientAPI client, uint localID) { // m_log.DebugFormat( // "[PRIM INVENTORY]: Received request from client {0} for inventory file name of {1}, {2}", // client.AgentId, Name, UUID); if (m_inventorySerial > 0) { client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial, Utils.StringToBytes(GetInventoryFileName())); return true; } else { client.SendTaskInventory(m_part.UUID, 0, new byte[0]); return false; } } /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="xferManager"></param> public void RequestInventoryFile(IClientAPI client, IXfer xferManager) { byte[] fileData = new byte[0]; // Confusingly, the folder item has to be the object id, while the 'parent id' has to be zero. This matches // what appears to happen in the Second Life protocol. If this isn't the case. then various functionality // isn't available (such as drag from prim inventory to agent inventory) InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero); bool includeAssets = false; if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId)) includeAssets = true; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { UUID ownerID = item.OwnerID; uint everyoneMask = 0; uint baseMask = item.BasePermissions; uint ownerMask = item.CurrentPermissions; uint groupMask = item.GroupPermissions; invString.AddItemStart(); invString.AddNameValueLine("item_id", item.ItemID.ToString()); invString.AddNameValueLine("parent_id", m_part.UUID.ToString()); invString.AddPermissionsStart(); invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask)); invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask)); invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask)); invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask)); invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions)); invString.AddNameValueLine("creator_id", item.CreatorID.ToString()); invString.AddNameValueLine("owner_id", ownerID.ToString()); invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString()); invString.AddNameValueLine("group_id", item.GroupID.ToString()); invString.AddSectionEnd(); if (includeAssets) invString.AddNameValueLine("asset_id", item.AssetID.ToString()); else invString.AddNameValueLine("asset_id", UUID.Zero.ToString()); invString.AddNameValueLine("type", TaskInventoryItem.Types[item.Type]); invString.AddNameValueLine("inv_type", TaskInventoryItem.InvTypes[item.InvType]); invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags)); invString.AddSaleStart(); invString.AddNameValueLine("sale_type", "not"); invString.AddNameValueLine("sale_price", "0"); invString.AddSectionEnd(); invString.AddNameValueLine("name", item.Name + "|"); invString.AddNameValueLine("desc", item.Description + "|"); invString.AddNameValueLine("creation_date", item.CreationDate.ToString()); invString.AddSectionEnd(); } } fileData = Utils.StringToBytes(invString.BuildString); //m_log.Debug(Utils.BytesToString(fileData)); //m_log.Debug("[PRIM INVENTORY]: RequestInventoryFile fileData: " + Utils.BytesToString(fileData)); if (fileData.Length > 2) { xferManager.AddNewFile(m_inventoryFileName, fileData); } } /// <summary> /// Process inventory backup /// </summary> /// <param name="datastore"></param> public void ProcessInventoryBackup(IRegionDataStore datastore) { if (HasInventoryChanged) { lock (Items) { datastore.StorePrimInventory(m_part.UUID, Items.Values); } HasInventoryChanged = false; } } public class InventoryStringBuilder { public string BuildString = String.Empty; public InventoryStringBuilder(UUID folderID, UUID parentID) { BuildString += "\tinv_object\t0\n\t{\n"; AddNameValueLine("obj_id", folderID.ToString()); AddNameValueLine("parent_id", parentID.ToString()); AddNameValueLine("type", "category"); AddNameValueLine("name", "Contents|"); AddSectionEnd(); } public void AddItemStart() { BuildString += "\tinv_item\t0\n"; AddSectionStart(); } public void AddPermissionsStart() { BuildString += "\tpermissions 0\n"; AddSectionStart(); } public void AddSaleStart() { BuildString += "\tsale_info\t0\n"; AddSectionStart(); } protected void AddSectionStart() { BuildString += "\t{\n"; } public void AddSectionEnd() { BuildString += "\t}\n"; } public void AddLine(string addLine) { BuildString += addLine; } public void AddNameValueLine(string name, string value) { BuildString += "\t\t"; BuildString += name + "\t"; BuildString += value + "\n"; } public void Close() { } } public uint MaskEffectivePermissions() { uint mask=0x7fffffff; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType != (int)InventoryType.Object) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } else { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~(uint)PermissionMask.Modify; } } return mask; } public void ApplyNextOwnerPermissions() { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Modify; item.CurrentPermissions |= 8; } item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; } } m_part.TriggerScriptChangedEvent(Changed.OWNER); } public void ApplyGodPermissions(uint perms) { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { item.CurrentPermissions = perms; item.BasePermissions = perms; } } } public bool ContainsScripts() { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { return true; } } } return false; } public List<UUID> GetInventoryList() { List<UUID> ret = new List<UUID>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) ret.Add(item.ItemID); } return ret; } public Dictionary<UUID, string> GetScriptStates() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); if (engines == null) // No engine at all return ret; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { foreach (IScriptModule e in engines) { if (e != null) { string n = e.GetXMLState(item.ItemID); if (n != String.Empty) { if (!ret.ContainsKey(item.ItemID)) ret[item.ItemID] = n; break; } } } } } } return ret; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Ojibwe.Public.Api.Actions; using Ojibwe.Public.Sdk.Interfaces; using Ojibwe.Public.Sdk.Models; using Ojibwe.Public.Sdk.Models.Interfaces; using Ojibwe.Public.Sdk.Utilities; namespace Ojibwe.Public.Api.Controllers { using Microsoft.AspNet.Mvc; using App; using WebSocketAccept = Action<IDictionary<string, object>, Func<IDictionary<string, object>, Task>>; // callback using Microsoft.AspNet.Http; public class BlobsController : ControllerBase { // GET api/values public BlobsController(HttpContext httpContext, IDataProvider provider) : base(httpContext, provider) { } [HttpGet(Name = "BlobsGet")] public IEnumerable<IBlob> Get(IUser user, string query = null, int? limit = 0, int? offset = 0) { LogVerbose("BlobsGet entering."); LogDebug(string.Format("query = '{0}', limit = '{1}', offset = '{2}'", query ?? "NULL", limit, offset)); if (!IsAdministrator(user)) throw new UnauthorizedAccessException(); IEnumerable<IBlob> blobs = null; blobs = !string.IsNullOrWhiteSpace(query) ? Provider.BlobRetrieveByList((new SearchQuery<IBlob>(query)).SearchFunction, limit.GetValueOrDefault(), offset.GetValueOrDefault()) : Provider.BlobRetrieveList(limit.GetValueOrDefault(), offset.GetValueOrDefault()); LogVerbose("BlobsGet leaving."); return blobs; } // GET api/values/5 [HttpGet("{id}", Name = "BlobGet")] public IBlob Get(IUser user, Guid id) { LogVerbose("BlobGet entering."); LogDebug(String.Format("id = '{0}'", id)); if (!IsAdministrator(user) && !IsBlobOwned(user, id) && !IsBlobShared(user, id)) throw new UnauthorizedAccessException(); LogVerbose("BlobGet leaving."); return Provider.BlobRetrieve(id); } [HttpGet("~/api/blobs/info", Name = "BlobsGetByInfo")] public IEnumerable<IBlob> GetBlobsByInfo(IUser user, string key, string value = null, int? limit = 0, int? offset = 0) { LogVerbose("BlobsGetByInfo entering."); LogDebug(String.Format("key = '{0}', value = '{1}', limit = '{2}', offset = '{3}'", key, value ?? "NULL", limit, offset)); var currentUserId = user.Id; var result = Provider.BlobRetrieveByList(b => { if (b.OwnerUserId == currentUserId || b.TrustedUserIds.Contains(currentUserId)) { var match = true; if (!string.IsNullOrWhiteSpace(key)) match &= b.Info.ContainsKey(key); if (!string.IsNullOrWhiteSpace(value)) match &= b.Info.ContainsValue(value); return match; } return false; }, limit.GetValueOrDefault(), offset.GetValueOrDefault()); LogVerbose("BlobsGetByInfo leaving."); return result; } [HttpGet("~/api/containers/{containerId}/blobs/info", Name = "BlobsGetByContainerAndInfo")] public IEnumerable<IBlob> GetBlobsInContainerByInfo(IUser user, Guid containerId, string key, string value = null, int? limit = 0, int? offset = 0) { LogVerbose("BlobsGetByContainerAndInfo entering."); LogDebug(String.Format("containerId = '{0}', key = '{1}', value = '{2}', limit = '{3}', offset = '{4}'", containerId, key, value ?? "NULL", limit, offset)); if (!IsAdministrator(user) && !IsContainerOwned(user, containerId)) throw new UnauthorizedAccessException(); var currentUserId = user.Id; var container = Provider.ContainerRetrieve(containerId); var result = Provider.BlobRetrieveByList(b => { if (container.BlobIds != null && container.BlobIds.Contains(b.Id)) { if (b.OwnerUserId == currentUserId || b.TrustedUserIds.Contains(currentUserId)) { var match = true; if (!string.IsNullOrWhiteSpace(key)) match &= b.Info.ContainsKey(key); if (!string.IsNullOrWhiteSpace(value)) match &= b.Info.ContainsValue(value); return match; } } return false; }); LogVerbose("BlobsGetByContainerAndInfo leaving."); return result; } [HttpPut("{id}", Name = "BlobPut")] public bool Put(IUser user, Guid id, [FromBody] Blob value) { LogVerbose("BlobPut entering."); LogDebug(String.Format("id = '{0}'", id)); if (!IsAdministrator(user) && !IsBlobOwned(user, id)) throw new UnauthorizedAccessException(); if (!value.Id.Equals(id)) throw new ApplicationException("Model's id does not match"); var originalBlob = Provider.BlobRetrieve(id); if (originalBlob == null) throw new FileNotFoundException(string.Format("Could not find blob with Id: {0}", id)); value.StorageKey = originalBlob.StorageKey; LogVerbose("BlobPut leaving."); return Provider.BlobUpdate(value); } [HttpGet("~/api/blobs/{id}/upload", Name = "BlobUploadData")] public ActionResult UploadData(IUser user, Guid id) { LogVerbose("BlobUploadData entering/leaving."); LogDebug(String.Format("id = '{0}'", id)); throw new NotImplementedException(); if (!IsAdministrator(user) && !IsBlobOwned(user, id)) throw new UnauthorizedAccessException(); if (HttpContext.WebSockets.IsWebSocketRequest) return new AcceptWebSocketRequestActionResult((stream) => { BlobStreamStore(id, stream); }); else return new BadRequestResult(); //if (HttpContext.WebSockets.IsWebSocketRequest) //{ // var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); // BlockingStream stream = new BlockingStream(16); // var receive = Task.Factory.StartNew((async () => // { // byte[] buffer = new byte[1024*64]; // while (true) // { // // MUST read if we want the state to get updated... // var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); // stream.Write(buffer, 0, result.Count); // if (result.MessageType == WebSocketMessageType.Close) // { // await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None); // stream.CompleteWriting(); // break; // } // } // })); // Task.WaitAll(receive); // return new HttpStatusCodeResult((int) HttpStatusCode.SwitchingProtocols); //} //return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest); //if (Request.Properties.ContainsKey("MS_HttpContext")) //{ // var httpContext = Request.Properties["MS_HttpContext"] as HttpContextBase; // if (httpContext != null) // { // httpContext.AcceptWebSocketRequest(new WebSocketUploadHandler((stream) => // { // BlobStreamStore(id, stream); // }).ProcessAspWebSocketSession); // return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); // } //} //else if (Request.Properties.ContainsKey("MS_OwinContext")) //For OjibweSdkTest, self hosted has no access to HttpContext //{ // var owinContext = Request.Properties["MS_OwinContext"] as OwinContext; // if (owinContext != null) // { // WebSocketAccept accept = owinContext.Get<WebSocketAccept>("websocket.Accept"); // await(new WebSocketUploadHandler((stream) => // { // BlobStreamStore(id, stream); // }).ProcessOwinWebSocketSession(accept)); // return Request.CreateResponse(HttpStatusCode.OK); // } //} //return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "Could not determine context"); } [HttpGet("~/api/blobs/{id}/download", Name = "BlobDownloadData")] public HttpResponseMessage DownloadData(IUser user, Guid id) { LogVerbose("BlobUploadData entering/leaving."); LogDebug(String.Format("id = '{0}'", id)); throw new NotImplementedException(); //if (!IsAdministrator(user) && !IsBlobOwned(user, id) && !IsBlobShared(user, id)) // throw new UnauthorizedAccessException(); //if (Request.Properties.ContainsKey("MS_HttpContext")) //{ // var httpContext = Request.Properties["MS_HttpContext"] as HttpContextBase; // if (httpContext != null) // { // httpContext.AcceptWebSocketRequest(new WebSocketDownloadHandler((stream) => // { // BlobStreamRetreive(id, stream); // }).ProcessAspWebSocketSession); // return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); // } //} //else if (Request.Properties.ContainsKey("MS_OwinContext")) //For OjibweSdkTest, self hosted has no access to HttpContext //{ // var owinContext = Request.Properties["MS_OwinContext"] as OwinContext; // if (owinContext != null) // { // WebSocketAccept accept = owinContext.Get<WebSocketAccept>("websocket.Accept"); // await(new WebSocketDownloadHandler((stream) => // { // BlobStreamRetreive(id, stream); // })).ProcessOwinWebSocketSession(accept); // return Request.CreateResponse(HttpStatusCode.OK); // } //} //return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "Could not determine context"); } [HttpGet("~/api/blobs/{id}/data", Name = "BlobDataGet")] public MultiBlobPartStreamActionResult GetData(IUser user, Guid id) { LogVerbose("BlobDataGet entering."); LogDebug(String.Format("id = '{0}'", id)); if (!IsAdministrator(user) && !IsBlobOwned(user, id) && !IsBlobShared(user, id)) throw new UnauthorizedAccessException(); var blob = Provider.BlobRetrieve(id); List<BlobPart> parts; using (var partStream = StorageAdapter.Read(blob.StorageKey)) { parts = JsonSerializer.Deserialize<List<BlobPart>>(new JsonTextReader(new StreamReader(partStream))); } if (parts == null) throw new ApplicationException("Could not deserialize existing parts"); LogVerbose("BlobDataGet leaving."); return new MultiBlobPartStreamActionResult(parts, part => StorageAdapter.Read(part.ExternalStorageKey)); } [HttpPut("~/api/blobs/{id}/data", Name = "BlobDataPut")] public bool PutData(IUser user, Guid id, HttpRequestMessage request) { LogVerbose("BlobDataPut entering."); LogDebug(String.Format("id = '{0}'", id)); if (!IsAdministrator(user) && !IsBlobOwned(user, id)) throw new UnauthorizedAccessException(); var blob = Provider.BlobRetrieve(id); if (blob.StorageKey != null) { LogDebug(string.Format("Existing StorageKey: {0}", blob.StorageKey)); List<BlobPart> existingParts; using (var partStream = StorageAdapter.Read(blob.StorageKey)) { existingParts = JsonSerializer.Deserialize<List<BlobPart>>(new JsonTextReader(new StreamReader(partStream))); } if (existingParts == null) throw new ApplicationException("Could not deserialize existing parts"); bool success = existingParts.Aggregate(true, (current, part) => current & StorageAdapter.Delete(part.ExternalStorageKey)); if (!success) throw new ApplicationException("Could not clean up existing parts"); } using (var streamPartsStream = StreamUtility.GetTempFileStream()) using (var streamWriter = new StreamWriter(streamPartsStream)) { LogDebug("Starting stream splitter"); List<BlobPart> streamParts; try { streamParts = StreamUtility.SplitStream(HttpContext.Request.Body, Config.StorageBlobChunkSize, (streamChunk, checkSum, partId) => { LogVerbose(string.Format("Storing StreamChunk for BlobPartId: {0}", partId)); BlobPart part = new BlobPart(); part.Part = partId; part.CheckSum = checkSum; part.ExternalStorageKey = StorageAdapter.Create(streamChunk); LogDebug(string.Format("BlobPart: {0}", part.ToString())); return part; }, LogDebug); } catch (Exception ex) { LogError("Could not split stream.", ex); throw; } JsonSerializer.Serialize(streamWriter, streamParts); streamWriter.Flush(); streamPartsStream.Position = 0; blob.StorageKey = StorageAdapter.Create(streamPartsStream); LogVerbose("PutData leaving."); return Provider.BlobUpdate(blob); } } [HttpGet("~/api/containers/{containerId}/blobs", Name = "BlobsGetByContainer")] public IEnumerable<IBlob> GetBlobsByContainer(IUser user, Guid containerId, int? limit = 0, int? offset = 0) { LogVerbose("BlobsGetByContainer entering."); LogDebug(String.Format("containerId = '{0}', limit = '{1}', offset = '{2}'", containerId, limit, offset)); if (!IsAdministrator(user) && !IsContainerOwned(user, containerId)) throw new UnauthorizedAccessException(); var container = Provider.ContainerRetrieve(containerId); var result = container.BlobIds.Select(blobId => Provider.BlobRetrieve(blobId)); if (offset.HasValue) result = result.Skip(offset.GetValueOrDefault()); if (limit.HasValue) result = result.Take(limit.GetValueOrDefault()); LogVerbose("BlobsGetByContainer leaving."); return result; } [HttpPost(Name = "BlobPost")] public IBlob Post(IUser user, [FromBody]Blob value) { LogVerbose("BlobPost entering."); if (value.OwnerUserId.Equals(Guid.Empty)) value.OwnerUserId = user.Id; if (!IsAdministrator(user) && !IsBlobOwned(user, value.Id)) throw new UnauthorizedAccessException(); LogVerbose("BlobPost leaving."); return Provider.BlobCreate(value); } [HttpPost("~/api/containers/{containerId}/blobs", Name = "BlobPostByContainer")] public IBlob PostByContainer(IUser user, Guid containerId, [FromBody]Blob value) { LogVerbose("BlobPostByContainer entering."); LogDebug(String.Format("containerId = '{0}'", containerId)); if (!IsAdministrator(user) && !IsContainerOwned(user, containerId)) throw new UnauthorizedAccessException(); if (value.OwnerUserId.Equals(Guid.Empty)) value.OwnerUserId = user.Id; var blob = Provider.BlobCreate(value); LinkBlobByContainer(user, containerId, blob.Id); LogVerbose("BlobPostByContainer leaving."); return blob; } [HttpPost("~/api/containers/{containerId}/blobs/{itemId}", Name = "BlobLinkByContainer")] public bool LinkBlobByContainer(IUser user, Guid containerId, Guid itemId) { LogVerbose("BlobLinkByContainer entering."); LogDebug(String.Format("containerId = '{0}', itemId = '{1}'", containerId, itemId)); if (!IsAdministrator(user) && !IsContainerOwned(user, containerId) && !IsBlobShared(user, itemId)) throw new UnauthorizedAccessException(); var container = Provider.ContainerRetrieve(containerId); if(container.BlobIds == null) container.BlobIds = new List<Guid>(); container.BlobIds.Add(itemId); LogVerbose("BlobLinkByContainer leaving."); return Provider.ContainerUpdate(container); } [HttpDelete("~/api/containers/{containerId}/blobs/{itemId}", Name = "BlobUnlinkByContainer")] public bool UnlinkBlobByContainer(IUser user, Guid containerId, Guid itemId) { LogVerbose("BlobUnlinkByContainer entering."); LogDebug(String.Format("containerId = '{0}', itemId = '{1}'", containerId, itemId)); if (!IsAdministrator(user) && !IsContainerOwned(user, containerId) && !IsBlobShared(user, itemId)) throw new UnauthorizedAccessException(); var container = Provider.ContainerRetrieve(containerId); if (container.BlobIds == null) return true; container.BlobIds.Remove(itemId); LogVerbose("BlobUnlinkByContainer leaving."); return Provider.ContainerUpdate(container); } // DELETE api/values/5 [HttpDelete("{id}", Name = "BlobDelete")] public bool Delete(IUser user, Guid id) { LogVerbose("BlobDelete entering."); LogDebug(String.Format("id = '{0}'", id)); if (!IsAdministrator(user) && !IsBlobOwned(user, id)) throw new UnauthorizedAccessException(); var blob = Provider.BlobRetrieve(id); LogVerbose("BlobDelete leaving."); return StorageAdapter.Delete(blob.StorageKey) && Provider.BlobDelete(blob); } protected void BlobStreamStore(Guid id, Stream stream) { var blob = Provider.BlobRetrieve(id); if (blob.StorageKey != null) { List<BlobPart> existingParts; using (var partStream = StorageAdapter.Read(blob.StorageKey)) { existingParts = JsonSerializer.Deserialize<List<BlobPart>>( new JsonTextReader(new StreamReader(partStream))); } if (existingParts == null) throw new ApplicationException("Could not deserialize existing parts"); bool success = existingParts.Aggregate(true, (current, part) => current & StorageAdapter.Delete(part.ExternalStorageKey)); if (!success) throw new ApplicationException("Could not clean up existing parts"); } using (var streamPartsStream = StreamUtility.GetTempFileStream()) using (var streamWriter = new StreamWriter(streamPartsStream)) { var streamParts = StreamUtility.SplitStream(stream, Config.StorageBlobChunkSize, (streamChunk, checkSum, partId) => { BlobPart part = new BlobPart(); part.Part = partId; part.CheckSum = checkSum; part.ExternalStorageKey = StorageAdapter.Create(streamChunk); return part; }); JsonSerializer.Serialize(streamWriter, streamParts); streamWriter.Flush(); streamPartsStream.Position = 0; blob.StorageKey = StorageAdapter.Create(streamPartsStream); Provider.BlobUpdate(blob); } } protected void BlobStreamRetreive(Guid id, Stream stream) { var blob = Provider.BlobRetrieve(id); List<BlobPart> parts; using (var partStream = StorageAdapter.Read(blob.StorageKey)) { parts = JsonSerializer.Deserialize<List<BlobPart>>(new JsonTextReader(new StreamReader(partStream))); if (parts == null) throw new ApplicationException("Could not deserialize existing parts"); StreamUtility.JoinStreamParts(parts, stream, part => StorageAdapter.Read(part.ExternalStorageKey)); } } } }
// <copyright file="CreateMatrix.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2015 Math.NET // // 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. // </copyright> using System; using System.Collections.Generic; using MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra.Storage; namespace MathNet.Numerics.LinearAlgebra { public static class CreateMatrix { /// <summary> /// Create a new matrix straight from an initialized matrix storage instance. /// If you have an instance of a discrete storage type instead, use their direct methods instead. /// </summary> public static Matrix<T> WithStorage<T>(MatrixStorage<T> storage) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.OfStorage(storage); } /// <summary> /// Create a new matrix with the same kind of the provided example. /// </summary> public static Matrix<T> SameAs<T,TU>(Matrix<TU> example, int rows, int columns, bool fullyMutable = false) where T : struct, IEquatable<T>, IFormattable where TU : struct, IEquatable<TU>, IFormattable { return Matrix<T>.Build.SameAs(example, rows, columns, fullyMutable); } /// <summary> /// Create a new matrix with the same kind and dimensions of the provided example. /// </summary> public static Matrix<T> SameAs<T,TU>(Matrix<TU> example) where T : struct, IEquatable<T>, IFormattable where TU : struct, IEquatable<TU>, IFormattable { return Matrix<T>.Build.SameAs(example); } /// <summary> /// Create a new matrix with the same kind of the provided example. /// </summary> public static Matrix<T> SameAs<T>(Vector<T> example, int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SameAs(example, rows, columns); } /// <summary> /// Create a new matrix with a type that can represent and is closest to both provided samples. /// </summary> public static Matrix<T> SameAs<T>(Matrix<T> example, Matrix<T> otherExample, int rows, int columns, bool fullyMutable = false) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SameAs(example, otherExample, rows, columns, fullyMutable); } /// <summary> /// Create a new matrix with a type that can represent and is closest to both provided samples and the dimensions of example. /// </summary> public static Matrix<T> SameAs<T>(Matrix<T> example, Matrix<T> otherExample) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SameAs(example, otherExample); } /// <summary> /// Create a new dense matrix with values sampled from the provided random distribution. /// </summary> public static Matrix<T> Random<T>(int rows, int columns, IContinuousDistribution distribution) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Random(rows, columns, distribution); } /// <summary> /// Create a new dense matrix with values sampled from the standard distribution with a system random source. /// </summary> public static Matrix<T> Random<T>(int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Random(rows, columns); } /// <summary> /// Create a new dense matrix with values sampled from the standard distribution with a system random source. /// </summary> public static Matrix<T> Random<T>(int rows, int columns, int seed) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Random(rows, columns, seed); } /// <summary> /// Create a new positive definite dense matrix where each value is the product /// of two samples from the provided random distribution. /// </summary> public static Matrix<T> RandomPositiveDefinite<T>(int order, IContinuousDistribution distribution) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.RandomPositiveDefinite(order, distribution); } /// <summary> /// Create a new positive definite dense matrix where each value is the product /// of two samples from the standard distribution. /// </summary> public static Matrix<T> RandomPositiveDefinite<T>(int order) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.RandomPositiveDefinite(order); } /// <summary> /// Create a new positive definite dense matrix where each value is the product /// of two samples from the provided random distribution. /// </summary> public static Matrix<T> RandomPositiveDefinite<T>(int order, int seed) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.RandomPositiveDefinite(order, seed); } /// <summary> /// Create a new dense matrix straight from an initialized matrix storage instance. /// The storage is used directly without copying. /// Intended for advanced scenarios where you're working directly with /// storage for performance or interop reasons. /// </summary> public static Matrix<T> Dense<T>(DenseColumnMajorMatrixStorage<T> storage) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Dense(storage); } /// <summary> /// Create a new dense matrix with the given number of rows and columns. /// All cells of the matrix will be initialized to zero. /// Zero-length matrices are not supported. /// </summary> public static Matrix<T> Dense<T>(int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Dense(rows, columns); } /// <summary> /// Create a new dense matrix with the given number of rows and columns directly binding to a raw array. /// The array is assumed to be in column-major order (column by column) and is used directly without copying. /// Very efficient, but changes to the array and the matrix will affect each other. /// </summary> /// <seealso href="http://en.wikipedia.org/wiki/Row-major_order"/> public static Matrix<T> Dense<T>(int rows, int columns, T[] storage) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Dense(rows, columns, storage); } /// <summary> /// Create a new dense matrix and initialize each value to the same provided value. /// </summary> public static Matrix<T> Dense<T>(int rows, int columns, T value) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Dense(rows, columns, value); } /// <summary> /// Create a new dense matrix and initialize each value using the provided init function. /// </summary> public static Matrix<T> Dense<T>(int rows, int columns, Func<int, int, T> init) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Dense(rows, columns, init); } /// <summary> /// Create a new diagonal dense matrix and initialize each diagonal value to the same provided value. /// </summary> public static Matrix<T> DenseDiagonal<T>(int rows, int columns, T value) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseDiagonal(rows, columns, value); } /// <summary> /// Create a new diagonal dense matrix and initialize each diagonal value to the same provided value. /// </summary> public static Matrix<T> DenseDiagonal<T>(int order, T value) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseDiagonal(order, value); } /// <summary> /// Create a new diagonal dense matrix and initialize each diagonal value using the provided init function. /// </summary> public static Matrix<T> DenseDiagonal<T>(int rows, int columns, Func<int, T> init) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseDiagonal(rows, columns, init); } /// <summary> /// Create a new diagonal dense identity matrix with a one-diagonal. /// </summary> public static Matrix<T> DenseIdentity<T>(int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseIdentity(rows, columns); } /// <summary> /// Create a new diagonal dense identity matrix with a one-diagonal. /// </summary> public static Matrix<T> DenseIdentity<T>(int order) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseIdentity(order); } /// <summary> /// Create a new dense matrix as a copy of the given other matrix. /// This new matrix will be independent from the other matrix. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfMatrix<T>(Matrix<T> matrix) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfMatrix(matrix); } /// <summary> /// Create a new dense matrix as a copy of the given two-dimensional array. /// This new matrix will be independent from the provided array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfArray<T>(T[,] array) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfArray(array); } /// <summary> /// Create a new dense matrix as a copy of the given indexed enumerable. /// Keys must be provided at most once, zero is assumed if a key is omitted. /// This new matrix will be independent from the enumerable. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfIndexed<T>(int rows, int columns, IEnumerable<Tuple<int, int, T>> enumerable) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfIndexed(rows, columns, enumerable); } /// <summary> /// Create a new dense matrix as a copy of the given enumerable. /// The enumerable is assumed to be in column-major order (column by column). /// This new matrix will be independent from the enumerable. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfColumnMajor<T>(int rows, int columns, IEnumerable<T> columnMajor) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfColumnMajor(rows, columns, columnMajor); } /// <summary> /// Create a new dense matrix as a copy of the given enumerable of enumerable columns. /// Each enumerable in the master enumerable specifies a column. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfColumns<T>(IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfColumns(data); } /// <summary> /// Create a new dense matrix as a copy of the given enumerable of enumerable columns. /// Each enumerable in the master enumerable specifies a column. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfColumns<T>(int rows, int columns, IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfColumns(rows, columns, data); } /// <summary> /// Create a new dense matrix of T as a copy of the given column arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfColumnArrays<T>(params T[][] columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfColumnArrays(columns); } /// <summary> /// Create a new dense matrix of T as a copy of the given column arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfColumnArrays<T>(IEnumerable<T[]> columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfColumnArrays(columns); } /// <summary> /// Create a new dense matrix as a copy of the given column vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfColumnVectors<T>(params Vector<T>[] columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfColumnVectors(columns); } /// <summary> /// Create a new dense matrix as a copy of the given column vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfColumnVectors<T>(IEnumerable<Vector<T>> columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfColumnVectors(columns); } /// <summary> /// Create a new dense matrix as a copy of the given enumerable of enumerable rows. /// Each enumerable in the master enumerable specifies a row. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfRows<T>(IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfRows(data); } /// <summary> /// Create a new dense matrix as a copy of the given enumerable of enumerable rows. /// Each enumerable in the master enumerable specifies a row. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfRows<T>(int rows, int columns, IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfRows(rows, columns, data); } /// <summary> /// Create a new dense matrix of T as a copy of the given row arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfRowArrays<T>(params T[][] rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfRowArrays(rows); } /// <summary> /// Create a new dense matrix of T as a copy of the given row arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfRowArrays<T>(IEnumerable<T[]> rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfRowArrays(rows); } /// <summary> /// Create a new dense matrix as a copy of the given row vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfRowVectors<T>(params Vector<T>[] rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfRowVectors(rows); } /// <summary> /// Create a new dense matrix as a copy of the given row vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfRowVectors<T>(IEnumerable<Vector<T>> rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfRowVectors(rows); } /// <summary> /// Create a new dense matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfDiagonalVector<T>(Vector<T> diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfDiagonalVector(diagonal); } /// <summary> /// Create a new dense matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfDiagonalVector<T>(int rows, int columns, Vector<T> diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfDiagonalVector(rows, columns, diagonal); } /// <summary> /// Create a new dense matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfDiagonalArray<T>(T[] diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfDiagonalArray(diagonal); } /// <summary> /// Create a new dense matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DenseOfDiagonalArray<T>(int rows, int columns, T[] diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfDiagonalArray(rows, columns, diagonal); } /// <summary> /// Create a new dense matrix from a 2D array of existing matrices. /// The matrices in the array are not required to be dense already. /// If the matrices do not align properly, they are placed on the top left /// corner of their cell with the remaining fields left zero. /// </summary> public static Matrix<T> DenseOfMatrixArray<T>(Matrix<T>[,] matrices) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DenseOfMatrixArray(matrices); } /// <summary> /// Create a new sparse matrix straight from an initialized matrix storage instance. /// The storage is used directly without copying. /// Intended for advanced scenarios where you're working directly with /// storage for performance or interop reasons. /// </summary> public static Matrix<T> Sparse<T>(SparseCompressedRowMatrixStorage<T> storage) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Sparse(storage); } /// <summary> /// Create a sparse matrix of T with the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> public static Matrix<T> Sparse<T>(int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Sparse(rows, columns); } /// <summary> /// Create a new sparse matrix and initialize each value to the same provided value. /// </summary> public static Matrix<T> Sparse<T>(int rows, int columns, T value) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Sparse(rows, columns, value); } /// <summary> /// Create a new sparse matrix and initialize each value using the provided init function. /// </summary> public static Matrix<T> Sparse<T>(int rows, int columns, Func<int, int, T> init) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Sparse(rows, columns, init); } /// <summary> /// Create a new diagonal sparse matrix and initialize each diagonal value to the same provided value. /// </summary> public static Matrix<T> SparseDiagonal<T>(int rows, int columns, T value) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseDiagonal(rows, columns, value); } /// <summary> /// Create a new diagonal sparse matrix and initialize each diagonal value to the same provided value. /// </summary> public static Matrix<T> SparseDiagonal<T>(int order, T value) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseDiagonal(order, value); } /// <summary> /// Create a new diagonal sparse matrix and initialize each diagonal value using the provided init function. /// </summary> public static Matrix<T> SparseDiagonal<T>(int rows, int columns, Func<int, T> init) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseDiagonal(rows, columns, init); } /// <summary> /// Create a new diagonal dense identity matrix with a one-diagonal. /// </summary> public static Matrix<T> SparseIdentity<T>(int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseIdentity(rows, columns); } /// <summary> /// Create a new diagonal dense identity matrix with a one-diagonal. /// </summary> public static Matrix<T> SparseIdentity<T>(int order) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseIdentity(order); } /// <summary> /// Create a new sparse matrix as a copy of the given other matrix. /// This new matrix will be independent from the other matrix. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfMatrix<T>(Matrix<T> matrix) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfMatrix(matrix); } /// <summary> /// Create a new sparse matrix as a copy of the given two-dimensional array. /// This new matrix will be independent from the provided array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfArray<T>(T[,] array) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfArray(array); } /// <summary> /// Create a new sparse matrix as a copy of the given indexed enumerable. /// Keys must be provided at most once, zero is assumed if a key is omitted. /// This new matrix will be independent from the enumerable. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfIndexed<T>(int rows, int columns, IEnumerable<Tuple<int, int, T>> enumerable) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfIndexed(rows, columns, enumerable); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable. /// The enumerable is assumed to be in row-major order (row by row). /// This new matrix will be independent from the enumerable. /// A new memory block will be allocated for storing the vector. /// </summary> /// <seealso href="http://en.wikipedia.org/wiki/Row-major_order"/> public static Matrix<T> SparseOfRowMajor<T>(int rows, int columns, IEnumerable<T> rowMajor) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfRowMajor(rows, columns, rowMajor); } /// <summary> /// Create a new sparse matrix with the given number of rows and columns as a copy of the given array. /// The array is assumed to be in column-major order (column by column). /// This new matrix will be independent from the provided array. /// A new memory block will be allocated for storing the matrix. /// </summary> /// <seealso href="http://en.wikipedia.org/wiki/Row-major_order"/> public static Matrix<T> SparseOfColumnMajor<T>(int rows, int columns, IList<T> columnMajor) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfColumnMajor(rows, columns, columnMajor); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable columns. /// Each enumerable in the master enumerable specifies a column. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfColumns<T>(IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfColumns(data); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable columns. /// Each enumerable in the master enumerable specifies a column. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfColumns<T>(int rows, int columns, IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfColumns(rows, columns, data); } /// <summary> /// Create a new sparse matrix as a copy of the given column arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfColumnArrays<T>(params T[][] columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfColumnArrays(columns); } /// <summary> /// Create a new sparse matrix as a copy of the given column arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfColumnArrays<T>(IEnumerable<T[]> columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfColumnArrays(columns); } /// <summary> /// Create a new sparse matrix as a copy of the given column vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfColumnVectors<T>(params Vector<T>[] columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfColumnVectors(columns); } /// <summary> /// Create a new sparse matrix as a copy of the given column vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfColumnVectors<T>(IEnumerable<Vector<T>> columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfColumnVectors(columns); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable rows. /// Each enumerable in the master enumerable specifies a row. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfRows<T>(IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfRows(data); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable rows. /// Each enumerable in the master enumerable specifies a row. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfRows<T>(int rows, int columns, IEnumerable<IEnumerable<T>> data) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfRows(rows, columns, data); } /// <summary> /// Create a new sparse matrix as a copy of the given row arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfRowArrays<T>(params T[][] rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfRowArrays(rows); } /// <summary> /// Create a new sparse matrix as a copy of the given row arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfRowArrays<T>(IEnumerable<T[]> rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfRowArrays(rows); } /// <summary> /// Create a new sparse matrix as a copy of the given row vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfRowVectors<T>(params Vector<T>[] rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfRowVectors(rows); } /// <summary> /// Create a new sparse matrix as a copy of the given row vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfRowVectors<T>(IEnumerable<Vector<T>> rows) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfRowVectors(rows); } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfDiagonalVector<T>(Vector<T> diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfDiagonalVector(diagonal); } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfDiagonalVector<T>(int rows, int columns, Vector<T> diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfDiagonalVector(rows, columns, diagonal); } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfDiagonalArray<T>(T[] diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfDiagonalArray(diagonal); } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> SparseOfDiagonalArray<T>(int rows, int columns, T[] diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfDiagonalArray(rows, columns, diagonal); } /// <summary> /// Create a new sparse matrix from a 2D array of existing matrices. /// The matrices in the array are not required to be sparse already. /// If the matrices do not align properly, they are placed on the top left /// corner of their cell with the remaining fields left zero. /// </summary> public static Matrix<T> SparseOfMatrixArray<T>(Matrix<T>[,] matrices) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.SparseOfMatrixArray(matrices); } /// <summary> /// Create a new diagonal matrix straight from an initialized matrix storage instance. /// The storage is used directly without copying. /// Intended for advanced scenarios where you're working directly with /// storage for performance or interop reasons. /// </summary> public static Matrix<T> Diagonal<T>(DiagonalMatrixStorage<T> storage) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Diagonal(storage); } /// <summary> /// Create a new diagonal matrix with the given number of rows and columns. /// All cells of the matrix will be initialized to zero. /// Zero-length matrices are not supported. /// </summary> public static Matrix<T> Diagonal<T>(int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Diagonal(rows, columns); } /// <summary> /// Create a new diagonal matrix with the given number of rows and columns directly binding to a raw array. /// The array is assumed to represent the diagonal values and is used directly without copying. /// Very efficient, but changes to the array and the matrix will affect each other. /// </summary> public static Matrix<T> Diagonal<T>(int rows, int columns, T[] storage) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Diagonal(rows, columns, storage); } /// <summary> /// Create a new square diagonal matrix directly binding to a raw array. /// The array is assumed to represent the diagonal values and is used directly without copying. /// Very efficient, but changes to the array and the matrix will affect each other. /// </summary> public static Matrix<T> Diagonal<T>(T[] storage) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Diagonal(storage); } /// <summary> /// Create a new diagonal matrix and initialize each diagonal value to the same provided value. /// </summary> public static Matrix<T> Diagonal<T>(int rows, int columns, T value) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Diagonal(rows, columns, value); } /// <summary> /// Create a new diagonal matrix and initialize each diagonal value using the provided init function. /// </summary> public static Matrix<T> Diagonal<T>(int rows, int columns, Func<int, T> init) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.Diagonal(rows, columns, init); } /// <summary> /// Create a new diagonal identity matrix with a one-diagonal. /// </summary> public static Matrix<T> DiagonalIdentity<T>(int rows, int columns) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DiagonalIdentity(rows, columns); } /// <summary> /// Create a new diagonal identity matrix with a one-diagonal. /// </summary> public static Matrix<T> DiagonalIdentity<T>(int order) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DiagonalIdentity(order); } /// <summary> /// Create a new diagonal matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DiagonalOfDiagonalVector<T>(Vector<T> diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DiagonalOfDiagonalVector(diagonal); } /// <summary> /// Create a new diagonal matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DiagonalOfDiagonalVector<T>(int rows, int columns, Vector<T> diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DiagonalOfDiagonalVector(rows, columns, diagonal); } /// <summary> /// Create a new diagonal matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DiagonalOfDiagonalArray<T>(T[] diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DiagonalOfDiagonalArray(diagonal); } /// <summary> /// Create a new diagonal matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static Matrix<T> DiagonalOfDiagonalArray<T>(int rows, int columns, T[] diagonal) where T : struct, IEquatable<T>, IFormattable { return Matrix<T>.Build.DiagonalOfDiagonalArray(rows, columns, diagonal); } } }
using System; using System.Collections; using HalconDotNet; namespace HDisplayControl { public delegate void GCDelegate(string val); /// <summary> /// This class contains the graphical context of an HALCON object. The /// set of graphical modes is defined by the hashlist 'graphicalSettings'. /// If the list is empty, then there is no difference to the graphical /// setting defined by the system by default. Otherwise, the provided /// HALCON window is adjusted according to the entries of the supplied /// graphical context (when calling applyContext()) /// </summary> public class GraphicsContext { /// <summary> /// Graphical mode for the output color (see dev_set_color) /// </summary> public const string GC_COLOR = "Color"; /// <summary> /// Graphical mode for the multi-color output (see dev_set_colored) /// </summary> public const string GC_COLORED = "Colored"; /// <summary> /// Graphical mode for the line width (see set_line_width) /// </summary> public const string GC_LINEWIDTH = "LineWidth"; /// <summary> /// Graphical mode for the drawing (see set_draw) /// </summary> public const string GC_DRAWMODE = "DrawMode"; /// <summary> /// Graphical mode for the drawing shape (see set_shape) /// </summary> public const string GC_SHAPE = "Shape"; /// <summary> /// Graphical mode for the LUT (lookup table) (see set_lut) /// </summary> public const string GC_LUT = "Lut"; /// <summary> /// Graphical mode for the painting (see set_paint) /// </summary> public const string GC_PAINT = "Paint"; /// <summary> /// Graphical mode for the line style (see set_line_style) /// </summary> public const string GC_LINESTYLE = "LineStyle"; /// <summary> /// Hashlist containing entries for graphical modes (defined by GC_*), /// which is then linked to some HALCON object to describe its /// graphical context. /// </summary> private Hashtable graphicalSettings; /// <summary> /// Backup of the last graphical context applied to the window. /// </summary> public Hashtable stateOfSettings; private IEnumerator iterator; /// <summary> /// Option to delegate messages from the graphical context /// to some observer class /// </summary> public GCDelegate gcNotification; /// <summary> /// Creates a graphical context with no initial /// graphical modes /// </summary> public GraphicsContext() { graphicalSettings = new Hashtable(10, 0.2f); gcNotification = new GCDelegate(dummy); stateOfSettings = new Hashtable(10, 0.2f); } /// <summary> /// Creates an instance of the graphical context with /// the modes defined in the hashtable 'settings' /// </summary> /// <param name="settings"> /// List of modes, which describes the graphical context /// </param> public GraphicsContext(Hashtable settings) { graphicalSettings = settings; gcNotification = new GCDelegate(dummy); stateOfSettings = new Hashtable(10, 0.2f); } /// <summary>Applies graphical context to the HALCON window</summary> /// <param name="window">Active HALCON window</param> /// <param name="cContext"> /// List that contains graphical modes for window /// </param> public void applyContext(HWindow window, Hashtable cContext) { string key = ""; string valS = ""; int valI = -1; HTuple valH = null; iterator = cContext.Keys.GetEnumerator(); try { while (iterator.MoveNext()) { key = (string)iterator.Current; if (stateOfSettings.Contains(key) && stateOfSettings[key] == cContext[key]) continue; switch (key) { case GC_COLOR: valS = (string)cContext[key]; window.SetColor(valS); if (stateOfSettings.Contains(GC_COLORED)) stateOfSettings.Remove(GC_COLORED); break; case GC_COLORED: valI = (int)cContext[key]; window.SetColored(valI); if (stateOfSettings.Contains(GC_COLOR)) stateOfSettings.Remove(GC_COLOR); break; case GC_DRAWMODE: valS = (string)cContext[key]; window.SetDraw(valS); break; case GC_LINEWIDTH: valI = (int)cContext[key]; window.SetLineWidth(valI); break; case GC_LUT: valS = (string)cContext[key]; window.SetLut(valS); break; case GC_PAINT: valS = (string)cContext[key]; window.SetPaint(valS); break; case GC_SHAPE: valS = (string)cContext[key]; window.SetShape(valS); break; case GC_LINESTYLE: valH = (HTuple)cContext[key]; window.SetLineStyle(valH); break; default: break; } if (valI != -1) { if (stateOfSettings.Contains(key)) stateOfSettings[key] = valI; else stateOfSettings.Add(key, valI); valI = -1; } else if (valS != "") { if (stateOfSettings.Contains(key)) stateOfSettings[key] = valI; else stateOfSettings.Add(key, valI); valS = ""; } else if (valH != null) { if (stateOfSettings.Contains(key)) stateOfSettings[key] = valI; else stateOfSettings.Add(key, valI); valH = null; } }//while } catch (HOperatorException e) { gcNotification(e.Message); return; } } /// <summary>Sets a value for the graphical mode GC_COLOR</summary> /// <param name="val"> /// A single color, e.g. "blue", "green" ...etc. /// </param> public void setColorAttribute(string val) { if (graphicalSettings.ContainsKey(GC_COLORED)) graphicalSettings.Remove(GC_COLORED); addValue(GC_COLOR, val); } /// <summary>Sets a value for the graphical mode GC_COLORED</summary> /// <param name="val"> /// The colored mode, which can be either "colored3" or "colored6" /// or "colored12" /// </param> public void setColoredAttribute(int val) { if (graphicalSettings.ContainsKey(GC_COLOR)) graphicalSettings.Remove(GC_COLOR); addValue(GC_COLORED, val); } /// <summary>Sets a value for the graphical mode GC_DRAWMODE</summary> /// <param name="val"> /// One of the possible draw modes: "margin" or "fill" /// </param> public void setDrawModeAttribute(string val) { addValue(GC_DRAWMODE, val); } /// <summary>Sets a value for the graphical mode GC_LINEWIDTH</summary> /// <param name="val"> /// The line width, which can range from 1 to 50 /// </param> public void setLineWidthAttribute(int val) { addValue(GC_LINEWIDTH, val); } /// <summary>Sets a value for the graphical mode GC_LUT</summary> /// <param name="val"> /// One of the possible modes of look up tables. For /// further information on particular setups, please refer to the /// Reference Manual entry of the operator set_lut. /// </param> public void setLutAttribute(string val) { addValue(GC_LUT, val); } /// <summary>Sets a value for the graphical mode GC_PAINT</summary> /// <param name="val"> /// One of the possible paint modes. For further /// information on particular setups, please refer refer to the /// Reference Manual entry of the operator set_paint. /// </param> public void setPaintAttribute(string val) { addValue(GC_PAINT, val); } /// <summary>Sets a value for the graphical mode GC_SHAPE</summary> /// <param name="val"> /// One of the possible shape modes. For further /// information on particular setups, please refer refer to the /// Reference Manual entry of the operator set_shape. /// </param> public void setShapeAttribute(string val) { addValue(GC_SHAPE, val); } /// <summary>Sets a value for the graphical mode GC_LINESTYLE</summary> /// <param name="val"> /// A line style mode, which works /// identical to the input for the HDevelop operator /// 'set_line_style'. For particular information on this /// topic, please refer to the Reference Manual entry of the operator /// set_line_style. /// </param> public void setLineStyleAttribute(HTuple val) { addValue(GC_LINESTYLE, val); } /// <summary> /// Adds a value to the hashlist 'graphicalSettings' for the /// graphical mode described by the parameter 'key' /// </summary> /// <param name="key"> /// A graphical mode defined by the constant GC_* /// </param> /// <param name="val"> /// Defines the value as an int for this graphical /// mode 'key' /// </param> private void addValue(string key, int val) { if (graphicalSettings.ContainsKey(key)) graphicalSettings[key] = val; else graphicalSettings.Add(key, val); } /// <summary> /// Adds a value to the hashlist 'graphicalSettings' for the /// graphical mode, described by the parameter 'key' /// </summary> /// <param name="key"> /// A graphical mode defined by the constant GC_* /// </param> /// <param name="val"> /// Defines the value as a string for this /// graphical mode 'key' /// </param> private void addValue(string key, string val) { if (graphicalSettings.ContainsKey(key)) graphicalSettings[key] = val; else graphicalSettings.Add(key, val); } /// <summary> /// Adds a value to the hashlist 'graphicalSettings' for the /// graphical mode, described by the parameter 'key' /// </summary> /// <param name="key"> /// A graphical mode defined by the constant GC_* /// </param> /// <param name="val"> /// Defines the value as a HTuple for this /// graphical mode 'key' /// </param> private void addValue(string key, HTuple val) { if (graphicalSettings.ContainsKey(key)) graphicalSettings[key] = val; else graphicalSettings.Add(key, val); } /// <summary> /// Clears the list of graphical settings. /// There will be no graphical changes made prior /// before drawing objects, since there are no /// graphical entries to be applied to the window. /// </summary> public void clear() { graphicalSettings.Clear(); } /// <summary> /// Returns an exact clone of this graphicsContext instance /// </summary> public GraphicsContext copy() { return new GraphicsContext((Hashtable)this.graphicalSettings.Clone()); } /// <summary> /// If the hashtable contains the key, the corresponding /// hashtable value is returned /// </summary> /// <param name="key"> /// One of the graphical keys starting with GC_* /// </param> public object getGraphicsAttribute(string key) { if (graphicalSettings.ContainsKey(key)) return graphicalSettings[key]; return null; } /// <summary> /// Returns a copy of the hashtable that carries the /// entries for the current graphical context /// </summary> /// <returns> current graphical context </returns> public Hashtable copyContextList() { return (Hashtable)graphicalSettings.Clone(); } /********************************************************************/ public void dummy(string val) { } }//end of class }//end of namespace
using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal; using Microsoft.Extensions.Logging; namespace RedHatX.AspNetCore.Server.Kestrel.Transport.Linux { internal class Transport : ITransport { private static readonly TransportThread[] EmptyThreads = Array.Empty<TransportThread>(); private IPEndPoint _endPoint; private IConnectionHandler _connectionHandler; private TransportThread[] _threads; private LinuxTransportOptions _transportOptions; private ILoggerFactory _loggerFactory; private ILogger _logger; public Transport(IEndPointInformation IEndPointInformation, IConnectionHandler connectionHandler, LinuxTransportOptions transportOptions, ILoggerFactory loggerFactory) : this(CreateEndPointFromIEndPointInformation(IEndPointInformation), connectionHandler, transportOptions, loggerFactory) {} private static IPEndPoint CreateEndPointFromIEndPointInformation(IEndPointInformation IEndPointInformation) { if (IEndPointInformation == null) { throw new ArgumentNullException(nameof(IEndPointInformation)); } if (IEndPointInformation.Type != ListenType.IPEndPoint) { throw new NotSupportedException("Only IPEndPoints are supported."); } if (IEndPointInformation.IPEndPoint == null) { throw new ArgumentNullException(nameof(IEndPointInformation.IPEndPoint)); } return IEndPointInformation.IPEndPoint; } public Transport(IPEndPoint listenEndPoint, IConnectionHandler connectionHandler, LinuxTransportOptions transportOptions, ILoggerFactory loggerFactory) { if (connectionHandler == null) { throw new ArgumentNullException(nameof(connectionHandler)); } if (transportOptions == null) { throw new ArgumentException(nameof(transportOptions)); } if (loggerFactory == null) { throw new ArgumentException(nameof(loggerFactory)); } if (listenEndPoint == null) { throw new ArgumentException(nameof(listenEndPoint)); } _endPoint = listenEndPoint; _connectionHandler = connectionHandler; _transportOptions = transportOptions; _loggerFactory = loggerFactory; _logger = loggerFactory.CreateLogger<Transport>(); } public async Task BindAsync() { var threads = CreateTransportThreads(); var original = Interlocked.CompareExchange(ref _threads, threads, null); ThrowIfInvalidState(state: original, starting: true); IPEndPoint endPoint = Interlocked.Exchange(ref _endPoint, null); if (endPoint == null) { throw new InvalidOperationException("Already bound"); } _logger.LogInformation($@"BindAsync TC:{_transportOptions.ThreadCount} TA:{_transportOptions.SetThreadAffinity} IC:{_transportOptions.ReceiveOnIncomingCpu} DA:{_transportOptions.DeferAccept}"); var tasks = new Task[threads.Length]; for (int i = 0; i < threads.Length; i++) { tasks[i] = threads[i].StartAsync(); } try { await Task.WhenAll(tasks); } catch { await StopAsync(); throw; } } private static int s_threadId = 0; private TransportThread[] CreateTransportThreads() { var threads = new TransportThread[_transportOptions.ThreadCount]; IList<int> preferredCpuIds = null; if (_transportOptions.SetThreadAffinity) { preferredCpuIds = GetPreferredCpuIds(); } int cpuIdx = 0; for (int i = 0; i < _transportOptions.ThreadCount; i++) { int cpuId = preferredCpuIds == null ? -1 : preferredCpuIds[cpuIdx++ % preferredCpuIds.Count]; int threadId = Interlocked.Increment(ref s_threadId); var thread = new TransportThread(_endPoint, _connectionHandler, _transportOptions, threadId, cpuId, _loggerFactory); threads[i] = thread; } return threads; } private IList<int> GetPreferredCpuIds() { if (!_transportOptions.CpuSet.IsEmpty) { return _transportOptions.CpuSet.Cpus; } var ids = new List<int>(); bool found = true; int level = 0; do { found = false; foreach (var socket in CpuInfo.GetSockets()) { var cores = CpuInfo.GetCores(socket); foreach (var core in cores) { var cpuIdIterator = CpuInfo.GetCpuIds(socket, core).GetEnumerator(); int d = 0; while (cpuIdIterator.MoveNext()) { if (d++ == level) { ids.Add(cpuIdIterator.Current); found = true; break; } } } } level++; } while (found && ids.Count < _transportOptions.ThreadCount); return ids; } public Task UnbindAsync() { var threads = Volatile.Read(ref _threads); ThrowIfInvalidState(state: threads, starting: false); var tasks = new Task[threads.Length]; for (int i = 0; i < threads.Length; i++) { tasks[i] = threads[i].CloseAcceptAsync(); } return Task.WhenAll(tasks); } public Task StopAsync() { var threads = Volatile.Read(ref _threads); ThrowIfInvalidState(state: threads, starting: false); var tasks = new Task[threads.Length]; for (int i = 0; i < threads.Length; i++) { tasks[i] = threads[i].StopAsync(); } return Task.WhenAll(tasks); } public void Dispose() { var threads = Interlocked.Exchange(ref _threads, EmptyThreads); if (threads.Length == 0) { return; } var tasks = new Task[threads.Length]; for (int i = 0; i < threads.Length; i++) { tasks[i] = threads[i].StopAsync(); } try { Task.WaitAll(tasks); } finally {} } private void ThrowIfInvalidState(TransportThread[] state, bool starting) { if (state == EmptyThreads) { throw new ObjectDisposedException(nameof(Transport)); } else if (state == null && !starting) { throw new InvalidOperationException("Not started"); } else if (state != null && starting) { throw new InvalidOperationException("Already starting"); } } /* // TODO: We'd like Kestrel to use these values for MaximumSize{Low,Heigh} but the abstraction // doesn't support it. public static PipeOptions InputPipeOptions = new PipeOptions() { // Would be nice if we could set this to 1 to limit prefetching to a single receive // but we can't: https://github.com/dotnet/corefxlab/issues/1355 MaximumSizeHigh = 2000, MaximumSizeLow = 2000, WriterScheduler = InlineScheduler.Default, ReaderScheduler = InlineScheduler.Default, }; public static PipeOptions OutputPipeOptions = new PipeOptions() { // Buffer as much as we can send in a single system call // Wait until everything is sent. MaximumSizeHigh = TransportThread.MaxSendLength, MaximumSizeLow = 1, WriterScheduler = InlineScheduler.Default, ReaderScheduler = InlineScheduler.Default, };*/ } }
namespace android.view.inputmethod { [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.inputmethod.InputConnection_))] public interface InputConnection : global::MonoJavaBridge.IJavaObject { bool setSelection(int arg0, int arg1); bool beginBatchEdit(); bool endBatchEdit(); global::java.lang.CharSequence getTextBeforeCursor(int arg0, int arg1); global::java.lang.CharSequence getTextAfterCursor(int arg0, int arg1); int getCursorCapsMode(int arg0); global::android.view.inputmethod.ExtractedText getExtractedText(android.view.inputmethod.ExtractedTextRequest arg0, int arg1); bool deleteSurroundingText(int arg0, int arg1); bool setComposingText(java.lang.CharSequence arg0, int arg1); bool finishComposingText(); bool commitText(java.lang.CharSequence arg0, int arg1); bool commitCompletion(android.view.inputmethod.CompletionInfo arg0); bool performEditorAction(int arg0); bool performContextMenuAction(int arg0); bool sendKeyEvent(android.view.KeyEvent arg0); bool clearMetaKeyStates(int arg0); bool reportFullscreenMode(bool arg0); bool performPrivateCommand(java.lang.String arg0, android.os.Bundle arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.inputmethod.InputConnection))] public sealed partial class InputConnection_ : java.lang.Object, InputConnection { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static InputConnection_() { InitJNI(); } internal InputConnection_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _setSelection10160; bool android.view.inputmethod.InputConnection.setSelection(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._setSelection10160, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._setSelection10160, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _beginBatchEdit10161; bool android.view.inputmethod.InputConnection.beginBatchEdit() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._beginBatchEdit10161); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._beginBatchEdit10161); } internal static global::MonoJavaBridge.MethodId _endBatchEdit10162; bool android.view.inputmethod.InputConnection.endBatchEdit() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._endBatchEdit10162); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._endBatchEdit10162); } internal static global::MonoJavaBridge.MethodId _getTextBeforeCursor10163; global::java.lang.CharSequence android.view.inputmethod.InputConnection.getTextBeforeCursor(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._getTextBeforeCursor10163, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._getTextBeforeCursor10163, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _getTextAfterCursor10164; global::java.lang.CharSequence android.view.inputmethod.InputConnection.getTextAfterCursor(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._getTextAfterCursor10164, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._getTextAfterCursor10164, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _getCursorCapsMode10165; int android.view.inputmethod.InputConnection.getCursorCapsMode(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._getCursorCapsMode10165, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._getCursorCapsMode10165, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getExtractedText10166; global::android.view.inputmethod.ExtractedText android.view.inputmethod.InputConnection.getExtractedText(android.view.inputmethod.ExtractedTextRequest arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._getExtractedText10166, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.inputmethod.ExtractedText; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._getExtractedText10166, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.inputmethod.ExtractedText; } internal static global::MonoJavaBridge.MethodId _deleteSurroundingText10167; bool android.view.inputmethod.InputConnection.deleteSurroundingText(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._deleteSurroundingText10167, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._deleteSurroundingText10167, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setComposingText10168; bool android.view.inputmethod.InputConnection.setComposingText(java.lang.CharSequence arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._setComposingText10168, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._setComposingText10168, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _finishComposingText10169; bool android.view.inputmethod.InputConnection.finishComposingText() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._finishComposingText10169); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._finishComposingText10169); } internal static global::MonoJavaBridge.MethodId _commitText10170; bool android.view.inputmethod.InputConnection.commitText(java.lang.CharSequence arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._commitText10170, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._commitText10170, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _commitCompletion10171; bool android.view.inputmethod.InputConnection.commitCompletion(android.view.inputmethod.CompletionInfo arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._commitCompletion10171, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._commitCompletion10171, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _performEditorAction10172; bool android.view.inputmethod.InputConnection.performEditorAction(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._performEditorAction10172, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._performEditorAction10172, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _performContextMenuAction10173; bool android.view.inputmethod.InputConnection.performContextMenuAction(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._performContextMenuAction10173, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._performContextMenuAction10173, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _sendKeyEvent10174; bool android.view.inputmethod.InputConnection.sendKeyEvent(android.view.KeyEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._sendKeyEvent10174, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._sendKeyEvent10174, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _clearMetaKeyStates10175; bool android.view.inputmethod.InputConnection.clearMetaKeyStates(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._clearMetaKeyStates10175, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._clearMetaKeyStates10175, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _reportFullscreenMode10176; bool android.view.inputmethod.InputConnection.reportFullscreenMode(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._reportFullscreenMode10176, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._reportFullscreenMode10176, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _performPrivateCommand10177; bool android.view.inputmethod.InputConnection.performPrivateCommand(java.lang.String arg0, android.os.Bundle arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_._performPrivateCommand10177, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.inputmethod.InputConnection_.staticClass, global::android.view.inputmethod.InputConnection_._performPrivateCommand10177, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.inputmethod.InputConnection_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/inputmethod/InputConnection")); global::android.view.inputmethod.InputConnection_._setSelection10160 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "setSelection", "(II)Z"); global::android.view.inputmethod.InputConnection_._beginBatchEdit10161 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "beginBatchEdit", "()Z"); global::android.view.inputmethod.InputConnection_._endBatchEdit10162 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "endBatchEdit", "()Z"); global::android.view.inputmethod.InputConnection_._getTextBeforeCursor10163 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "getTextBeforeCursor", "(II)Ljava/lang/CharSequence;"); global::android.view.inputmethod.InputConnection_._getTextAfterCursor10164 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "getTextAfterCursor", "(II)Ljava/lang/CharSequence;"); global::android.view.inputmethod.InputConnection_._getCursorCapsMode10165 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "getCursorCapsMode", "(I)I"); global::android.view.inputmethod.InputConnection_._getExtractedText10166 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "getExtractedText", "(Landroid/view/inputmethod/ExtractedTextRequest;I)Landroid/view/inputmethod/ExtractedText;"); global::android.view.inputmethod.InputConnection_._deleteSurroundingText10167 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "deleteSurroundingText", "(II)Z"); global::android.view.inputmethod.InputConnection_._setComposingText10168 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "setComposingText", "(Ljava/lang/CharSequence;I)Z"); global::android.view.inputmethod.InputConnection_._finishComposingText10169 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "finishComposingText", "()Z"); global::android.view.inputmethod.InputConnection_._commitText10170 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "commitText", "(Ljava/lang/CharSequence;I)Z"); global::android.view.inputmethod.InputConnection_._commitCompletion10171 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "commitCompletion", "(Landroid/view/inputmethod/CompletionInfo;)Z"); global::android.view.inputmethod.InputConnection_._performEditorAction10172 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "performEditorAction", "(I)Z"); global::android.view.inputmethod.InputConnection_._performContextMenuAction10173 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "performContextMenuAction", "(I)Z"); global::android.view.inputmethod.InputConnection_._sendKeyEvent10174 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "sendKeyEvent", "(Landroid/view/KeyEvent;)Z"); global::android.view.inputmethod.InputConnection_._clearMetaKeyStates10175 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "clearMetaKeyStates", "(I)Z"); global::android.view.inputmethod.InputConnection_._reportFullscreenMode10176 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "reportFullscreenMode", "(Z)Z"); global::android.view.inputmethod.InputConnection_._performPrivateCommand10177 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.InputConnection_.staticClass, "performPrivateCommand", "(Ljava/lang/String;Landroid/os/Bundle;)Z"); } } }
//******************************************************* // // Delphi DataSnap Framework // // Copyright(c) 1995-2011 Embarcadero Technologies, Inc. // //******************************************************* using System; using System.Globalization; using System.Text; namespace Embarcadero.Datasnap.WindowsPhone7 { /** * Contains methods to represent a TDBX type to a string format and vice versa. */ class DBXDefaultFormatter { public const String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss.fff"; public const String DATEFORMAT = "yyyy-MM-dd"; public const String TIMEFORMAT = "HH:mm:ss.fff"; public const String TIMEFORMAT_WO_MS = "HH:mm:ss"; public const int CURRENCYDECIMALPLACE = 4; private static DBXDefaultFormatter instance; private static CultureInfo Culture; public static DBXDefaultFormatter getInstance() { if (instance == null) instance = new DBXDefaultFormatter(); return instance; } private DBXDefaultFormatter() : base() { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); Culture = CultureInfo.InvariantCulture; } /** * create a Date from a string * @param StringValue * @return */ public DateTime StringToDate(String StringValue) { return DateTime.ParseExact(StringValue, DATEFORMAT, Culture); } /** * create a Time from a string * @param StringValue * @return */ public DateTime StringToTime(String StringValue) { return DateTime.ParseExact(StringValue, TIMEFORMAT, Culture); } /** * format a double as a string with max allowed decimal positions * @param value * @return The formatted string */ public String doubleToString(double value) { return Convert.ToString(value); } /** * format a string as a base64string * @param value * @return The base64 string */ public String Base64Encode(String value) { return Base64.encode(value); } /** * format a TDBXTime as a string * @param value * @return The formatted string */ public string TDBXTimeToString(int value) { TimeSpan ts = TimeSpan.FromMilliseconds(value); DateTime d = new DateTime(1,1,1,0,0,0,0) + ts; return d.ToString(TIMEFORMAT); } /** * format a TDBXDate as a string * @param value * @return The formatted string */ private const long MILLISECONDSINADAY = 1000 * 60 * 60 * 24; private String multiplyString(String c, int howManyTimes) { if (howManyTimes == 0) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < howManyTimes; i++) sb.Append(c); return sb.ToString(); } /** * format a TDBXDate as a string * @param value * @return The formatted string */ public string TDBXDateToString(int d) { TimeSpan ts = TimeSpan.FromDays(d); DateTime dt = DateTime.MinValue + ts - TimeSpan.Parse("1"); return dt.ToString(DATEFORMAT); } /** * create a TDBXTime (int) from a string * @param value * @return The int value */ public int StringToTDBXTime(String value) { String[] parts = value.Split(':'); return (Int32.Parse(parts[0]) * 3600000) + (Int32.Parse(parts[1]) * 60000) + (Int32.Parse(parts[2]) * 1000); } /** * create a TDBXDate (int) from a string * @param value * @return The int value */ public int StringToTDBXDate(string s) { String[] parts = s.Split('-'); int yyyy = Int32.Parse(parts[0]); int mm = (Int32.Parse(parts[1])); int dd = (Int32.Parse(parts[2])); DateTime d = new DateTime(yyyy, mm, dd); return Convert.ToInt32(((TimeSpan)(d - DateTime.MinValue + TimeSpan.Parse("1"))).TotalDays); } /** * format a float as a string with max allowed decimal positions * @param value * @return The formatted string */ public String floatToString(float value) { return value.ToString("R"); } /** * format a double as a string with only 4 decimal position * @param value * @return The formatted string */ public String currencyToString(double value) { return String.Format("{0:0.0000}", value); } private CultureInfo GetCulture() { return Culture; } /** * convert a String to Double * @param value * @return */ public double StringToDouble(String value) { return Double.Parse(value); } /** * Convert a DateTime to String * @param dateValue * @return */ public String DateTimeToString(DateTime dateValue) { return dateValue.ToString(DATETIMEFORMAT); } /** * Convert a Date to String * @param dateValue * @return */ public String DateToString(DateTime dateValue) { return dateValue.ToString(DATEFORMAT); } /** * Convert a Time to String including milliseconds * @param timeValue * @return */ public String TimeToString(DateTime dateValue) { return dateValue.ToString(TIMEFORMAT); } /** * Convert a Time to String without milliseconds * @param timeValue * @return */ public String TimeToStringWOms(DateTime dateValue) { return dateValue.ToString(TIMEFORMAT_WO_MS); } /** * Create a DateTime from a String * @param value * @return */ public DateTime StringToDateTime(String value) { value = value.PadRight(23,'0'); return DateTime.ParseExact(value, DATETIMEFORMAT, CultureInfo.InvariantCulture); } /** * Returns the string representation of the AnsiString argument. * @param value * @return String */ public String AnsiStringToString(String value) { return value; } /** * Returns the string representation of the WideString argument. * @param value * @return String */ public String WideStringToString(String value) { return value; } /** * Returns the string representation of the int argument. * @param value * @return the string representation. */ public String Int8ToString(int value) { return value.ToString(); } /** * Returns the string representation of the int16 argument. * @param value * @return String */ public String Int16ToString(int value) { return value.ToString(); } /** * Returns the string representation of the int32 argument. * @param value * @return String */ public String Int32ToString(int value) { return value.ToString(); } /** * Returns the string representation of the int64 argument. * @param value * @return String */ public String Int64ToString(long value) { return value.ToString(); } /** * Returns the string representation of the UInt8 argument. * @param value * @return String */ public String UInt8ToString(int value) { return value.ToString(); } /** * Returns the string representation of the UInt16 argument. * @param value * @return String */ public String UInt16ToString(int value) { return value.ToString(); } /** * Returns the string representation of the Uint32 argument. * @param value * @return String */ public String UInt32ToString(long value) { return value.ToString(); } /** * Returns the string representation of the Uint64 argument. * @param value * @return String */ public String UInt64ToString(long value) { return value.ToString(); } /** * try to convert a Object to a String * @param value * @return */ public String tryObjectToString(Object value) { if (value == null) return "null"; if (value is String) return (String)value; //AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short if (value is Double) return doubleToString((Double)value); if (value is float) return floatToString((float)value); if (value is long) return Int64ToString((long)value); if (value is DateTime) return DateTimeToString((DateTime)value); if (value is Boolean) return booleanToString((Boolean)value); return "unsupportedtype(" + value.GetType().FullName+")"; } /** * Convert a Boolean to String * @param booleanValue * @return string */ public String booleanToString(bool booleanValue) { return booleanValue?"true":"false"; } /** * Convert a String to Boolean value * @param stringValue * @return boolean value */ public bool stringToBoolean(String stringValue) { if (stringValue.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return true; if (stringValue.Equals("false", StringComparison.InvariantCultureIgnoreCase)) return false; throw new DBXException("[" + stringValue + "] is not a valid boolean"); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpDoNotRaiseExceptionsInUnexpectedLocationsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicDoNotRaiseExceptionsInUnexpectedLocationsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class DoNotRaiseExceptionsInUnexpectedLocationsTests { #region Property and Event Tests [Fact] public async Task CSharpPropertyNoDiagnostics() { var code = @" using System; public class C { public int PropWithNoException { get { return 10; } set { } } public int PropWithSetterException { get { return 10; } set { throw new NotSupportedException(); } } public int PropWithAllowedException { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public int this[int x] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } } class NonPublic { public int PropWithException { get { throw new Exception(); } set { throw new NotSupportedException(); } } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpPropertyWithDerivedExceptionNoDiagnostics() { var code = @" using System; public class C { public int this[int x] { get { throw new ArgumentOutOfRangeException(); } set { throw new ArgumentOutOfRangeException(); } } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicPropertyNoDiagnostics() { var code = @" Imports System Public Class C Public Property PropWithNoException As Integer Get Return 10 End Get Set End Set End Property Public Property PropWithSetterException As Integer Get Return 10 End Get Set Throw New NotSupportedException() End Set End Property Public Property PropWithAllowedException As Integer Get Throw New NotSupportedException() End Get Set Throw New NotSupportedException() End Set End Property Default Public Property Item(x As Integer) As Integer Get Throw New NotSupportedException() End Get Set Throw New NotSupportedException() End Set End Property End Class Class NonPublic Public Property PropWithInvalidException As Integer Get Throw New Exception() 'Doesn't fire because it's not visible outside assembly End Get Set End Set End Property End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicPropertyWithDerivedExceptionNoDiagnostics() { var code = @" Imports System Public Class C Default Public Property Item(x As Integer) As Integer Get Throw New ArgumentOutOfRangeException() End Get Set Throw New ArgumentOutOfRangeException() End Set End Property End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpPropertyWithInvalidExceptions() { var code = @" using System; public class C { public int Prop1 { get { throw new Exception(); } set { throw new NotSupportedException(); } } public int this[int x] { get { throw new Exception(); } set { throw new NotSupportedException(); } } public event EventHandler Event1 { add { throw new Exception(); } remove { throw new Exception(); } } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpPropertyResultAt(6, 30, "get_Prop1", "Exception"), GetCSharpPropertyResultAt(7, 36, "get_Item", "Exception"), GetCSharpAllowedExceptionsResultAt(8, 46, "add_Event1", "Exception"), GetCSharpAllowedExceptionsResultAt(8, 80, "remove_Event1", "Exception")); } [Fact] public async Task BasicPropertyWithInvalidExceptions() { var code = @" Imports System Public Class C Public Property Prop1 As Integer Get Throw New Exception() End Get Set Throw New NotSupportedException() End Set End Property Default Public Property Item(x As Integer) As Integer Get Throw New Exception() End Get Set Throw New NotSupportedException() End Set End Property Public Custom Event Event1 As EventHandler AddHandler(ByVal value As EventHandler) Throw New Exception() End AddHandler RemoveHandler(ByVal value As EventHandler) Throw New Exception() End RemoveHandler ' RaiseEvent accessors are considered private and we won't flag this exception. RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) Throw New Exception() End RaiseEvent End Event End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicPropertyResultAt(7, 12, "get_Prop1", "Exception"), GetBasicPropertyResultAt(15, 12, "get_Item", "Exception"), GetBasicAllowedExceptionsResultAt(24, 13, "add_Event1", "Exception"), GetBasicAllowedExceptionsResultAt(28, 13, "remove_Event1", "Exception")); } [Fact, WorkItem(1842, "https://github.com/dotnet/roslyn-analyzers/issues/1842")] public async Task CSharpIndexer_KeyNotFoundException_NoDiagnostics() { var code = @" using System.Collections.Generic; public class C { public int this[int x] { get { throw new KeyNotFoundException(); } } }"; await VerifyCS.VerifyAnalyzerAsync(code); } #endregion #region Equals, GetHashCode, Dispose and ToString Tests [Fact] public async Task CSharpEqualsAndGetHashCodeWithExceptions() { var code = @" using System; public class C { public override bool Equals(object obj) { throw new Exception(); } public override int GetHashCode() { throw new ArgumentException(""""); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"), GetCSharpNoExceptionsResultAt(12, 9, "GetHashCode", "ArgumentException")); } [Fact] public async Task BasicEqualsAndGetHashCodeWithExceptions() { var code = @" Imports System Public Class C Public Overrides Function Equals(obj As Object) As Boolean Throw New Exception() End Function Public Overrides Function GetHashCode() As Integer Throw New ArgumentException("""") End Function End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(6, 9, "Equals", "Exception"), GetBasicNoExceptionsResultAt(9, 9, "GetHashCode", "ArgumentException")); } [Fact] public async Task CSharpEqualsAndGetHashCodeNoDiagnostics() { var code = @" using System; public class C { public new bool Equals(object obj) { throw new Exception(); } public new int GetHashCode() { throw new ArgumentException(""""); } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicEqualsAndGetHashCodeNoDiagnostics() { var code = @" Imports System Public Class C Public Shadows Function Equals(obj As Object) As Boolean Throw New Exception() End Function Public Shadows Function GetHashCode() As Integer Throw New ArgumentException("""") End Function End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpIEquatableEqualsWithExceptions() { var code = @" using System; public class C : IEquatable<C> { public bool Equals(C obj) { throw new Exception(); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception")); } [Fact] public async Task BasicIEquatableEqualsExceptions() { var code = @" Imports System Public Class C Implements IEquatable(Of C) Public Function Equals(obj As C) As Boolean Implements IEquatable(Of C).Equals Throw New Exception() End Function End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception")); } [Fact] public async Task CSharpIHashCodeProviderGetHashCode() { var code = @" using System; using System.Collections; public class C : IHashCodeProvider { public int GetHashCode(object obj) { throw new Exception(); } } public class D : IHashCodeProvider { public int GetHashCode(object obj) { throw new ArgumentException(""obj""); // this is fine. } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpAllowedExceptionsResultAt(8, 9, "GetHashCode", "Exception")); } [Fact] public async Task BasicIHashCodeProviderGetHashCode() { var code = @" Imports System Imports System.Collections Public Class C Implements IHashCodeProvider Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode Throw New Exception() End Function End Class Public Class D Implements IHashCodeProvider Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode Throw New ArgumentException() ' This is fine. End Function End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicAllowedExceptionsResultAt(7, 9, "GetHashCode", "Exception")); } [Fact] public async Task CSharpIEqualityComparer() { var code = @" using System; using System.Collections.Generic; public class C : IEqualityComparer<C> { public bool Equals(C obj1, C obj2) { throw new Exception(); } public int GetHashCode(C obj) { throw new Exception(); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"), GetCSharpAllowedExceptionsResultAt(12, 9, "GetHashCode", "Exception")); } [Fact] public async Task BasicIEqualityComparer() { var code = @" Imports System Imports System.Collections.Generic Public Class C Implements IEqualityComparer(Of C) Public Function Equals(obj1 As C, obj2 As C) As Boolean Implements IEqualityComparer(Of C).Equals Throw New Exception() End Function Public Function GetHashCode(obj As C) As Integer Implements IEqualityComparer(Of C).GetHashCode Throw New Exception() End Function End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception"), GetBasicAllowedExceptionsResultAt(10, 9, "GetHashCode", "Exception")); } [Fact] public async Task CSharpIDisposable() { var code = @" using System; public class C : IDisposable { public void Dispose() { throw new Exception(); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "Dispose", "Exception")); } [Fact] public async Task BasicIDisposable() { var code = @" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New Exception() End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(7, 9, "Dispose", "Exception")); } [Fact] public async Task CSharpToStringWithExceptions() { var code = @" using System; public class C { public override string ToString() { throw new Exception(); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "ToString", "Exception")); } [Fact] public async Task BasicToStringWithExceptions() { var code = @" Imports System Public Class C Public Overrides Function ToString() As String Throw New Exception() End Function End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(6, 9, "ToString", "Exception")); } #endregion #region Constructor and Destructor tests [Fact] public async Task CSharpStaticConstructorWithExceptions() { var code = @" using System; class NonPublic { static NonPublic() { throw new Exception(); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, ".cctor", "Exception")); } [Fact] public async Task BasicStaticConstructorWithExceptions() { var code = @" Imports System Class NonPublic Shared Sub New() Throw New Exception() End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(6, 9, ".cctor", "Exception")); } [Fact] public async Task CSharpFinalizerWithExceptions() { var code = @" using System; class NonPublic { ~NonPublic() { throw new Exception(); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "Finalize", "Exception")); } [Fact] public async Task BasicFinalizerWithExceptions() { var code = @" Imports System Class NonPublic Protected Overrides Sub Finalize() Throw New Exception() End Sub End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(6, 9, "Finalize", "Exception")); } #endregion #region Operator tests [Fact] public async Task CSharpEqualityOperatorWithExceptions() { var code = @" using System; public class C { public static C operator ==(C c1, C c2) { throw new Exception(); } public static C operator !=(C c1, C c2) { throw new Exception(); } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "op_Equality", "Exception"), GetCSharpNoExceptionsResultAt(12, 9, "op_Inequality", "Exception")); } [Fact] public async Task BasicEqualityOperatorWithExceptions() { var code = @" Imports System Public Class C Public Shared Operator =(c1 As C, c2 As C) As C Throw New Exception() End Operator Public Shared Operator <>(c1 As C, c2 As C) As C Throw New Exception() End Operator End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(6, 9, "op_Equality", "Exception"), GetBasicNoExceptionsResultAt(9, 9, "op_Inequality", "Exception")); } [Fact] public async Task CSharpImplicitOperatorWithExceptions() { var code = @" using System; public class C { public static implicit operator int(C c1) { throw new Exception(); } public static explicit operator double(C c1) { throw new Exception(); // This is fine. } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpNoExceptionsResultAt(8, 9, "op_Implicit", "Exception")); } [Fact] public async Task BasicImplicitOperatorWithExceptions() { var code = @" Imports System Public Class C Public Shared Widening Operator CType(x As Integer) As C Throw New Exception() End Operator Public Shared Narrowing Operator CType(x As Double) As C Throw New Exception() End Operator End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicNoExceptionsResultAt(6, 9, "op_Implicit", "Exception")); } #endregion private static DiagnosticResult GetCSharpPropertyResultAt(int line, int column, string methodName, string exceptionName) { return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName); } private static DiagnosticResult GetCSharpAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName) { return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName); } private static DiagnosticResult GetCSharpNoExceptionsResultAt(int line, int column, string methodName, string exceptionName) { return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName); } private static DiagnosticResult GetBasicPropertyResultAt(int line, int column, string methodName, string exceptionName) { return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName); } private static DiagnosticResult GetBasicAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName) { return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName); } private static DiagnosticResult GetBasicNoExceptionsResultAt(int line, int column, string methodName, string exceptionName) { return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName); } private static DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments) => VerifyCS.Diagnostic(rule) .WithLocation(line, column) .WithArguments(arguments); private static DiagnosticResult GetBasicResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments) => VerifyVB.Diagnostic(rule) .WithLocation(line, column) .WithArguments(arguments); } }