context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { #region Enums public enum CCClipMode { None, // No clipping of children Bounds, // Clipping with a ScissorRect BoundsWithRenderTarget // Clipping with the ScissorRect and in a RenderTarget } // Conform to XNA 4.0 public enum CCDepthFormat { None = -1, Depth16 = 54, Depth24 = 51, Depth24Stencil8 = 48, } public enum CCBufferUsage { None, WriteOnly } #endregion Enums internal class CCDrawManager { const int DefaultQuadBufferSize = 1024 * 4; bool needReinitResources; bool textureEnabled; bool vertexColorEnabled; bool worldMatrixChanged; bool projectionMatrixChanged; bool viewMatrixChanged; bool textureChanged; bool effectChanged; bool depthTest; bool allowNonPower2Textures; bool hasStencilBuffer; bool maskOnceLog = false; int stackIndex; int maskLayer = -1; CCDisplayOrientation currentDisplayOrientation; CCSize initialProposedScreenSizeInPixels; CCBlendFunc currBlend; CCDepthFormat platformDepthFormat; CCQuadVertexBuffer quadsBuffer; CCIndexBuffer<short> quadsIndexBuffer; CCV3F_C4B_T2F[] quadVertices; readonly Matrix[] matrixStack; Matrix worldMatrix; Matrix viewMatrix; Matrix projectionMatrix; Matrix matrix; Matrix tmpMatrix; Matrix transform; readonly Dictionary<CCBlendFunc, BlendState> blendStates; DepthStencilState depthEnableStencilState; DepthStencilState depthDisableStencilState; DepthStencilState[] maskSavedStencilStates = new DepthStencilState[8]; MaskState[] maskStates = new MaskState[8]; MaskDepthStencilStateCacheEntry[] maskStatesCache = new MaskDepthStencilStateCacheEntry[8]; readonly Stack<Effect> effectStack; BasicEffect defaultEffect; Effect currentEffect; RenderTarget2D currentRenderTarget; RenderTarget2D previousRenderTarget; Matrix savedViewMatrix; Matrix savedProjectionMatrix; Viewport savedViewport; Texture2D currentTexture; GraphicsDevice graphicsDevice; GraphicsDeviceManager graphicsDeviceMgr; List<RasterizerState> rasterizerStatesCache; #region Properties public static CCDrawManager SharedDrawManager { get; set; } public SpriteBatch SpriteBatch { get; set; } internal int DrawCount { get; set; } internal BasicEffect PrimitiveEffect { get; private set; } internal AlphaTestEffect AlphaTestEffect { get; private set; } internal CCRawList<CCV3F_C4B_T2F> TmpVertices { get; private set; } public bool VertexColorEnabled { get { return vertexColorEnabled; } set { if (vertexColorEnabled != value) { vertexColorEnabled = value; textureChanged = true; } } } public bool TextureEnabled { get { return textureEnabled; } set { if (textureEnabled != value) { textureEnabled = value; textureChanged = true; } } } public bool ScissorRectEnabled { get { return graphicsDevice.RasterizerState.ScissorTestEnable; } set { if (graphicsDevice.RasterizerState.ScissorTestEnable != value) { graphicsDevice.RasterizerState = GetScissorRasterizerState(value); } } } public bool DepthTest { get { return depthTest; } set { depthTest = value; // NOTE: This must be disabled when primitives are drawing, e.g. lines, polylines, etc. graphicsDevice.DepthStencilState = value ? depthEnableStencilState : depthDisableStencilState; } } internal CCDisplayOrientation SupportedDisplayOrientations { get { return (CCDisplayOrientation)graphicsDeviceMgr.SupportedOrientations; } set { graphicsDeviceMgr.SupportedOrientations = (DisplayOrientation)value; graphicsDeviceMgr.ApplyChanges(); UpdateDisplayOrientation(); } } internal CCDisplayOrientation CurrentDisplayOrientation { set { if(currentDisplayOrientation != value) { currentDisplayOrientation = value; UpdateDisplayOrientation(); } } } internal BlendState BlendState { get { return graphicsDevice.BlendState; } set { graphicsDevice.BlendState = value; currBlend.Source = -1; currBlend.Destination = -1; } } public DepthStencilState DepthStencilState { get { return graphicsDevice.DepthStencilState; } set { graphicsDevice.DepthStencilState = value; } } internal CCRect ScissorRectInPixels { get { return new CCRect(graphicsDevice.ScissorRectangle); } set { graphicsDevice.ScissorRectangle = new Rectangle ((int)value.Origin.X, (int)value.Origin.Y, (int)value.Size.Width, (int)value.Size.Height); } } internal Viewport Viewport { get { return graphicsDevice.Viewport; } set { graphicsDevice.Viewport = value; } } internal Matrix ViewMatrix { get { return viewMatrix; } set { viewMatrix = value; viewMatrixChanged = true; } } internal Matrix ProjectionMatrix { get { return projectionMatrix; } set { projectionMatrix = value; projectionMatrixChanged = true; } } internal Matrix WorldMatrix { get { return matrix; } set { matrix = worldMatrix = value; worldMatrixChanged = true; } } internal GraphicsDevice XnaGraphicsDevice { get { return graphicsDevice; } } internal GraphicsDeviceManager XnaGraphicsDeviceManager { get { return graphicsDeviceMgr; } } internal RenderTarget2D CurrentRenderTarget { get { return currentRenderTarget; } set { previousRenderTarget = currentRenderTarget; currentRenderTarget = value; if (graphicsDevice != null && graphicsDevice.GraphicsDeviceStatus == GraphicsDeviceStatus.Normal) { graphicsDevice.SetRenderTarget(currentRenderTarget); } } } #endregion Properties #region Constructors internal CCDrawManager(GraphicsDeviceManager deviceManager, CCSize proposedScreenSize, CCDisplayOrientation supportedOrientations) { graphicsDeviceMgr = deviceManager; depthTest = true; allowNonPower2Textures = true; hasStencilBuffer = true; currBlend = CCBlendFunc.AlphaBlend; platformDepthFormat = CCDepthFormat.Depth24; transform = Matrix.Identity; TmpVertices = new CCRawList<CCV3F_C4B_T2F>(); matrixStack = new Matrix[100]; blendStates = new Dictionary<CCBlendFunc, BlendState>(); effectStack = new Stack<Effect>(); rasterizerStatesCache = new List<RasterizerState>(); hasStencilBuffer = (deviceManager.PreferredDepthStencilFormat == DepthFormat.Depth24Stencil8); if (deviceManager.GraphicsDevice == null) { initialProposedScreenSizeInPixels = proposedScreenSize; graphicsDeviceMgr.PreferredBackBufferWidth = (int)initialProposedScreenSizeInPixels.Width; graphicsDeviceMgr.PreferredBackBufferHeight = (int)initialProposedScreenSizeInPixels.Height; graphicsDeviceMgr.SupportedOrientations = (DisplayOrientation)supportedOrientations; graphicsDeviceMgr.DeviceCreated += GraphicsDeviceCreated; graphicsDeviceMgr.PreparingDeviceSettings += PreparingDeviceSettings; } } void GraphicsDeviceCreated(object sender, EventArgs e) { graphicsDevice = graphicsDeviceMgr.GraphicsDevice; InitializeGraphicsDevice(); } void PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e) { var gdipp = e.GraphicsDeviceInformation.PresentationParameters; PresentationParameters presParams = new PresentationParameters(); presParams.RenderTargetUsage = RenderTargetUsage.PreserveContents; presParams.DepthStencilFormat = DepthFormat.Depth24Stencil8; presParams.BackBufferFormat = SurfaceFormat.Color; presParams.RenderTargetUsage = RenderTargetUsage.PreserveContents; gdipp.RenderTargetUsage = presParams.RenderTargetUsage; gdipp.DepthStencilFormat = presParams.DepthStencilFormat; gdipp.BackBufferFormat = presParams.BackBufferFormat; gdipp.RenderTargetUsage = presParams.RenderTargetUsage; gdipp.BackBufferWidth = (int)initialProposedScreenSizeInPixels.Width; gdipp.BackBufferHeight = (int)initialProposedScreenSizeInPixels.Height; } void InitializeGraphicsDevice() { SpriteBatch = new SpriteBatch(graphicsDevice); defaultEffect = new BasicEffect(graphicsDevice); AlphaTestEffect = new AlphaTestEffect(graphicsDevice); PrimitiveEffect = new BasicEffect(graphicsDevice) { TextureEnabled = false, VertexColorEnabled = true }; depthEnableStencilState = new DepthStencilState { DepthBufferEnable = true, DepthBufferWriteEnable = true, TwoSidedStencilMode = true }; depthDisableStencilState = new DepthStencilState { DepthBufferEnable = false }; #if !WINDOWS_PHONE && !XBOX && !WINDOWS &&!NETFX_CORE List<string> extensions = CCUtils.GetGLExtensions(); foreach(string s in extensions) { switch(s) { case "GL_OES_depth24": platformDepthFormat = CCDepthFormat.Depth24; break; case "GL_IMG_texture_npot": allowNonPower2Textures = true; break; case "GL_NV_depth_nonlinear": // nVidia Depth 16 non-linear platformDepthFormat = CCDepthFormat.Depth16; break; case "GL_NV_texture_npot_2D_mipmap": // nVidia - nPot textures and mipmaps allowNonPower2Textures = true; break; } } #endif projectionMatrix = Matrix.Identity; viewMatrix = Matrix.Identity; worldMatrix = Matrix.Identity; matrix = Matrix.Identity; worldMatrixChanged = viewMatrixChanged = projectionMatrixChanged = true; // Need to change DrawPrim to no longer be static !!! CCDrawingPrimitives.Initialize(graphicsDevice, this); graphicsDevice.Disposing += GraphicsDeviceDisposing; graphicsDevice.DeviceLost += GraphicsDeviceDeviceLost; graphicsDevice.DeviceReset += GraphicsDeviceDeviceReset; graphicsDevice.DeviceResetting += GraphicsDeviceDeviceResetting; graphicsDevice.ResourceCreated += GraphicsDeviceResourceCreated; graphicsDevice.ResourceDestroyed += GraphicsDeviceResourceDestroyed; DepthTest = false; } #endregion Constructors #region Updating view void UpdateDisplayOrientation() { // Make sure chosen orientation is supported if((currentDisplayOrientation & SupportedDisplayOrientations) != currentDisplayOrientation) { currentDisplayOrientation = CCDisplayOrientation.Default; } } #endregion Updating view RasterizerState GetScissorRasterizerState(bool scissorEnabled) { var currentState = graphicsDevice.RasterizerState; for (int i = 0; i < rasterizerStatesCache.Count; i++) { var state = rasterizerStatesCache[i]; if ( state.ScissorTestEnable == scissorEnabled && currentState.CullMode == state.CullMode && currentState.DepthBias == state.DepthBias && currentState.FillMode == state.FillMode && currentState.MultiSampleAntiAlias == state.MultiSampleAntiAlias && currentState.SlopeScaleDepthBias == state.SlopeScaleDepthBias ) { return state; } } var newState = new RasterizerState { ScissorTestEnable = scissorEnabled, CullMode = currentState.CullMode, DepthBias = currentState.DepthBias, FillMode = currentState.FillMode, MultiSampleAntiAlias = currentState.MultiSampleAntiAlias, SlopeScaleDepthBias = currentState.SlopeScaleDepthBias }; rasterizerStatesCache.Add(newState); return newState; } #region GraphicsDevice callbacks void GraphicsDeviceResourceDestroyed(object sender, ResourceDestroyedEventArgs e) { } void GraphicsDeviceResourceCreated(object sender, ResourceCreatedEventArgs e) { } void GraphicsDeviceDeviceResetting(object sender, EventArgs e) { CCSpriteFontCache.SharedInstance.Clear(); #if XNA CCContentManager.SharedContentManager.ReloadGraphicsAssets(); #endif needReinitResources = true; } void GraphicsDeviceDeviceReset(object sender, EventArgs e) { } void GraphicsDeviceDeviceLost(object sender, EventArgs e) { } void GraphicsDeviceDisposing(object sender, EventArgs e) { } #endregion GraphicsDevice callbacks #region Cleanup public void PurgeDrawManager() { graphicsDevice = null; SpriteBatch = null; blendStates.Clear(); depthEnableStencilState = null; depthDisableStencilState = null; effectStack.Clear(); PrimitiveEffect = null; AlphaTestEffect = null; defaultEffect = null; currentEffect = null; currentRenderTarget = null; quadsBuffer = null; quadsIndexBuffer = null; currentTexture = null; quadVertices = null; TmpVertices.Clear(); } internal void ResetDevice() { vertexColorEnabled = true; worldMatrixChanged = false; projectionMatrixChanged = false; viewMatrixChanged = false; textureChanged = false; effectChanged = false; DepthTest = depthTest; defaultEffect.VertexColorEnabled = true; defaultEffect.TextureEnabled = false; defaultEffect.Alpha = 1f; defaultEffect.Texture = null; defaultEffect.View = viewMatrix; defaultEffect.World = worldMatrix; defaultEffect.Projection = projectionMatrix; matrix = worldMatrix; effectStack.Clear(); currentEffect = defaultEffect; currentTexture = null; graphicsDevice.RasterizerState = RasterizerState.CullNone; graphicsDevice.BlendState = BlendState.AlphaBlend; graphicsDevice.SetVertexBuffer(null); graphicsDevice.SetRenderTarget(null); graphicsDevice.Indices = null; graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp; } #endregion Cleanup #region Drawing internal void Clear(ClearOptions options, Color color, float depth, int stencil) { graphicsDevice.Clear(options, color, depth, stencil); } public void Clear(CCColor4B color, float depth, int stencil) { Clear(ClearOptions.Target | ClearOptions.Stencil | ClearOptions.DepthBuffer, color.ToColor(), depth, stencil); } public void Clear(CCColor4B color, float depth) { Clear(color, depth, 0); } public void Clear(CCColor4B color) { Clear(color, 1.0f); } internal void BeginDraw() { if (graphicsDevice == null || graphicsDevice.IsDisposed) { // We are exiting the game return; } if (needReinitResources) { //CCGraphicsResource.ReinitAllResources(); needReinitResources = false; } ResetDevice(); if (hasStencilBuffer) { try { Clear(CCColor4B.Transparent, 1, 0); } catch (InvalidOperationException) { // no stencil buffer hasStencilBuffer = false; Clear(CCColor4B.Transparent); } } else { Clear(CCColor4B.Transparent); } DrawCount = 0; } internal void EndDraw() { if (graphicsDevice == null || graphicsDevice.IsDisposed) { // We are exiting the game return; } Debug.Assert(stackIndex == 0); if (currentRenderTarget != null) { graphicsDevice.SetRenderTarget(null); SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, DepthStencilState, null, AlphaTestEffect); SpriteBatch.Draw(currentRenderTarget, new Vector2(0, 0), Color.White); SpriteBatch.End(); } ResetDevice(); } internal void DrawPrimitives<T>(PrimitiveType type, T[] vertices, int offset, int count) where T : struct, IVertexType { if (count <= 0) { return; } ApplyEffectParams(); EffectPassCollection passes = currentEffect.CurrentTechnique.Passes; for (int i = 0; i < passes.Count; i++) { passes[i].Apply(); graphicsDevice.DrawUserPrimitives(type, vertices, offset, count); } DrawCount++; } internal void DrawIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount) where T : struct, IVertexType { if (primitiveCount <= 0) { return; } ApplyEffectParams(); EffectPassCollection passes = currentEffect.CurrentTechnique.Passes; for (int i = 0; i < passes.Count; i++) { passes[i].Apply(); graphicsDevice.DrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount); } DrawCount++; } public void DrawQuad(ref CCV3F_C4B_T2F_Quad quad) { CCV3F_C4B_T2F[] vertices = quadVertices; if (vertices == null) { vertices = quadVertices = new CCV3F_C4B_T2F[4]; CheckQuadsIndexBuffer(1); } vertices[0] = quad.TopLeft; vertices[1] = quad.BottomLeft; vertices[2] = quad.TopRight; vertices[3] = quad.BottomRight; DrawIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, 4, quadsIndexBuffer.Data.Elements, 0, 2); } public void DrawQuads(CCRawList<CCV3F_C4B_T2F_Quad> quads, int start, int n) { if (n == 0) { return; } CheckQuadsIndexBuffer(start + n); CheckQuadsVertexBuffer(start + n); quadsBuffer.UpdateBuffer(quads, start, n); graphicsDevice.SetVertexBuffer(quadsBuffer.VertexBuffer); graphicsDevice.Indices = quadsIndexBuffer.IndexBuffer; ApplyEffectParams(); EffectPassCollection passes = currentEffect.CurrentTechnique.Passes; for (int i = 0; i < passes.Count; i++) { passes[i].Apply(); graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, n * 4, start * 6, n * 2); } graphicsDevice.SetVertexBuffer(null); graphicsDevice.Indices = null; DrawCount++; } internal void DrawBuffer<T, T2>(CCVertexBuffer<T> vertexBuffer, CCIndexBuffer<T2> indexBuffer, int start, int count) where T : struct, IVertexType where T2 : struct { graphicsDevice.Indices = indexBuffer.IndexBuffer; graphicsDevice.SetVertexBuffer(vertexBuffer.VertexBuffer); ApplyEffectParams(); EffectPassCollection passes = currentEffect.CurrentTechnique.Passes; for (int i = 0; i < passes.Count; i++) { passes[i].Apply(); graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexBuffer.VertexCount, start, count); } graphicsDevice.SetVertexBuffer(null); graphicsDevice.Indices = null; DrawCount++; } internal void DrawQuadsBuffer<T>(CCVertexBuffer<T> vertexBuffer, int start, int n) where T : struct, IVertexType { if (n == 0) { return; } CheckQuadsIndexBuffer(start + n); graphicsDevice.Indices = quadsIndexBuffer.IndexBuffer; graphicsDevice.SetVertexBuffer(vertexBuffer.VertexBuffer); ApplyEffectParams(); EffectPassCollection passes = currentEffect.CurrentTechnique.Passes; for (int i = 0; i < passes.Count; i++) { passes[i].Apply(); graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexBuffer.VertexCount, start * 6, n * 2); } graphicsDevice.SetVertexBuffer(null); graphicsDevice.Indices = null; DrawCount++; } #endregion Drawing #region Effect management internal void PushEffect(Effect effect) { effectStack.Push(currentEffect); currentEffect = effect; effectChanged = true; } internal void PopEffect() { currentEffect = effectStack.Pop(); effectChanged = true; } void ApplyEffectTexture() { if (currentEffect is BasicEffect) { var effect = (BasicEffect)currentEffect; effect.TextureEnabled = textureEnabled; effect.VertexColorEnabled = vertexColorEnabled; effect.Texture = currentTexture; } else if (currentEffect is AlphaTestEffect) { var effect = (AlphaTestEffect)currentEffect; effect.VertexColorEnabled = vertexColorEnabled; effect.Texture = currentTexture; } else { throw new Exception(String.Format("Effect {0} not supported", currentEffect.GetType().Name)); } } void ApplyEffectParams() { if (effectChanged) { var matrices = currentEffect as IEffectMatrices; if (matrices != null) { matrices.Projection = projectionMatrix; matrices.View = viewMatrix; matrices.World = matrix; } ApplyEffectTexture(); } else { if (worldMatrixChanged || projectionMatrixChanged || viewMatrixChanged) { var matrices = currentEffect as IEffectMatrices; if (matrices != null) { if (worldMatrixChanged) { matrices.World = matrix; } if (projectionMatrixChanged) { matrices.Projection = projectionMatrix; } if (viewMatrixChanged) { matrices.View = viewMatrix; } } } if (textureChanged) { ApplyEffectTexture(); } } effectChanged = false; textureChanged = false; worldMatrixChanged = false; projectionMatrixChanged = false; viewMatrixChanged = false; } #endregion Effect management public void BlendFunc(CCBlendFunc blendFunc) { BlendState bs = null; if (blendFunc == CCBlendFunc.AlphaBlend) { bs = BlendState.AlphaBlend; } else if (blendFunc == CCBlendFunc.Additive) { bs = BlendState.Additive; } else if (blendFunc == CCBlendFunc.NonPremultiplied) { bs = BlendState.NonPremultiplied; } else if (blendFunc == CCBlendFunc.Opaque) { bs = BlendState.Opaque; } else { if (!blendStates.TryGetValue(blendFunc, out bs)) { bs = new BlendState(); bs.ColorSourceBlend = CCOGLES.GetXNABlend(blendFunc.Source); bs.AlphaSourceBlend = CCOGLES.GetXNABlend(blendFunc.Source); bs.ColorDestinationBlend = CCOGLES.GetXNABlend(blendFunc.Destination); bs.AlphaDestinationBlend = CCOGLES.GetXNABlend(blendFunc.Destination); blendStates.Add(blendFunc, bs); } } graphicsDevice.BlendState = bs; currBlend.Source = blendFunc.Source; currBlend.Destination = blendFunc.Destination; } #region Texture managment internal Texture2D CreateTexture2D(int width, int height) { PresentationParameters pp = graphicsDevice.PresentationParameters; if (!allowNonPower2Textures) { width = CCUtils.CCNextPOT(width); height = CCUtils.CCNextPOT(height); } return new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); } public void BindTexture(CCTexture2D texture) { Texture2D tex = texture != null ? texture.XNATexture : null; if (!graphicsDevice.IsDisposed && graphicsDevice.GraphicsDeviceStatus == GraphicsDeviceStatus.Normal) { if (tex == null) { graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp; TextureEnabled = false; } else { graphicsDevice.SamplerStates[0] = texture.SamplerState; TextureEnabled = true; } if (currentTexture != tex) { currentTexture = tex; textureChanged = true; } } } #endregion Texture management #region Render target management internal void CreateRenderTarget(CCTexture2D texture, CCRenderTargetUsage usage) { CCSize size = texture.ContentSizeInPixels; var rtarget = CreateRenderTarget((int)size.Width, (int)size.Height, CCTexture2D.DefaultAlphaPixelFormat, platformDepthFormat, usage); texture.InitWithTexture(rtarget, CCTexture2D.DefaultAlphaPixelFormat, true, false); } internal RenderTarget2D CreateRenderTarget(int width, int height, CCRenderTargetUsage usage) { return CreateRenderTarget(width, height, CCTexture2D.DefaultAlphaPixelFormat, CCDepthFormat.None, usage); } internal RenderTarget2D CreateRenderTarget(int width, int height, CCSurfaceFormat colorFormat, CCRenderTargetUsage usage) { return CreateRenderTarget(width, height, colorFormat, CCDepthFormat.None, usage); } internal RenderTarget2D CreateRenderTarget(int width, int height, CCSurfaceFormat colorFormat, CCDepthFormat depthFormat, CCRenderTargetUsage usage) { if (!allowNonPower2Textures) { width = CCUtils.CCNextPOT(width); height = CCUtils.CCNextPOT(height); } return new RenderTarget2D(graphicsDevice, width, height, false, (SurfaceFormat)colorFormat, (DepthFormat)depthFormat, 0, (RenderTargetUsage)usage); } public void SetRenderTarget(CCTexture2D texture) { RenderTarget2D target = null; if (texture != null) { CCSize texSize = texture.ContentSizeInPixels; CCRect texRect = new CCRect (0.0f, 0.0f, texSize.Width, texSize.Height); CCPoint texCenter = texRect.Center; savedViewMatrix = ViewMatrix; savedProjectionMatrix = ProjectionMatrix; savedViewport = Viewport; ProjectionMatrix = Matrix.CreateOrthographic ( texSize.Width, texSize.Height, 1024f, -1024); ViewMatrix = Matrix.CreateLookAt(new CCPoint3(texCenter, 300.0f).XnaVector, new CCPoint3(texCenter, 0.0f).XnaVector, Vector3.Up); Viewport = new Viewport(0, 0, (int)texSize.Width, (int)texSize.Height); target = texture.XNATexture as RenderTarget2D; } CurrentRenderTarget = target; } public void RestoreRenderTarget() { ViewMatrix = savedViewMatrix; ProjectionMatrix = savedProjectionMatrix; Viewport = savedViewport; CurrentRenderTarget = previousRenderTarget; } #endregion Render target management void CheckQuadsIndexBuffer(int capacity) { if (quadsIndexBuffer == null || quadsIndexBuffer.Capacity < capacity * 6) { capacity = Math.Max(capacity, DefaultQuadBufferSize); if (quadsIndexBuffer == null) { quadsIndexBuffer = new CCIndexBuffer<short>(capacity * 6, BufferUsage.WriteOnly); quadsIndexBuffer.Count = quadsIndexBuffer.Capacity; } if (quadsIndexBuffer.Capacity < capacity * 6) { quadsIndexBuffer.Capacity = capacity * 6; quadsIndexBuffer.Count = quadsIndexBuffer.Capacity; } var indices = quadsIndexBuffer.Data.Elements; int i6 = 0; int i4 = 0; for (int i = 0; i < capacity; ++i) { indices[i6 + 0] = (short)(i4 + 0); indices[i6 + 1] = (short)(i4 + 2); indices[i6 + 2] = (short)(i4 + 1); indices[i6 + 3] = (short)(i4 + 1); indices[i6 + 4] = (short)(i4 + 2); indices[i6 + 5] = (short)(i4 + 3); i6 += 6; i4 += 4; } quadsIndexBuffer.UpdateBuffer(); } } void CheckQuadsVertexBuffer(int capacity) { if (quadsBuffer == null || quadsBuffer.Capacity < capacity) { capacity = Math.Max(capacity, DefaultQuadBufferSize); if (quadsBuffer == null) { quadsBuffer = new CCQuadVertexBuffer(capacity, CCBufferUsage.WriteOnly); } else { quadsBuffer.Capacity = capacity; } } } #region Matrix management public void SetIdentityMatrix() { matrix = Matrix.Identity; worldMatrixChanged = true; } public void PushMatrix() { matrixStack[stackIndex++] = matrix; } public void PopMatrix() { matrix = matrixStack[--stackIndex]; worldMatrixChanged = true; Debug.Assert(stackIndex >= 0); } public void Translate(float x, float y, int z) { tmpMatrix = Matrix.CreateTranslation(x, y, z); Matrix.Multiply(ref tmpMatrix, ref matrix, out matrix); worldMatrixChanged = true; } public void MultMatrix(ref Matrix matrixIn) { Matrix.Multiply(ref matrixIn, ref matrix, out matrix); worldMatrixChanged = true; } public void MultMatrix(CCAffineTransform transform, float z) { MultMatrix(ref transform, z); } public void MultMatrix(ref CCAffineTransform affineTransform, float z) { transform.M11 = affineTransform.A; transform.M21 = affineTransform.C; transform.M12 = affineTransform.B; transform.M22 = affineTransform.D; transform.M41 = affineTransform.Tx; transform.M42 = affineTransform.Ty; transform.M43 = z; matrix = Matrix.Multiply(transform, matrix); worldMatrixChanged = true; } #endregion Matrix management #region Mask management public void SetClearMaskState(int layer, bool inverted) { DepthStencilState = maskStatesCache[layer].GetClearState(layer, inverted); } public void SetDrawMaskState(int layer, bool inverted) { DepthStencilState = maskStatesCache[layer].GetDrawMaskState(layer, inverted); } public void SetDrawMaskedState(int layer, bool depth) { DepthStencilState = maskStatesCache[layer].GetDrawContentState(layer, depth, maskSavedStencilStates, this.maskLayer); } public bool BeginDrawMask(CCRect screenRect, bool inverted=false, float alphaTreshold=1f) { if (maskLayer + 1 == 8) //DepthFormat.Depth24Stencil8 { if (maskOnceLog) { CCLog.Log( @"Nesting more than 8 stencils is not supported. Everything will be drawn without stencil for this node and its childs." ); maskOnceLog = false; } return false; } maskLayer++; var maskState = new MaskState() { Layer = maskLayer, Inverted = inverted, AlphaTreshold = alphaTreshold }; maskStates[maskLayer] = maskState; maskSavedStencilStates[maskLayer] = DepthStencilState; int newMaskLayer = 1 << this.maskLayer; /////////////////////////////////// // CLEAR STENCIL BUFFER SetClearMaskState(newMaskLayer, maskState.Inverted); // draw a fullscreen solid rectangle to clear the stencil buffer XnaGraphicsDevice.Clear (ClearOptions.Target | ClearOptions.Stencil, Color.Transparent, 1, 0); /////////////////////////////////// // PREPARE TO DRAW MASK SetDrawMaskState(newMaskLayer, maskState.Inverted); if (maskState.AlphaTreshold < 1f) { AlphaTestEffect.AlphaFunction = CompareFunction.Greater; AlphaTestEffect.ReferenceAlpha = (byte)(255 * maskState.AlphaTreshold); PushEffect(AlphaTestEffect); } return true; } public void EndDrawMask() { var maskState = maskStates[maskLayer]; /////////////////////////////////// // PREPARE TO DRAW MASKED CONTENT if (maskState.AlphaTreshold < 1) { PopEffect(); } SetDrawMaskedState(maskLayer, maskSavedStencilStates[maskLayer].DepthBufferEnable); } public void EndMask() { /////////////////////////////////// // RESTORE STATE DepthStencilState = maskSavedStencilStates[maskLayer]; maskLayer--; } #endregion } internal struct MaskState { public int Layer; public bool Inverted; public float AlphaTreshold; } internal struct MaskDepthStencilStateCacheEntry { public DepthStencilState Clear; public DepthStencilState ClearInvert; public DepthStencilState DrawMask; public DepthStencilState DrawMaskInvert; public DepthStencilState DrawContent; public DepthStencilState DrawContentDepth; public DepthStencilState GetClearState(int layer, bool inverted) { DepthStencilState result = inverted ? ClearInvert : Clear; if (result == null) { int maskLayer = 1 << layer; result = new DepthStencilState() { DepthBufferEnable = false, StencilEnable = true, StencilFunction = CompareFunction.Never, StencilMask = maskLayer, StencilWriteMask = maskLayer, ReferenceStencil = maskLayer, StencilFail = !inverted ? StencilOperation.Zero : StencilOperation.Replace }; if (inverted) { ClearInvert = result; } else { Clear = result; } } return result; } public DepthStencilState GetDrawMaskState(int layer, bool inverted) { DepthStencilState result = inverted ? DrawMaskInvert : DrawMask; if (result == null) { int maskLayer = 1 << layer; result = new DepthStencilState() { DepthBufferEnable = false, StencilEnable = true, StencilFunction = CompareFunction.Never, StencilMask = maskLayer, StencilWriteMask = maskLayer, ReferenceStencil = maskLayer, StencilFail = !inverted ? StencilOperation.Replace : StencilOperation.Zero, }; if (inverted) { DrawMaskInvert = result; } else { DrawMask = result; } } return result; } public DepthStencilState GetDrawContentState(int layer, bool depth, DepthStencilState[] maskSavedStencilStates, int currentMaskLayer) { DepthStencilState result = depth ? DrawContentDepth : DrawContent; if (result == null) { int maskLayer = 1 << layer; int maskLayerL = maskLayer - 1; int maskLayerLe = maskLayer | maskLayerL; result = new DepthStencilState() { DepthBufferEnable = maskSavedStencilStates[currentMaskLayer].DepthBufferEnable, StencilEnable = true, StencilMask = maskLayerLe, StencilWriteMask = 0, ReferenceStencil = maskLayerLe, StencilFunction = CompareFunction.Equal, StencilPass = StencilOperation.Zero, StencilFail = StencilOperation.Zero, }; if (depth) { DrawContentDepth = result; } else { DrawContent = result; } } return result; } } public class CCGraphicsResource : IDisposable { bool isDisposed; public bool IsDisposed { get { return isDisposed; } } #region Constructors public CCGraphicsResource() { } #endregion Constructors #region Cleaning up ~CCGraphicsResource() { this.Dispose(false); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { isDisposed = true; } } #endregion Cleaning up public virtual void ReinitResource() { } } internal class CCVertexBuffer<T> : CCGraphicsResource where T : struct, IVertexType { protected VertexBuffer vertexBuffer; protected CCBufferUsage usage; protected CCRawList<T> data; #region Properties internal VertexBuffer VertexBuffer { get { return vertexBuffer; } } public CCRawList<T> Data { get { return data; } } public int Count { get { return data.Count; } set { Debug.Assert(value <= data.Capacity); data.Count = value; } } public int Capacity { get { return data.Capacity; } set { if (data.Capacity != value) { data.Capacity = value; ReinitResource(); } } } #endregion Properties #region Constructors public CCVertexBuffer(int vertexCount, CCBufferUsage usage) { data = new CCRawList<T>(vertexCount); this.usage = usage; ReinitResource(); } #endregion Constructors public override void ReinitResource() { if (vertexBuffer != null && !vertexBuffer.IsDisposed) { vertexBuffer.Dispose(); } vertexBuffer = new VertexBuffer(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, typeof(T), data.Capacity, (BufferUsage)usage); } public void UpdateBuffer() { UpdateBuffer(0, data.Count); } public virtual void UpdateBuffer(int startIndex, int elementCount) { if (elementCount > 0) { vertexBuffer.SetData(data.Elements, startIndex, elementCount); } } } internal class CCQuadVertexBuffer : CCVertexBuffer<CCV3F_C4B_T2F_Quad> { public CCQuadVertexBuffer(int vertexCount, CCBufferUsage usage) : base(vertexCount, usage) { } public void UpdateBuffer(CCRawList<CCV3F_C4B_T2F_Quad> dataIn, int startIndex, int elementCount) { //TODO: var tmp = data; data = dataIn; UpdateBuffer(startIndex, elementCount); data = tmp; } public override void UpdateBuffer(int startIndex, int elementCount) { if (elementCount == 0) { return; } var quads = data.Elements; var tmp = CCDrawManager.SharedDrawManager.TmpVertices; while (tmp.Capacity < elementCount) { tmp.Capacity = tmp.Capacity * 2; } tmp.Count = elementCount * 4; var vertices = tmp.Elements; int i4 = 0; for (int i = startIndex; i < startIndex + elementCount; i++) { vertices[i4 + 0] = quads[i].TopLeft; vertices[i4 + 1] = quads[i].BottomLeft; vertices[i4 + 2] = quads[i].TopRight; vertices[i4 + 3] = quads[i].BottomRight; i4 += 4; } int vertexByteSize = vertexBuffer.VertexDeclaration.VertexStride; vertexBuffer.SetData(vertexByteSize * startIndex * 4, vertices, 0, elementCount * 4, vertexByteSize); } public override void ReinitResource() { if (vertexBuffer != null && !vertexBuffer.IsDisposed) { vertexBuffer.Dispose(); } vertexBuffer = new VertexBuffer(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, typeof(CCV3F_C4B_T2F), data.Capacity * 4, (BufferUsage)usage); UpdateBuffer(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing && vertexBuffer != null && !vertexBuffer.IsDisposed) { vertexBuffer.Dispose(); } vertexBuffer = null; } } internal class CCIndexBuffer<T> : CCGraphicsResource where T : struct { IndexBuffer indexBuffer; BufferUsage usage; CCRawList<T> data; #region Properties internal IndexBuffer IndexBuffer { get { return indexBuffer; } } public CCRawList<T> Data { get { return data; } } public int Count { get { return data.Count; } set { Debug.Assert(value <= data.Capacity); data.Count = value; } } public int Capacity { get { return data.Capacity; } set { if (data.Capacity != value) { data.Capacity = value; ReinitResource(); } } } #endregion Properties #region Constructors public CCIndexBuffer(int indexCount, BufferUsage usage) { data = new CCRawList<T>(indexCount); this.usage = usage; ReinitResource(); } #endregion Constructors public override void ReinitResource() { if (indexBuffer != null && !indexBuffer.IsDisposed) { indexBuffer.Dispose(); } indexBuffer = new IndexBuffer(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, typeof(T), data.Capacity, usage); UpdateBuffer(); } public void UpdateBuffer() { UpdateBuffer(0, data.Count); } public void UpdateBuffer(int startIndex, int elementCount) { if (elementCount > 0) { indexBuffer.SetData(data.Elements, startIndex, elementCount); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing && indexBuffer != null && !indexBuffer.IsDisposed) { indexBuffer.Dispose(); } indexBuffer = null; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools; namespace Microsoft.PythonTools.ML { [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", 1)] [Description("Python Machine Learning Support Package")] // This attribute is used to register the informations needed to show the this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [Guid(GuidList.guidPythonMLPkgString)] [ProvideAutoLoad("ADFC4E64-0397-11D1-9F4E-00A0C911004F")] [ProvideAutoLoad("f1536ef8-92ec-443c-9ed7-fdadf150da82")] sealed class MLSupportPackage : Package { internal static MLSupportPackage Instance; public MLSupportPackage() { Instance = this; } protected override void Initialize() { base.Initialize(); OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; CommandID toolwndCommandID = new CommandID(GuidList.guidPythonMLCmdSet, PkgCmdIDList.AddAzureMLServiceTemplate); OleMenuCommand menuToolWin = new OleMenuCommand(InvokeAddAzureMLService, toolwndCommandID); menuToolWin.BeforeQueryStatus += QueryStatusAddAzureMLService; mcs.AddCommand(menuToolWin); toolwndCommandID = new CommandID(GuidList.guidPythonMLCmdSet, PkgCmdIDList.AddAzureMLServiceTemplateToFile); menuToolWin = new OleMenuCommand(InvokeAddAzureMLServiceToFile, toolwndCommandID); menuToolWin.BeforeQueryStatus += QueryStatusAddAzureMLServiceToFile; mcs.AddCommand(menuToolWin); } // TODO: Break functionality out to it's own class private void QueryStatusAddAzureMLService(object sender, EventArgs args) { var oleMenuCmd = (Microsoft.VisualStudio.Shell.OleMenuCommand)sender; var item = GetSelectedItem(); if (item == null) { oleMenuCmd.Supported = oleMenuCmd.Visible = false; return; } object name; ErrorHandler.ThrowOnFailure(item.Value.pHier.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_TypeName, out name)); if (!(name is string) || !((string)name == "PythonProject") || GetProjectKind(item) == ProjectKind.None || IsCommandDisabledForFolder(item)) { oleMenuCmd.Supported = oleMenuCmd.Visible = false; return; } oleMenuCmd.Supported = oleMenuCmd.Visible = true; } private void QueryStatusAddAzureMLServiceToFile(object sender, EventArgs args) { var oleMenuCmd = (Microsoft.VisualStudio.Shell.OleMenuCommand)sender; var item = GetSelectedItem(); if (item == null || IsCommandDisabledForFile(item)) { oleMenuCmd.Supported = oleMenuCmd.Visible = false; } else { oleMenuCmd.Supported = oleMenuCmd.Visible = true; } } private static bool IsCommandDisabledForFolder(VSITEMSELECTION? item) { if (item.Value.IsFolder()) { return false; } return true; } private static bool IsCommandDisabledForFile(VSITEMSELECTION? item) { if (item.Value.IsFile() && String.Equals(Path.GetExtension(item.Value.GetCanonicalName()), ".py", StringComparison.OrdinalIgnoreCase)) { return false; } return true; } enum ProjectKind { None, Flask, Bottle, Django, Worker } /// <summary> /// Command used when user invokes to add an azure ML service to a file or the /// project node. /// /// By default we bring the dialog up to be configured to add to a new file in /// the folder. /// </summary> private void InvokeAddAzureMLService(object sender, EventArgs args) { var item = GetSelectedItem().Value; var dlg = CreateAddServiceDialog(item); // collect the items in the folder... foreach (var child in item.GetChildren()) { if (String.Equals(Path.GetExtension(child), ".py", StringComparison.OrdinalIgnoreCase)) { dlg.AddTargetFile(Path.GetFileName(child)); } } var res = dlg.ShowModal(); if (res == true) { string importName; if (dlg.AddToCombo.SelectedIndex == 0) { // add to new file.. AddToNewFile(item, dlg); importName = dlg.ServiceName.Text; } else { // user selected a file in the folder, add the code to it. var projectItem = GetProjectItems(item).Item(dlg.AddToCombo.Text); AddToExisting(projectItem, dlg.GenerateServiceCode()); importName = Path.GetFileNameWithoutExtension(dlg.AddToCombo.Text); } GenerateExtraFiles(dlg, importName); } } /// <summary> /// Command used when user invoeks to add an azure ML service to a .py file. /// /// By default we bring the service up configured to add to the file. /// </summary> private void InvokeAddAzureMLServiceToFile(object sender, EventArgs args) { var item = GetSelectedItem().Value; var dlg = CreateAddServiceDialog(item); // file should be the default dlg.AddTargetFile(Path.GetFileName(item.GetCanonicalName())); dlg.AddToCombo.SelectedIndex = 1; var res = dlg.ShowModal(); if (res == true) { string importName; if (dlg.AddToCombo.SelectedIndex == 0) { // add to new file.. AddToNewFile( dlg.GenerateServiceCode(), GetExtensionObject(item).Collection, dlg.ServiceName.Text + ".py" ); importName = dlg.ServiceName.Text; } else { // add to the existing file that the user right clicked on. var extObject = GetExtensionObject(item); AddToExisting(extObject, dlg.GenerateServiceCode()); importName = Path.GetFileNameWithoutExtension(item.GetCanonicalName()); } GenerateExtraFiles(dlg, importName); } } private static void AddToNewFile(string code, ProjectItems items, string filename) { var tempFile = Path.GetTempFileName(); File.WriteAllText(tempFile, code); var projectItem = items.AddFromTemplate(tempFile, filename); var window = projectItem.Open(); window.Activate(); } private void GenerateExtraFiles(AddAzureServiceDialog dlg, string importName) { var item = GetSelectedItem().Value; var dteProject = GetProject(item.pHier); if (dlg.AddDashboardDisplay.IsChecked.Value) { var targetFolder = GetTargetFolder(dteProject, dlg.DashboardTargetFolder.Text); switch (GetProjectKind(item)) { case ProjectKind.Bottle: AddToNewFile( dlg.GenerateBottleDashboardTemplate(), targetFolder, dlg.ServiceName.Text + "_dashboard" + ".tpl" ); // TODO: Find actual routes file AddToExisting( dteProject.ProjectItems.Item("routes.py"), dlg.GenerateBottleDashboardRoute(importName) ); break; } } if (dlg.AddInputForm.IsChecked.Value) { switch (GetProjectKind(item)) { case ProjectKind.Bottle: AddToNewFile( dlg.GenerateBottleFormTemplate(), GetTargetFolder(dteProject, dlg.InputTargetFolder.Text), dlg.ServiceName.Text + "_form" + ".tpl" ); if (!dlg.AddDashboardDisplay.IsChecked.Value) { // we need the dashboard template to view the results. AddToNewFile( dlg.GenerateBottleDashboardTemplate(), GetTargetFolder(dteProject, dlg.InputTargetFolder.Text), dlg.ServiceName.Text + "_dashboard" + ".tpl" ); } AddToExisting( dteProject.ProjectItems.Item("routes.py"), dlg.GenerateBottleFormRoute(importName) ); break; } } } private static EnvDTE.ProjectItems GetTargetFolder(EnvDTE.Project dteProject, string folder) { var curItems = dteProject.ProjectItems; foreach (var folderPath in folder.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)) { curItems = curItems.Item(folderPath).ProjectItems; } return curItems; } private static AddAzureServiceDialog CreateAddServiceDialog(VSITEMSELECTION item) { switch (GetProjectKind(item)) { case ProjectKind.Bottle: return new AddAzureServiceDialog("views", true); default: return new AddAzureServiceDialog(null, false); } } private static void AddToNewFile(VSITEMSELECTION item, AddAzureServiceDialog dlg) { var code = dlg.GenerateServiceCode(); var tempFile = Path.GetTempFileName(); File.WriteAllText(tempFile, code); var projectItem = GetProjectItems(item).AddFromTemplate( tempFile, dlg.ServiceName.Text + ".py" ); var window = projectItem.Open(); window.Activate(); } private static void AddToExisting(ProjectItem extObject, string code) { // TODO: Need to handle failure here. var window = extObject.Open(); window.Activate(); TextSelection selection = (TextSelection)extObject.Document.Selection; selection.SelectAll(); var text = selection.Text; selection.EndOfDocument(); selection.NewLine(); selection.Insert(code); } internal static EnvDTE.ProjectItems GetProjectItems(VSITEMSELECTION selection) { object project; ErrorHandler.ThrowOnFailure( selection.pHier.GetProperty( selection.itemid, (int)__VSHPROPID.VSHPROPID_ExtObject, out project ) ); if (project is EnvDTE.ProjectItem) { return ((EnvDTE.ProjectItem)project).ProjectItems; } return ((EnvDTE.Project)project).ProjectItems; } internal static EnvDTE.ProjectItem GetExtensionObject(VSITEMSELECTION selection) { object project; ErrorHandler.ThrowOnFailure( selection.pHier.GetProperty( selection.itemid, (int)__VSHPROPID.VSHPROPID_ExtObject, out project ) ); return (project as EnvDTE.ProjectItem); } internal static EnvDTE.Project GetProject(IVsHierarchy hierarchy) { object project; ErrorHandler.ThrowOnFailure( hierarchy.GetProperty( VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out project ) ); return (project as EnvDTE.Project); } private static ProjectKind GetProjectKind(VSITEMSELECTION? item) { if (item == null) { throw new InvalidOperationException(); } string projectTypeGuids; ErrorHandler.ThrowOnFailure( ((IVsAggregatableProject)item.Value.pHier).GetAggregateProjectTypeGuids(out projectTypeGuids) ); var guidStrs = projectTypeGuids.Split(';'); foreach (var guidStr in guidStrs) { Guid projectGuid; if (Guid.TryParse(guidStr, out projectGuid)) { if (projectGuid == GuidList.FlaskGuid) { return ProjectKind.Flask; } else if (projectGuid == GuidList.BottleGuid) { return ProjectKind.Bottle; } else if (projectGuid == GuidList.DjangoGuid) { return ProjectKind.Django; } else if (projectGuid == GuidList.WorkerRoleGuid) { return ProjectKind.Worker; } } } return ProjectKind.None; } /// <summary> /// Gets all of the currently selected items. /// </summary> /// <returns></returns> private VSITEMSELECTION? GetSelectedItem() { IVsMonitorSelection monitorSelection = GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection; IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainer = IntPtr.Zero; try { uint selectionItemId; IVsMultiItemSelect multiItemSelect = null; ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out selectionItemId, out multiItemSelect, out selectionContainer)); if (selectionItemId != VSConstants.VSITEMID_NIL && hierarchyPtr != IntPtr.Zero) { IVsHierarchy hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; if (selectionItemId != VSConstants.VSITEMID_SELECTION) { // This is a single selection. Compare hirarchy with our hierarchy and get node from itemid return new VSITEMSELECTION() { itemid = selectionItemId, pHier = hierarchy }; } } } finally { if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } if (selectionContainer != IntPtr.Zero) { Marshal.Release(selectionContainer); } } return null; } } }
using System.Data; using System.Data.SqlClient; using Rainbow.Framework.Settings; using Rainbow.Framework.Data; namespace Rainbow.Framework.Content.Data { /// <summary> /// Summary description for ContentManager. /// </summary> public class ContentManagerDB { /// <summary> /// Gets the module types. /// </summary> /// <returns></returns> public SqlDataReader GetModuleTypes() { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_GetModuleTypes", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Execute the command myConnection.Open(); return myCommand.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Gets the portals. /// </summary> /// <returns></returns> public SqlDataReader GetPortals() { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_GetPortals", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Execute the command myConnection.Open(); return myCommand.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Gets the module instances. /// </summary> /// <param name="ItemID">The item ID.</param> /// <param name="PortalID">The portal ID.</param> /// <returns></returns> public SqlDataReader GetModuleInstances(int ItemID,int PortalID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_GetModuleInstances",myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int,4); parameterItemID.Value = ItemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int,4); parameterPortalID.Value = PortalID; myCommand.Parameters.Add(parameterPortalID); myConnection.Open(); return myCommand.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Gets the module instances exc. /// </summary> /// <param name="ItemID">The item ID.</param> /// <param name="ExcludeItem">The exclude item.</param> /// <param name="PortalID">The portal ID.</param> /// <returns></returns> /// ExcludeItem == ModuleID of selected Module to use for source. //Since we do not want to allow copy from A->A,B->B we exclude that item. public SqlDataReader GetModuleInstancesExc(int ItemID, int ExcludeItem, int PortalID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_GetModuleInstancesExc",myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int,4); parameterItemID.Value = ItemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterExcludeItem = new SqlParameter("@ExcludeItem", SqlDbType.Int,4); parameterExcludeItem.Value = ExcludeItem; myCommand.Parameters.Add(parameterExcludeItem); SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int,4); parameterPortalID.Value = PortalID; myCommand.Parameters.Add(parameterPortalID); myConnection.Open(); return myCommand.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Gets the source module data. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="ModuleID">The module ID.</param> /// <returns></returns> public SqlDataReader GetSourceModuleData(int ContentMgr_ItemID,int ModuleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_GetSourceModuleData", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int,4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int,4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); myConnection.Open(); return myCommand.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Gets the dest module data. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="ModuleID">The module ID.</param> /// <returns></returns> public SqlDataReader GetDestModuleData(int ContentMgr_ItemID,int ModuleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_GetDestModuleData", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int,4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int,4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); myConnection.Open(); return myCommand.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Moves the item left. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="TargetItemID">The target item ID.</param> /// <param name="TargetModuleID">The target module ID.</param> public void MoveItemLeft(int ContentMgr_ItemID,int TargetItemID,int TargetModuleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_MoveItemLeft", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int, 4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = TargetItemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterTargetModuleID = new SqlParameter("@TargetModuleID", SqlDbType.Int, 4); parameterTargetModuleID.Value = TargetModuleID; myCommand.Parameters.Add(parameterTargetModuleID); myConnection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); } /// <summary> /// Moves the item right. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="TargetItemID">The target item ID.</param> /// <param name="TargetModuleID">The target module ID.</param> public void MoveItemRight(int ContentMgr_ItemID,int TargetItemID,int TargetModuleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_MoveItemRight", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int, 4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = TargetItemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterTargetModuleID = new SqlParameter("@TargetModuleID", SqlDbType.Int, 4); parameterTargetModuleID.Value = TargetModuleID; myCommand.Parameters.Add(parameterTargetModuleID); myConnection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); } /// <summary> /// Copies the item. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="ItemID">The item ID.</param> /// <param name="TargetModuleID">The target module ID.</param> public void CopyItem(int ContentMgr_ItemID,int ItemID, int TargetModuleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_CopyItem", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int, 4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = ItemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterTargetModuleID = new SqlParameter("@TargetModuleID", SqlDbType.Int, 4); parameterTargetModuleID.Value = TargetModuleID; myCommand.Parameters.Add(parameterTargetModuleID); myConnection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); } /// <summary> /// Copies all. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="SourceModuleID">The source module ID.</param> /// <param name="TargetModuleID">The target module ID.</param> public void CopyAll(int ContentMgr_ItemID,int SourceModuleID, int TargetModuleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_CopyAll", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int, 4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); SqlParameter parameterSourceModuleID = new SqlParameter("@SourceModuleID", SqlDbType.Int, 4); parameterSourceModuleID.Value = SourceModuleID; myCommand.Parameters.Add(parameterSourceModuleID); SqlParameter parameterTargetModuleID = new SqlParameter("@TargetModuleID", SqlDbType.Int, 4); parameterTargetModuleID.Value = TargetModuleID; myCommand.Parameters.Add(parameterTargetModuleID); myConnection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); } /// <summary> /// Deletes the item left. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="ItemID">The item ID.</param> public void DeleteItemLeft(int ContentMgr_ItemID,int ItemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_DeleteItemLeft", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int, 4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = ItemID; myCommand.Parameters.Add(parameterItemID); myConnection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); } /// <summary> /// Deletes the item right. /// </summary> /// <param name="ContentMgr_ItemID">The content MGR_ item ID.</param> /// <param name="ItemID">The item ID.</param> public void DeleteItemRight(int ContentMgr_ItemID,int ItemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ContentMgr_DeleteItemRight", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterContentMgr_ItemID = new SqlParameter("@ContentMgr_ItemID", SqlDbType.Int, 4); parameterContentMgr_ItemID.Value = ContentMgr_ItemID; myCommand.Parameters.Add(parameterContentMgr_ItemID); SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = ItemID; myCommand.Parameters.Add(parameterItemID); myConnection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); } }//end class }//end namespace
using System; using System.Collections.Generic; using System.Linq; using spreadsheet = DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using Signum.Utilities; using System.Globalization; using Signum.Entities; namespace Signum.Engine.Excel { public static class ExcelExtensions { public static string ToExcelDate(DateTime datetime) { return datetime.ToUserInterface().ToOADate().ToString(CultureInfo.InvariantCulture); //Convert to Julean Format } public static DateTime FromExcelDate(string datetime) { return DateTime.FromOADate(double.Parse(datetime, CultureInfo.InstalledUICulture)).FromUserInterface(); //Convert to Julean Format } public static string ToExcelNumber(decimal number) { return number.ToString(CultureInfo.InvariantCulture); } public static decimal FromExcelNumber(string number) { return decimal.Parse(number, CultureInfo.InvariantCulture); } public static SheetData ToSheetData(this IEnumerable<Row> rows) { return new SheetData(rows.Cast<OpenXmlElement>()); } public static Row ToRow(this IEnumerable<Cell> rows) { return new Row(rows.Cast<OpenXmlElement>()); } public static WorksheetPart AddWorksheet(this WorkbookPart workbookPart, string name, Worksheet sheet) { sheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); var result = workbookPart.AddNewPart<WorksheetPart>(); result.Worksheet = sheet; sheet.Save(); workbookPart.Workbook.Sheets.Append( new Sheet { Name = name, SheetId = (uint)workbookPart.Workbook.Sheets.Count() + 1, Id = workbookPart.GetIdOfPart(result) }); return result; } public static void XLDeleteSheet(this SpreadsheetDocument document, string sheetId) { WorkbookPart wbPart = document.WorkbookPart; Sheet? theSheet = wbPart.Workbook.Descendants<Sheet>(). Where(s => s.Id == sheetId).FirstOrDefault(); if (theSheet == null) return; // Remove the sheet reference from the workbook. WorksheetPart worksheetPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); theSheet.Remove(); // Delete the worksheet part. wbPart.DeletePart(worksheetPart); } public static Cell FindCell(this Worksheet worksheet, string addressName) { return worksheet.Descendants<Cell>().FirstEx(c => c.CellReference == addressName); } public static Cell FindCell(this SheetData sheetData, string addressName) { return sheetData.Descendants<Cell>().FirstEx(c => c.CellReference == addressName); } public static string GetCellValue(this SpreadsheetDocument document, Worksheet worksheet, string addressName) { Cell? theCell = worksheet.Descendants<Cell>(). Where(c => c.CellReference == addressName).FirstOrDefault(); // If the cell doesn't exist, return an empty string: if (theCell == null) return ""; return GetCellValue(document, theCell); } public static string GetCellValue(this SpreadsheetDocument document, Cell theCell) { string value = theCell.InnerText; // If the cell represents an integer number, you're done. // For dates, this code returns the serialized value that // represents the date. The code handles strings and booleans // individually. For shared strings, the code looks up the corresponding // value in the shared string table. For booleans, the code converts // the value into the words TRUE or FALSE. if (theCell.DataType == null) return value; switch (theCell.DataType.Value) { case CellValues.SharedString: // For shared strings, look up the value in the shared strings table. var stringTable = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault(); // If the shared string table is missing, something's wrong. // Just return the index that you found in the cell. // Otherwise, look up the correct text in the table. if (stringTable != null) return stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText; break; case CellValues.Boolean: switch (value) { case "0": return "FALSE"; default: return "TRUE"; } //break; } return value; } public static void SetCellValue(this Cell cell, object? value, Type type) { if(type == typeof(string)) { cell.RemoveAllChildren(); cell.Append(new InlineString(new Text((string?)value))); cell.DataType = CellValues.InlineString; } else { string excelValue = value == null ? "" : type.UnNullify() == typeof(DateTime) ? ExcelExtensions.ToExcelDate(((DateTime)value)) : type.UnNullify() == typeof(bool) ? (((bool)value) ? "TRUE": "FALSE") : IsNumber(type.UnNullify()) ? ExcelExtensions.ToExcelNumber(Convert.ToDecimal(value)) : value.ToString()!; cell.CellValue = new CellValue(excelValue); } } private static bool IsNumber(Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; default: return false; } } public static WorksheetPart GetWorksheetPartById(this SpreadsheetDocument document, string sheetId) { WorkbookPart wbPart = document.WorkbookPart; Sheet? theSheet = wbPart.Workbook.Descendants<Sheet>(). Where(s => s.Id == sheetId).FirstOrDefault(); if (theSheet == null) throw new ArgumentException("Sheet with id {0} not found".FormatWith(sheetId)); // Retrieve a reference to the worksheet part, and then use its Worksheet property to get // a reference to the cell whose address matches the address you've supplied: WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); return wsPart; } public static WorksheetPart GetWorksheetPartByName(this SpreadsheetDocument document, string sheetName) { WorkbookPart wbPart = document.WorkbookPart; Sheet? theSheet = wbPart.Workbook.Descendants<Sheet>(). Where(s => s.Name == sheetName).FirstOrDefault(); if (theSheet == null) throw new ArgumentException("Sheet with name {0} not found".FormatWith(sheetName)); // Retrieve a reference to the worksheet part, and then use its Worksheet property to get // a reference to the cell whose address matches the address you've supplied: WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); return wsPart; } } }
// 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.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Reflection { [Serializable] internal class MemberInfoSerializationHolder : ISerializable, IObjectReference { #region Staitc Public Members public static void GetSerializationInfo(SerializationInfo info, String name, RuntimeType reflectedClass, String signature, MemberTypes type) { GetSerializationInfo(info, name, reflectedClass, signature, null, type, null); } public static void GetSerializationInfo( SerializationInfo info, String name, RuntimeType reflectedClass, String signature, String signature2, MemberTypes type, Type[] genericArguments) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); String assemblyName = reflectedClass.Module.Assembly.FullName; String typeName = reflectedClass.FullName; info.SetType(typeof(MemberInfoSerializationHolder)); info.AddValue("Name", name, typeof(String)); info.AddValue("AssemblyName", assemblyName, typeof(String)); info.AddValue("ClassName", typeName, typeof(String)); info.AddValue("Signature", signature, typeof(String)); info.AddValue("Signature2", signature2, typeof(String)); info.AddValue("MemberType", (int)type); info.AddValue("GenericArguments", genericArguments, typeof(Type[])); } #endregion #region Private Data Members private String m_memberName; private RuntimeType m_reflectedType; // m_signature stores the ToString() representation of the member which is sometimes ambiguous. // Mulitple overloads of the same methods or properties can identical ToString(). // m_signature2 stores the SerializationToString() representation which should be unique for each member. // It is only written and used by post 4.0 CLR versions. private String m_signature; private String m_signature2; private MemberTypes m_memberType; private SerializationInfo m_info; #endregion #region Constructor internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); String assemblyName = info.GetString("AssemblyName"); String typeName = info.GetString("ClassName"); if (assemblyName == null || typeName == null) throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); Assembly assem = FormatterServices.LoadAssemblyFromString(assemblyName); m_reflectedType = assem.GetType(typeName, true, false) as RuntimeType; m_memberName = info.GetString("Name"); m_signature = info.GetString("Signature"); // Only v4.0 and later generates and consumes Signature2 m_signature2 = (string)info.GetValueNoThrow("Signature2", typeof(string)); m_memberType = (MemberTypes)info.GetInt32("MemberType"); m_info = info; } #endregion #region ISerializable [System.Security.SecurityCritical] // auto-generated public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method)); } #endregion #region IObjectReference [System.Security.SecurityCritical] // auto-generated public virtual Object GetRealObject(StreamingContext context) { if (m_memberName == null || m_reflectedType == null || m_memberType == 0) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState)); BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.OptionalParamBinding; switch (m_memberType) { #region case MemberTypes.Field: case MemberTypes.Field: { FieldInfo[] fields = m_reflectedType.GetMember(m_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[]; if (fields.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); return fields[0]; } #endregion #region case MemberTypes.Event: case MemberTypes.Event: { EventInfo[] events = m_reflectedType.GetMember(m_memberName, MemberTypes.Event, bindingFlags) as EventInfo[]; if (events.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); return events[0]; } #endregion #region case MemberTypes.Property: case MemberTypes.Property: { PropertyInfo[] properties = m_reflectedType.GetMember(m_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[]; if (properties.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); if (properties.Length == 1) return properties[0]; if (properties.Length > 1) { for (int i = 0; i < properties.Length; i++) { if (m_signature2 != null) { if (((RuntimePropertyInfo)properties[i]).SerializationToString().Equals(m_signature2)) return properties[i]; } else { if ((properties[i]).ToString().Equals(m_signature)) return properties[i]; } } } throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); } #endregion #region case MemberTypes.Constructor: case MemberTypes.Constructor: { if (m_signature == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature)); ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[]; if (constructors.Length == 1) return constructors[0]; if (constructors.Length > 1) { for (int i = 0; i < constructors.Length; i++) { if (m_signature2 != null) { if (((RuntimeConstructorInfo)constructors[i]).SerializationToString().Equals(m_signature2)) return constructors[i]; } else { if (constructors[i].ToString().Equals(m_signature)) return constructors[i]; } } } throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); } #endregion #region case MemberTypes.Method: case MemberTypes.Method: { MethodInfo methodInfo = null; if (m_signature == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature)); Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[]; MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[]; if (methods.Length == 1) methodInfo = methods[0]; else if (methods.Length > 1) { for (int i = 0; i < methods.Length; i++) { if (m_signature2 != null) { if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2)) { methodInfo = methods[i]; break; } } else { if (methods[i].ToString().Equals(m_signature)) { methodInfo = methods[i]; break; } } // Handle generic methods specially since the signature match above probably won't work (the candidate // method info hasn't been instantiated). If our target method is generic as well we can skip this. if (genericArguments != null && methods[i].IsGenericMethod) { if (methods[i].GetGenericArguments().Length == genericArguments.Length) { MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments); if (m_signature2 != null) { if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2)) { methodInfo = candidateMethod; break; } } else { if (candidateMethod.ToString().Equals(m_signature)) { methodInfo = candidateMethod; break; } } } } } } if (methodInfo == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); if (!methodInfo.IsGenericMethodDefinition) return methodInfo; if (genericArguments == null) return methodInfo; if (genericArguments[0] == null) return null; return methodInfo.MakeGenericMethod(genericArguments); } #endregion default: throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized")); } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NUnit.Framework; namespace DDay.Collections.Test { [TestFixture] public class GroupedValueListTests { GroupedValueList<string, Property, Property, string> _Properties; [SetUp] public void Setup() { _Properties = new GroupedValueList<string, Property, Property, string>(); } private IEnumerable<string> Categories { get { return new string[] { "Work", "Personal", "A", "Few", "More" }; } } private IList<string> AddCategories() { var categories = _Properties.GetMany<string>("CATEGORIES"); categories.Add("Work"); categories.Add("Personal"); var property = new Property(); property.Group = "CATEGORIES"; property.SetValue(new string[] { "A", "Few", "More" }); _Properties.Add(property); return categories; } [Test] public void ItemAdded1() { int itemsAdded = 0; _Properties.ItemAdded += (s, e) => itemsAdded++; Assert.AreEqual(0, itemsAdded); _Properties.Set("CATEGORIES", "Test"); Assert.AreEqual(1, itemsAdded); Assert.AreEqual("Test", _Properties.Get<string>("CATEGORIES")); } [Test] public void ItemAdded2() { int itemsAdded = 0; _Properties.ItemAdded += (s, e) => itemsAdded++; var categories = _Properties.GetMany<string>("CATEGORIES"); Assert.AreEqual(0, itemsAdded); _Properties.Set("CATEGORIES", new string[] { "Work", "Personal" }); Assert.AreEqual(1, itemsAdded); #pragma warning disable 0219 var items = categories.ToArray(); #pragma warning restore 0219 Assert.AreEqual(2, categories.Count); } [Test] public void ItemAdded3() { int itemsAdded = 0; _Properties.ItemAdded += (s, e) => itemsAdded++; // Get a collection value proxy ICollection<string> categories = _Properties.GetMany<string>("CATEGORIES"); Assert.AreEqual(0, itemsAdded); // Add a work category categories.Add("Work"); // Ensure a "CATEGORIES" item was added Assert.AreEqual(1, itemsAdded); // Ensure the "Work" value is accounted for Assert.AreEqual(1, categories.Count); Assert.AreEqual(1, _Properties.AllOf("CATEGORIES").Sum(o => o.ValueCount)); // Add a personal category categories.Add("Personal"); // Ensure only the original "CATEGORY" item was added Assert.AreEqual(1, itemsAdded); // Ensure the "Work" and "Personal" categories are accounted for Assert.AreEqual(2, categories.Count); Assert.AreEqual(2, _Properties.AllOf("CATEGORIES").Sum(o => o.ValueCount)); } /// <summary> /// Ensures the Add() method works properly with GroupedValueListProxy. /// </summary> [Test] public void AddProxy1() { var proxy = _Properties.GetMany<string>("CATEGORIES"); Assert.AreEqual(0, proxy.Count); proxy.Add("Work"); Assert.AreEqual(1, proxy.Count); proxy.Add("Personal"); Assert.AreEqual(2, proxy.Count); proxy.Add("A"); Assert.AreEqual(3, proxy.Count); proxy.Add("Few"); Assert.AreEqual(4, proxy.Count); proxy.Add("More"); Assert.AreEqual(5, proxy.Count); Assert.IsTrue(Categories.SequenceEqual(_Properties.AllOf("CATEGORIES").SelectMany(p => p.Values))); } [Test] public void ClearProxy1() { _Properties.Set("Test", "Test"); // Set another property to ensure it isn't cleared when the categories are cleared Assert.AreEqual(1, _Properties.AllOf("Test").Count()); Assert.AreEqual(1, _Properties.GetMany<string>("Test").Count); // Get a proxy for categories, and add items to it, ensuring // the items are added propertly afterward. var proxy = _Properties.GetMany<string>("CATEGORIES"); foreach (var category in Categories) proxy.Add(category); Assert.IsTrue(Categories.SequenceEqual(proxy.ToArray())); proxy.Clear(); Assert.AreEqual(0, proxy.Count); Assert.AreEqual(1, _Properties.AllOf("Test").Count()); Assert.AreEqual(1, _Properties.GetMany<string>("Test").Count); } /// <summary> /// Ensures the Contains() method works properly with GroupedValueListProxy. /// </summary> [Test] public void ContainsProxy1() { var proxy = _Properties.GetMany<string>("CATEGORIES"); Assert.IsFalse(proxy.Contains("Work")); proxy.Add("Work"); Assert.IsTrue(proxy.Contains("Work")); } [Test] public void CopyToProxy1() { var categories = AddCategories(); string[] values = new string[5]; categories.CopyTo(values, 0); Assert.IsTrue(categories.ToArray().SequenceEqual(values)); } [Test] public void CountProxy1() { var categories = AddCategories(); Assert.AreEqual(5, categories.Count); } [Test] public void RemoveProxy1() { var categories = AddCategories(); Assert.AreEqual(5, categories.Count); categories.Remove("Work"); Assert.AreEqual(4, categories.Count); categories.Remove("Bla"); Assert.AreEqual(4, categories.Count); categories.Remove(null); Assert.AreEqual(4, categories.Count); categories.Remove("Personal"); Assert.AreEqual(3, categories.Count); categories.Remove("A"); Assert.AreEqual(2, categories.Count); categories.Remove("Few"); Assert.AreEqual(1, categories.Count); categories.Remove("More"); Assert.AreEqual(0, categories.Count); } [Test] public void IndexOfProxy1() { var categories = AddCategories(); Assert.AreEqual(0, categories.IndexOf("Work")); Assert.AreEqual(1, categories.IndexOf("Personal")); Assert.AreEqual(2, categories.IndexOf("A")); Assert.AreEqual(3, categories.IndexOf("Few")); Assert.AreEqual(4, categories.IndexOf("More")); } [Test] public void InsertProxy1() { var categories = AddCategories(); Assert.AreEqual(5, categories.Count); Assert.AreEqual("Work", categories.First()); categories.Insert(0, "Test"); Assert.AreEqual(6, categories.Count); Assert.AreEqual("Test", categories.First()); categories.Insert(2, "Bla!"); Assert.AreEqual(7, categories.Count); Assert.AreEqual("Bla!", categories.Skip(2).First()); } [Test] public void RemoveAtProxy1() { var categories = AddCategories(); Assert.AreEqual(5, categories.Count); categories.RemoveAt(0); Assert.AreEqual(4, categories.Count); categories.RemoveAt(0); Assert.AreEqual(3, categories.Count); categories.RemoveAt(0); Assert.AreEqual(2, categories.Count); categories.RemoveAt(0); Assert.AreEqual(1, categories.Count); categories.RemoveAt(0); Assert.AreEqual(0, categories.Count); } [Test] public void RemoveAtProxy2() { var categories = AddCategories(); Assert.AreEqual(5, categories.Count); categories.RemoveAt(1); Assert.AreEqual(4, categories.Count); categories.RemoveAt(0); Assert.AreEqual(3, categories.Count); categories.RemoveAt(0); Assert.AreEqual(2, categories.Count); categories.RemoveAt(0); Assert.AreEqual(1, categories.Count); categories.RemoveAt(0); Assert.AreEqual(0, categories.Count); } [Test] public void IndexerProxy1() { var categories = AddCategories(); Assert.AreEqual("Work", categories[0]); Assert.AreEqual(5, categories.Count); categories[0] = "Test"; Assert.AreEqual("Test", categories[0]); Assert.AreEqual(5, categories.Count); Assert.AreEqual("Personal", categories[1]); categories[1] = "Blah!"; Assert.AreEqual("Blah!", categories[1]); Assert.AreEqual(5, categories.Count); } } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2001 // // File: BamlLocalizationDictionary.cs // // Contents: BamlLocalizationDictionary and BamlLocalizationDictionaryEnumerator // // History: 8/3/2004 Move to System.Windows namespace // 11/30/2004 Garyyang Move to System.Windows.Markup.Localization namespace // Renamed class to BamlLocalizationDictionary // 03/24/2005 Garyyang Move to System.Windows.Markup.Localizer namespace //------------------------------------------------------------------------ using System; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Windows.Markup; using System.Diagnostics; using System.Text; using System.Windows; namespace System.Windows.Markup.Localizer { /// <summary> /// BamlLocalizationDictionaryEnumerator /// </summary> public sealed class BamlLocalizationDictionaryEnumerator : IDictionaryEnumerator { internal BamlLocalizationDictionaryEnumerator(IEnumerator enumerator) { _enumerator = enumerator; } /// <summary> /// move to the next entry /// </summary> public bool MoveNext() { return _enumerator.MoveNext(); } /// <summary> /// reset /// </summary> public void Reset() { _enumerator.Reset(); } /// <summary> /// gets the DictionaryEntry /// </summary> public DictionaryEntry Entry { get{ return (DictionaryEntry) _enumerator.Current; } } /// <summary> /// gets the key /// </summary> public BamlLocalizableResourceKey Key { get{ return (BamlLocalizableResourceKey) Entry.Key; } } /// <summary> /// gets the value /// </summary> public BamlLocalizableResource Value { get{ return (BamlLocalizableResource) Entry.Value; } } /// <summary> /// return the current entry /// </summary> public DictionaryEntry Current { get { return this.Entry; } } //------------------------------------ // Interfaces //------------------------------------ /// <summary> /// Return the current object /// </summary> /// <value>object </value> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// return the key /// </summary> /// <value>key</value> object IDictionaryEnumerator.Key { get { return this.Key; } } /// <summary> /// Value /// </summary> /// <value>value</value> object IDictionaryEnumerator.Value { get { return this.Value; } } //--------------------------------------- // Private //--------------------------------------- private IEnumerator _enumerator; } /// <summary> /// Enumerator that enumerates all the localizable resources in /// a baml stream /// </summary> public sealed class BamlLocalizationDictionary : IDictionary { /// <summary> /// Constructor that creates an empty baml resource dictionary /// </summary> public BamlLocalizationDictionary() { _dictionary = new Dictionary<BamlLocalizableResourceKey, BamlLocalizableResource>(); } /// <summary> /// gets value indicating whether the dictionary has fixed size /// </summary> /// <value>true for fixed size, false otherwise.</value> public bool IsFixedSize { get { return false; } } /// <summary> /// get value indicating whether it is readonly /// </summary> /// <value>true for readonly, false otherwise.</value> public bool IsReadOnly { get { return false;} } /// <summary> /// Return the key to the root element if the root element is localizable, return null otherwise /// </summary> /// <remarks> /// Modifications can be added to the proeprties of the root element which will have a global effect /// on the UI. For example, changing CulutreInfo or FlowDirection on the root element (if applicable) /// will have impact to the whole UI. /// </remarks> public BamlLocalizableResourceKey RootElementKey { get { return _rootElementKey; } } /// <summary> /// gets the collection of keys /// </summary> /// <value>a collection of keys</value> public ICollection Keys { get { return ((IDictionary)_dictionary).Keys; } } /// <summary> /// gets the collection of values /// </summary> /// <value>a collection of values</value> public ICollection Values { get { return ((IDictionary)_dictionary).Values; } } /// <summary> /// Gets or sets a localizable resource by the key /// </summary> /// <param name="key">BamlLocalizableResourceKey key</param> /// <returns>BamlLocalizableResource object identified by the key</returns> public BamlLocalizableResource this[BamlLocalizableResourceKey key] { get { CheckNonNullParam(key, "key"); return _dictionary[key]; } set { CheckNonNullParam(key, "key"); _dictionary[key] = value; } } /// <summary> /// Adds a localizable resource with the provided key /// </summary> /// <param name="key">the BamlLocalizableResourceKey key</param> /// <param name="value">the BamlLocalizableResource</param> public void Add(BamlLocalizableResourceKey key, BamlLocalizableResource value) { CheckNonNullParam(key, "key"); _dictionary.Add(key, value); } /// <summary> /// removes all the resources in the dictionary. /// </summary> public void Clear() { _dictionary.Clear(); } /// <summary> /// removes the localizable resource with the specified key /// </summary> /// <param name="key">the key</param> public void Remove(BamlLocalizableResourceKey key) { _dictionary.Remove(key); } /// <summary> /// determines whether the dictionary contains the localizable resource /// with the specified key /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Contains(BamlLocalizableResourceKey key) { CheckNonNullParam(key, "key"); return _dictionary.ContainsKey(key); } /// <summary> /// returns an IDictionaryEnumerator for the dictionary. /// </summary> /// <returns>the enumerator for the dictionary</returns> public BamlLocalizationDictionaryEnumerator GetEnumerator() { return new BamlLocalizationDictionaryEnumerator( ((IDictionary)_dictionary).GetEnumerator() ); } /// <summary> /// gets the number of localizable resources in the dictionary /// </summary> /// <value>number of localizable resources</value> public int Count { get { return _dictionary.Count; } } /// <summary> /// Copies the dictionary's elements to a one-dimensional /// Array instance at the specified index. /// </summary> public void CopyTo(DictionaryEntry[] array, int arrayIndex) { CheckNonNullParam(array, "array"); if (arrayIndex < 0) { throw new ArgumentOutOfRangeException( "arrayIndex", SR.Get(SRID.ParameterCannotBeNegative) ); } if (arrayIndex >= array.Length) { throw new ArgumentException( SR.Get( SRID.Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength, "arrayIndex", "array" ), "arrayIndex" ); } if (Count > (array.Length - arrayIndex)) { throw new ArgumentException( SR.Get( SRID.Collection_CopyTo_NumberOfElementsExceedsArrayLength, "arrayIndex", "array" ) ); } foreach(KeyValuePair<BamlLocalizableResourceKey, BamlLocalizableResource> pair in _dictionary) { DictionaryEntry entry = new DictionaryEntry(pair.Key, pair.Value); array[arrayIndex++] = entry; } } #region interface ICollection, IEnumerable, IDictionary //------------------------------ // interface functions //------------------------------ bool IDictionary.Contains(object key) { CheckNonNullParam(key, "key"); return ((IDictionary)_dictionary).Contains(key); } void IDictionary.Add(object key, object value) { CheckNonNullParam(key, "key"); ((IDictionary) _dictionary).Add(key, value); } void IDictionary.Remove(object key) { CheckNonNullParam(key, "key"); ((IDictionary) _dictionary).Remove(key); } object IDictionary.this[object key] { get { CheckNonNullParam(key, "key"); return ((IDictionary)_dictionary)[key]; } set { CheckNonNullParam(key, "key"); ((IDictionary)_dictionary)[key] = value; } } IDictionaryEnumerator IDictionary.GetEnumerator() { return this.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { if (array != null && array.Rank != 1) { throw new ArgumentException( SR.Get( SRID.Collection_CopyTo_ArrayCannotBeMultidimensional ), "array" ); } CopyTo(array as DictionaryEntry[], index); } int ICollection.Count { get { return Count; } } object ICollection.SyncRoot { get { return ((IDictionary)_dictionary).SyncRoot; } } bool ICollection.IsSynchronized { get { return ((IDictionary)_dictionary).IsSynchronized; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion //------------------------------ // internal functions //------------------------------ internal BamlLocalizationDictionary Copy() { BamlLocalizationDictionary newDictionary = new BamlLocalizationDictionary(); foreach (KeyValuePair<BamlLocalizableResourceKey, BamlLocalizableResource> pair in _dictionary) { BamlLocalizableResource resourceCopy = pair.Value == null ? null : new BamlLocalizableResource(pair.Value); newDictionary.Add(pair.Key, resourceCopy); } newDictionary._rootElementKey = _rootElementKey; // return the new dictionary return newDictionary; } internal void SetRootElementKey(BamlLocalizableResourceKey key) { _rootElementKey = key; } //------------------------------ // private methods //------------------------------ private void CheckNonNullParam(object param, string paramName) { if (param == null) throw new ArgumentNullException(paramName); } //------------------------------ // private member //------------------------------ private IDictionary<BamlLocalizableResourceKey, BamlLocalizableResource> _dictionary; private BamlLocalizableResourceKey _rootElementKey; } }
using VRage.Game.Components; using Sandbox.Common.ObjectBuilders; using VRage.ObjectBuilders; using VRage.Game.ModAPI; using Sandbox.ModAPI; using Sandbox.Game.EntityComponents; using System.Collections.Generic; using VRage.ModAPI; using System.Text; using System; using VRageMath; using VRage.Game; using VRage.Game.ObjectBuilders.Definitions; using Sandbox.ModAPI.Interfaces.Terminal; using VRage.Utils; namespace Cython.PowerTransmission { [MyEntityComponentDescriptor(typeof(MyObjectBuilder_Refinery), "LargeBlockSmallRadialPowerTransmitter", "SmallBlockSmallRadialPowerTransmitter")] public class RadialPowerTransmitter: MyGameLogicComponent { class ReceiverInfo { public float powerToAdd = 0f; public float maximumPower = 0f; public ReceiverInfo(float powerToAdd, float maximumPower) { this.powerToAdd = powerToAdd; this.maximumPower = maximumPower; } } static bool m_controlsInit = false; static IMyTerminalControlOnOffSwitch m_controlSender = null; static IMyTerminalControlTextbox m_controlChannel = null; static IMyTerminalControlTextbox m_controlPower = null; public MyDefinitionId m_electricityDefinition; MyObjectBuilder_EntityBase m_objectBuilder; IMyFunctionalBlock m_functionalBlock; IMyCubeBlock m_cubeBlock; IMyTerminalBlock m_terminalBlock; int m_ticks = 0; long m_entityId; string m_subtypeName; public RadialPowerTransmitterInfo m_info = new RadialPowerTransmitterInfo(); public PTInfo m_saveInfo; MyResourceSinkComponent m_resourceSink; float m_oldTransmittedPower = 0f; public float m_transmittedPower = 0f; float m_maxRange = 1.0f; float m_maxRangeSquared = 1.0f; float m_falloffRange = 0.00005f; float m_maxPower = 1.0f; float m_currentMaxPower = 1.0f; public uint m_channel = 0; public bool m_sender = false; float m_currentOutput = 0f; uint m_infoReceivers = 0; float m_infoReceivingPower = 0f; Dictionary<IMyFunctionalBlock, ReceiverInfo> m_receivers = new Dictionary<IMyFunctionalBlock, ReceiverInfo> (); public override void Init (MyObjectBuilder_EntityBase objectBuilder) { base.Init (objectBuilder); m_objectBuilder = objectBuilder; Entity.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_FRAME; m_entityId = Entity.EntityId; m_functionalBlock = Entity as IMyFunctionalBlock; m_electricityDefinition = new MyDefinitionId (typeof(MyObjectBuilder_GasProperties), "Electricity"); m_subtypeName = m_functionalBlock.BlockDefinition.SubtypeName; m_falloffRange = getRangeMultiplier (m_subtypeName); m_maxPower = getMaxPower (m_subtypeName); m_currentMaxPower = m_maxPower; m_info.functionalBlock = m_functionalBlock; m_info.subtypeName = m_subtypeName; m_cubeBlock = Entity as IMyCubeBlock; m_cubeBlock.AddUpgradeValue ("RadialPowerStrength", 1.0f); m_functionalBlock.CustomNameChanged += parseName; m_cubeBlock.OnUpgradeValuesChanged += onUpgradeValuesChanged; m_terminalBlock = Entity as IMyTerminalBlock; m_terminalBlock.AppendingCustomInfo += appendCustomInfo; } void onUpgradeValuesChanged () { m_currentMaxPower = m_cubeBlock.UpgradeValues["RadialPowerStrength"] * m_maxPower; parseName ((IMyTerminalBlock)m_functionalBlock); m_info.strength = m_currentMaxPower; } public void appendCustomInfo(IMyTerminalBlock block, StringBuilder info) { info.Clear (); info.AppendLine (" "); info.AppendLine ("-----Radial Transmitter Info-----"); info.AppendLine (" "); if (m_sender) { info.AppendLine ("(M)ode: Sender"); info.AppendLine ("(C)hannel: " + m_channel); info.AppendLine ("(P)ower Sent: " + m_currentOutput + "MW / " + m_transmittedPower + "MW"); info.AppendLine (" "); info.AppendLine ("Maximum Output: " + m_currentMaxPower.ToString("N") + "MW"); info.AppendLine ("Range (10kW threshold): " + (Math.Sqrt(m_maxRangeSquared) / 1000d).ToString("N") + "KM"); info.AppendLine ("Receivers in Range: " + m_receivers.Count); } else { info.AppendLine ("(M)ode: Receiver"); info.AppendLine ("(C)hannel: " + m_channel); info.AppendLine (" "); info.AppendLine ("Power Receiving: " + m_infoReceivingPower.ToString("N") + "MW / " + m_currentMaxPower.ToString("N") + "MW"); info.AppendLine ("Number of Sources: " + m_infoReceivers); } info.AppendLine (" "); info.AppendLine ("-----Usage-----"); info.AppendLine (" "); info.AppendLine ("To configure this Radial Transmitter as a sender you write its configuration tags that are explained below within a pair of brackets into its name."); info.AppendLine (""); info.AppendLine ("Example: Radial Power Transmitter (C:1, P:10, M:S)"); info.AppendLine (""); info.AppendLine ("C: Defines the channel to send power on. A receiver has to be set on that channel to receive power that is sent on it. It has to be a positive number."); info.AppendLine (""); info.AppendLine ("P: Defines the amount of power in MW to send on the specified channel."); info.AppendLine (""); info.AppendLine ("M: Defines the mode of the Transmitter, in this case it is set so (S)ender. If it is not a sender, it is a receiver by default."); info.AppendLine (""); info.AppendLine ("To configure this Radial Transmitter as a receiver you write its configuration tags that are explained below within a pair of brackets into its name."); info.AppendLine (""); info.AppendLine ("Example: Radial Power Transmitter (C:1)"); info.AppendLine (""); info.AppendLine ("C: Defines the channel to receive power on. It has to match with the channel your senders send on to receive their power. It has to be a positive number."); info.AppendLine (""); info.AppendLine ("(Optional) M: Defines the mode of the Transmitter. By default a Radial Transmitter is in Receiver mode, so you do not have to define it."); } public override void UpdateOnceBeforeFrame () { base.UpdateOnceBeforeFrame (); m_resourceSink = Entity.Components.Get<MyResourceSinkComponent> (); parseName ((IMyTerminalBlock)m_functionalBlock); m_info.strength = m_currentMaxPower; if(!MyAPIGateway.Multiplayer.IsServer) requestSettingsFromServer(); createUI(); m_saveInfo = new PTInfo(Entity.EntityId, m_sender, m_channel, m_transmittedPower, "R"); } public override void OnRemovedFromScene () { if (TransmissionManager.radialTransmitters.ContainsKey (m_entityId)) { TransmissionManager.radialTransmitters.Remove (m_entityId); } base.OnRemovedFromScene (); } public override void OnAddedToScene () { base.OnAddedToScene (); m_entityId = Entity.EntityId; if (Entity.InScene) { if (!TransmissionManager.radialTransmitters.ContainsKey (m_entityId)) { TransmissionManager.radialTransmitters.Add (m_entityId, m_info); } if(!TransmissionManager.totalPowerPerGrid.ContainsKey(m_functionalBlock.CubeGrid.EntityId)) { TransmissionManager.totalPowerPerGrid.Add (m_functionalBlock.CubeGrid.EntityId, 0); } } } void updatePowerInput() { if (!m_sender) { m_resourceSink.SetRequiredInputByType (m_electricityDefinition, 0); } else if (m_functionalBlock.Enabled && m_functionalBlock.IsFunctional) { m_resourceSink.SetRequiredInputByType (m_electricityDefinition, m_transmittedPower); } else { m_resourceSink.SetRequiredInputByType (m_electricityDefinition, 0); } } void requestSettingsFromServer() { byte[] message = new byte[20]; byte[] messageId = BitConverter.GetBytes(10); byte[] messageSender = BitConverter.GetBytes(MyAPIGateway.Session.Player.SteamUserId); byte[] messageEntityId = BitConverter.GetBytes(Entity.EntityId); for(int i = 0; i < 4; i++) message[i] = messageId[i]; for(int i = 0; i < 8; i++) message[i+4] = messageSender[i]; for(int i = 0; i < 8; i++) message[i+12] = messageEntityId[i]; MyAPIGateway.Multiplayer.SendMessageToServer(5910, message, true); } public override void UpdateBeforeSimulation () { base.UpdateBeforeSimulation(); if (m_functionalBlock.IsFunctional) { if (m_functionalBlock.Enabled) { m_info.enabled = true; } else { m_info.enabled = false; } } else { m_info.enabled = false; } updatePowerInput(); findReceivers (); calculateReceiverPower (); m_info.currentInput = 0; if(m_receivers.Count == 0) { m_currentOutput = 0; m_resourceSink.SetRequiredInputByType (m_electricityDefinition, 0); } m_oldTransmittedPower = m_transmittedPower; m_terminalBlock.RefreshCustomInfo (); m_infoReceivers = 0; m_infoReceivingPower = 0f; // writing newest values into the save file m_saveInfo.ChannelTarget = m_channel; m_saveInfo.Sender = m_sender; m_saveInfo.Power = m_transmittedPower; m_ticks++; } public override void UpdateAfterSimulation () { bool contains = false; if(m_ticks == 1) { foreach(var ptInfo in TransmitterLogic.transmittersSaveFile.Transmitters) { if(ptInfo.Id == Entity.EntityId) { contains = true; m_saveInfo = ptInfo; } } if(!contains) { m_saveInfo = new PTInfo(Entity.EntityId, m_sender, m_channel, m_transmittedPower, "R"); TransmitterLogic.transmittersSaveFile.Transmitters.Add(m_saveInfo); } } } public override void MarkForClose () { if (TransmissionManager.radialTransmitters.ContainsKey (m_entityId)) { TransmissionManager.radialTransmitters.Remove (m_entityId); } base.MarkForClose (); } public override void Close () { if (TransmissionManager.radialTransmitters.ContainsKey (m_entityId)) { TransmissionManager.radialTransmitters.Remove (m_entityId); } m_functionalBlock.CustomNameChanged -= parseName; m_cubeBlock.OnUpgradeValuesChanged -= onUpgradeValuesChanged; m_terminalBlock.AppendingCustomInfo -= appendCustomInfo; if(TransmitterLogic.transmittersSaveFile.Transmitters.Contains(m_saveInfo)) { TransmitterLogic.transmittersSaveFile.Transmitters.Remove(m_saveInfo); } base.Close (); } void findReceivers() { m_receivers.Clear (); if (m_functionalBlock.IsFunctional && m_functionalBlock.Enabled) { m_currentOutput = m_resourceSink.CurrentInputByType (m_electricityDefinition); float falloffMultiplier = m_falloffRange; m_maxRangeSquared = (m_currentOutput * 1000f - 10f) / m_falloffRange; foreach (var radialTransmitter in TransmissionManager.radialTransmitters) { if (radialTransmitter.Key != m_entityId) { if (m_sender) { if (m_transmittedPower != 0f) { if (radialTransmitter.Value.channel == m_channel) { if (!radialTransmitter.Value.sender) { if (radialTransmitter.Value.enabled) { float distanceSquared = (float)Vector3D.DistanceSquared (m_functionalBlock.GetPosition (), radialTransmitter.Value.functionalBlock.GetPosition ()); if(distanceSquared < m_maxRangeSquared) { float powerToTransfer = (m_currentOutput * 1000f - distanceSquared * falloffMultiplier)/1000f; if ((powerToTransfer + radialTransmitter.Value.currentInput) > radialTransmitter.Value.strength) { powerToTransfer = radialTransmitter.Value.strength - radialTransmitter.Value.currentInput; } radialTransmitter.Value.currentInput += powerToTransfer; m_receivers.Add (radialTransmitter.Value.functionalBlock, new ReceiverInfo(powerToTransfer, radialTransmitter.Value.strength)); } } } } } } } } } } void calculateReceiverPower() { foreach (var receiver in m_receivers) { if (TransmissionManager.configuration.RadialFalloff) { float powerToAdd = receiver.Value.powerToAdd / m_receivers.Count; var transmitterComponent = receiver.Key.GameLogic.GetAs<RadialPowerTransmitter>(); transmitterComponent.m_infoReceivers++; transmitterComponent.m_infoReceivingPower += powerToAdd; TransmissionManager.totalPowerPerGrid[receiver.Key.CubeGrid.EntityId] += powerToAdd; } } } float getRangeMultiplier(string subtypeName) { if(subtypeName == "LargeBlockSmallRadialPowerTransmitter") { return TransmissionManager.configuration.LargeBlockSmallRadialPowerTransmitter.RadialFalloffMultiplier; } else if(subtypeName == "SmallBlockSmallRadialPowerTransmitter") { return TransmissionManager.configuration.SmallBlockSmallRadialPowerTransmitter.RadialFalloffMultiplier; } return 1.0f; } float getMaxPower(string subtypeName) { if (TransmissionManager.configuration.UseMaximumPower) { if (subtypeName == "LargeBlockSmallRadialPowerTransmitter") { return TransmissionManager.configuration.LargeBlockSmallRadialPowerTransmitter.MaximumPower; } if (subtypeName == "SmallBlockSmallRadialPowerTransmitter") { return TransmissionManager.configuration.SmallBlockSmallRadialPowerTransmitter.MaximumPower; } } else { return float.PositiveInfinity; } return 1.0f; } void parseName(IMyTerminalBlock terminalBlock) { int settingsStart = terminalBlock.CustomName.IndexOf ("("); if (settingsStart != -1) { if(settingsStart < (terminalBlock.CustomName.Length-1)) { int start = terminalBlock.CustomName.IndexOf ("P:", settingsStart + 1); if (start != -1) { if ((start + 2) < (terminalBlock.CustomName.Length - 1)) { int end = terminalBlock.CustomName.IndexOf (',', start + 2); if (end != -1) { try { m_transmittedPower = Convert.ToSingle (terminalBlock.CustomName.Substring (start + 2, end - (start + 2))); if(m_transmittedPower > m_currentMaxPower) { m_transmittedPower = m_currentMaxPower; } } catch (Exception e) { } } else { end = terminalBlock.CustomName.IndexOf (')', start + 2); if (end != -1) { try { m_transmittedPower = Convert.ToSingle (terminalBlock.CustomName.Substring (start + 2, end - (start + 2))); if(m_transmittedPower > m_currentMaxPower) { m_transmittedPower = m_currentMaxPower; } } catch (Exception e) { } } } } } else { m_transmittedPower = 0f; } start = terminalBlock.CustomName.IndexOf ("C:", settingsStart + 1); if (start != -1) { if ((start + 2) < (terminalBlock.CustomName.Length-1)) { int end = terminalBlock.CustomName.IndexOf (',', start + 2); if (end != -1) { try { m_channel = Convert.ToUInt32 (terminalBlock.CustomName.Substring (start + 2, end - (start + 2))); m_info.channel = m_channel; } catch (Exception e) { } } else { end = terminalBlock.CustomName.IndexOf (')', start + 2); if (end != -1) { try { m_channel = Convert.ToUInt32 (terminalBlock.CustomName.Substring (start + 2, end - (start + 2))); m_info.channel = m_channel; } catch (Exception e) { } } } } } start = terminalBlock.CustomName.IndexOf ("M:", settingsStart + 1); if (start != -1) { if ((start + 2) < (terminalBlock.CustomName.Length - 1)) { int end = terminalBlock.CustomName.IndexOf (',', start + 2); if (end != -1) { try { m_sender = terminalBlock.CustomName.Substring (start + 2, end - (start + 2)) == "S"; m_info.sender = m_sender; } catch (Exception e) { } } else { end = terminalBlock.CustomName.IndexOf (')', start + 2); if (end != -1) { try { m_sender = terminalBlock.CustomName.Substring (start + 2, end - (start + 2)) == "S"; m_info.sender = m_sender; } catch (Exception e) { } } } } } else { m_sender = false; m_info.sender = m_sender; } } } } public override MyObjectBuilder_EntityBase GetObjectBuilder (bool copy = false) { return m_objectBuilder; } static void createUI() { if (m_controlsInit) return; m_controlsInit = true; MyAPIGateway.TerminalControls.CustomControlGetter -= customControlGetter; MyAPIGateway.TerminalControls.CustomControlGetter += customControlGetter; // sender/receiver switch m_controlSender = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlOnOffSwitch, IMyRefinery>("Cython.RPT.SenderReceiver"); m_controlSender.Enabled = (b) => true; m_controlSender.Visible = (b) => b.BlockDefinition.SubtypeId.Equals("LargeBlockSmallRadialPowerTransmitter") || b.BlockDefinition.SubtypeId.Equals("SmallBlockSmallRadialPowerTransmitter"); m_controlSender.Title = MyStringId.GetOrCompute("Mode"); m_controlSender.Tooltip = MyStringId.GetOrCompute("Switches this transmitters mode to Sender or Receiver"); m_controlSender.OnText = MyStringId.GetOrCompute("Send"); m_controlSender.OffText = MyStringId.GetOrCompute("Rec."); m_controlSender.Getter = (b) => b.GameLogic.GetAs<RadialPowerTransmitter>().m_sender; m_controlSender.Setter = (b, v) => { b.GameLogic.GetAs<RadialPowerTransmitter>().m_sender = v; b.GameLogic.GetAs<RadialPowerTransmitter>().m_info.sender = v; m_controlSender.UpdateVisual(); m_controlPower.UpdateVisual(); byte[] message = new byte[13]; byte[] messageId = BitConverter.GetBytes(0); byte[] entityId = BitConverter.GetBytes(b.EntityId); for(int i = 0; i < 4; i++) { message[i] = messageId[i]; } for(int i = 0; i < 8; i++) { message[i+4] = entityId[i]; } message[12] = BitConverter.GetBytes(v)[0]; MyAPIGateway.Multiplayer.SendMessageToOthers(5910, message, true); }; MyAPIGateway.TerminalControls.AddControl<IMyRefinery>(m_controlSender); // channel field m_controlChannel = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlTextbox, IMyRefinery>("Cython.RPT.Channel"); m_controlChannel.Enabled = (b) => true; m_controlChannel.Visible = (b) => b.BlockDefinition.SubtypeId.Equals("LargeBlockSmallRadialPowerTransmitter") || b.BlockDefinition.SubtypeId.Equals("SmallBlockSmallRadialPowerTransmitter"); m_controlChannel.Title = MyStringId.GetOrCompute("Channel"); m_controlChannel.Tooltip = MyStringId.GetOrCompute("Channel this transmitter is supposed to send or receive on."); m_controlChannel.Getter = (b) => (new StringBuilder()).Append(b.GameLogic.GetAs<RadialPowerTransmitter>().m_channel); m_controlChannel.Setter = (b, s) => { uint channel; if(uint.TryParse(s.ToString(), out channel)) { var RPT = b.GameLogic.GetAs<RadialPowerTransmitter>(); RPT.m_channel = channel; RPT.m_info.channel = channel; byte[] message = new byte[16]; byte[] messageId = BitConverter.GetBytes(1); byte[] entityId = BitConverter.GetBytes(b.EntityId); byte[] value = BitConverter.GetBytes(channel); for(int i = 0; i < 4; i++) { message[i] = messageId[i]; } for(int i = 0; i < 8; i++) { message[i+4] = entityId[i]; } for(int i = 0; i < 4; i++) { message[i+12] = value[i]; } MyAPIGateway.Multiplayer.SendMessageToOthers(5910, message, true); } }; MyAPIGateway.TerminalControls.AddControl<IMyRefinery>(m_controlChannel); // power field m_controlPower = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlTextbox, IMyRefinery>("Cython.RPT.Power"); m_controlPower.Enabled = (b) => b.GameLogic.GetAs<RadialPowerTransmitter>().m_sender; m_controlPower.Visible = (b) => b.BlockDefinition.SubtypeId.Equals("LargeBlockSmallRadialPowerTransmitter") || b.BlockDefinition.SubtypeId.Equals("SmallBlockSmallRadialPowerTransmitter"); m_controlPower.Title = MyStringId.GetOrCompute("Power"); m_controlPower.Tooltip = MyStringId.GetOrCompute("Maximum power this transmitter is supposed to send."); m_controlPower.Getter = (b) => (new StringBuilder()).Append(b.GameLogic.GetAs<RadialPowerTransmitter>().m_transmittedPower); m_controlPower.Setter = (b, s) => { float power; if(float.TryParse(s.ToString(), out power)) { var RPT = b.GameLogic.GetAs<RadialPowerTransmitter>(); RPT.m_transmittedPower = power; if(RPT.m_transmittedPower > RPT.m_currentMaxPower) { RPT.m_transmittedPower = RPT.m_currentMaxPower; } byte[] message = new byte[16]; byte[] messageId = BitConverter.GetBytes(2); byte[] entityId = BitConverter.GetBytes(b.EntityId); byte[] value = BitConverter.GetBytes(RPT.m_transmittedPower); for(int i = 0; i < 4; i++) { message[i] = messageId[i]; } for(int i = 0; i < 8; i++) { message[i+4] = entityId[i]; } for(int i = 0; i < 4; i++) { message[i+12] = value[i]; } MyAPIGateway.Multiplayer.SendMessageToOthers(5910, message, true); } }; MyAPIGateway.TerminalControls.AddControl<IMyRefinery>(m_controlPower); } static void customControlGetter(IMyTerminalBlock block, List<IMyTerminalControl> controls) { List<IMyTerminalControl> toRemove = new List<IMyTerminalControl>(); foreach(var control in controls) { if(block is IMyRefinery) { if(block.BlockDefinition.SubtypeName.Equals("LargeBlockSmallRadialPowerTransmitter") || block.BlockDefinition.SubtypeName.Equals("SmallBlockSmallRadialPowerTransmitter")) { if(control.Id.Equals("UseConveyor")) { toRemove.Add(control); } } } } foreach(var control in toRemove) { controls.Remove(control); } } } }
using System; using System.Drawing; #if !PocketPC || DesignTime using System.ComponentModel; #endif using System.Reflection; using System.Xml.Serialization; namespace DotSpatial.Positioning { /// <summary>Calculates intermediate colors between two other colors.</summary> /// <remarks> /// <para>This class is used to create a smooth transition from one color to another. /// After specifying a start color, end color, and number of intervals, the indexer /// will return a calculated <strong>Color</strong>. Specifying a greater number of /// intervals creates a smoother color gradient.</para> /// <para>Instances of this class are guaranteed to be thread-safe because the class /// uses thread synchronization.</para> /// <para>On the .NET Compact Framework, the alpha channel is not supported.</para> /// </remarks> /// <example> /// This example uses a <strong>ColorInterpolator</strong> to calculate ten colors /// between (and including) <strong>Blue</strong> and <strong>Red</strong> . /// <code lang="VB" title="[New Example]"> /// ' Create a New color interpolator /// Dim Interpolator As New ColorInterpolator(Color.Blue, Color.Red, 10) /// ' Output Each calculated color /// Dim i As Integer /// For i = 0 To 9 /// ' Get the Next color In the sequence /// Dim NewColor As Color = Interpolator(i) /// ' Output RGB values of this color /// Debug.Write(NewColor.R.ToString() + ",") /// Debug.Write(NewColor.G.ToString() + ",") /// Debug.WriteLine(NewColor.B.ToString()) /// Next i /// </code> /// <code lang="CS" title="[New Example]"> /// // Create a new color interpolator /// ColorInterpolator Interpolator = new ColorInterpolator(Color.Blue, Color.Red, 10); /// // Output each calculated color /// for(int i = 0; i &lt; 10; i++) /// { /// // Get the next color in the sequence /// Color NewColor = Interpolator[i]; /// // Output RGB values of this color /// Console.Write(NewColor.R.ToString() + ","); /// Console.Write(NewColor.G.ToString() + ","); /// Console.WriteLine(NewColor.B.ToString()); /// } /// </code> /// </example> #if !PocketPC || DesignTime #if Framework20 [Obfuscation(Feature = "renaming", Exclude = false, ApplyToMembers = true)] [Obfuscation(Feature = "controlflow", Exclude = true, ApplyToMembers = true)] [Obfuscation(Feature = "stringencryption", Exclude = false, ApplyToMembers = true)] #endif [TypeConverter(typeof(ExpandableObjectConverter))] [ImmutableObject(false)] [Serializable()] #endif public sealed class ColorInterpolator { #if !PocketPC private Interpolator A = new Interpolator(); #endif private Interpolator R = new Interpolator(); private Interpolator G = new Interpolator(); private Interpolator B = new Interpolator(); /// <summary>Creates a new instance.</summary> /// <param name="startColor">A <strong>Color</strong> at the start of the sequence.</param> /// <param name="endColor">A <strong>Color</strong> at the end of the sequence.</param> /// <param name="count"> /// The total number of colors in the sequence, including the start and end /// colors. /// </param> public ColorInterpolator(Color startColor, Color endColor, int count) { this.Count = count; this.StartColor = startColor; this.EndColor = endColor; } /// <summary>Returns a calculated color in the sequence.</summary> /// <value>A <strong>Color</strong> value representing a calculated color.</value> /// <example> /// This example creates a new color interpolator between blue and red, then accesses /// the sixth item in the sequence. /// <code lang="VB" title="[New Example]"> /// ' Create a New color interpolator /// Dim Interpolator As New ColorInterpolator(Color.Blue, Color.Red, 10) /// ' Access the sixth item /// Color CalculatedColor = Interpolator(5); /// </code> /// <code lang="CS" title="[New Example]"> /// // Create a New color interpolator /// ColorInterpolator Interpolator = new ColorInterpolator(Color.Blue, Color.Red, 10); /// // Access the sixth item /// Color CalculatedColor = Interpolator[5]; /// </code> /// </example> /// <param name="index"> /// An <strong>Integer</strong> between 0 and <strong>Count</strong> minus /// one. /// </param> public Color this[int index] { get { #if PocketPC return Color.FromArgb((byte)R[index], (byte)G[index], (byte)B[index]); #else return Color.FromArgb((byte)A[index], (byte)R[index], (byte)G[index], (byte)B[index]); #endif } } /// <summary> /// Controls the interpolation technique used to calculate intermediate /// colors. /// </summary> /// <value> /// An <strong>InterpolationMethod</strong> value indicating the interpolation /// technique. Default is <strong>Linear</strong>. /// </value> /// <remarks> /// This property controls the rate at which the start color transitions to the end /// color. Values other than Linear can "accelerate" and/or "decelerate" towards the end /// color. /// </remarks> public InterpolationMethod InterpolationMethod { get { return R.InterpolationMethod; } set { #if !PocketPC A.InterpolationMethod = value; #endif R.InterpolationMethod = value; G.InterpolationMethod = value; B.InterpolationMethod = value; } } /// <summary>Controls the first color in the sequence.</summary> /// <value> /// A <strong>Color</strong> object representing the first color in the /// sequence. /// </value> /// <remarks>Changing this property causes the entire sequence to be recalculated.</remarks> /// <example> /// This example changes the start color from Green to Orange. /// </example> public Color StartColor { get { #if PocketPC return Color.FromArgb((byte)R.Minimum, (byte)G.Minimum, (byte)B.Minimum); #else return Color.FromArgb((byte)A.Minimum, (byte)R.Minimum, (byte)G.Minimum, (byte)B.Minimum); #endif } set { #if !PocketPC A.Minimum = value.A; #endif R.Minimum = value.R; G.Minimum = value.G; B.Minimum = value.B; } } /// <value> /// A <strong>Color</strong> object representing the last color in the /// sequence. /// </value> /// <summary>Controls the last color in the sequence.</summary> /// <remarks>Changing this property causes the entire sequence to be recalculated.</remarks> public Color EndColor { get { #if PocketPC return Color.FromArgb((byte)R.Maximum, (byte)G.Maximum, (byte)B.Maximum); #else return Color.FromArgb((byte)A.Maximum, (byte)R.Maximum, (byte)G.Maximum, (byte)B.Maximum); #endif } set { #if !PocketPC A.Maximum = value.A; #endif R.Maximum = value.R; G.Maximum = value.G; B.Maximum = value.B; } } /// <summary>Controls the number of colors in the sequence.</summary> /// <remarks>Changing this property causes the entire sequence to be recalculated.</remarks> /// <value> /// An <strong>Integer</strong> indicating the total number of colors, including the /// start and end colors. /// </value> public int Count { get { return R.Count; } set { #if !PocketPC A.Count = value; #endif R.Count = value; G.Count = value; B.Count = value; } } } }
using System; using System.Collections.Generic; namespace NRules.RuleModel.Builders { /// <summary> /// Type of group element. /// </summary> public enum GroupType { /// <summary> /// Logical AND. /// </summary> And = 0, /// <summary> /// Logical OR. /// </summary> Or = 1, } /// <summary> /// Builder to compose a group element. /// </summary> public class GroupBuilder : RuleElementBuilder, IBuilder<GroupElement> { private readonly List<IBuilder<RuleElement>> _nestedBuilders = new(); private GroupType _groupType; /// <summary> /// Initializes a new instance of the <see cref="GroupBuilder"/>. /// </summary> public GroupBuilder() { } /// <summary> /// Sets type of the group element. /// </summary> /// <param name="groupType">Group type to set.</param> public void GroupType(GroupType groupType) { _groupType = groupType; } /// <summary> /// Adds a pattern to the group element. /// </summary> /// <param name="element">Element to add.</param> public void Pattern(PatternElement element) { var builder = BuilderAdapter.Create(element); _nestedBuilders.Add(builder); } /// <summary> /// Adds a pattern builder to the group element. /// </summary> /// <param name="builder">Element builder to add.</param> public void Pattern(PatternBuilder builder) { _nestedBuilders.Add(builder); } /// <summary> /// Creates a pattern builder that builds a pattern as part of the current group element. /// </summary> /// <param name="type">Pattern type.</param> /// <param name="name">Pattern name (optional).</param> /// <returns>Pattern builder.</returns> public PatternBuilder Pattern(Type type, string name = null) { var declaration = Element.Declaration(type, DeclarationName(name)); return Pattern(declaration); } /// <summary> /// Creates a pattern builder that builds a pattern as part of the current group element. /// </summary> /// <param name="declaration">Pattern declaration.</param> /// <returns>Pattern builder.</returns> public PatternBuilder Pattern(Declaration declaration) { var builder = new PatternBuilder(declaration); _nestedBuilders.Add(builder); return builder; } /// <summary> /// Adds a nested group to this group element. /// </summary> /// <param name="element">Element to add.</param> public void Group(GroupElement element) { var builder = BuilderAdapter.Create(element); _nestedBuilders.Add(builder); } /// <summary> /// Adds a nested group builder to this group element. /// </summary> /// <param name="builder">Element builder to add.</param> public void Group(GroupBuilder builder) { _nestedBuilders.Add(builder); } /// <summary> /// Creates a group builder that builds a group as part of the current group element. /// </summary> /// <param name="groupType">Group type.</param> /// <returns>Group builder.</returns> public GroupBuilder Group(GroupType groupType) { var builder = new GroupBuilder(); builder.GroupType(groupType); _nestedBuilders.Add(builder); return builder; } /// <summary> /// Adds an existential element to the group element. /// </summary> /// <param name="element">Element to add.</param> public void Exists(ExistsElement element) { var builder = BuilderAdapter.Create(element); _nestedBuilders.Add(builder); } /// <summary> /// Adds an existential element builder to the group element. /// </summary> /// <param name="builder">Element builder to add.</param> public void Exists(ExistsBuilder builder) { _nestedBuilders.Add(builder); } /// <summary> /// Creates a builder for an existential element as part of the current group element. /// </summary> /// <returns>Existential builder.</returns> public ExistsBuilder Exists() { var builder = new ExistsBuilder(); _nestedBuilders.Add(builder); return builder; } /// <summary> /// Adds a negative existential element to the group element. /// </summary> /// <param name="element">Element to add.</param> public void Not(NotElement element) { var builder = BuilderAdapter.Create(element); _nestedBuilders.Add(builder); } /// <summary> /// Adds a negative existential element builder to the group element. /// </summary> /// <param name="builder">Element builder to add.</param> public void Not(NotBuilder builder) { _nestedBuilders.Add(builder); } /// <summary> /// Creates a builder for a negative existential element as part of the current group element. /// </summary> /// <returns>Negative existential builder.</returns> public NotBuilder Not() { var builder = new NotBuilder(); _nestedBuilders.Add(builder); return builder; } /// <summary> /// Adds a forall element to the group element. /// </summary> /// <param name="element">Element to add.</param> public void ForAll(ForAllElement element) { var builder = BuilderAdapter.Create(element); _nestedBuilders.Add(builder); } /// <summary> /// Adds a forall element builder to the group element. /// </summary> /// <param name="builder">Element builder to add.</param> public void ForAll(ForAllBuilder builder) { _nestedBuilders.Add(builder); } /// <summary> /// Creates a builder for a forall element as part of the current group element. /// </summary> /// <returns>Forall builder.</returns> public ForAllBuilder ForAll() { var builder = new ForAllBuilder(); _nestedBuilders.Add(builder); return builder; } GroupElement IBuilder<GroupElement>.Build() { var childElements = new List<RuleElement>(); foreach (var builder in _nestedBuilders) { var childElement = builder.Build(); childElements.Add(childElement); } var groupElement = Element.Group(_groupType, childElements); return groupElement; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Transactions { using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Transactions; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Transactions facade. /// </summary> internal class TransactionsImpl : PlatformTarget, ITransactions { /** */ private const int OpCacheConfigParameters = 1; /** */ private const int OpMetrics = 2; /** */ private readonly TransactionConcurrency _dfltConcurrency; /** */ private readonly TransactionIsolation _dfltIsolation; /** */ private readonly TimeSpan _dfltTimeout; /** */ private readonly Guid _localNodeId; /// <summary> /// Initializes a new instance of the <see cref="TransactionsImpl" /> class. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="localNodeId">Local node id.</param> public TransactionsImpl(IUnmanagedTarget target, Marshaller marsh, Guid localNodeId) : base(target, marsh) { _localNodeId = localNodeId; TransactionConcurrency concurrency = default(TransactionConcurrency); TransactionIsolation isolation = default(TransactionIsolation); TimeSpan timeout = default(TimeSpan); DoInOp(OpCacheConfigParameters, stream => { var reader = marsh.StartUnmarshal(stream).GetRawReader(); concurrency = (TransactionConcurrency) reader.ReadInt(); isolation = (TransactionIsolation) reader.ReadInt(); timeout = reader.ReadLongAsTimespan(); }); _dfltConcurrency = concurrency; _dfltIsolation = isolation; _dfltTimeout = timeout; } /** <inheritDoc /> */ public ITransaction TxStart() { return TxStart(_dfltConcurrency, _dfltIsolation); } /** <inheritDoc /> */ public ITransaction TxStart(TransactionConcurrency concurrency, TransactionIsolation isolation) { return TxStart(concurrency, isolation, _dfltTimeout, 0); } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public ITransaction TxStart(TransactionConcurrency concurrency, TransactionIsolation isolation, TimeSpan timeout, int txSize) { var id = UU.TransactionsStart(Target, (int)concurrency, (int)isolation, (long)timeout.TotalMilliseconds, txSize); var innerTx = new TransactionImpl(id, this, concurrency, isolation, timeout, _localNodeId); return new Transaction(innerTx); } /** <inheritDoc /> */ public ITransaction Tx { get { return TransactionImpl.Current; } } /** <inheritDoc /> */ public ITransactionMetrics GetMetrics() { return DoInOp(OpMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new TransactionMetricsImpl(reader); }); } /** <inheritDoc /> */ public void ResetMetrics() { UU.TransactionsResetMetrics(Target); } /// <summary> /// Commit transaction. /// </summary> /// <param name="tx">Transaction.</param> /// <returns>Final transaction state.</returns> internal TransactionState TxCommit(TransactionImpl tx) { return (TransactionState) UU.TransactionsCommit(Target, tx.Id); } /// <summary> /// Rollback transaction. /// </summary> /// <param name="tx">Transaction.</param> /// <returns>Final transaction state.</returns> internal TransactionState TxRollback(TransactionImpl tx) { return (TransactionState)UU.TransactionsRollback(Target, tx.Id); } /// <summary> /// Close transaction. /// </summary> /// <param name="tx">Transaction.</param> /// <returns>Final transaction state.</returns> internal int TxClose(TransactionImpl tx) { return UU.TransactionsClose(Target, tx.Id); } /// <summary> /// Get transaction current state. /// </summary> /// <param name="tx">Transaction.</param> /// <returns>Transaction current state.</returns> internal TransactionState TxState(TransactionImpl tx) { return GetTransactionState(UU.TransactionsState(Target, tx.Id)); } /// <summary> /// Set transaction rollback-only flag. /// </summary> /// <param name="tx">Transaction.</param> /// <returns><c>true</c> if the flag was set.</returns> internal bool TxSetRollbackOnly(TransactionImpl tx) { return UU.TransactionsSetRollbackOnly(Target, tx.Id); } /// <summary> /// Commits tx in async mode. /// </summary> internal Task CommitAsync(TransactionImpl tx) { return GetFuture<object>((futId, futTyp) => UU.TransactionsCommitAsync(Target, tx.Id, futId)).Task; } /// <summary> /// Rolls tx back in async mode. /// </summary> internal Task RollbackAsync(TransactionImpl tx) { return GetFuture<object>((futId, futTyp) => UU.TransactionsRollbackAsync(Target, tx.Id, futId)).Task; } /// <summary> /// Gets the state of the transaction from int. /// </summary> private static TransactionState GetTransactionState(int state) { return (TransactionState)state; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2017 FUJIWARA, Yusuke // // 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 -- 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; #if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // FEATURE_MPCONTRACT namespace MsgPack { partial struct Timestamp { private const int SecondsPerMinutes = 60; private const int SecondsPerHours = SecondsPerMinutes * 60; private const int SecondsPerDay = SecondsPerHours * 24; private const int DaysPerYear = 365; private const int DaysPer4Years = DaysPerYear * 4 + 1; private const int DaysPer100Years = DaysPer4Years * 25 - 1; private const int DaysPer400Years = DaysPer100Years * 4 + 1; private const int DayOfWeekOfEpoc = 4; // day of week of 1970-01-01 private static readonly uint[] DaysToMonth365 = new uint[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly uint[] DaysToMonth366 = new uint[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static readonly uint[] ReversedDaysToMonth365 = new uint[] { 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 334, 365 }; private static readonly uint[] ReversedDaysToMonth366 = new uint[] { 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 335, 366 }; /// <summary> /// Gets a unix epoch seconds part of msgpack timestamp spec. /// </summary> /// <value>A value of unix epoch seconds part of msgpack timestamp spec. This value may be negative, BC dates, and dates after 9999-12-31.</value> /// <remarks> /// If you want to get "nanosecond" portion of this instance, use <see cref="Nanosecond"/> property instead. /// </remarks> public long UnixEpochSecondsPart { get { return this.unixEpochSeconds; } } /// <summary> /// Gets a nanoseconds part of msgpack timestamp spec. /// </summary> /// <value>A value of nanoseconds part of msgpack timestamp spec. This value will be between 0 to 999,999,999.</value> /// <remarks> /// If you want to get "nanosecond" portion of this instance, use <see cref="Nanosecond"/> property instead. /// </remarks> public int NanosecondsPart { get { return unchecked( ( int )this.nanoseconds ); } } /// <summary> /// Gets an year portion of this instance. /// </summary> /// <value>An year portion of this instance. The value may be zero or negative, and may exceed 9,999.</value> public long Year { get { long year; int month, day, dayOfYear; this.GetDatePart( out year, out month, out day, out dayOfYear ); return year; } } /// <summary> /// Gets a month portion of this instance. /// </summary> /// <value>A month portion of this instance. The value will be between 1 and 12.</value> public int Month { get { long year; int month, day, dayOfYear; this.GetDatePart( out year, out month, out day, out dayOfYear ); return month; } } /// <summary> /// Gets a day portion of this instance. /// </summary> /// <value>A day portion of this instance. The value will be valid day of <see cref="Month"/>.</value> public int Day { get { long year; int month, day, dayOfYear; this.GetDatePart( out year, out month, out day, out dayOfYear ); return day; } } /// <summary> /// Gets an hour portion of this instance. /// </summary> /// <value>An hour portion of this instance. The value will be between 0 and 59.</value> public int Hour { get { long remainder; var hour = DivRem( this.unixEpochSeconds, SecondsPerHours, out remainder ) % 24; unchecked { return ( int )( this.unixEpochSeconds < 0 ? hour + ( remainder != 0 ? 23 : ( hour < 0 ? 24 : 0 ) ) : hour ); } } } /// <summary> /// Gets a minute portion of this instance. /// </summary> /// <value>A minute portion of this instance. The value will be between 0 and 59.</value> public int Minute { get { long remainder; var minute = DivRem( this.unixEpochSeconds, SecondsPerMinutes, out remainder ) % 60; unchecked { return ( int )( this.unixEpochSeconds < 0 ? minute + ( remainder != 0 ? 59 : ( minute < 0 ? 60 : 0 ) ) : minute ); } } } /// <summary> /// Gets a second portion of this instance. /// </summary> /// <value>A second portion of this instance. The value will be between 0 and 59.</value> public int Second { get { var second = unchecked( ( int )( this.unixEpochSeconds % 60 ) ); return second < 0 ? second + 60 : second; } } /// <summary> /// Gets a millisecond portion of this instance. /// </summary> /// <value>A millisecond portion of this instance. The value will be between 0 and 999.</value> public int Millisecond { get { return this.NanosecondsPart / ( 1000 * 1000 ); } } /// <summary> /// Gets a microsecond portion of this instance. /// </summary> /// <value>A microsecond portion of this instance. The value will be between 0 and 999.</value> public int Microsecond { get { return ( this.NanosecondsPart / 1000 ) % 1000; } } /// <summary> /// Gets a nanosecond portion of this instance. /// </summary> /// <value>A nanosecond portion of this instance. The value will be between 0 and 999.</value> /// <remarks> /// If you want to get "nanoseconds" part of msgpack timestamp spec, use <see cref="NanosecondsPart"/> property instead. /// </remarks> public int Nanosecond { get { return ( this.NanosecondsPart ) % 1000; } } /// <summary> /// Gets a <see cref="Timestamp"/> which only contains date portion of this instance. /// </summary> /// <value>A <see cref="Timestamp"/> which only contains date portion of this instance.</value> public Timestamp Date { get { return new Timestamp( this.unixEpochSeconds - this.TimeOfDay.unixEpochSeconds, 0 ); } } /// <summary> /// Gets a <see cref="Timestamp"/> which only contains time portion of this instance. /// </summary> /// <value>A <see cref="Timestamp"/> which only contains time portion of this instance.</value> public Timestamp TimeOfDay { get { return new Timestamp( this.unixEpochSeconds < 0 ? ( this.unixEpochSeconds % SecondsPerDay + SecondsPerDay ) : ( this.unixEpochSeconds % SecondsPerDay ), this.NanosecondsPart ); } } /// <summary> /// Gets a <see cref="DayOfWeek"/> of this day. /// </summary> /// <value>A <see cref="DayOfWeek"/> of this day.</value> public DayOfWeek DayOfWeek { get { long remainder; var divided = unchecked( ( int )DivRem( this.unixEpochSeconds, SecondsPerDay, out remainder )); return ( DayOfWeek )( ( ( this.unixEpochSeconds < 0 ? ( ( divided + ( ( int )remainder < 0 ? -1 : 0 ) ) % 7 + 7 ) : divided ) + DayOfWeekOfEpoc ) % 7 ); } } /// <summary> /// Gets a number of days of this year. /// </summary> /// <value>A number of days of this year.</value> public int DayOfYear { get { long year; int month, day, dayOfYear; this.GetDatePart( out year, out month, out day, out dayOfYear ); return dayOfYear; } } /// <summary> /// Gets a value which indicates <see cref="Year"/> is leap year or not. /// </summary> /// <value> /// <c>true</c>, when <see cref="Year"/> is leap year; otherwise, <c>false</c>. /// </value> /// <remarks> /// A <see cref="Year"/> of B.C.1 is <c>0</c>, so if the <see cref="Year"/> is <c>0</c> then it is leap year. /// In addition, B.C.3 (the <see cref="Year"/> is <c>-3</c>) is leap year, B.C.99 (the <see cref="Year"/> is <c>-100</c>) is not, /// and B.C.399 (the <see cref="Year"/> is <c>-400</c>) is leap year. /// </remarks> public bool IsLeapYear { get { return IsLeapYearInternal( this.Year ); } } internal static bool IsLeapYearInternal( long year ) { // Note: This algorithm assumes that BC uses leap year same as AD and B.C.1 is 0. // This algorithm avoids remainder operation as possible. return !( year % 4 != 0 || ( year % 100 == 0 && year % 400 != 0 ) ); } internal static int GetLastDay( int month, bool isLeapYear ) { var lastDay = LastDays[ month ]; if ( month == 2 ) { lastDay = isLeapYear ? 29 : 28; } return lastDay; } private void GetDatePart( out long year, out int month, out int day, out int dayOfYear ) { if ( this.unixEpochSeconds < -UnixEpochInSeconds ) { this.GetDatePartBC( out year, out month, out day, out dayOfYear ); } else { this.GetDatePartAD( out year, out month, out day, out dayOfYear ); } } private void GetDatePartAD( out long year, out int month, out int day, out int dayOfYear ) { Contract.Assert( this.unixEpochSeconds >= -UnixEpochInSeconds, this.unixEpochSeconds + " > " + ( -UnixEpochInSeconds ) ); // From coreclr System.DateTime.cs // https://github.com/dotnet/coreclr/blob/0825741447c14a6a70c60b7c429e16f95214e74e/src/mscorlib/shared/System/DateTime.cs#L863 // First, use 0001-01-01 as epoch to simplify leap year calculation var seconds = unchecked( ( ulong )( this.unixEpochSeconds + UnixEpochInSeconds ) ); // number of days since 0001-01-01 var daysOffset = seconds / SecondsPerDay; // number of whole 400-year periods since 0001-01-01 var numberOf400Years = daysOffset / DaysPer400Years; // day number within 400-year period var daysIn400Years = unchecked( ( uint )( daysOffset - numberOf400Years * DaysPer400Years ) ); // number of whole 100-year periods within 400-year period var numberOf100Years = daysIn400Years / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if ( numberOf100Years == 4 ) { numberOf100Years = 3; } // day number within 100-year period var daysIn100Years = daysIn400Years - numberOf100Years * DaysPer100Years; // number of whole 4-year periods within 100-year period var numberOf4years = daysIn100Years / DaysPer4Years; // day number within 4-year period var daysIn4Years = daysIn100Years - numberOf4years * DaysPer4Years; // number of whole years within 4-year period var numberOf1Year = daysIn4Years / DaysPerYear; // Last year has an extra day, so decrement result if 4 if ( numberOf1Year == 4 ) { numberOf1Year = 3; } // compute year year = unchecked( ( long )( numberOf400Years * 400 + numberOf100Years * 100 + numberOf4years * 4 + numberOf1Year + 1 ) ); // day number within year var daysInYear = daysIn4Years - numberOf1Year * DaysPerYear; dayOfYear = unchecked( ( int )( daysInYear + 1 ) ); // Leap year calculation var isLeapYear = numberOf1Year == 3 && ( numberOf4years != 24 || numberOf100Years == 3 ); var days = isLeapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month var numberOfMonth = ( daysInYear >> 5 ) + 1; #if DEBUG Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); #endif // DEBUG // m = 1-based month number while ( daysInYear >= days[ numberOfMonth ] ) { numberOfMonth++; #if DEBUG Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); #endif // DEBUG } // compute month and day month = unchecked( ( int )numberOfMonth ); day = unchecked( ( int )( daysInYear - days[ numberOfMonth - 1 ] + 1 ) ); } private void GetDatePartBC( out long year, out int month, out int day, out int dayOfYear ) { Contract.Assert( this.unixEpochSeconds < -UnixEpochInSeconds, this.unixEpochSeconds + " > " + ( -UnixEpochInSeconds ) ); // From coreclr System.DateTime.cs // https://github.com/dotnet/coreclr/blob/0825741447c14a6a70c60b7c429e16f95214e74e/src/mscorlib/shared/System/DateTime.cs#L863 // First, use 0001-01-01 as epoch to simplify leap year calculation. // This method calculate negative offset from 0001-01-01. var seconds = unchecked( ( ulong )( ( this.unixEpochSeconds + UnixEpochInSeconds ) * -1 ) ); // number of days since 0001-01-01 var daysOffset = seconds / SecondsPerDay; daysOffset += ( seconds % SecondsPerDay ) > 0 ? 1u : 0u; // number of whole 400-year periods since 0001-01-01 var numberOf400Years = ( daysOffset - 1 ) / DaysPer400Years; // decrement offset 1 to adjust 1 to 12-31 // day number within 400-year period var daysIn400Years = unchecked( ( uint )( daysOffset - numberOf400Years * DaysPer400Years ) ); // number of whole 100-year periods within 400-year period var numberOf100Years = daysIn400Years <= ( DaysPer100Years + 1 ) // 1st year is leap year (power of 400) ? 0 : ( ( daysIn400Years - 2 ) / DaysPer100Years ); // decrement 1st leap year day and offset 1 to adjust 1 to 12-31 // day number within 100-year period var daysIn100Years = daysIn400Years - numberOf100Years * DaysPer100Years; // number of whole 4-year periods within 100-year period var numberOf4years = daysIn100Years == 0 ? 0 : ( ( daysIn100Years - 1 ) / DaysPer4Years ); // decrement offset 1 to adjust 1 to 12-31 // day number within 4-year period var daysIn4Years = daysIn100Years - numberOf4years * DaysPer4Years; // number of whole years within 4-year period var numberOf1Year = daysIn4Years <= ( DaysPerYear + ( numberOf4years != 0 ? 1 : 0 ) ) // is leap year in 4 years range? ? 0 : ( ( daysIn4Years - 2 ) / DaysPerYear ); // decrement 1st leap year day and offset 1 to adjust 1 to 12-31 // compute year, note that 0001 -1 is 0000 (=B.C.1) year = -unchecked( ( long )( numberOf400Years * 400 + numberOf100Years * 100 + numberOf4years * 4 + numberOf1Year ) ); var isLeapYear = numberOf1Year == 0 && ( numberOf4years != 0 || numberOf100Years == 0 ); // day number within year var daysInYear = isLeapYear ? ( 366 - daysIn4Years ) : ( 365 - ( daysIn4Years - 1 - numberOf1Year * DaysPerYear ) ); dayOfYear = unchecked( ( int )( daysInYear + 1 ) ); // Leap year calculation var days = isLeapYear ? DaysToMonth366 : DaysToMonth365; // All months have more than 32 days, so n >> 5 is a good conservative // estimate for the month var numberOfMonth = ( daysInYear >> 5 ) + 1; #if DEBUG Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); #endif // DEBUG // m = 1-based month number while ( daysInYear >= days[ numberOfMonth ] ) { numberOfMonth++; #if DEBUG Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); #endif // DEBUG } // compute month and day month = unchecked( ( int )numberOfMonth ); day = unchecked( ( int )( daysInYear - days[ numberOfMonth - 1 ] + 1 ) ); } /// <summary> /// Gets a <see cref="Timestamp"/> instance which represents today on UTC. The result only contains date part. /// </summary> /// <value>A <see cref="Timestamp"/> instance which represents today on UTC. The result only contains date part.</value> /// <remarks> /// For underlying system API restriction, this method cannot work after 9999-12-31 in current implementation. /// </remarks> public static Timestamp Today { get { return UtcNow.Date; } } /// <summary> /// Gets a <see cref="Timestamp"/> instance of now on UTC. /// </summary> /// <value>A <see cref="Timestamp"/> instance of now on UTC.</value> /// <remarks> /// <para> /// For underlying system API restriction, this method cannot work after 9999-12-31T23:59:59.999999900 in current implementation. /// </para> /// <para> /// In addition, the precision of the returned <see cref="Timestamp"/> will be restricted by underlying platform. /// In current implementation, the precision is 100 nano-seconds at most, and about 1/60 milliseconds on normal Windows platform. /// </para> /// </remarks> public static Timestamp UtcNow { get { var now = DateTimeOffset.UtcNow; return new Timestamp( #if !NET35 && !NET45 && !NETSTANDARD1_1 && !UNITY && !SILVERLIGHT now.ToUnixTimeSeconds(), #else // !NET35 && !NET45 && !NETSTANDARD1_1 && !UNITY && !SILVERLIGHT ( now.Ticks / TimeSpan.TicksPerSecond ) - UnixEpochInSeconds, #endif // !NET35 && !NET45 && !NETSTANDARD1_1 && !UNITY && !SILVERLIGHT unchecked( ( int )( now.Ticks % 10000000 * 100 ) ) ); } } } }
#region Apache License // // 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. // #endregion using System; using System.IO; using System.Collections; using Ctrip.Filter; using Ctrip.Util; using Ctrip.Layout; using Ctrip.Core; namespace Ctrip.Appender { /// <summary> /// Abstract base class implementation of <see cref="IAppender"/>. /// </summary> /// <remarks> /// <para> /// This class provides the code for common functionality, such /// as support for threshold filtering and support for general filters. /// </para> /// <para> /// Appenders can also implement the <see cref="IOptionHandler"/> interface. Therefore /// they would require that the <see cref="M:IOptionHandler.ActivateOptions()"/> method /// be called after the appenders properties have been configured. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public abstract class AppenderSkeleton : IAppender, IBulkAppender, IOptionHandler { #region Protected Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para>Empty default constructor</para> /// </remarks> protected AppenderSkeleton() { m_errorHandler = new OnlyOnceErrorHandler(this.GetType().Name); } #endregion Protected Instance Constructors #region Finalizer /// <summary> /// Finalizes this appender by calling the implementation's /// <see cref="Close"/> method. /// </summary> /// <remarks> /// <para> /// If this appender has not been closed then the <c>Finalize</c> method /// will call <see cref="Close"/>. /// </para> /// </remarks> ~AppenderSkeleton() { // An appender might be closed then garbage collected. // There is no point in closing twice. if (!m_closed) { LogLog.Debug(declaringType, "Finalizing appender named ["+m_name+"]."); Close(); } } #endregion Finalizer #region Public Instance Properties /// <summary> /// Gets or sets the threshold <see cref="Level"/> of this appender. /// </summary> /// <value> /// The threshold <see cref="Level"/> of the appender. /// </value> /// <remarks> /// <para> /// All log events with lower level than the threshold level are ignored /// by the appender. /// </para> /// <para> /// In configuration files this option is specified by setting the /// value of the <see cref="Threshold"/> option to a level /// string, such as "DEBUG", "INFO" and so on. /// </para> /// </remarks> public Level Threshold { get { return m_threshold; } set { m_threshold = value; } } /// <summary> /// Gets or sets the <see cref="IErrorHandler"/> for this appender. /// </summary> /// <value>The <see cref="IErrorHandler"/> of the appender</value> /// <remarks> /// <para> /// The <see cref="AppenderSkeleton"/> provides a default /// implementation for the <see cref="ErrorHandler"/> property. /// </para> /// </remarks> virtual public IErrorHandler ErrorHandler { get { return this.m_errorHandler; } set { lock(this) { if (value == null) { // We do not throw exception here since the cause is probably a // bad config file. LogLog.Warn(declaringType, "You have tried to set a null error-handler."); } else { m_errorHandler = value; } } } } /// <summary> /// The filter chain. /// </summary> /// <value>The head of the filter chain filter chain.</value> /// <remarks> /// <para> /// Returns the head Filter. The Filters are organized in a linked list /// and so all Filters on this Appender are available through the result. /// </para> /// </remarks> virtual public IFilter FilterHead { get { return m_headFilter; } } /// <summary> /// Gets or sets the <see cref="ILayout"/> for this appender. /// </summary> /// <value>The layout of the appender.</value> /// <remarks> /// <para> /// See <see cref="RequiresLayout"/> for more information. /// </para> /// </remarks> /// <seealso cref="RequiresLayout"/> virtual public ILayout Layout { get { return m_layout; } set { m_layout = value; } } #endregion #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> virtual public void ActivateOptions() { } #endregion Implementation of IOptionHandler #region Implementation of IAppender /// <summary> /// Gets or sets the name of this appender. /// </summary> /// <value>The name of the appender.</value> /// <remarks> /// <para> /// The name uniquely identifies the appender. /// </para> /// </remarks> public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// Closes the appender and release resources. /// </summary> /// <remarks> /// <para> /// Release any resources allocated within the appender such as file handles, /// network connections, etc. /// </para> /// <para> /// It is a programming error to append to a closed appender. /// </para> /// <para> /// This method cannot be overridden by subclasses. This method /// delegates the closing of the appender to the <see cref="OnClose"/> /// method which must be overridden in the subclass. /// </para> /// </remarks> public void Close() { // This lock prevents the appender being closed while it is still appending lock(this) { if (!m_closed) { OnClose(); m_closed = true; } } } /// <summary> /// Performs threshold checks and invokes filters before /// delegating actual logging to the subclasses specific /// <see cref="M:Append(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// This method cannot be overridden by derived classes. A /// derived class should override the <see cref="M:Append(LoggingEvent)"/> method /// which is called by this method. /// </para> /// <para> /// The implementation of this method is as follows: /// </para> /// <para> /// <list type="bullet"> /// <item> /// <description> /// Checks that the severity of the <paramref name="loggingEvent"/> /// is greater than or equal to the <see cref="Threshold"/> of this /// appender.</description> /// </item> /// <item> /// <description> /// Checks that the <see cref="IFilter"/> chain accepts the /// <paramref name="loggingEvent"/>. /// </description> /// </item> /// <item> /// <description> /// Calls <see cref="M:PreAppendCheck()"/> and checks that /// it returns <c>true</c>.</description> /// </item> /// </list> /// </para> /// <para> /// If all of the above steps succeed then the <paramref name="loggingEvent"/> /// will be passed to the abstract <see cref="M:Append(LoggingEvent)"/> method. /// </para> /// </remarks> public void DoAppend(LoggingEvent loggingEvent) { // This lock is absolutely critical for correct formatting // of the message in a multi-threaded environment. Without // this, the message may be broken up into elements from // multiple thread contexts (like get the wrong thread ID). lock(this) { if (m_closed) { ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"]."); return; } // prevent re-entry if (m_recursiveGuard) { return; } try { m_recursiveGuard = true; if (FilterEvent(loggingEvent) && PreAppendCheck()) { this.Append(loggingEvent); } } catch(Exception ex) { ErrorHandler.Error("Failed in DoAppend", ex); } #if !MONO && !NET_2_0 // on .NET 2.0 (and higher) and Mono (all profiles), // exceptions that do not derive from System.Exception will be // wrapped in a RuntimeWrappedException by the runtime, and as // such will be catched by the catch clause above catch { // Catch handler for non System.Exception types ErrorHandler.Error("Failed in DoAppend (unknown exception)"); } #endif finally { m_recursiveGuard = false; } } } #endregion Implementation of IAppender #region Implementation of IBulkAppender /// <summary> /// Performs threshold checks and invokes filters before /// delegating actual logging to the subclasses specific /// <see cref="M:Append(LoggingEvent[])"/> method. /// </summary> /// <param name="loggingEvents">The array of events to log.</param> /// <remarks> /// <para> /// This method cannot be overridden by derived classes. A /// derived class should override the <see cref="M:Append(LoggingEvent[])"/> method /// which is called by this method. /// </para> /// <para> /// The implementation of this method is as follows: /// </para> /// <para> /// <list type="bullet"> /// <item> /// <description> /// Checks that the severity of the <paramref name="loggingEvents"/> /// is greater than or equal to the <see cref="Threshold"/> of this /// appender.</description> /// </item> /// <item> /// <description> /// Checks that the <see cref="IFilter"/> chain accepts the /// <paramref name="loggingEvents"/>. /// </description> /// </item> /// <item> /// <description> /// Calls <see cref="M:PreAppendCheck()"/> and checks that /// it returns <c>true</c>.</description> /// </item> /// </list> /// </para> /// <para> /// If all of the above steps succeed then the <paramref name="loggingEvents"/> /// will be passed to the <see cref="M:Append(LoggingEvent[])"/> method. /// </para> /// </remarks> public void DoAppend(LoggingEvent[] loggingEvents) { // This lock is absolutely critical for correct formatting // of the message in a multi-threaded environment. Without // this, the message may be broken up into elements from // multiple thread contexts (like get the wrong thread ID). lock(this) { if (m_closed) { ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"]."); return; } // prevent re-entry if (m_recursiveGuard) { return; } try { m_recursiveGuard = true; ArrayList filteredEvents = new ArrayList(loggingEvents.Length); foreach(LoggingEvent loggingEvent in loggingEvents) { if (FilterEvent(loggingEvent)) { filteredEvents.Add(loggingEvent); } } if (filteredEvents.Count > 0 && PreAppendCheck()) { this.Append((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); } } catch(Exception ex) { ErrorHandler.Error("Failed in Bulk DoAppend", ex); } #if !MONO && !NET_2_0 // on .NET 2.0 (and higher) and Mono (all profiles), // exceptions that do not derive from System.Exception will be // wrapped in a RuntimeWrappedException by the runtime, and as // such will be catched by the catch clause above catch { // Catch handler for non System.Exception types ErrorHandler.Error("Failed in Bulk DoAppend (unknown exception)"); } #endif finally { m_recursiveGuard = false; } } } #endregion Implementation of IBulkAppender /// <summary> /// Test if the logging event should we output by this appender /// </summary> /// <param name="loggingEvent">the event to test</param> /// <returns><c>true</c> if the event should be output, <c>false</c> if the event should be ignored</returns> /// <remarks> /// <para> /// This method checks the logging event against the threshold level set /// on this appender and also against the filters specified on this /// appender. /// </para> /// <para> /// The implementation of this method is as follows: /// </para> /// <para> /// <list type="bullet"> /// <item> /// <description> /// Checks that the severity of the <paramref name="loggingEvent"/> /// is greater than or equal to the <see cref="Threshold"/> of this /// appender.</description> /// </item> /// <item> /// <description> /// Checks that the <see cref="IFilter"/> chain accepts the /// <paramref name="loggingEvent"/>. /// </description> /// </item> /// </list> /// </para> /// </remarks> virtual protected bool FilterEvent(LoggingEvent loggingEvent) { if (!IsAsSevereAsThreshold(loggingEvent.Level)) { return false; } IFilter f = this.FilterHead; while(f != null) { switch(f.Decide(loggingEvent)) { case FilterDecision.Deny: return false; // Return without appending case FilterDecision.Accept: f = null; // Break out of the loop break; case FilterDecision.Neutral: f = f.Next; // Move to next filter break; } } return true; } #region Public Instance Methods /// <summary> /// Adds a filter to the end of the filter chain. /// </summary> /// <param name="filter">the filter to add to this appender</param> /// <remarks> /// <para> /// The Filters are organized in a linked list. /// </para> /// <para> /// Setting this property causes the new filter to be pushed onto the /// back of the filter chain. /// </para> /// </remarks> virtual public void AddFilter(IFilter filter) { if (filter == null) { throw new ArgumentNullException("filter param must not be null"); } if (m_headFilter == null) { m_headFilter = m_tailFilter = filter; } else { m_tailFilter.Next = filter; m_tailFilter = filter; } } /// <summary> /// Clears the filter list for this appender. /// </summary> /// <remarks> /// <para> /// Clears the filter list for this appender. /// </para> /// </remarks> virtual public void ClearFilters() { m_headFilter = m_tailFilter = null; } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Checks if the message level is below this appender's threshold. /// </summary> /// <param name="level"><see cref="Level"/> to test against.</param> /// <remarks> /// <para> /// If there is no threshold set, then the return value is always <c>true</c>. /// </para> /// </remarks> /// <returns> /// <c>true</c> if the <paramref name="level"/> meets the <see cref="Threshold"/> /// requirements of this appender. /// </returns> virtual protected bool IsAsSevereAsThreshold(Level level) { return ((m_threshold == null) || level >= m_threshold); } /// <summary> /// Is called when the appender is closed. Derived classes should override /// this method if resources need to be released. /// </summary> /// <remarks> /// <para> /// Releases any resources allocated within the appender such as file handles, /// network connections, etc. /// </para> /// <para> /// It is a programming error to append to a closed appender. /// </para> /// </remarks> virtual protected void OnClose() { // Do nothing by default } /// <summary> /// Subclasses of <see cref="AppenderSkeleton"/> should implement this method /// to perform actual logging. /// </summary> /// <param name="loggingEvent">The event to append.</param> /// <remarks> /// <para> /// A subclass must implement this method to perform /// logging of the <paramref name="loggingEvent"/>. /// </para> /// <para>This method will be called by <see cref="M:DoAppend(LoggingEvent)"/> /// if all the conditions listed for that method are met. /// </para> /// <para> /// To restrict the logging of events in the appender /// override the <see cref="M:PreAppendCheck()"/> method. /// </para> /// </remarks> abstract protected void Append(LoggingEvent loggingEvent); /// <summary> /// Append a bulk array of logging events. /// </summary> /// <param name="loggingEvents">the array of logging events</param> /// <remarks> /// <para> /// This base class implementation calls the <see cref="M:Append(LoggingEvent)"/> /// method for each element in the bulk array. /// </para> /// <para> /// A sub class that can better process a bulk array of events should /// override this method in addition to <see cref="M:Append(LoggingEvent)"/>. /// </para> /// </remarks> virtual protected void Append(LoggingEvent[] loggingEvents) { foreach(LoggingEvent loggingEvent in loggingEvents) { Append(loggingEvent); } } /// <summary> /// Called before <see cref="M:Append(LoggingEvent)"/> as a precondition. /// </summary> /// <remarks> /// <para> /// This method is called by <see cref="M:DoAppend(LoggingEvent)"/> /// before the call to the abstract <see cref="M:Append(LoggingEvent)"/> method. /// </para> /// <para> /// This method can be overridden in a subclass to extend the checks /// made before the event is passed to the <see cref="M:Append(LoggingEvent)"/> method. /// </para> /// <para> /// A subclass should ensure that they delegate this call to /// this base class if it is overridden. /// </para> /// </remarks> /// <returns><c>true</c> if the call to <see cref="M:Append(LoggingEvent)"/> should proceed.</returns> virtual protected bool PreAppendCheck() { if ((m_layout == null) && RequiresLayout) { ErrorHandler.Error("AppenderSkeleton: No layout set for the appender named ["+m_name+"]."); return false; } return true; } /// <summary> /// Renders the <see cref="LoggingEvent"/> to a string. /// </summary> /// <param name="loggingEvent">The event to render.</param> /// <returns>The event rendered as a string.</returns> /// <remarks> /// <para> /// Helper method to render a <see cref="LoggingEvent"/> to /// a string. This appender must have a <see cref="Layout"/> /// set to render the <paramref name="loggingEvent"/> to /// a string. /// </para> /// <para>If there is exception data in the logging event and /// the layout does not process the exception, this method /// will append the exception text to the rendered string. /// </para> /// <para> /// Where possible use the alternative version of this method /// <see cref="M:RenderLoggingEvent(TextWriter,LoggingEvent)"/>. /// That method streams the rendering onto an existing Writer /// which can give better performance if the caller already has /// a <see cref="TextWriter"/> open and ready for writing. /// </para> /// </remarks> protected string RenderLoggingEvent(LoggingEvent loggingEvent) { // Create the render writer on first use if (m_renderWriter == null) { m_renderWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); } lock (m_renderWriter) { // Reset the writer so we can reuse it m_renderWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); RenderLoggingEvent(m_renderWriter, loggingEvent); return m_renderWriter.ToString(); } } /// <summary> /// Renders the <see cref="LoggingEvent"/> to a string. /// </summary> /// <param name="loggingEvent">The event to render.</param> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Helper method to render a <see cref="LoggingEvent"/> to /// a string. This appender must have a <see cref="Layout"/> /// set to render the <paramref name="loggingEvent"/> to /// a string. /// </para> /// <para>If there is exception data in the logging event and /// the layout does not process the exception, this method /// will append the exception text to the rendered string. /// </para> /// <para> /// Use this method in preference to <see cref="M:RenderLoggingEvent(LoggingEvent)"/> /// where possible. If, however, the caller needs to render the event /// to a string then <see cref="M:RenderLoggingEvent(LoggingEvent)"/> does /// provide an efficient mechanism for doing so. /// </para> /// </remarks> protected void RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent) { if (m_layout == null) { throw new InvalidOperationException("A layout must be set"); } if (m_layout.IgnoresException) { string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // render the event and the exception m_layout.Format(writer, loggingEvent); writer.WriteLine(exceptionStr); } else { // there is no exception to render m_layout.Format(writer, loggingEvent); } } else { // The layout will render the exception m_layout.Format(writer, loggingEvent); } } /// <summary> /// Tests if this appender requires a <see cref="Layout"/> to be set. /// </summary> /// <remarks> /// <para> /// In the rather exceptional case, where the appender /// implementation admits a layout but can also work without it, /// then the appender should return <c>true</c>. /// </para> /// <para> /// This default implementation always returns <c>false</c>. /// </para> /// </remarks> /// <returns> /// <c>true</c> if the appender requires a layout object, otherwise <c>false</c>. /// </returns> virtual protected bool RequiresLayout { get { return false; } } #endregion #region Private Instance Fields /// <summary> /// The layout of this appender. /// </summary> /// <remarks> /// See <see cref="Layout"/> for more information. /// </remarks> private ILayout m_layout; /// <summary> /// The name of this appender. /// </summary> /// <remarks> /// See <see cref="Name"/> for more information. /// </remarks> private string m_name; /// <summary> /// The level threshold of this appender. /// </summary> /// <remarks> /// <para> /// There is no level threshold filtering by default. /// </para> /// <para> /// See <see cref="Threshold"/> for more information. /// </para> /// </remarks> private Level m_threshold; /// <summary> /// It is assumed and enforced that errorHandler is never null. /// </summary> /// <remarks> /// <para> /// It is assumed and enforced that errorHandler is never null. /// </para> /// <para> /// See <see cref="ErrorHandler"/> for more information. /// </para> /// </remarks> private IErrorHandler m_errorHandler; /// <summary> /// The first filter in the filter chain. /// </summary> /// <remarks> /// <para> /// Set to <c>null</c> initially. /// </para> /// <para> /// See <see cref="IFilter"/> for more information. /// </para> /// </remarks> private IFilter m_headFilter; /// <summary> /// The last filter in the filter chain. /// </summary> /// <remarks> /// See <see cref="IFilter"/> for more information. /// </remarks> private IFilter m_tailFilter; /// <summary> /// Flag indicating if this appender is closed. /// </summary> /// <remarks> /// See <see cref="Close"/> for more information. /// </remarks> private bool m_closed = false; /// <summary> /// The guard prevents an appender from repeatedly calling its own DoAppend method /// </summary> private bool m_recursiveGuard = false; /// <summary> /// StringWriter used to render events /// </summary> private ReusableStringWriter m_renderWriter = null; #endregion Private Instance Fields #region Constants /// <summary> /// Initial buffer size /// </summary> private const int c_renderBufferSize = 256; /// <summary> /// Maximum buffer size before it is recycled /// </summary> private const int c_renderBufferMaxCapacity = 1024; #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the AppenderSkeleton class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(AppenderSkeleton); #endregion Private Static Fields } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing; using System.Diagnostics; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Localization; namespace OpenLiveWriter.HtmlEditor { /// <summary> /// Summary description for HtmlSourceEditorFindTextForm. /// </summary> public class HtmlSourceEditorFindTextForm : ApplicationDialog { private System.Windows.Forms.Label labelFindWhat; private System.Windows.Forms.TextBox textBoxFindWhat; private System.Windows.Forms.Button buttonFindNext; private System.Windows.Forms.Button buttonClose; private System.Windows.Forms.GroupBox groupBoxDirection; private System.Windows.Forms.RadioButton radioButtonUp; private System.Windows.Forms.RadioButton radioButtonDown; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private TextBox _targetTextBox ; public HtmlSourceEditorFindTextForm(TextBox targetTextBox) { // // Required for Windows Form Designer support // InitializeComponent(); this.labelFindWhat.Text = Res.Get(StringId.FindWhatLabel); this.buttonFindNext.Text = Res.Get(StringId.FindNextButton); this.buttonClose.Text = Res.Get(StringId.CloseButton); this.groupBoxDirection.Text = Res.Get(StringId.FindDirection); this.radioButtonDown.Text = Res.Get(StringId.FindDirectionDown); this.radioButtonUp.Text = Res.Get(StringId.FindDirectionUp); this.Text = Res.Get(StringId.FindTitle); buttonFindNext.Enabled = false; // save referenced to text text box _targetTextBox = targetTextBox ; // initialize search text textBoxFindWhat.Text = targetTextBox.SelectedText ; // initialize direction radioButtonDown.Checked = targetTextBox.SelectionStart < (targetTextBox.Text.Length/2) ; } protected override void OnLoad(EventArgs e) { base.OnLoad (e); int distance = radioButtonDown.Left - radioButtonUp.Right; DisplayHelper.AutoFitSystemRadioButton(radioButtonDown, 0, int.MaxValue); DisplayHelper.AutoFitSystemRadioButton(radioButtonUp, 0, int.MaxValue); radioButtonDown.Left = radioButtonUp.Right + distance; using (new AutoGrow(this, AnchorStyles.Bottom | AnchorStyles.Right, false)) { int oldTop = radioButtonDown.Top; radioButtonDown.Top = radioButtonUp.Top = Res.DefaultFont.Height + 3; groupBoxDirection.Height += Math.Max(radioButtonDown.Top - oldTop,0); LayoutHelper.EqualizeButtonWidthsVert(AnchorStyles.Left, buttonClose.Width, int.MaxValue, buttonFindNext, buttonClose); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } private void textBoxFindWhat_TextChanged(object sender, System.EventArgs e) { buttonFindNext.Enabled = textBoxFindWhat.Text.Length != 0 ; } private void buttonFindNext_Click(object sender, System.EventArgs e) { try { string findText = textBoxFindWhat.Text.Trim(); int nextOccurance = -1 ; if ( radioButtonDown.Checked ) { nextOccurance = _targetTextBox.Text.IndexOf( findText, _targetTextBox.SelectionStart + _targetTextBox.SelectionLength); } else { int start = _targetTextBox.SelectionStart; if (_targetTextBox.SelectionLength == 1 && start > 0) start = start - 1; nextOccurance = _targetTextBox.Text.LastIndexOf(findText, start); } if ( nextOccurance != -1 ) { _targetTextBox.Select(nextOccurance, findText.Length) ; _targetTextBox.ScrollToCaret(); } else { DisplayMessage.Show(MessageId.FinishedSearchingDocument, this ); } } catch(Exception ex) { UnexpectedErrorMessage.Show(this, ex); } } #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.labelFindWhat = new System.Windows.Forms.Label(); this.textBoxFindWhat = new System.Windows.Forms.TextBox(); this.buttonFindNext = new System.Windows.Forms.Button(); this.buttonClose = new System.Windows.Forms.Button(); this.groupBoxDirection = new System.Windows.Forms.GroupBox(); this.radioButtonDown = new System.Windows.Forms.RadioButton(); this.radioButtonUp = new System.Windows.Forms.RadioButton(); this.groupBoxDirection.SuspendLayout(); this.SuspendLayout(); // // labelFindWhat // this.labelFindWhat.AutoSize = true; this.labelFindWhat.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelFindWhat.Location = new System.Drawing.Point(10, 7); this.labelFindWhat.Name = "labelFindWhat"; this.labelFindWhat.Size = new System.Drawing.Size(62, 15); this.labelFindWhat.TabIndex = 0; this.labelFindWhat.Text = "Fi&nd what:"; // // textBoxFindWhat // this.textBoxFindWhat.Location = new System.Drawing.Point(10, 25); this.textBoxFindWhat.Name = "textBoxFindWhat"; this.textBoxFindWhat.Size = new System.Drawing.Size(297, 23); this.textBoxFindWhat.TabIndex = 1; this.textBoxFindWhat.TextChanged += new System.EventHandler(this.textBoxFindWhat_TextChanged); // // buttonFindNext // this.buttonFindNext.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonFindNext.Location = new System.Drawing.Point(317, 25); this.buttonFindNext.Name = "buttonFindNext"; this.buttonFindNext.Size = new System.Drawing.Size(90, 26); this.buttonFindNext.TabIndex = 2; this.buttonFindNext.Text = "&Find Next"; this.buttonFindNext.Click += new System.EventHandler(this.buttonFindNext_Click); // // buttonClose // this.buttonClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonClose.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonClose.Location = new System.Drawing.Point(317, 57); this.buttonClose.Name = "buttonClose"; this.buttonClose.Size = new System.Drawing.Size(90, 26); this.buttonClose.TabIndex = 3; this.buttonClose.Text = "Close"; // // groupBoxDirection // this.groupBoxDirection.Controls.Add(this.radioButtonDown); this.groupBoxDirection.Controls.Add(this.radioButtonUp); this.groupBoxDirection.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxDirection.Location = new System.Drawing.Point(10, 53); this.groupBoxDirection.Name = "groupBoxDirection"; this.groupBoxDirection.Size = new System.Drawing.Size(297, 45); this.groupBoxDirection.TabIndex = 4; this.groupBoxDirection.TabStop = false; this.groupBoxDirection.Text = "Direction"; // // radioButtonDown // this.radioButtonDown.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonDown.Location = new System.Drawing.Point(86, 15); this.radioButtonDown.Name = "radioButtonDown"; this.radioButtonDown.Size = new System.Drawing.Size(64, 27); this.radioButtonDown.TabIndex = 1; this.radioButtonDown.Text = "&Down"; // // radioButtonUp // this.radioButtonUp.Checked = true; this.radioButtonUp.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonUp.Location = new System.Drawing.Point(19, 15); this.radioButtonUp.Name = "radioButtonUp"; this.radioButtonUp.Size = new System.Drawing.Size(58, 27); this.radioButtonUp.TabIndex = 0; this.radioButtonUp.TabStop = true; this.radioButtonUp.Text = "&Up"; // // HtmlSourceEditorFindTextForm // this.AcceptButton = this.buttonFindNext; this.CancelButton = this.buttonClose; this.ClientSize = new System.Drawing.Size(416, 105); this.Controls.Add(this.groupBoxDirection); this.Controls.Add(this.buttonClose); this.Controls.Add(this.buttonFindNext); this.Controls.Add(this.textBoxFindWhat); this.Controls.Add(this.labelFindWhat); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "HtmlSourceEditorFindTextForm"; this.Text = "Find"; this.groupBoxDirection.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Globalization; using TestLibrary; /// <summary> /// UInt32.ToString(System.IFormatProvider) /// </summary> public class UInt32ToString3 { public static int Main() { UInt32ToString3 ui32ts3 = new UInt32ToString3(); TestLibrary.TestFramework.BeginTestCase("UInt32ToString3"); if (ui32ts3.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); if (Utilities.IsWindows) { // retVal = NegTest1() && retVal; // Disabled until neutral cultures are available } return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: UInt32 minValue ToString"); try { UInt32 uintA = UInt32.MinValue; CultureInfo myculture = new CultureInfo("en-us"); String strA = uintA.ToString(myculture.NumberFormat); if (strA != GlobLocHelper.OSUInt32ToString(uintA, new CultureInfo("en-US"))) { TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: UInt32 maxValue ToString 1"); try { UInt32 uintA = UInt32.MaxValue; CultureInfo myculture = new CultureInfo("en-us"); String strA = uintA.ToString(myculture); if (strA != GlobLocHelper.OSUInt32ToString(uintA, new CultureInfo("en-US"))) { TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: UInt32 maxValue ToString 2"); try { UInt32 uintA = UInt32.MaxValue; CultureInfo myculture = new CultureInfo("fr-FR"); String strA = uintA.ToString(myculture); if (strA != GlobLocHelper.OSUInt32ToString(uintA, new CultureInfo("fr-FR"))) { TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: UInt32 maxValue ToString but provider is null"); try { UInt32 uintA = UInt32.MaxValue; CultureInfo myculture = null; String strA = uintA.ToString(myculture); if (strA != GlobLocHelper.OSUInt32ToString(uintA, (CultureInfo)null)) { TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: random UInt32 ToString"); try { UInt32 uintA = 2147483648; CultureInfo myculture = new CultureInfo("en-us"); String strA = uintA.ToString(myculture); if (strA != GlobLocHelper.OSUInt32ToString(uintA, new CultureInfo("en-US"))) { TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The provider parameter is Invalid"); try { UInt32 uintA = (UInt32)(this.GetInt32(1, Int32.MaxValue) + this.GetInt32(0, Int32.MaxValue)); CultureInfo myculture = new CultureInfo("pl"); String strA = uintA.ToString(myculture); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N001", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region ForTestObject private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
// ========================================================== // FreeImage 3 .NET wrapper // Original FreeImage 3 functions and .NET compatible derived functions // // Design and implementation by // - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net) // - Carsten Klein (cklein05@users.sourceforge.net) // // Contributors: // - David Boland (davidboland@vodafone.ie) // // Main reference : MSDN Knowlede Base // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== // ========================================================== // CVS // $Revision: 1.4 $ // $Date: 2009/02/20 07:40:53 $ // $Id: RGBQUAD.cs,v 1.4 2009/02/20 07:40:53 cklein05 Exp $ // ========================================================== using System; using System.Drawing; using System.Runtime.InteropServices; namespace FreeImageAPI { /// <summary> /// The <b>RGBQUAD</b> structure describes a color consisting of relative /// intensities of red, green, blue and alpha value. Each single color /// component consumes 8 bits and so, takes values in the range from 0 to 255. /// </summary> /// <remarks> /// <para> /// The <b>RGBQUAD</b> structure provides access to an underlying Win32 <b>RGBQUAD</b> /// structure. To determine the alpha, red, green or blue component of a color, /// use the rgbReserved, rgbRed, rgbGreen or rgbBlue fields, respectively. /// </para> /// <para>For easy integration of the underlying structure into the .NET framework, /// the <b>RGBQUAD</b> structure implements implicit conversion operators to /// convert the represented color to and from the <see cref="System.Drawing.Color"/> /// type. This makes the <see cref="System.Drawing.Color"/> type a real replacement /// for the <b>RGBQUAD</b> structure and my be used in all situations which require /// an <b>RGBQUAD</b> type. /// </para> /// <para> /// Each color component rgbReserved, rgbRed, rgbGreen or rgbBlue of <b>RGBQUAD</b> /// is translated into it's corresponding color component A, R, G or B of /// <see cref="System.Drawing.Color"/> by an one-to-one manner and vice versa. /// </para> /// <para> /// <b>Conversion from System.Drawing.Color to RGBQUAD</b> /// </para> /// <c>RGBQUAD.component = Color.component</c> /// <para> /// <b>Conversion from RGBQUAD to System.Drawing.Color</b> /// </para> /// <c>Color.component = RGBQUAD.component</c> /// <para> /// The same conversion is also applied when the <see cref="FreeImageAPI.RGBQUAD.Color"/> /// property or the <see cref="FreeImageAPI.RGBQUAD(System.Drawing.Color)"/> constructor /// is invoked. /// </para> /// </remarks> /// <example> /// The following code example demonstrates the various conversions between the /// <b>RGBQUAD</b> structure and the <see cref="System.Drawing.Color"/> structure. /// <code> /// RGBQUAD rgbq; /// // Initialize the structure using a native .NET Color structure. /// rgbq = new RGBQUAD(Color.Indigo); /// // Initialize the structure using the implicit operator. /// rgbq = Color.DarkSeaGreen; /// // Convert the RGBQUAD instance into a native .NET Color /// // using its implicit operator. /// Color color = rgbq; /// // Using the structure's Color property for converting it /// // into a native .NET Color. /// Color another = rgbq.Color; /// </code> /// </example> [Serializable, StructLayout(LayoutKind.Explicit)] public struct RGBQUAD : IComparable, IComparable<RGBQUAD>, IEquatable<RGBQUAD> { /// <summary> /// The blue color component. /// </summary> [FieldOffset(0)] public byte rgbBlue; /// <summary> /// The green color component. /// </summary> [FieldOffset(1)] public byte rgbGreen; /// <summary> /// The red color component. /// </summary> [FieldOffset(2)] public byte rgbRed; /// <summary> /// The alpha color component. /// </summary> [FieldOffset(3)] public byte rgbReserved; /// <summary> /// The color's value. /// </summary> [FieldOffset(0)] public uint uintValue; /// <summary> /// Initializes a new instance based on the specified <see cref="System.Drawing.Color"/>. /// </summary> /// <param name="color"><see cref="System.Drawing.Color"/> to initialize with.</param> public RGBQUAD(Color color) { uintValue = 0u; rgbBlue = color.B; rgbGreen = color.G; rgbRed = color.R; rgbReserved = color.A; } /// <summary> /// Tests whether two specified <see cref="RGBQUAD"/> structures are equivalent. /// </summary> /// <param name="left">The <see cref="RGBQUAD"/> that is to the left of the equality operator.</param> /// <param name="right">The <see cref="RGBQUAD"/> that is to the right of the equality operator.</param> /// <returns> /// <b>true</b> if the two <see cref="RGBQUAD"/> structures are equal; otherwise, <b>false</b>. /// </returns> public static bool operator ==(RGBQUAD left, RGBQUAD right) { return (left.uintValue == right.uintValue); } /// <summary> /// Tests whether two specified <see cref="RGBQUAD"/> structures are different. /// </summary> /// <param name="left">The <see cref="RGBQUAD"/> that is to the left of the inequality operator.</param> /// <param name="right">The <see cref="RGBQUAD"/> that is to the right of the inequality operator.</param> /// <returns> /// <b>true</b> if the two <see cref="RGBQUAD"/> structures are different; otherwise, <b>false</b>. /// </returns> public static bool operator !=(RGBQUAD left, RGBQUAD right) { return (left.uintValue != right.uintValue); } /// <summary> /// Converts the value of a <see cref="System.Drawing.Color"/> structure to a <see cref="RGBQUAD"/> structure. /// </summary> /// <param name="value">A <see cref="System.Drawing.Color"/> structure.</param> /// <returns>A new instance of <see cref="RGBQUAD"/> initialized to <paramref name="value"/>.</returns> public static implicit operator RGBQUAD(Color value) { return new RGBQUAD(value); } /// <summary> /// Converts the value of a <see cref="RGBQUAD"/> structure to a Color structure. /// </summary> /// <param name="value">A <see cref="RGBQUAD"/> structure.</param> /// <returns>A new instance of <see cref="System.Drawing.Color"/> initialized to <paramref name="value"/>.</returns> public static implicit operator Color(RGBQUAD value) { return value.Color; } /// <summary> /// Converts the value of an <see cref="UInt32"/> structure to a <see cref="RGBQUAD"/> structure. /// </summary> /// <param name="value">An <see cref="UInt32"/> structure.</param> /// <returns>A new instance of <see cref="RGBQUAD"/> initialized to <paramref name="value"/>.</returns> public static implicit operator RGBQUAD(uint value) { RGBQUAD result = new RGBQUAD(); result.uintValue = value; return result; } /// <summary> /// Converts the value of a <see cref="RGBQUAD"/> structure to an <see cref="UInt32"/> structure. /// </summary> /// <param name="value">A <see cref="RGBQUAD"/> structure.</param> /// <returns>A new instance of <see cref="RGBQUAD"/> initialized to <paramref name="value"/>.</returns> public static implicit operator uint(RGBQUAD value) { return value.uintValue; } /// <summary> /// Gets or sets the <see cref="System.Drawing.Color"/> of the structure. /// </summary> public Color Color { get { return Color.FromArgb( rgbReserved, rgbRed, rgbGreen, rgbBlue); } set { rgbRed = value.R; rgbGreen = value.G; rgbBlue = value.B; rgbReserved = value.A; } } /// <summary> /// Converts an array of <see cref="Color"/> into an array of /// <see cref="RGBQUAD"/>. /// </summary> /// <param name="array">The array to convert.</param> /// <returns>An array of <see cref="RGBQUAD"/>.</returns> public static RGBQUAD[] ToRGBQUAD(Color[] array) { if (array == null) return null; RGBQUAD[] result = new RGBQUAD[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = array[i]; } return result; } /// <summary> /// Converts an array of <see cref="RGBQUAD"/> into an array of /// <see cref="Color"/>. /// </summary> /// <param name="array">The array to convert.</param> /// <returns>An array of <see cref="RGBQUAD"/>.</returns> public static Color[] ToColor(RGBQUAD[] array) { if (array == null) return null; Color[] result = new Color[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = array[i].Color; } return result; } /// <summary> /// Compares this instance with a specified <see cref="Object"/>. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>A 32-bit signed integer indicating the lexical relationship between the two comparands.</returns> /// <exception cref="ArgumentException"><paramref name="obj"/> is not a <see cref="RGBQUAD"/>.</exception> public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is RGBQUAD)) { throw new ArgumentException("obj"); } return CompareTo((RGBQUAD)obj); } /// <summary> /// Compares this instance with a specified <see cref="RGBQUAD"/> object. /// </summary> /// <param name="other">A <see cref="RGBQUAD"/> to compare.</param> /// <returns>A signed number indicating the relative values of this instance /// and <paramref name="other"/>.</returns> public int CompareTo(RGBQUAD other) { return this.Color.ToArgb().CompareTo(other.Color.ToArgb()); } /// <summary> /// Tests whether the specified object is a <see cref="RGBQUAD"/> structure /// and is equivalent to this <see cref="RGBQUAD"/> structure. /// </summary> /// <param name="obj">The object to test.</param> /// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="RGBQUAD"/> structure /// equivalent to this <see cref="RGBQUAD"/> structure; otherwise, <b>false</b>.</returns> public override bool Equals(object obj) { return ((obj is RGBQUAD) && (this == ((RGBQUAD)obj))); } /// <summary> /// Tests whether the specified <see cref="RGBQUAD"/> structure is equivalent to this <see cref="RGBQUAD"/> structure. /// </summary> /// <param name="other">A <see cref="RGBQUAD"/> structure to compare to this instance.</param> /// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="RGBQUAD"/> structure /// equivalent to this <see cref="RGBQUAD"/> structure; otherwise, <b>false</b>.</returns> public bool Equals(RGBQUAD other) { return (this == other); } /// <summary> /// Returns a hash code for this <see cref="RGBQUAD"/> structure. /// </summary> /// <returns>An integer value that specifies the hash code for this <see cref="RGBQUAD"/>.</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Converts the numeric value of the <see cref="RGBQUAD"/> object /// to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance.</returns> public override string ToString() { return FreeImage.ColorToString(Color); } } }
// // Pop3Stream.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2014 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Threading; using Buffer = System.Buffer; #if NETFX_CORE using Windows.Storage.Streams; using Windows.Networking.Sockets; using Socket = Windows.Networking.Sockets.StreamSocket; #else using System.Net.Security; using System.Net.Sockets; #endif using MimeKit.IO; namespace MailKit.Net.Pop3 { /// <summary> /// An enumeration of the possible POP3 streaming modes. /// </summary> /// <remarks> /// Normal operation is done in the <see cref="Pop3StreamMode.Line"/> mode, /// but when retrieving messages (via RETR) or headers (via TOP), the /// <see cref="Pop3StreamMode.Data"/> mode should be used. /// </remarks> enum Pop3StreamMode { /// <summary> /// Reads 1 line at a time. /// </summary> Line, /// <summary> /// Reads data in chunks, ignoring line state. /// </summary> Data } /// <summary> /// A stream for communicating with a POP3 server. /// </summary> /// <remarks> /// A stream capable of reading data line-by-line (<see cref="Pop3StreamMode.Line"/>) /// or by raw byte streams (<see cref="Pop3StreamMode.Data"/>). /// </remarks> class Pop3Stream : Stream, ICancellableStream { const int ReadAheadSize = 128; const int BlockSize = 4096; const int PadSize = 4; // I/O buffering readonly byte[] input = new byte[ReadAheadSize + BlockSize + PadSize]; const int inputStart = ReadAheadSize; readonly byte[] output = new byte[BlockSize]; int outputIndex; readonly IProtocolLogger logger; int inputIndex = ReadAheadSize; int inputEnd = ReadAheadSize; Pop3StreamMode mode; bool disposed; bool midline; /// <summary> /// Initializes a new instance of the <see cref="MailKit.Net.Pop3.Pop3Stream"/> class. /// </summary> /// <param name="source">The underlying network stream.</param> /// <param name="socket">The underlying network socket.</param> /// <param name="protocolLogger">The protocol logger.</param> public Pop3Stream (Stream source, Socket socket, IProtocolLogger protocolLogger) { logger = protocolLogger; IsConnected = true; Stream = source; Socket = socket; } /// <summary> /// Gets or sets the underlying network stream. /// </summary> /// <value>The underlying network stream.</value> public Stream Stream { get; internal set; } /// <summary> /// Gets the underlying network socket. /// </summary> /// <value>The underlying network socket.</value> public Socket Socket { get; private set; } /// <summary> /// Gets or sets the mode used for reading. /// </summary> /// <value>The mode.</value> public Pop3StreamMode Mode { get { return mode; } set { IsEndOfData = false; mode = value; } } /// <summary> /// Gets whether or not the stream is connected. /// </summary> /// <value><c>true</c> if the stream is connected; otherwise, <c>false</c>.</value> public bool IsConnected { get; private set; } /// <summary> /// Gets whether or not the end of the raw data has been reached in <see cref="Pop3StreamMode.Data"/> mode. /// </summary> /// <remarks> /// When reading the resonse to a command such as RETR, the end of the data is marked by line matching ".\r\n". /// </remarks> /// <value><c>true</c> if the end of the data has been reached; otherwise, <c>false</c>.</value> public bool IsEndOfData { get; private set; } /// <summary> /// Gets whether the stream supports reading. /// </summary> /// <value><c>true</c> if the stream supports reading; otherwise, <c>false</c>.</value> public override bool CanRead { get { return Stream.CanRead; } } /// <summary> /// Gets whether the stream supports writing. /// </summary> /// <value><c>true</c> if the stream supports writing; otherwise, <c>false</c>.</value> public override bool CanWrite { get { return Stream.CanWrite; } } /// <summary> /// Gets whether the stream supports seeking. /// </summary> /// <value><c>true</c> if the stream supports seeking; otherwise, <c>false</c>.</value> public override bool CanSeek { get { return false; } } /// <summary> /// Gets whether the stream supports I/O timeouts. /// </summary> /// <value><c>true</c> if the stream supports I/O timeouts; otherwise, <c>false</c>.</value> public override bool CanTimeout { get { return Stream.CanTimeout; } } /// <summary> /// Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. /// </summary> /// <returns>A value, in miliseconds, that determines how long the stream will attempt to read before timing out.</returns> /// <value>The read timeout.</value> public override int ReadTimeout { get { return Stream.ReadTimeout; } set { Stream.ReadTimeout = value; } } /// <summary> /// Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. /// </summary> /// <returns>A value, in miliseconds, that determines how long the stream will attempt to write before timing out.</returns> /// <value>The write timeout.</value> public override int WriteTimeout { get { return Stream.WriteTimeout; } set { Stream.WriteTimeout = value; } } /// <summary> /// Gets or sets the position within the current stream. /// </summary> /// <returns>The current position within the stream.</returns> /// <value>The position of the stream.</value> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support seeking. /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> public override long Position { get { return Stream.Position; } set { Stream.Position = value; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> /// <returns>A long value representing the length of the stream in bytes.</returns> /// <value>The length of the stream.</value> /// <exception cref="System.NotSupportedException"> /// The stream does not support seeking. /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> public override long Length { get { return Stream.Length; } } void Poll (SelectMode mode, CancellationToken cancellationToken) { #if NETFX_CORE cancellationToken.ThrowIfCancellationRequested (); #else if (!cancellationToken.CanBeCanceled) return; if (Socket != null) { do { cancellationToken.ThrowIfCancellationRequested (); } while (!Socket.Poll (1000, mode)); } else { cancellationToken.ThrowIfCancellationRequested (); } #endif } unsafe int ReadAhead (CancellationToken cancellationToken) { int left = inputEnd - inputIndex; int start = inputStart; int end = inputEnd; int nread; if (left > 0) { int index = inputIndex; // attempt to align the end of the remaining input with ReadAheadSize if (index >= start) { start -= Math.Min (ReadAheadSize, left); Buffer.BlockCopy (input, index, input, start, left); index = start; start += left; } else if (index > 0) { int shift = Math.Min (index, end - start); Buffer.BlockCopy (input, index, input, index - shift, left); index -= shift; start = index + left; } else { // we can't shift... start = end; } inputIndex = index; inputEnd = start; } else { inputIndex = start; inputEnd = start; } end = input.Length - PadSize; try { #if !NETFX_CORE bool buffered = Stream is SslStream; #else bool buffered = true; #endif if (buffered) { cancellationToken.ThrowIfCancellationRequested (); nread = Stream.Read (input, start, end - start); } else { Poll (SelectMode.SelectRead, cancellationToken); nread = Stream.Read (input, start, end - start); } if (nread > 0) { logger.LogServer (input, start, nread); inputEnd += nread; } else { throw new Pop3ProtocolException ("The POP3 server has unexpectedly disconnected."); } } catch { IsConnected = false; throw; } return inputEnd - inputIndex; } static void ValidateArguments (byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException ("offset"); if (count < 0 || offset + count > buffer.Length) throw new ArgumentOutOfRangeException ("count"); } void CheckDisposed () { if (disposed) throw new ObjectDisposedException ("Pop3Stream"); } unsafe bool NeedInput (byte* inptr, int inputLeft) { if (inputLeft == 2 && *inptr == (byte) '.' && *(inptr + 1) == '\n') return false; return true; } /// <summary> /// Reads a sequence of bytes from the stream and advances the position /// within the stream by the number of bytes read. /// </summary> /// <remarks> /// Reads a sequence of bytes from the stream and advances the position /// within the stream by the number of bytes read. /// </remarks> /// <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> /// <param name="buffer">The buffer.</param> /// <param name="offset">The buffer offset.</param> /// <param name="count">The number of bytes to read.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para> /// <para>-or-</para> /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting /// at the specified <paramref name="offset"/>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.InvalidOperationException"> /// The stream is in line mode (see <see cref="Pop3StreamMode.Line"/>). /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public int Read (byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckDisposed (); ValidateArguments (buffer, offset, count); if (Mode != Pop3StreamMode.Data) throw new InvalidOperationException (); if (IsEndOfData || count == 0) return 0; unsafe { fixed (byte* inbuf = input, bufptr = buffer) { byte* outbuf = bufptr + offset; byte* outend = outbuf + count; byte* outptr = outbuf; byte* inptr, inend; int inputLeft; do { inputLeft = inputEnd - inputIndex; inptr = inbuf + inputIndex; // we need at least 3 bytes: ".\r\n" if (inputLeft < 3 && (midline || NeedInput (inptr, inputLeft))) { if (outptr > outbuf) break; ReadAhead (cancellationToken); inptr = inbuf + inputIndex; } inend = inbuf + inputEnd; *inend = (byte) '\n'; while (inptr < inend) { if (midline) { // read until end-of-line while (outptr < outend && *inptr != (byte) '\n') *outptr++ = *inptr++; if (inptr == inend || outptr == outend) break; *outptr++ = *inptr++; midline = false; } if (inptr == inend) break; if (*inptr == (byte) '.') { inputLeft = (int) (inend - inptr); if (inputLeft >= 3 && *(inptr + 1) == (byte) '\r' && *(inptr + 2) == (byte) '\n') { IsEndOfData = true; midline = false; inptr += 3; break; } if (inputLeft >= 2 && *(inptr + 1) == (byte) '\n') { IsEndOfData = true; midline = false; inptr += 2; break; } if (inputLeft == 1 || (inputLeft == 2 && *(inptr + 1) == (byte) '\r')) { // not enough data... break; } if (*(inptr + 1) == (byte) '.') inptr++; } midline = true; } inputIndex = (int) (inptr - inbuf); } while (outptr < outend && !IsEndOfData); return (int) (outptr - outbuf); } } } /// <summary> /// Reads a sequence of bytes from the stream and advances the position /// within the stream by the number of bytes read. /// </summary> /// <remarks> /// Reads a sequence of bytes from the stream and advances the position /// within the stream by the number of bytes read. /// </remarks> /// <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> /// <param name="buffer">The buffer.</param> /// <param name="offset">The buffer offset.</param> /// <param name="count">The number of bytes to read.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para> /// <para>-or-</para> /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting /// at the specified <paramref name="offset"/>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.InvalidOperationException"> /// The stream is in line mode (see <see cref="Pop3StreamMode.Line"/>). /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public override int Read (byte[] buffer, int offset, int count) { return Read (buffer, offset, count, CancellationToken.None); } /// <summary> /// Reads a single line of input from the stream. /// </summary> /// <remarks> /// This method should be called in a loop until it returns <c>true</c>. /// </remarks> /// <returns><c>true</c>, if reading the line is complete, <c>false</c> otherwise.</returns> /// <param name="buffer">The buffer containing the line data.</param> /// <param name="offset">The offset into the buffer containing bytes read.</param> /// <param name="count">The number of bytes read.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> internal bool ReadLine (out byte[] buffer, out int offset, out int count, CancellationToken cancellationToken) { CheckDisposed (); unsafe { fixed (byte* inbuf = input) { byte* start, inptr, inend; if (inputIndex == inputEnd) ReadAhead (cancellationToken); offset = inputIndex; buffer = input; start = inbuf + inputIndex; inend = inbuf + inputEnd; *inend = (byte) '\n'; inptr = start; // FIXME: use SIMD to optimize this while (*inptr != (byte) '\n') inptr++; inputIndex = (int) (inptr - inbuf); count = (int) (inptr - start); if (inptr == inend) { midline = true; return false; } // consume the '\n' midline = false; inputIndex++; count++; return true; } } } /// <summary> /// Writes a sequence of bytes to the stream and advances the current /// position within this stream by the number of bytes written. /// </summary> /// <remarks> /// Writes a sequence of bytes to the stream and advances the current /// position within this stream by the number of bytes written. /// </remarks> /// <param name='buffer'>The buffer to write.</param> /// <param name='offset'>The offset of the first byte to write.</param> /// <param name='count'>The number of bytes to write.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para> /// <para>-or-</para> /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting /// at the specified <paramref name="offset"/>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support writing. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public void Write (byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckDisposed (); ValidateArguments (buffer, offset, count); try { int index = offset; int left = count; while (left > 0) { int n = Math.Min (BlockSize - outputIndex, left); if (outputIndex > 0 || n < BlockSize) { // append the data to the output buffer Buffer.BlockCopy (buffer, index, output, outputIndex, n); outputIndex += n; index += n; left -= n; } if (outputIndex == BlockSize) { // flush the output buffer Poll (SelectMode.SelectWrite, cancellationToken); Stream.Write (output, 0, BlockSize); logger.LogClient (output, 0, BlockSize); outputIndex = 0; } if (outputIndex == 0) { // write blocks of data to the stream without buffering while (left >= BlockSize) { Poll (SelectMode.SelectWrite, cancellationToken); Stream.Write (buffer, index, BlockSize); logger.LogClient (buffer, index, BlockSize); index += BlockSize; left -= BlockSize; } } } } catch { IsConnected = false; throw; } IsEndOfData = false; } /// <summary> /// Writes a sequence of bytes to the stream and advances the current /// position within this stream by the number of bytes written. /// </summary> /// <remarks> /// Writes a sequence of bytes to the stream and advances the current /// position within this stream by the number of bytes written. /// </remarks> /// <param name='buffer'>The buffer to write.</param> /// <param name='offset'>The offset of the first byte to write.</param> /// <param name='count'>The number of bytes to write.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para> /// <para>-or-</para> /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting /// at the specified <paramref name="offset"/>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support writing. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public override void Write (byte[] buffer, int offset, int count) { Write (buffer, offset, count, CancellationToken.None); } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written /// to the underlying device. /// </summary> /// <remarks> /// Clears all buffers for this stream and causes any buffered data to be written /// to the underlying device. /// </remarks> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support writing. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public void Flush (CancellationToken cancellationToken) { CheckDisposed (); if (outputIndex == 0) return; try { Poll (SelectMode.SelectWrite, cancellationToken); Stream.Write (output, 0, outputIndex); Stream.Flush (); logger.LogClient (output, 0, outputIndex); outputIndex = 0; } catch { IsConnected = false; throw; } } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written /// to the underlying device. /// </summary> /// <remarks> /// Clears all buffers for this stream and causes any buffered data to be written /// to the underlying device. /// </remarks> /// <exception cref="System.ObjectDisposedException"> /// The stream has been disposed. /// </exception> /// <exception cref="System.NotSupportedException"> /// The stream does not support writing. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public override void Flush () { Flush (CancellationToken.None); } /// <summary> /// Sets the position within the current stream. /// </summary> /// <returns>The new position within the stream.</returns> /// <param name="offset">The offset into the stream relative to the <paramref name="origin"/>.</param> /// <param name="origin">The origin to seek from.</param> /// <exception cref="System.NotSupportedException"> /// The stream does not support seeking. /// </exception> public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException (); } /// <summary> /// Sets the length of the stream. /// </summary> /// <param name="value">The desired length of the stream in bytes.</param> /// <exception cref="System.NotSupportedException"> /// The stream does not support setting the length. /// </exception> public override void SetLength (long value) { throw new NotSupportedException (); } /// <summary> /// Releases the unmanaged resources used by the <see cref="Pop3Stream"/> and /// optionally releases the managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; /// <c>false</c> to release only the unmanaged resources.</param> protected override void Dispose (bool disposing) { if (disposing && !disposed) { IsConnected = false; Stream.Dispose (); disposed = true; } base.Dispose (disposing); } } }
// 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.Runtime.InteropServices; using Point = Windows.Foundation.Point; using Windows.Foundation; #pragma warning disable 436 // Redefining types from Windows.Foundation namespace Windows.UI.Xaml.Media { // // Matrix is the managed projection of Windows.UI.Xaml.Media.Matrix. Any changes to the layout of // this type must be exactly mirrored on the native WinRT side as well. // // Note that this type is owned by the Jupiter team. Please contact them before making any // changes here. // [StructLayout(LayoutKind.Sequential)] public struct Matrix : IFormattable { public Matrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } // the transform is identity by default private static Matrix s_identity = CreateIdentity(); public double M11 { get { return _m11; } set { _m11 = value; } } public double M12 { get { return _m12; } set { _m12 = value; } } public double M21 { get { return _m21; } set { _m21 = value; } } public double M22 { get { return _m22; } set { _m22 = value; } } public double OffsetX { get { return _offsetX; } set { _offsetX = value; } } public double OffsetY { get { return _offsetY; } set { _offsetY = value; } } public static Matrix Identity { get { return s_identity; } } public bool IsIdentity { get { return (_m11 == 1 && _m12 == 0 && _m21 == 0 && _m22 == 1 && _offsetX == 0 && _offsetY == 0); } } public override string ToString() { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } public string ToString(IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } string IFormattable.ToString(string format, IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } private string ConvertToString(string format, IFormatProvider provider) { if (IsIdentity) { return "Identity"; } // Helper to get the numeric list separator for a given culture. char separator = TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}{0}{5:" + format + "}{0}{6:" + format + "}", separator, _m11, _m12, _m21, _m22, _offsetX, _offsetY); } public Point Transform(Point point) { float x = (float)point.X; float y = (float)point.Y; this.MultiplyPoint(ref x, ref y); Point point2 = new Point(x, y); return point2; } public override int GetHashCode() { // Perform field-by-field XOR of HashCodes return M11.GetHashCode() ^ M12.GetHashCode() ^ M21.GetHashCode() ^ M22.GetHashCode() ^ OffsetX.GetHashCode() ^ OffsetY.GetHashCode(); } public override bool Equals(object o) { return o is Matrix && Matrix.Equals(this, (Matrix)o); } public bool Equals(Matrix value) { return Matrix.Equals(this, value); } public static bool operator ==(Matrix matrix1, Matrix matrix2) { return matrix1.M11 == matrix2.M11 && matrix1.M12 == matrix2.M12 && matrix1.M21 == matrix2.M21 && matrix1.M22 == matrix2.M22 && matrix1.OffsetX == matrix2.OffsetX && matrix1.OffsetY == matrix2.OffsetY; } public static bool operator !=(Matrix matrix1, Matrix matrix2) { return !(matrix1 == matrix2); } private static Matrix CreateIdentity() { Matrix matrix = new Matrix(); matrix.SetMatrix(1, 0, 0, 1, 0, 0); return matrix; } private void SetMatrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } private void MultiplyPoint(ref float x, ref float y) { double num = (y * _m21) + _offsetX; double num2 = (x * _m12) + _offsetY; x *= (float)_m11; x += (float)num; y *= (float)_m22; y += (float)num2; } private static bool Equals(Matrix matrix1, Matrix matrix2) { return matrix1.M11.Equals(matrix2.M11) && matrix1.M12.Equals(matrix2.M12) && matrix1.M21.Equals(matrix2.M21) && matrix1.M22.Equals(matrix2.M22) && matrix1.OffsetX.Equals(matrix2.OffsetX) && matrix1.OffsetY.Equals(matrix2.OffsetY); } private double _m11; private double _m12; private double _m21; private double _m22; private double _offsetX; private double _offsetY; } } #pragma warning restore 436
// 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; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer { public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture> { protected override void TestWorker(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition) { var root = document.GetSyntaxTreeAsync().Result.GetRoot(); var node = FindExpressionSyntaxFromSpan(root, textSpan); var typeInference = document.GetLanguageService<ITypeInferenceService>(); var inferredType = useNodeStartPosition ? typeInference.InferType(document.GetSemanticModelForSpanAsync(new TextSpan(node.SpanStart, 0), CancellationToken.None).Result, node.SpanStart, objectAsDefault: true, cancellationToken: CancellationToken.None) : typeInference.InferType(document.GetSemanticModelForSpanAsync(node.Span, CancellationToken.None).Result, node, objectAsDefault: true, cancellationToken: CancellationToken.None); var typeSyntax = inferredType.GenerateTypeSyntax(); Assert.Equal(expectedType, typeSyntax.ToString()); } private void TestInClass(string text, string expectedType) { text = @"class C { $ }".Replace("$", text); Test(text, expectedType); } private void TestInMethod(string text, string expectedType, bool testNode = true, bool testPosition = true) { text = @"class C { void M() { $ } }".Replace("$", text); Test(text, expectedType, testNode: testNode, testPosition: testPosition); } private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan) { var token = root.FindToken(textSpan.Start); var currentNode = token.Parent; while (currentNode != null) { ExpressionSyntax result = currentNode as ExpressionSyntax; if (result != null && result.Span == textSpan) { return result; } currentNode = currentNode.Parent; } return null; } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConditional1() { // We do not support position inference here as we're before the ? and we only look // backwards to infer a type here. TestInMethod("var q = [|Foo()|] ? 1 : 2;", "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConditional2() { TestInMethod("var q = a ? [|Foo()|] : 2;", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConditional3() { TestInMethod(@"var q = a ? """" : [|Foo()|];", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestVariableDeclarator1() { TestInMethod("int q = [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestVariableDeclarator2() { TestInMethod("var q = [|Foo()|];", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce1() { TestInMethod("var q = [|Foo()|] ?? 1;", "System.Int32?", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce2() { TestInMethod(@"bool? b; var q = b ?? [|Foo()|];", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce3() { TestInMethod(@"string s; var q = s ?? [|Foo()|];", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce4() { TestInMethod("var q = [|Foo()|] ?? string.Empty;", "System.String", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryExpression1() { TestInMethod(@"string s; var q = s + [|Foo()|];", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryExpression2() { TestInMethod(@"var s; var q = s || [|Foo()|];", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryOperator1() { TestInMethod(@"var q = x << [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryOperator2() { TestInMethod(@"var q = x >> [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestAssignmentOperator3() { TestInMethod(@"var q <<= [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestAssignmentOperator4() { TestInMethod(@"var q >>= [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestOverloadedConditionalLogicalOperatorsInferBool() { Test(@"using System; class C { public static C operator &(C c, C d) { return null; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main(string[] args) { var c = new C() && [|Foo()|]; } }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestConditionalLogicalOrOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a || [|7|]; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestConditionalLogicalAndOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a && [|7|]; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | true; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | b | c || d; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a | b | [|c|] || d; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(Program p) { return p; } }"; Test(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(bool p) { return p; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] | y) != 0) {} } }"; Test(text, "System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] | y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & true; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & b & c && d; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a & b & [|c|] && d; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(Program p) { return p; } }"; Test(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(bool p) { return p; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] & y) != 0) {} } }"; Test(text, "System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] & y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ true; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ b ^ c && d; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a ^ b ^ [|c|] && d; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(Program p) { return p; } }"; Test(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(bool p) { return p; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] ^ y) != 0) {} } }"; Test(text, "System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^ y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] |= y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] |= y; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] &= y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] &= y; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^= y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] ^= y; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturn1() { TestInClass(@"int M() { return [|Foo()|]; }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturn2() { TestInMethod("return [|Foo()|];", "void"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturn3() { TestInClass(@"int Property { get { return [|Foo()|]; } }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897)] public void TestYieldReturn() { var markup = @"using System.Collections.Generic; class Program { IEnumerable<int> M() { yield return [|abc|] } }"; Test(markup, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturnInLambda() { TestInMethod("System.Func<string,int> f = s => { return [|Foo()|]; };", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestLambda() { TestInMethod("System.Func<string, int> f = s => [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestThrow() { TestInMethod("throw [|Foo()|];", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCatch() { TestInMethod("try { } catch ([|Foo|] ex) { }", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIf() { TestInMethod(@"if ([|Foo()|]) { }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestWhile() { TestInMethod(@"while ([|Foo()|]) { }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestDo() { TestInMethod(@"do { } while ([|Foo()|])", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestFor1() { TestInMethod(@"for (int i = 0; [|Foo()|]; i++) { }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestFor2() { TestInMethod(@"for (string i = [|Foo()|]; ; ) { }", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestFor3() { TestInMethod(@"for (var i = [|Foo()|]; ; ) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestUsing1() { TestInMethod(@"using ([|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestUsing2() { TestInMethod(@"using (int i = [|Foo()|]) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestUsing3() { TestInMethod(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestForEach() { TestInMethod(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression1() { TestInMethod(@"var q = +[|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression2() { TestInMethod(@"var q = -[|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression3() { TestInMethod(@"var q = ~[|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression4() { TestInMethod(@"var q = ![|Foo()|];", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayRankSpecifier() { TestInMethod(@"var q = new string[[|Foo()|]];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestSwitch1() { TestInMethod(@"switch ([|Foo()|]) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestSwitch2() { TestInMethod(@"switch ([|Foo()|]) { default: }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestSwitch3() { TestInMethod(@"switch ([|Foo()|]) { case ""a"": }", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall1() { TestInMethod(@"Bar([|Foo()|]);", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall2() { TestInClass(@"void M() { Bar([|Foo()|]); } void Bar(int i);", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall3() { TestInClass(@"void M() { Bar([|Foo()|]); } void Bar();", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall4() { TestInClass(@"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall5() { TestInClass(@"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall1() { TestInMethod(@"new C([|Foo()|]);", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall2() { TestInClass(@"void M() { new C([|Foo()|]); } C(int i) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall3() { TestInClass(@"void M() { new C([|Foo()|]); } C() { }", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall4() { TestInClass(@"void M() { new C([|Foo()|]); } C(int i, string s) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall5() { TestInClass(@"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "System.String"); } [WorkItem(858112)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestThisConstructorInitializer1() { Test(@"class MyClass { public MyClass(int x) : this([|test|]) { } }", "System.Int32"); } [WorkItem(858112)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestThisConstructorInitializer2() { Test(@"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "System.String"); } [WorkItem(858112)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBaseConstructorInitializer() { Test(@"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexAccess1() { TestInMethod(@"string[] i; i[[|Foo()|]];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall1() { TestInMethod(@"this[[|Foo()|]];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall2() { // Update this when binding of indexers is working. TestInClass(@"void M() { this[[|Foo()|]]; } int this [int i] { get; }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall3() { // Update this when binding of indexers is working. TestInClass(@"void M() { this[[|Foo()|]]; } int this [int i, string s] { get; }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall5() { TestInClass(@"void M() { this[s: [|Foo()|]]; } int this [int i, string s] { get; }", "System.String"); } [Fact] public void TestArrayInitializerInImplicitArrayCreationSimple() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { 1, [|2|] }; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInImplicitArrayCreation1() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } int Foo() { return 2; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInImplicitArrayCreation2() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInImplicitArrayCreation3() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } }"; Test(text, "System.Object"); } [Fact] public void TestArrayInitializerInEqualsValueClauseSimple() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { 1, [|2|] }; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInEqualsValueClause() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; Test(text, "System.Int32"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCollectionInitializer1() { var text = @"using System.Collections.Generic; class C { void M() { new List<int>() { [|Foo()|] }; } }"; Test(text, "System.Int32"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCollectionInitializer2() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { [|Foo()|], """" } }; } }"; Test(text, "System.Int32"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCollectionInitializer3() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { 0, [|Foo()|] } }; } }"; Test(text, "System.String"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCustomCollectionInitializerAddMethod1() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { [|a|] }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; Test(text, "System.Int32", testPosition: false); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCustomCollectionInitializerAddMethod2() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|b|] } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; Test(text, "System.Boolean"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCustomCollectionInitializerAddMethod3() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { [|s|], true } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; Test(text, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference1() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; Test(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference1_Position() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; Test(text, "global::A[]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference2() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; Test(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference2_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; Test(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference3() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; Test(text, "global::A[]", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference3_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; Test(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference4() { var text = @" using System; class A { void Foo() { Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] }; } }"; Test(text, "global::System.Func<System.Int32,System.Int32>"); } [WorkItem(538993)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestInsideLambda2() { var text = @"using System; class C { void M() { Func<int,int> f = i => [|here|] } }"; Test(text, "System.Int32"); } [WorkItem(539813)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPointer1() { var text = @"class C { void M(int* i) { var q = i[[|Foo()|]]; } }"; Test(text, "System.Int32"); } [WorkItem(539813)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestDynamic1() { var text = @"class C { void M(dynamic i) { var q = i[[|Foo()|]]; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestChecked1() { var text = @"class C { void M() { string q = checked([|Foo()|]); } }"; Test(text, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public void TestAwaitTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { int x = await [|Foo()|]; } }"; Test(text, "global::System.Threading.Tasks.Task<System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public void TestAwaitTaskOfTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { Task<int> x = await [|Foo()|]; } }"; Test(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<System.Int32>>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public void TestAwaitTask() { var text = @"using System.Threading.Tasks; class C { void M() { await [|Foo()|]; } }"; Test(text, "global::System.Threading.Tasks.Task"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622)] public void TestLockStatement() { var text = @"class C { void M() { lock([|Foo()|]) { } } }"; Test(text, "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622)] public void TestAwaitExpressionInLockStatement() { var text = @"class C { async void M() { lock(await [|Foo()|]) { } } }"; Test(text, "global::System.Threading.Tasks.Task<System.Object>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897)] public void TestReturnFromAsyncTaskOfT() { var markup = @"using System.Threading.Tasks; class Program { async Task<int> M() { await Task.Delay(1); return [|ab|] } }"; Test(markup, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public void TestAttributeArguments1() { var markup = @"[A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; Test(markup, "global::System.DayOfWeek"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public void TestAttributeArguments2() { var markup = @"[A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; Test(markup, "System.Double"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public void TestAttributeArguments3() { var markup = @"[A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; Test(markup, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(757111)] public void TestReturnStatementWithinDelegateWithinAMethodCall() { var text = @"using System; class Program { delegate string A(int i); static void Main(string[] args) { B(delegate(int i) { return [|M()|]; }); } private static void B(A a) { } }"; Test(text, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public void TestCatchFilterClause() { var text = @" try { } catch (Exception) if ([|M()|]) }"; TestInMethod(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public void TestCatchFilterClause1() { var text = @" try { } catch (Exception) if ([|M|]) }"; TestInMethod(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public void TestCatchFilterClause2() { var text = @" try { } catch (Exception) if ([|M|].N) }"; TestInMethod(text, "System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public void TestAwaitExpressionWithChainingMethod() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M()|].ConfigureAwait(false); } }"; Test(text, "global::System.Threading.Tasks.Task<System.Boolean>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public void TestAwaitExpressionWithChainingMethod2() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } }"; Test(text, "global::System.Threading.Tasks.Task<System.Boolean>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public void TestAwaitExpressionWithGenericMethod1() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await X([|Test()|]); } private async Task<T> X<T>(T t) { return t; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public void TestAwaitExpressionWithGenericMethod2() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await Task.Run(() => [|Test()|]);; } private async Task<T> X<T>(T t) { return t; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public void TestNullCoalescingOperator1() { var text = @"class C { void M() { object z = [|a|]?? null; } }"; Test(text, "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public void TestNullCoalescingOperator2() { var text = @"class C { void M() { object z = [|a|] ?? b ?? c; } }"; Test(text, "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public void TestNullCoalescingOperator3() { var text = @"class C { void M() { object z = a ?? [|b|] ?? c; } }"; Test(text, "System.Object"); } } }
// // Options.cs // // Authors: // Jonathan Pryor <jpryor@novell.com> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif #if NDESK_OPTIONS namespace NDesk.Options #else namespace Mono.Options #endif { public class OptionValueCollection : IList, IList<string> { List<string> values = new List<string> (); OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count {get {return values.Count;}} public bool IsReadOnly {get {return false;}} #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize {get {return false;}} object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException ("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set { values [index] = value; } } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public OptionContext (OptionSet set) { this.set = set; this.c = new OptionValueCollection (this); } public Option Option { get {return option;} set {option = value;} } public string OptionName { get {return name;} set {name = value;} } public int OptionIndex { get {return index;} set {index = value;} } public OptionSet OptionSet { get {return set;} } public OptionValueCollection OptionValues { get {return c;} } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { string prototype, description; string[] names; OptionValueType type; int count; string[] separators; protected Option (string prototype, string description) : this (prototype, description, 1) { } protected Option (string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException ("prototype"); if (prototype.Length == 0) throw new ArgumentException ("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException ("maxValueCount"); this.prototype = prototype; this.names = prototype.Split ('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype (); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException ( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException ( string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf (names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException ( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype {get {return prototype;}} public string Description {get {return description;}} public OptionValueType OptionValueType {get {return type;}} public int MaxValueCount {get {return count;}} public string[] GetNames () { return (string[]) names.Clone (); } public string[] GetValueSeparators () { if (separators == null) return new string [0]; return (string[]) separators.Clone (); } protected static T Parse<T> (string value, OptionContext c) { Type tt = typeof (T); bool nullable = tt.IsValueType && tt.IsGenericType && !tt.IsGenericTypeDefinition && tt.GetGenericTypeDefinition () == typeof (Nullable<>); Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); TypeConverter conv = TypeDescriptor.GetConverter (targetType); T t = default (T); try { if (value != null) t = (T) conv.ConvertFromString (value); } catch (Exception e) { throw new OptionException ( string.Format ( c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), value, targetType.Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names {get {return names;}} internal string[] ValueSeparators {get {return separators;}} static readonly char[] NameTerminator = new char[]{'=', ':'}; private OptionValueType ParsePrototype () { char type = '\0'; List<string> seps = new List<string> (); for (int i = 0; i < names.Length; ++i) { string name = names [i]; if (name.Length == 0) throw new ArgumentException ("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny (NameTerminator); if (end == -1) continue; names [i] = name.Substring (0, end); if (type == '\0' || type == name [end]) type = name [end]; else throw new ArgumentException ( string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), "prototype"); AddSeparators (name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException ( string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[]{":", "="}; else if (seps.Count == 1 && seps [0].Length == 0) this.separators = null; else this.separators = seps.ToArray (); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators (string name, int end, ICollection<string> seps) { int start = -1; for (int i = end+1; i < name.Length; ++i) { switch (name [i]) { case '{': if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i+1; break; case '}': if (start == -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add (name.Substring (start, i-start)); start = -1; break; default: if (start == -1) seps.Add (name [i].ToString ()); break; } } if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke (OptionContext c) { OnParseComplete (c); c.OptionName = null; c.Option = null; c.OptionValues.Clear (); } protected abstract void OnParseComplete (OptionContext c); public override string ToString () { return Prototype; } } [Serializable] public class OptionException : Exception { private string option; public OptionException () { } public OptionException (string message, string optionName) : base (message) { this.option = optionName; } public OptionException (string message, string optionName, Exception innerException) : base (message, innerException) { this.option = optionName; } protected OptionException (SerializationInfo info, StreamingContext context) : base (info, context) { this.option = info.GetString ("OptionName"); } public string OptionName { get {return this.option;} } [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); info.AddValue ("OptionName", option); } } public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { public OptionSet () : this (delegate (string f) {return f;}) { } public OptionSet (Converter<string, string> localizer) { this.localizer = localizer; } Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get {return localizer;} } protected override string GetKeyForItem (Option item) { if (item == null) throw new ArgumentNullException ("option"); if (item.Names != null && item.Names.Length > 0) return item.Names [0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException ("Option has no names!"); } [Obsolete ("Use KeyedCollection.this[string]")] protected Option GetOptionForName (string option) { if (option == null) throw new ArgumentNullException ("option"); try { return base [option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem (int index, Option item) { base.InsertItem (index, item); AddImpl (item); } protected override void RemoveItem (int index) { base.RemoveItem (index); Option p = Items [index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove (p.Names [i]); } } protected override void SetItem (int index, Option item) { base.SetItem (index, item); RemoveItem (index); AddImpl (item); } private void AddImpl (Option option) { if (option == null) throw new ArgumentNullException ("option"); List<string> added = new List<string> (option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add (option.Names [i], option); added.Add (option.Names [i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove (name); throw; } } public new OptionSet Add (Option option) { base.Add (option); return this; } sealed class ActionOption : Option { Action<OptionValueCollection> action; public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) : base (prototype, description, count) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (c.OptionValues); } } public OptionSet Add (string prototype, Action<string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 1, delegate (OptionValueCollection v) { action (v [0]); }); base.Add (p); return this; } public OptionSet Add (string prototype, OptionAction<string, string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 2, delegate (OptionValueCollection v) {action (v [0], v [1]);}); base.Add (p); return this; } sealed class ActionOption<T> : Option { Action<T> action; public ActionOption (string prototype, string description, Action<T> action) : base (prototype, description, 1) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (Parse<T> (c.OptionValues [0], c)); } } sealed class ActionOption<TKey, TValue> : Option { OptionAction<TKey, TValue> action; public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) : base (prototype, description, 2) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action ( Parse<TKey> (c.OptionValues [0], c), Parse<TValue> (c.OptionValues [1], c)); } } public OptionSet Add<T> (string prototype, Action<T> action) { return Add (prototype, null, action); } public OptionSet Add<T> (string prototype, string description, Action<T> action) { return Add (new ActionOption<T> (prototype, description, action)); } public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) { return Add (prototype, null, action); } public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) { return Add (new ActionOption<TKey, TValue> (prototype, description, action)); } protected virtual OptionContext CreateOptionContext () { return new OptionContext (this); } #if LINQ public List<string> Parse (IEnumerable<string> arguments) { bool process = true; OptionContext c = CreateOptionContext (); c.OptionIndex = -1; var def = GetOptionForName ("<>"); var unprocessed = from argument in arguments where ++c.OptionIndex >= 0 && (process || def != null) ? process ? argument == "--" ? (process = false) : !Parse (argument, c) ? def != null ? Unprocessed (null, def, c, argument) : true : false : def != null ? Unprocessed (null, def, c, argument) : true : true select argument; List<string> r = unprocessed.ToList (); if (c.Option != null) c.Option.Invoke (c); return r; } #else public List<string> Parse (IEnumerable<string> arguments) { OptionContext c = CreateOptionContext (); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string> (); Option def = Contains ("<>") ? this ["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed (unprocessed, def, c, argument); continue; } if (!Parse (argument, c)) Unprocessed (unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke (c); return unprocessed; } #endif private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add (argument); return false; } c.OptionValues.Add (argument); c.Option = def; c.Option.Invoke (c); return false; } private readonly Regex ValueOption = new Regex ( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException ("argument"); flag = name = sep = value = null; Match m = ValueOption.Match (argument); if (!m.Success) { return false; } flag = m.Groups ["flag"].Value; name = m.Groups ["name"].Value; if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { sep = m.Groups ["sep"].Value; value = m.Groups ["value"].Value; } return true; } protected virtual bool Parse (string argument, OptionContext c) { if (c.Option != null) { ParseValue (argument, c); return true; } string f, n, s, v; if (!GetOptionParts (argument, out f, out n, out s, out v)) return false; Option p; if (Contains (n)) { p = this [n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add (n); c.Option.Invoke (c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue (v, c); break; } return true; } // no match; is it a bool option? if (ParseBool (argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue (f, string.Concat (n + s + v), c)) return true; return false; } private void ParseValue (string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) : new string[]{option}) { c.OptionValues.Add (o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException (localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool (string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && Contains ((rn = n.Substring (0, n.Length-1)))) { p = this [rn]; string v = n [n.Length-1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add (v); p.Invoke (c); return true; } return false; } private bool ParseBundledValue (string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n [i].ToString (); string rn = n [i].ToString (); if (!Contains (rn)) { if (i == 0) return false; throw new OptionException (string.Format (localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke (c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring (i+1); c.Option = p; c.OptionName = opt; ParseValue (v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke (OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add (value); option.Invoke (c); } private const int OptionWidth = 29; public void WriteOptionDescriptions (TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype (o, p, ref written)) continue; if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } bool indent = false; string prefix = new string (' ', OptionWidth+2); foreach (string line in GetLines (localizer (GetDescription (p.Description)))) { if (indent) o.Write (prefix); o.WriteLine (line); indent = true; } } } bool WriteOptionPrototype (TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex (names, 0); if (i == names.Length) return false; if (names [i].Length == 1) { Write (o, ref written, " -"); Write (o, ref written, names [0]); } else { Write (o, ref written, " --"); Write (o, ref written, names [0]); } for ( i = GetNextOptionIndex (names, i+1); i < names.Length; i = GetNextOptionIndex (names, i+1)) { Write (o, ref written, ", "); Write (o, ref written, names [i].Length == 1 ? "-" : "--"); Write (o, ref written, names [i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("[")); } Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("]")); } } return true; } static int GetNextOptionIndex (string[] names, int i) { while (i < names.Length && names [i] == "<>") { ++i; } return i; } static void Write (TextWriter o, ref int n, string s) { n += s.Length; o.Write (s); } private static string GetArgumentName (int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[]{"{0:", "{"}; else nameStart = new string[]{"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf (nameStart [i], j); } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf ("}", start); if (end == -1) continue; return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription (string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder (description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description [i]) { case '{': if (i == start) { sb.Append ('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i+1) == description.Length || description [i+1] != '}') throw new InvalidOperationException ("Invalid option description: " + description); ++i; sb.Append ("}"); } else { sb.Append (description.Substring (start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append (description [i]); break; } } return sb.ToString (); } private static IEnumerable<string> GetLines (string description) { if (string.IsNullOrEmpty (description)) { yield return string.Empty; yield break; } int length = 80 - OptionWidth - 1; int start = 0, end; do { end = GetLineEnd (start, length, description); char c = description [end-1]; if (char.IsWhiteSpace (c)) --end; bool writeContinuation = end != description.Length && !IsEolChar (c); string line = description.Substring (start, end - start) + (writeContinuation ? "-" : ""); yield return line; start = end; if (char.IsWhiteSpace (c)) ++start; length = 80 - OptionWidth - 2 - 1; } while (end < description.Length); } private static bool IsEolChar (char c) { return !char.IsLetterOrDigit (c); } private static int GetLineEnd (int start, int length, string description) { int end = System.Math.Min (start + length, description.Length); int sep = -1; for (int i = start+1; i < end; ++i) { if (description [i] == '\n') return i+1; if (IsEolChar (description [i])) sep = i+1; } if (sep == -1 || end == description.Length) return end; return sep; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace System.Security.Cryptography.Asn1 { internal static class AsnCharacterStringEncodings { private static readonly Text.Encoding s_utf8Encoding = new UTF8Encoding(false, throwOnInvalidBytes: true); private static readonly Text.Encoding s_bmpEncoding = new BMPEncoding(); private static readonly Text.Encoding s_ia5Encoding = new IA5Encoding(); private static readonly Text.Encoding s_visibleStringEncoding = new VisibleStringEncoding(); private static readonly Text.Encoding s_numericStringEncoding = new NumericStringEncoding(); private static readonly Text.Encoding s_printableStringEncoding = new PrintableStringEncoding(); private static readonly Text.Encoding s_t61Encoding = new T61Encoding(); internal static Text.Encoding GetEncoding(UniversalTagNumber encodingType) => encodingType switch { UniversalTagNumber.UTF8String => s_utf8Encoding, UniversalTagNumber.NumericString => s_numericStringEncoding, UniversalTagNumber.PrintableString => s_printableStringEncoding, UniversalTagNumber.IA5String => s_ia5Encoding, UniversalTagNumber.VisibleString => s_visibleStringEncoding, UniversalTagNumber.BMPString => s_bmpEncoding, UniversalTagNumber.T61String => s_t61Encoding, _ => throw new ArgumentOutOfRangeException(nameof(encodingType), encodingType, null), }; } internal abstract class SpanBasedEncoding : Text.Encoding { protected SpanBasedEncoding() : base(0, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback) { } protected abstract int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write); protected abstract int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write); public override int GetByteCount(char[] chars, int index, int count) { return GetByteCount(new ReadOnlySpan<char>(chars, index, count)); } public override unsafe int GetByteCount(char* chars, int count) { return GetByteCount(new ReadOnlySpan<char>(chars, count)); } public override int GetByteCount(string s) { return GetByteCount(s.AsSpan()); } public #if NETCOREAPP || NETSTANDARD2_1 override #endif int GetByteCount(ReadOnlySpan<char> chars) { return GetBytes(chars, Span<byte>.Empty, write: false); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return GetBytes( new ReadOnlySpan<char>(chars, charIndex, charCount), new Span<byte>(bytes, byteIndex, bytes.Length - byteIndex), write: true); } public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return GetBytes( new ReadOnlySpan<char>(chars, charCount), new Span<byte>(bytes, byteCount), write: true); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(new ReadOnlySpan<byte>(bytes, index, count)); } public override unsafe int GetCharCount(byte* bytes, int count) { return GetCharCount(new ReadOnlySpan<byte>(bytes, count)); } public #if NETCOREAPP || NETSTANDARD2_1 override #endif int GetCharCount(ReadOnlySpan<byte> bytes) { return GetChars(bytes, Span<char>.Empty, write: false); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars( new ReadOnlySpan<byte>(bytes, byteIndex, byteCount), new Span<char>(chars, charIndex, chars.Length - charIndex), write: true); } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { return GetChars( new ReadOnlySpan<byte>(bytes, byteCount), new Span<char>(chars, charCount), write: true); } } internal class IA5Encoding : RestrictedAsciiStringEncoding { // T-REC-X.680-201508 sec 41, Table 8. // ISO International Register of Coded Character Sets to be used with Escape Sequences 001 // is ASCII 0x00 - 0x1F // ISO International Register of Coded Character Sets to be used with Escape Sequences 006 // is ASCII 0x21 - 0x7E // Space is ASCII 0x20, delete is ASCII 0x7F. // // The net result is all of 7-bit ASCII internal IA5Encoding() : base(0x00, 0x7F) { } } internal class VisibleStringEncoding : RestrictedAsciiStringEncoding { // T-REC-X.680-201508 sec 41, Table 8. // ISO International Register of Coded Character Sets to be used with Escape Sequences 006 // is ASCII 0x21 - 0x7E // Space is ASCII 0x20. internal VisibleStringEncoding() : base(0x20, 0x7E) { } } internal class NumericStringEncoding : RestrictedAsciiStringEncoding { // T-REC-X.680-201508 sec 41.2 (Table 9) // 0, 1, ... 9 + space internal NumericStringEncoding() : base("0123456789 ") { } } internal class PrintableStringEncoding : RestrictedAsciiStringEncoding { // T-REC-X.680-201508 sec 41.4 internal PrintableStringEncoding() : base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '()+,-./:=?") { } } internal abstract class RestrictedAsciiStringEncoding : SpanBasedEncoding { private readonly bool[] _isAllowed; protected RestrictedAsciiStringEncoding(byte minCharAllowed, byte maxCharAllowed) { Debug.Assert(minCharAllowed <= maxCharAllowed); Debug.Assert(maxCharAllowed <= 0x7F); bool[] isAllowed = new bool[0x80]; for (byte charCode = minCharAllowed; charCode <= maxCharAllowed; charCode++) { isAllowed[charCode] = true; } _isAllowed = isAllowed; } protected RestrictedAsciiStringEncoding(IEnumerable<char> allowedChars) { bool[] isAllowed = new bool[0x7F]; foreach (char c in allowedChars) { if (c >= isAllowed.Length) { throw new ArgumentOutOfRangeException(nameof(allowedChars)); } Debug.Assert(isAllowed[c] == false); isAllowed[c] = true; } _isAllowed = isAllowed; } public override int GetMaxByteCount(int charCount) { return charCount; } public override int GetMaxCharCount(int byteCount) { return byteCount; } protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write) { if (chars.IsEmpty) { return 0; } for (int i = 0; i < chars.Length; i++) { char c = chars[i]; if ((uint)c >= (uint)_isAllowed.Length || !_isAllowed[c]) { EncoderFallback.CreateFallbackBuffer().Fallback(c, i); Debug.Fail("Fallback should have thrown"); throw new CryptographicException(); } if (write) { bytes[i] = (byte)c; } } return chars.Length; } protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write) { if (bytes.IsEmpty) { return 0; } for (int i = 0; i < bytes.Length; i++) { byte b = bytes[i]; if ((uint)b >= (uint)_isAllowed.Length || !_isAllowed[b]) { DecoderFallback.CreateFallbackBuffer().Fallback( new[] { b }, i); Debug.Fail("Fallback should have thrown"); throw new CryptographicException(); } if (write) { chars[i] = (char)b; } } return bytes.Length; } } /// <summary> /// Big-Endian UCS-2 encoding (the same as UTF-16BE, but disallowing surrogate pairs to leave plane 0) /// </summary> // T-REC-X.690-201508 sec 8.23.8 says to see ISO/IEC 10646:2003 section 13.1. // ISO/IEC 10646:2003 sec 13.1 says each character is represented by "two octets". // ISO/IEC 10646:2003 sec 6.3 says that when serialized as octets to use big endian. internal class BMPEncoding : SpanBasedEncoding { protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write) { if (chars.IsEmpty) { return 0; } int writeIdx = 0; for (int i = 0; i < chars.Length; i++) { char c = chars[i]; if (char.IsSurrogate(c)) { EncoderFallback.CreateFallbackBuffer().Fallback(c, i); Debug.Fail("Fallback should have thrown"); throw new CryptographicException(); } ushort val16 = c; if (write) { bytes[writeIdx + 1] = (byte)val16; bytes[writeIdx] = (byte)(val16 >> 8); } writeIdx += 2; } return writeIdx; } protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write) { if (bytes.IsEmpty) { return 0; } if (bytes.Length % 2 != 0) { DecoderFallback.CreateFallbackBuffer().Fallback( bytes.Slice(bytes.Length - 1).ToArray(), bytes.Length - 1); Debug.Fail("Fallback should have thrown"); throw new CryptographicException(); } int writeIdx = 0; for (int i = 0; i < bytes.Length; i += 2) { int val = bytes[i] << 8 | bytes[i + 1]; char c = (char)val; if (char.IsSurrogate(c)) { DecoderFallback.CreateFallbackBuffer().Fallback( bytes.Slice(i, 2).ToArray(), i); Debug.Fail("Fallback should have thrown"); throw new CryptographicException(); } if (write) { chars[writeIdx] = c; } writeIdx++; } return writeIdx; } public override int GetMaxByteCount(int charCount) { checked { return charCount * 2; } } public override int GetMaxCharCount(int byteCount) { return byteCount / 2; } } /// <summary> /// Compatibility encoding for T61Strings. Interprets the characters as UTF-8 or /// ISO-8859-1 as a fallback. /// </summary> internal class T61Encoding : Text.Encoding { private static readonly Text.Encoding s_utf8Encoding = new UTF8Encoding(false, throwOnInvalidBytes: true); private static readonly Text.Encoding s_latin1Encoding = System.Text.Encoding.GetEncoding("iso-8859-1"); public override int GetByteCount(char[] chars, int index, int count) { return s_utf8Encoding.GetByteCount(chars, index, count); } public override unsafe int GetByteCount(char* chars, int count) { return s_utf8Encoding.GetByteCount(chars, count); } public override int GetByteCount(string s) { return s_utf8Encoding.GetByteCount(s); } #if NETCOREAPP || NETSTANDARD2_1 public override int GetByteCount(ReadOnlySpan<char> chars) { return s_utf8Encoding.GetByteCount(chars); } #endif public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return s_utf8Encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); } public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return s_utf8Encoding.GetBytes(chars, charCount, bytes, byteCount); } public override int GetCharCount(byte[] bytes, int index, int count) { try { return s_utf8Encoding.GetCharCount(bytes, index, count); } catch (DecoderFallbackException) { return s_latin1Encoding.GetCharCount(bytes, index, count); } } public override unsafe int GetCharCount(byte* bytes, int count) { try { return s_utf8Encoding.GetCharCount(bytes, count); } catch (DecoderFallbackException) { return s_latin1Encoding.GetCharCount(bytes, count); } } #if NETCOREAPP || NETSTANDARD2_1 public override int GetCharCount(ReadOnlySpan<byte> bytes) { try { return s_utf8Encoding.GetCharCount(bytes); } catch (DecoderFallbackException) { return s_latin1Encoding.GetCharCount(bytes); } } #endif public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { try { return s_utf8Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } catch (DecoderFallbackException) { return s_latin1Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { try { return s_utf8Encoding.GetChars(bytes, byteCount, chars, charCount); } catch (DecoderFallbackException) { return s_latin1Encoding.GetChars(bytes, byteCount, chars, charCount); } } public override int GetMaxByteCount(int charCount) { return s_utf8Encoding.GetMaxByteCount(charCount); } public override int GetMaxCharCount(int byteCount) { // Latin-1 is single byte encoding, so byteCount == charCount // UTF-8 is multi-byte encoding, so byteCount >= charCount // We want to return the maximum of those two, which happens to be byteCount. return byteCount; } } }
/* * * (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.Runtime.Serialization; using ASC.Api.Calendar.BusinessObjects; using ASC.Api.Calendar.ExternalCalendars; using ASC.Common.Security; using ASC.Core; using ASC.Core.Users; using ASC.Web.Core.Calendars; namespace ASC.Api.Calendar.Wrappers { [DataContract(Name = "calendar", Namespace = "")] public class CalendarWrapper { public BaseCalendar UserCalendar { get; private set; } protected UserViewSettings _userViewSettings; protected Guid _userId; public CalendarWrapper(BaseCalendar calendar) : this(calendar, null) { } public CalendarWrapper(BaseCalendar calendar, UserViewSettings userViewSettings) { _userViewSettings = userViewSettings; if (_userViewSettings == null && calendar is ASC.Api.Calendar.BusinessObjects.Calendar) { _userViewSettings = (calendar as ASC.Api.Calendar.BusinessObjects.Calendar) .ViewSettings.Find(s => s.UserId == SecurityContext.CurrentAccount.ID); } if (_userViewSettings == null) { UserCalendar = calendar; _userId = SecurityContext.CurrentAccount.ID; } else { UserCalendar = calendar.GetUserCalendar(_userViewSettings); _userId = _userViewSettings.UserId; } } [DataMember(Name = "isSubscription", Order = 80)] public virtual bool IsSubscription { get { if (UserCalendar.IsiCalStream()) return true; if (UserCalendar.Id.Equals(SharedEventsCalendar.CalendarId, StringComparison.InvariantCultureIgnoreCase)) return true; if (UserCalendar.OwnerId.Equals(_userId)) return false; return true; } set { } } [DataMember(Name = "iCalUrl", Order = 230)] public virtual string iCalUrl { get { if (UserCalendar.IsiCalStream()) return (UserCalendar as BusinessObjects.Calendar).iCalUrl; return ""; } set { } } [DataMember(Name = "isiCalStream", Order = 220)] public virtual bool IsiCalStream { get { if (UserCalendar.IsiCalStream()) return true; return false; } set { } } [DataMember(Name = "isHidden", Order = 50)] public virtual bool IsHidden { get { return _userViewSettings != null ? _userViewSettings.IsHideEvents : false; } set { } } [DataMember(Name = "canAlertModify", Order = 200)] public virtual bool CanAlertModify { get { return UserCalendar.Context.CanChangeAlertType; } set { } } [DataMember(Name = "isShared", Order = 60)] public virtual bool IsShared { get { return UserCalendar.SharingOptions.SharedForAll || UserCalendar.SharingOptions.PublicItems.Count > 0; } set { } } [DataMember(Name = "permissions", Order = 70)] public virtual CalendarPermissions Permissions { get { var p = new CalendarPermissions() { Data = PublicItemCollection.GetForCalendar(UserCalendar) }; foreach (var item in UserCalendar.SharingOptions.PublicItems) { if (item.IsGroup) p.UserParams.Add(new UserParams() { Id = item.Id, Name = CoreContext.UserManager.GetGroupInfo(item.Id).Name }); else p.UserParams.Add(new UserParams() { Id = item.Id, Name = CoreContext.UserManager.GetUsers(item.Id).DisplayUserName() }); } return p; } set { } } [DataMember(Name = "isEditable", Order = 90)] public virtual bool IsEditable { get { if (UserCalendar.IsiCalStream()) return false; if (UserCalendar is ISecurityObject) return SecurityContext.PermissionResolver.Check(CoreContext.Authentication.GetAccountByID(_userId), (ISecurityObject)UserCalendar as ISecurityObject, null, CalendarAccessRights.FullAccessAction); return false; } set { } } [DataMember(Name = "textColor", Order = 30)] public string TextColor { get { return String.IsNullOrEmpty(UserCalendar.Context.HtmlTextColor) ? BusinessObjects.Calendar.DefaultTextColor : UserCalendar.Context.HtmlTextColor; } set { } } [DataMember(Name = "backgroundColor", Order = 40)] public string BackgroundColor { get { return String.IsNullOrEmpty(UserCalendar.Context.HtmlBackgroundColor) ? BusinessObjects.Calendar.DefaultBackgroundColor : UserCalendar.Context.HtmlBackgroundColor; } set { } } [DataMember(Name = "description", Order = 20)] public string Description { get { return UserCalendar.Description; } set { } } [DataMember(Name = "title", Order = 30)] public string Title { get { return UserCalendar.Name; } set { } } [DataMember(Name = "objectId", Order = 0)] public string Id { get { return UserCalendar.Id; } set { } } [DataMember(Name = "isTodo", Order = 0)] public int IsTodo { get { if (UserCalendar.IsExistTodo()) return (UserCalendar as BusinessObjects.Calendar).IsTodo; return 0; } set { } } [DataMember(Name = "owner", Order = 120)] public UserParams Owner { get { var owner = new UserParams() { Id = UserCalendar.OwnerId, Name = "" }; if (UserCalendar.OwnerId != Guid.Empty) owner.Name = CoreContext.UserManager.GetUsers(UserCalendar.OwnerId).DisplayUserName(); return owner; } set { } } public bool IsAcceptedSubscription { get { return _userViewSettings == null || _userViewSettings.IsAccepted; } set { } } [DataMember(Name = "events", Order = 150)] public List<EventWrapper> Events { get; set; } [DataMember(Name = "todos", Order = 160)] public List<TodoWrapper> Todos { get; set; } [DataMember(Name = "defaultAlert", Order = 160)] public EventAlertWrapper DefaultAlertType { get { return EventAlertWrapper.ConvertToTypeSurrogated(UserCalendar.EventAlertType); } set { } } [DataMember(Name = "timeZone", Order = 160)] public TimeZoneWrapper TimeZoneInfo { get { return new TimeZoneWrapper(UserCalendar.TimeZone); } set { } } [DataMember(Name = "canEditTimeZone", Order = 160)] public bool CanEditTimeZone { get { return UserCalendar.Context.CanChangeTimeZone; } set { } } public static object GetSample() { return new { canEditTimeZone = false, timeZone = TimeZoneWrapper.GetSample(), defaultAlert = EventAlertWrapper.GetSample(), events = new List<object>() { EventWrapper.GetSample() }, owner = UserParams.GetSample(), objectId = "1", title = "Calendar Name", description = "Calendar Description", backgroundColor = "#000000", textColor = "#ffffff", isEditable = true, permissions = CalendarPermissions.GetSample(), isShared = true, canAlertModify = true, isHidden = false, isiCalStream = false, isSubscription = false }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Platform; using osu.Framework.Threading; using osu.Game.Graphics; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osu.Game.Tournament.Screens; using osu.Game.Tournament.Screens.Drawings; using osu.Game.Tournament.Screens.Editors; using osu.Game.Tournament.Screens.Gameplay; using osu.Game.Tournament.Screens.Ladder; using osu.Game.Tournament.Screens.MapPool; using osu.Game.Tournament.Screens.Schedule; using osu.Game.Tournament.Screens.Setup; using osu.Game.Tournament.Screens.Showcase; using osu.Game.Tournament.Screens.TeamIntro; using osu.Game.Tournament.Screens.TeamWin; using osuTK; using osuTK.Graphics; namespace osu.Game.Tournament { [Cached] public class TournamentSceneManager : CompositeDrawable { private Container screens; private TourneyVideo video; public const float CONTROL_AREA_WIDTH = 160; public const float STREAM_AREA_WIDTH = 1366; public const double REQUIRED_WIDTH = CONTROL_AREA_WIDTH * 2 + STREAM_AREA_WIDTH; [Cached] private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay(); private Container chatContainer; private FillFlowContainer buttons; public TournamentSceneManager() { RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(LadderInfo ladder, Storage storage) { InternalChildren = new Drawable[] { new Container { RelativeSizeAxes = Axes.Y, X = CONTROL_AREA_WIDTH, FillMode = FillMode.Fit, FillAspectRatio = 16 / 9f, Anchor = Anchor.TopLeft, Origin = Anchor.TopLeft, Width = STREAM_AREA_WIDTH, //Masking = true, Children = new Drawable[] { video = new TourneyVideo("main", true) { Loop = true, RelativeSizeAxes = Axes.Both, }, screens = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new SetupScreen(), new ScheduleScreen(), new LadderScreen(), new LadderEditorScreen(), new TeamEditorScreen(), new RoundEditorScreen(), new ShowcaseScreen(), new MapPoolScreen(), new TeamIntroScreen(), new SeedingScreen(), new DrawingsScreen(), new GameplayScreen(), new TeamWinScreen() } }, chatContainer = new Container { RelativeSizeAxes = Axes.Both, Child = chat }, } }, new Container { RelativeSizeAxes = Axes.Y, Width = CONTROL_AREA_WIDTH, Children = new Drawable[] { new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, }, buttons = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Spacing = new Vector2(5), Padding = new MarginPadding(5), Children = new Drawable[] { new ScreenButton(typeof(SetupScreen)) { Text = "Setup", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(TeamEditorScreen)) { Text = "Team Editor", RequestSelection = SetScreen }, new ScreenButton(typeof(RoundEditorScreen)) { Text = "Rounds Editor", RequestSelection = SetScreen }, new ScreenButton(typeof(LadderEditorScreen)) { Text = "Bracket Editor", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(ScheduleScreen)) { Text = "Schedule", RequestSelection = SetScreen }, new ScreenButton(typeof(LadderScreen)) { Text = "Bracket", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(TeamIntroScreen)) { Text = "Team Intro", RequestSelection = SetScreen }, new ScreenButton(typeof(SeedingScreen)) { Text = "Seeding", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(MapPoolScreen)) { Text = "Map Pool", RequestSelection = SetScreen }, new ScreenButton(typeof(GameplayScreen)) { Text = "Gameplay", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(TeamWinScreen)) { Text = "Win", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(DrawingsScreen)) { Text = "Drawings", RequestSelection = SetScreen }, new ScreenButton(typeof(ShowcaseScreen)) { Text = "Showcase", RequestSelection = SetScreen }, } }, }, }, }; foreach (var drawable in screens) drawable.Hide(); SetScreen(typeof(SetupScreen)); } private float depth; private Drawable currentScreen; private ScheduledDelegate scheduledHide; private Drawable temporaryScreen; public void SetScreen(Drawable screen) { currentScreen?.Hide(); currentScreen = null; screens.Add(temporaryScreen = screen); } public void SetScreen(Type screenType) { temporaryScreen?.Expire(); var target = screens.FirstOrDefault(s => s.GetType() == screenType); if (target == null || currentScreen == target) return; if (scheduledHide?.Completed == false) { scheduledHide.RunTask(); scheduledHide.Cancel(); // see https://github.com/ppy/osu-framework/issues/2967 scheduledHide = null; } var lastScreen = currentScreen; currentScreen = target; if (currentScreen is IProvideVideo) { video.FadeOut(200); // delay the hide to avoid a double-fade transition. scheduledHide = Scheduler.AddDelayed(() => lastScreen?.Hide(), TournamentScreen.FADE_DELAY); } else { lastScreen?.Hide(); video.Show(); } screens.ChangeChildDepth(currentScreen, depth--); currentScreen.Show(); switch (currentScreen) { case MapPoolScreen _: chatContainer.FadeIn(TournamentScreen.FADE_DELAY); chatContainer.ResizeWidthTo(1, 500, Easing.OutQuint); break; case GameplayScreen _: chatContainer.FadeIn(TournamentScreen.FADE_DELAY); chatContainer.ResizeWidthTo(0.5f, 500, Easing.OutQuint); break; default: chatContainer.FadeOut(TournamentScreen.FADE_DELAY); break; } foreach (var s in buttons.OfType<ScreenButton>()) s.IsSelected = screenType == s.Type; } private class Separator : CompositeDrawable { public Separator() { RelativeSizeAxes = Axes.X; Height = 20; } } private class ScreenButton : TourneyButton { public readonly Type Type; public ScreenButton(Type type) { Type = type; BackgroundColour = OsuColour.Gray(0.2f); Action = () => RequestSelection(type); RelativeSizeAxes = Axes.X; } private bool isSelected; public Action<Type> RequestSelection; public bool IsSelected { get => isSelected; set { if (value == isSelected) return; isSelected = value; BackgroundColour = isSelected ? Color4.SkyBlue : OsuColour.Gray(0.2f); SpriteText.Colour = isSelected ? Color4.Black : Color4.White; } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using QuantConnect.Brokerages; using QuantConnect.Configuration; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.Alphas; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Logging; using QuantConnect.Notifications; using QuantConnect.Orders; using QuantConnect.Packets; using QuantConnect.Securities; using QuantConnect.Statistics; using QuantConnect.Util; namespace QuantConnect.Lean.Engine.Results { /// <summary> /// Live trading result handler implementation passes the messages to the QC live trading interface. /// </summary> /// <remarks>Live trading result handler is quite busy. It sends constant price updates, equity updates and order/holdings updates.</remarks> public class LiveTradingResultHandler : BaseResultsHandler, IResultHandler { // Required properties for the cloud app. private LiveNodePacket _job; //Update loop: private DateTime _nextUpdate; private DateTime _nextChartsUpdate; private DateTime _nextChartTrimming; private DateTime _nextLogStoreUpdate; private DateTime _nextStatisticsUpdate; private DateTime _nextStatusUpdate; private DateTime _currentUtcDate; //Log Message Store: private DateTime _nextSample; private IApi _api; private readonly CancellationTokenSource _cancellationTokenSource; private readonly int _streamedChartLimit; private readonly int _streamedChartGroupSize; private bool _sampleChartAlways; private bool _userExchangeIsOpen; private decimal _portfolioValue; private decimal _benchmarkValue; private DateTime _lastChartSampleLogicCheck; private readonly Dictionary<string, SecurityExchangeHours> _exchangeHours; /// <summary> /// Creates a new instance /// </summary> public LiveTradingResultHandler() { _exchangeHours = new Dictionary<string, SecurityExchangeHours>(); _cancellationTokenSource = new CancellationTokenSource(); ResamplePeriod = TimeSpan.FromSeconds(2); NotificationPeriod = TimeSpan.FromSeconds(1); SetNextStatusUpdate(); _streamedChartLimit = Config.GetInt("streamed-chart-limit", 12); _streamedChartGroupSize = Config.GetInt("streamed-chart-group-size", 3); } /// <summary> /// Initialize the result handler with this result packet. /// </summary> /// <param name="job">Algorithm job packet for this result handler</param> /// <param name="messagingHandler">The handler responsible for communicating messages to listeners</param> /// <param name="api">The api instance used for handling logs</param> /// <param name="transactionHandler">The transaction handler used to get the algorithms Orders information</param> public override void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, ITransactionHandler transactionHandler) { _api = api; _job = (LiveNodePacket)job; if (_job == null) throw new Exception("LiveResultHandler.Constructor(): Submitted Job type invalid."); PreviousUtcSampleTime = DateTime.UtcNow; _currentUtcDate = PreviousUtcSampleTime.Date; base.Initialize(job, messagingHandler, api, transactionHandler); } /// <summary> /// Live trading result handler thread. /// </summary> protected override void Run() { // give the algorithm time to initialize, else we will log an error right away ExitEvent.WaitOne(3000); // -> 1. Run Primary Sender Loop: Continually process messages from queue as soon as they arrive. while (!(ExitTriggered && Messages.Count == 0)) { try { //1. Process Simple Messages in Queue Packet packet; if (Messages.TryDequeue(out packet)) { MessagingHandler.Send(packet); } //2. Update the packet scanner: Update(); if (Messages.Count == 0) { // prevent thread lock/tight loop when there's no work to be done ExitEvent.WaitOne(100); } } catch (Exception err) { Log.Error(err); } } // While !End. Log.Trace("LiveTradingResultHandler.Run(): Ending Thread..."); } // End Run(); /// <summary> /// Every so often send an update to the browser with the current state of the algorithm. /// </summary> private void Update() { //Error checks if the algorithm & threads have not loaded yet, or are closing down. if (Algorithm?.Transactions == null || TransactionHandler.Orders == null || !Algorithm.GetLocked()) { Log.Debug("LiveTradingResultHandler.Update(): Algorithm not yet initialized."); ExitEvent.WaitOne(1000); return; } if (ExitTriggered) { return; } var utcNow = DateTime.UtcNow; if (utcNow > _nextUpdate) { try { Dictionary<int, Order> deltaOrders; { var stopwatch = Stopwatch.StartNew(); deltaOrders = GetDeltaOrders(LastDeltaOrderPosition, shouldStop: orderCount => stopwatch.ElapsedMilliseconds > 15); } var deltaOrderEvents = TransactionHandler.OrderEvents.Skip(LastDeltaOrderEventsPosition).Take(50).ToList(); LastDeltaOrderEventsPosition += deltaOrderEvents.Count; //Create and send back the changes in chart since the algorithm started. var deltaCharts = new Dictionary<string, Chart>(); Log.Debug("LiveTradingResultHandler.Update(): Build delta charts"); var performanceCharts = new Dictionary<string, Chart>(); lock (ChartLock) { //Get the updates since the last chart foreach (var chart in Charts) { var chartUpdates = chart.Value.GetUpdates(); // we only want to stream charts that have new updates if (!chartUpdates.IsEmpty()) { // remove directory pathing characters from chart names var safeName = chart.Value.Name.Replace('/', '-'); DictionarySafeAdd(deltaCharts, safeName, chartUpdates, "deltaCharts"); } if (AlgorithmPerformanceCharts.Contains(chart.Key)) { performanceCharts[chart.Key] = chart.Value.Clone(); } } } Log.Debug("LiveTradingResultHandler.Update(): End build delta charts"); //Profit loss changes, get the banner statistics, summary information on the performance for the headers. var deltaStatistics = new Dictionary<string, string>(); var runtimeStatistics = new Dictionary<string, string>(); var serverStatistics = GetServerStatistics(utcNow); var holdings = GetHoldings(); //Add the algorithm statistics first. Log.Debug("LiveTradingResultHandler.Update(): Build run time stats"); lock (RuntimeStatistics) { foreach (var pair in RuntimeStatistics) { runtimeStatistics.Add(pair.Key, pair.Value); } } Log.Debug("LiveTradingResultHandler.Update(): End build run time stats"); //Add other fixed parameters. var summary = GenerateStatisticsResults(performanceCharts).Summary; GetAlgorithmRuntimeStatistics(summary, runtimeStatistics); // since we're sending multiple packets, let's do it async and forget about it // chart data can get big so let's break them up into groups var splitPackets = SplitPackets(deltaCharts, deltaOrders, holdings, Algorithm.Portfolio.CashBook, deltaStatistics, runtimeStatistics, serverStatistics, deltaOrderEvents); foreach (var liveResultPacket in splitPackets) { MessagingHandler.Send(liveResultPacket); } //Send full packet to storage. if (utcNow > _nextChartsUpdate) { Log.Debug("LiveTradingResultHandler.Update(): Pre-store result"); var chartComplete = new Dictionary<string, Chart>(); lock (ChartLock) { foreach (var chart in Charts) { // remove directory pathing characters from chart names var safeName = chart.Value.Name.Replace('/', '-'); DictionarySafeAdd(chartComplete, safeName, chart.Value.Clone(), "chartComplete"); } } var orderEvents = GetOrderEventsToStore(); var orders = new Dictionary<int, Order>(TransactionHandler.Orders); var complete = new LiveResultPacket(_job, new LiveResult(new LiveResultParameters(chartComplete, orders, Algorithm.Transactions.TransactionRecord, holdings, Algorithm.Portfolio.CashBook, deltaStatistics, runtimeStatistics, orderEvents, serverStatistics))); StoreResult(complete); _nextChartsUpdate = DateTime.UtcNow.Add(ChartUpdateInterval); Log.Debug("LiveTradingResultHandler.Update(): End-store result"); } // Upload the logs every 1-2 minutes; this can be a heavy operation depending on amount of live logging and should probably be done asynchronously. if (utcNow > _nextLogStoreUpdate) { List<LogEntry> logs; Log.Debug("LiveTradingResultHandler.Update(): Storing log..."); lock (LogStore) { // we need a new container instance so we can store the logs outside the lock logs = new List<LogEntry>(LogStore); LogStore.Clear(); } SaveLogs(AlgorithmId, logs); _nextLogStoreUpdate = DateTime.UtcNow.AddMinutes(2); Log.Debug("LiveTradingResultHandler.Update(): Finished storing log"); } // Every minute send usage statistics: if (utcNow > _nextStatisticsUpdate) { try { _api.SendStatistics( _job.AlgorithmId, Algorithm.Portfolio.TotalUnrealizedProfit, Algorithm.Portfolio.TotalFees, Algorithm.Portfolio.TotalProfit, Algorithm.Portfolio.TotalHoldingsValue, Algorithm.Portfolio.TotalPortfolioValue, GetNetReturn(), Algorithm.Portfolio.TotalSaleVolume, TransactionHandler.OrdersCount, 0); } catch (Exception err) { Log.Error(err, "Error sending statistics:"); } _nextStatisticsUpdate = utcNow.AddMinutes(1); } if (utcNow > _nextStatusUpdate) { var chartComplete = new Dictionary<string, Chart>(); lock (ChartLock) { foreach (var chart in Charts) { // remove directory pathing characters from chart names var safeName = chart.Value.Name.Replace('/', '-'); DictionarySafeAdd(chartComplete, safeName, chart.Value.Clone(), "chartComplete"); } } StoreStatusFile( runtimeStatistics, // only store holdings we are invested in holdings.Where(pair => pair.Value.Quantity != 0).ToDictionary(pair => pair.Key, pair => pair.Value), chartComplete, new SortedDictionary<DateTime, decimal>(Algorithm.Transactions.TransactionRecord), serverStatistics); SetNextStatusUpdate(); } if (_currentUtcDate != utcNow.Date) { StoreOrderEvents(_currentUtcDate, GetOrderEventsToStore()); // start storing in a new date file _currentUtcDate = utcNow.Date; } if (utcNow > _nextChartTrimming) { Log.Debug("LiveTradingResultHandler.Update(): Trimming charts"); var timeLimitUtc = Time.DateTimeToUnixTimeStamp(utcNow.AddDays(-2)); lock (ChartLock) { foreach (var chart in Charts) { foreach (var series in chart.Value.Series) { // trim data that's older than 2 days series.Value.Values = (from v in series.Value.Values where v.x > timeLimitUtc select v).ToList(); } } } _nextChartTrimming = DateTime.UtcNow.AddMinutes(10); Log.Debug("LiveTradingResultHandler.Update(): Finished trimming charts"); } } catch (Exception err) { Log.Error(err, "LiveTradingResultHandler().Update(): ", true); } //Set the new update time after we've finished processing. // The processing can takes time depending on how large the packets are. _nextUpdate = DateTime.UtcNow.Add(MainUpdateInterval); } // End Update Charts: } /// <summary> /// Stores the order events /// </summary> /// <param name="utcTime">The utc date associated with these order events</param> /// <param name="orderEvents">The order events to store</param> protected override void StoreOrderEvents(DateTime utcTime, List<OrderEvent> orderEvents) { if (orderEvents.Count <= 0) { return; } var filename = $"{AlgorithmId}-{utcTime:yyyy-MM-dd}-order-events.json"; var path = GetResultsPath(filename); var data = JsonConvert.SerializeObject(orderEvents, Formatting.None); File.WriteAllText(path, data); } /// <summary> /// Gets the order events generated in '_currentUtcDate' /// </summary> private List<OrderEvent> GetOrderEventsToStore() { return TransactionHandler.OrderEvents.Where(orderEvent => orderEvent.UtcTime >= _currentUtcDate).ToList(); } private void SetNextStatusUpdate() { // Update the status json file every hour _nextStatusUpdate = DateTime.UtcNow.AddHours(1); } /// <summary> /// Will store the complete status of the algorithm in a single json file /// </summary> /// <remarks>Will sample charts every 12 hours, 2 data points per day at maximum, /// to reduce file size</remarks> private void StoreStatusFile(Dictionary<string, string> runtimeStatistics, Dictionary<string, Holding> holdings, Dictionary<string, Chart> chartComplete, SortedDictionary<DateTime, decimal> profitLoss, Dictionary<string, string> serverStatistics = null, StatisticsResults statistics = null) { try { Log.Debug("LiveTradingResultHandler.Update(): status update start..."); if (statistics == null) { statistics = GenerateStatisticsResults(chartComplete, profitLoss); } // sample the entire charts with a 12 hours resolution var dailySampler = new SeriesSampler(TimeSpan.FromHours(12)); chartComplete = dailySampler.SampleCharts(chartComplete, Time.BeginningOfTime, Time.EndOfTime); var result = new LiveResult(new LiveResultParameters(chartComplete, new Dictionary<int, Order>(TransactionHandler.Orders), Algorithm.Transactions.TransactionRecord, holdings, Algorithm.Portfolio.CashBook, statistics: statistics.Summary, runtimeStatistics: runtimeStatistics, orderEvents: null, // we stored order events separately serverStatistics: serverStatistics, alphaRuntimeStatistics: AlphaRuntimeStatistics)); SaveResults($"{AlgorithmId}.json", result); Log.Debug("LiveTradingResultHandler.Update(): status update end."); } catch (Exception err) { Log.Error(err, "Error storing status update"); } } /// <summary> /// Run over all the data and break it into smaller packets to ensure they all arrive at the terminal /// </summary> private IEnumerable<LiveResultPacket> SplitPackets(Dictionary<string, Chart> deltaCharts, Dictionary<int, Order> deltaOrders, Dictionary<string, Holding> holdings, CashBook cashbook, Dictionary<string, string> deltaStatistics, Dictionary<string, string> runtimeStatistics, Dictionary<string, string> serverStatistics, List<OrderEvent> deltaOrderEvents) { // break the charts into groups var current = new Dictionary<string, Chart>(); var chartPackets = new List<LiveResultPacket>(); // First add send charts // Loop through all the charts, add them to packets to be sent. // Group three charts per packet foreach (var deltaChart in deltaCharts.Values) { current.Add(deltaChart.Name, deltaChart); if (current.Count >= _streamedChartGroupSize) { // Add the micro packet to transport. chartPackets.Add(new LiveResultPacket(_job, new LiveResult { Charts = current })); // Reset the carrier variable. current = new Dictionary<string, Chart>(); if (chartPackets.Count * _streamedChartGroupSize >= _streamedChartLimit) { // stream a maximum number of charts break; } } } // Add whatever is left over here too // unless it is a wildcard subscription if (current.Count > 0) { chartPackets.Add(new LiveResultPacket(_job, new LiveResult { Charts = current })); } // these are easier to split up, not as big as the chart objects var packets = new[] { new LiveResultPacket(_job, new LiveResult { Holdings = holdings, CashBook = cashbook}), new LiveResultPacket(_job, new LiveResult { Statistics = deltaStatistics, RuntimeStatistics = runtimeStatistics, ServerStatistics = serverStatistics, AlphaRuntimeStatistics = AlphaRuntimeStatistics }) }; var result = packets.Concat(chartPackets); // only send order and order event packet if there is actually any update if (deltaOrders.Count > 0 || deltaOrderEvents.Count > 0) { result= result.Concat(new []{ new LiveResultPacket(_job, new LiveResult { Orders = deltaOrders, OrderEvents = deltaOrderEvents }) }); } return result; } /// <summary> /// Send a live trading debug message to the live console. /// </summary> /// <param name="message">Message we'd like shown in console.</param> /// <remarks>When there are already 500 messages in the queue it stops adding new messages.</remarks> public void DebugMessage(string message) { if (Messages.Count > 500) return; //if too many in the queue already skip the logging. Messages.Enqueue(new DebugPacket(_job.ProjectId, AlgorithmId, CompileId, message)); AddToLogStore(message); } /// <summary> /// Send a live trading system debug message to the live console. /// </summary> /// <param name="message">Message we'd like shown in console.</param> public void SystemDebugMessage(string message) { Messages.Enqueue(new SystemDebugPacket(_job.ProjectId, AlgorithmId, CompileId, message)); AddToLogStore(message); } /// <summary> /// Log string messages and send them to the console. /// </summary> /// <param name="message">String message wed like logged.</param> /// <remarks>When there are already 500 messages in the queue it stops adding new messages.</remarks> public void LogMessage(string message) { //Send the logging messages out immediately for live trading: if (Messages.Count > 500) return; Messages.Enqueue(new LogPacket(AlgorithmId, message)); AddToLogStore(message); } /// <summary> /// Save an algorithm message to the log store. Uses a different timestamped method of adding messaging to interweve debug and logging messages. /// </summary> /// <param name="message">String message to send to browser.</param> protected override void AddToLogStore(string message) { Log.Debug("LiveTradingResultHandler.AddToLogStore(): Adding"); lock (LogStore) { LogStore.Add(new LogEntry(DateTime.Now.ToStringInvariant(DateFormat.UI) + " " + message)); } Log.Debug("LiveTradingResultHandler.AddToLogStore(): Finished adding"); } /// <summary> /// Send an error message back to the browser console and highlight it read. /// </summary> /// <param name="message">Message we'd like shown in console.</param> /// <param name="stacktrace">Stacktrace to show in the console.</param> public void ErrorMessage(string message, string stacktrace = "") { if (Messages.Count > 500) return; Messages.Enqueue(new HandledErrorPacket(AlgorithmId, message, stacktrace)); AddToLogStore(message + (!string.IsNullOrEmpty(stacktrace) ? ": StackTrace: " + stacktrace : string.Empty)); } /// <summary> /// Send a list of secutity types that the algorithm trades to the browser to show the market clock - is this market open or closed! /// </summary> /// <param name="types">List of security types</param> public void SecurityType(List<SecurityType> types) { var packet = new SecurityTypesPacket { Types = types }; Messages.Enqueue(packet); } /// <summary> /// Send a runtime error back to the users browser and highlight it red. /// </summary> /// <param name="message">Runtime error message</param> /// <param name="stacktrace">Associated error stack trace.</param> public virtual void RuntimeError(string message, string stacktrace = "") { Messages.Enqueue(new RuntimeErrorPacket(_job.UserId, AlgorithmId, message, stacktrace)); AddToLogStore(message + (!string.IsNullOrEmpty(stacktrace) ? ": StackTrace: " + stacktrace : string.Empty)); } /// <summary> /// Process brokerage message events /// </summary> /// <param name="brokerageMessageEvent">The brokerage message event</param> public virtual void BrokerageMessage(BrokerageMessageEvent brokerageMessageEvent) { // NOP } /// <summary> /// Add a sample to the chart specified by the chartName, and seriesName. /// </summary> /// <param name="chartName">String chart name to place the sample.</param> /// <param name="seriesName">Series name for the chart.</param> /// <param name="seriesIndex">Series chart index - which chart should this series belong</param> /// <param name="seriesType">Series type for the chart.</param> /// <param name="time">Time for the sample</param> /// <param name="value">Value for the chart sample.</param> /// <param name="unit">Unit for the chart axis</param> /// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks> protected override void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$") { // Sampling during warming up period skews statistics if (Algorithm.IsWarmingUp) { return; } Log.Debug("LiveTradingResultHandler.Sample(): Sampling " + chartName + "." + seriesName); lock (ChartLock) { //Add a copy locally: if (!Charts.ContainsKey(chartName)) { Charts.AddOrUpdate(chartName, new Chart(chartName)); } //Add the sample to our chart: if (!Charts[chartName].Series.ContainsKey(seriesName)) { Charts[chartName].Series.Add(seriesName, new Series(seriesName, seriesType, seriesIndex, unit)); } //Add our value: Charts[chartName].Series[seriesName].Values.Add(new ChartPoint(time, value)); } Log.Debug("LiveTradingResultHandler.Sample(): Done sampling " + chartName + "." + seriesName); } /// <summary> /// Wrapper methond on sample to create the equity chart. /// </summary> /// <param name="time">Time of the sample.</param> /// <param name="value">Equity value at this moment in time.</param> /// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/> protected override void SampleEquity(DateTime time, decimal value) { if (value > 0) { Log.Debug("LiveTradingResultHandler.SampleEquity(): " + time.ToShortTimeString() + " >" + value); base.SampleEquity(time, value); } } /// <summary> /// Add a range of samples from the users algorithms to the end of our current list. /// </summary> /// <param name="updates">Chart updates since the last request.</param> /// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/> protected void SampleRange(List<Chart> updates) { Log.Debug("LiveTradingResultHandler.SampleRange(): Begin sampling"); lock (ChartLock) { foreach (var update in updates) { //Create the chart if it doesn't exist already: Chart chart; if (!Charts.TryGetValue(update.Name, out chart)) { chart = new Chart(update.Name); Charts.AddOrUpdate(update.Name, chart); } // for alpha assets chart, we always create a new series instance (step on previous value) var forceNewSeries = update.Name == ChartingInsightManagerExtension.AlphaAssets; //Add these samples to this chart. foreach (var series in update.Series.Values) { if (series.Values.Count > 0) { var thisSeries = chart.TryAddAndGetSeries(series.Name, series.SeriesType, series.Index, series.Unit, series.Color, series.ScatterMarkerSymbol, forceNewSeries); if (series.SeriesType == SeriesType.Pie) { var dataPoint = series.ConsolidateChartPoints(); if (dataPoint != null) { thisSeries.AddPoint(dataPoint); } } else { //We already have this record, so just the new samples to the end: thisSeries.Values.AddRange(series.Values); } } } } } Log.Debug("LiveTradingResultHandler.SampleRange(): Finished sampling"); } /// <summary> /// Set the algorithm of the result handler after its been initialized. /// </summary> /// <param name="algorithm">Algorithm object matching IAlgorithm interface</param> /// <param name="startingPortfolioValue">Algorithm starting capital for statistics calculations</param> public virtual void SetAlgorithm(IAlgorithm algorithm, decimal startingPortfolioValue) { Algorithm = algorithm; _portfolioValue = DailyPortfolioValue = StartingPortfolioValue = startingPortfolioValue; CumulativeMaxPortfolioValue = StartingPortfolioValue; AlgorithmCurrencySymbol = Currencies.GetCurrencySymbol(Algorithm.AccountCurrency); var types = new List<SecurityType>(); foreach (var kvp in Algorithm.Securities) { var security = kvp.Value; if (!types.Contains(security.Type)) types.Add(security.Type); } SecurityType(types); // we need to forward Console.Write messages to the algorithm's Debug function var debug = new FuncTextWriter(algorithm.Debug); var error = new FuncTextWriter(algorithm.Error); Console.SetOut(debug); Console.SetError(error); UpdateAlgorithmStatus(); } /// <summary> /// Send a algorithm status update to the user of the algorithms running state. /// </summary> /// <param name="status">Status enum of the algorithm.</param> /// <param name="message">Optional string message describing reason for status change.</param> public void SendStatusUpdate(AlgorithmStatus status, string message = "") { Log.Trace($"LiveTradingResultHandler.SendStatusUpdate(): status: '{status}'. {(string.IsNullOrEmpty(message) ? string.Empty : " " + message)}"); var packet = new AlgorithmStatusPacket(_job.AlgorithmId, _job.ProjectId, status, message); Messages.Enqueue(packet); } /// <summary> /// Set a dynamic runtime statistic to show in the (live) algorithm header /// </summary> /// <param name="key">Runtime headline statistic name</param> /// <param name="value">Runtime headline statistic value</param> public void RuntimeStatistic(string key, string value) { Log.Debug("LiveTradingResultHandler.RuntimeStatistic(): Begin setting statistic"); lock (RuntimeStatistics) { if (!RuntimeStatistics.ContainsKey(key)) { RuntimeStatistics.Add(key, value); } RuntimeStatistics[key] = value; } Log.Debug("LiveTradingResultHandler.RuntimeStatistic(): End setting statistic"); } /// <summary> /// Send a final analysis result back to the IDE. /// </summary> protected void SendFinalResult() { Log.Trace("LiveTradingResultHandler.SendFinalResult(): Starting..."); try { LiveResultPacket result; // could happen if algorithm failed to init if (Algorithm != null) { //Convert local dictionary: var charts = new Dictionary<string, Chart>(); lock (ChartLock) { foreach (var kvp in Charts) { charts.Add(kvp.Key, kvp.Value.Clone()); } } var orders = new Dictionary<int, Order>(TransactionHandler.Orders); var profitLoss = new SortedDictionary<DateTime, decimal>(Algorithm.Transactions.TransactionRecord); var holdings = GetHoldings(onlyInvested: true); var statisticsResults = GenerateStatisticsResults(charts, profitLoss); var runtime = GetAlgorithmRuntimeStatistics(statisticsResults.Summary); StoreStatusFile(runtime, holdings, charts, profitLoss, statistics: statisticsResults); //Create a packet: result = new LiveResultPacket(_job, new LiveResult(new LiveResultParameters(charts, orders, profitLoss, new Dictionary<string, Holding>(), Algorithm.Portfolio.CashBook, statisticsResults.Summary, runtime, GetOrderEventsToStore()))); } else { result = LiveResultPacket.CreateEmpty(_job); } result.ProcessingTime = (DateTime.UtcNow - StartTime).TotalSeconds; //Store to S3: StoreResult(result); Log.Trace("LiveTradingResultHandler.SendFinalResult(): Finished storing results. Start sending..."); //Truncate packet to fit within 32kb: result.Results = new LiveResult(); //Send the truncated packet: MessagingHandler.Send(result); } catch (Exception err) { Log.Error(err); } Log.Trace("LiveTradingResultHandler.SendFinalResult(): Ended"); } /// <summary> /// Process the log entries and save it to permanent storage /// </summary> /// <param name="id">Id that will be incorporated into the algorithm log name</param> /// <param name="logs">Log list</param> /// <returns>Returns the location of the logs</returns> public override string SaveLogs(string id, List<LogEntry> logs) { try { var logLines = logs.Select(x => x.Message); var filename = $"{id}-log.txt"; var path = GetResultsPath(filename); File.AppendAllLines(path, logLines); return path; } catch (Exception err) { Log.Error(err); } return ""; } /// <summary> /// Save the snapshot of the total results to storage. /// </summary> /// <param name="packet">Packet to store.</param> protected override void StoreResult(Packet packet) { try { Log.Debug("LiveTradingResultHandler.StoreResult(): Begin store result sampling"); // Make sure this is the right type of packet: if (packet.Type != PacketType.LiveResult) return; // Port to packet format: var live = packet as LiveResultPacket; if (live != null) { if (live.Results.OrderEvents != null) { // we store order events separately StoreOrderEvents(_currentUtcDate, live.Results.OrderEvents); // lets null the orders events so that they aren't stored again and generate a giant file live.Results.OrderEvents = null; } live.Results.AlphaRuntimeStatistics = AlphaRuntimeStatistics; // we need to down sample var start = DateTime.UtcNow.Date; var stop = start.AddDays(1); // truncate to just today, we don't need more than this for anyone Truncate(live.Results, start, stop); var highResolutionCharts = new Dictionary<string, Chart>(live.Results.Charts); // minute resolution data, save today var minuteSampler = new SeriesSampler(TimeSpan.FromMinutes(1)); var minuteCharts = minuteSampler.SampleCharts(live.Results.Charts, start, stop); // swap out our charts with the sampled data live.Results.Charts = minuteCharts; SaveResults(CreateKey("minute"), live.Results); // 10 minute resolution data, save today var tenminuteSampler = new SeriesSampler(TimeSpan.FromMinutes(10)); var tenminuteCharts = tenminuteSampler.SampleCharts(live.Results.Charts, start, stop); live.Results.Charts = tenminuteCharts; SaveResults(CreateKey("10minute"), live.Results); // high resolution data, we only want to save an hour live.Results.Charts = highResolutionCharts; start = DateTime.UtcNow.RoundDown(TimeSpan.FromHours(1)); stop = DateTime.UtcNow.RoundUp(TimeSpan.FromHours(1)); Truncate(live.Results, start, stop); foreach (var name in live.Results.Charts.Keys) { var result = new LiveResult { Orders = new Dictionary<int, Order>(live.Results.Orders), Holdings = new Dictionary<string, Holding>(live.Results.Holdings), Charts = new Dictionary<string, Chart> { { name, live.Results.Charts[name] } } }; SaveResults(CreateKey("second_" + CreateSafeChartName(name), "yyyy-MM-dd-HH"), result); } } else { Log.Error("LiveResultHandler.StoreResult(): Result Null."); } Log.Debug("LiveTradingResultHandler.StoreResult(): End store result sampling"); } catch (Exception err) { Log.Error(err); } } /// <summary> /// New order event for the algorithm /// </summary> /// <param name="newEvent">New event details</param> public override void OrderEvent(OrderEvent newEvent) { var brokerIds = string.Empty; var order = TransactionHandler.GetOrderById(newEvent.OrderId); if (order != null && order.BrokerId.Count > 0) brokerIds = string.Join(", ", order.BrokerId); //Send the message to frontend as packet: Log.Trace("LiveTradingResultHandler.OrderEvent(): " + newEvent + " BrokerId: " + brokerIds, true); Messages.Enqueue(new OrderEventPacket(AlgorithmId, newEvent)); var message = "New Order Event: " + newEvent; DebugMessage(message); } /// <summary> /// Terminate the result thread and apply any required exit procedures like sending final results /// </summary> public override void Exit() { if (!ExitTriggered) { _cancellationTokenSource.Cancel(); if (Algorithm != null) { // first process synchronous events so we add any new message or log ProcessSynchronousEvents(true); } // Set exit flag, update task will send any message before stopping ExitTriggered = true; ExitEvent.Set(); lock (LogStore) { SaveLogs(AlgorithmId, LogStore); LogStore.Clear(); } StopUpdateRunner(); SendFinalResult(); base.Exit(); } } /// <summary> /// Truncates the chart and order data in the result packet to within the specified time frame /// </summary> private static void Truncate(LiveResult result, DateTime start, DateTime stop) { var unixDateStart = Time.DateTimeToUnixTimeStamp(start); var unixDateStop = Time.DateTimeToUnixTimeStamp(stop); //Log.Trace("LiveTradingResultHandler.Truncate: Start: " + start.ToString("u") + " Stop : " + stop.ToString("u")); //Log.Trace("LiveTradingResultHandler.Truncate: Truncate Delta: " + (unixDateStop - unixDateStart) + " Incoming Points: " + result.Charts["Strategy Equity"].Series["Equity"].Values.Count); var charts = new Dictionary<string, Chart>(); foreach (var kvp in result.Charts) { var chart = kvp.Value; var newChart = new Chart(chart.Name); charts.Add(kvp.Key, newChart); foreach (var series in chart.Series.Values) { var newSeries = new Series(series.Name, series.SeriesType, series.Unit, series.Color); newSeries.Values.AddRange(series.Values.Where(chartPoint => chartPoint.x >= unixDateStart && chartPoint.x <= unixDateStop)); newChart.AddSeries(newSeries); } } result.Charts = charts; result.Orders = result.Orders.Values.Where(x => (x.Time >= start && x.Time <= stop) || (x.LastFillTime != null && x.LastFillTime >= start && x.LastFillTime <= stop) || (x.LastUpdateTime != null && x.LastUpdateTime >= start && x.LastUpdateTime <= stop) ).ToDictionary(x => x.Id); //Log.Trace("LiveTradingResultHandler.Truncate: Truncate Outgoing: " + result.Charts["Strategy Equity"].Series["Equity"].Values.Count); } private string CreateKey(string suffix, string dateFormat = "yyyy-MM-dd") { return $"{AlgorithmId}-{DateTime.UtcNow.ToStringInvariant(dateFormat)}_{suffix}.json"; } /// <summary> /// Escape the chartname so that it can be saved to a file system /// </summary> /// <param name="chartName">The name of a chart</param> /// <returns>The name of the chart will all escape all characters except RFC 2396 unreserved characters</returns> protected virtual string CreateSafeChartName(string chartName) { return Uri.EscapeDataString(chartName); } /// <summary> /// Process the synchronous result events, sampling and message reading. /// This method is triggered from the algorithm manager thread. /// </summary> /// <remarks>Prime candidate for putting into a base class. Is identical across all result handlers.</remarks> public virtual void ProcessSynchronousEvents(bool forceProcess = false) { var time = DateTime.UtcNow; if (time > _nextSample || forceProcess) { Log.Debug("LiveTradingResultHandler.ProcessSynchronousEvents(): Enter"); //Set next sample time: 4000 samples per backtest _nextSample = time.Add(ResamplePeriod); //Sample the portfolio value over time for chart. SampleEquity(time, Math.Round(GetPortfolioValue(), 4)); //Also add the user samples / plots to the result handler tracking: SampleRange(Algorithm.GetChartUpdates(true)); } ProcessAlgorithmLogs(messageQueueLimit: 500); //Set the running statistics: foreach (var pair in Algorithm.RuntimeStatistics) { RuntimeStatistic(pair.Key, pair.Value); } //Send all the notification messages but timeout within a second, or if this is a force process, wait till its done. var start = DateTime.UtcNow; while (Algorithm.Notify.Messages.Count > 0 && (DateTime.UtcNow < start.AddSeconds(1) || forceProcess)) { Notification message; if (Algorithm.Notify.Messages.TryDequeue(out message)) { //Process the notification messages: Log.Trace("LiveTradingResultHandler.ProcessSynchronousEvents(): Processing Notification..."); try { MessagingHandler.SendNotification(message); } catch (Exception err) { Log.Error(err, "Sending notification: " + message.GetType().FullName); } } } Log.Debug("LiveTradingResultHandler.ProcessSynchronousEvents(): Exit"); } /// <summary> /// Event fired each time that we add/remove securities from the data feed. /// On Security change we re determine when should we sample charts, if the user added Crypto, Forex or an extended market hours subscription /// we will always sample charts. Else, we will keep the exchange per market to query later on demand /// </summary> public override void OnSecuritiesChanged(SecurityChanges changes) { if (_sampleChartAlways) { return; } foreach (var securityChange in changes.AddedSecurities) { var symbol = securityChange.Symbol; if (symbol.SecurityType == QuantConnect.SecurityType.Base) { // ignore custom data continue; } // if the user added Crypto, Forex or an extended market hours subscription just sample always, one way trip. _sampleChartAlways = symbol.SecurityType == QuantConnect.SecurityType.Crypto || symbol.SecurityType == QuantConnect.SecurityType.Forex || Algorithm.SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).Any(config => config.ExtendedMarketHours); if (!_exchangeHours.ContainsKey(securityChange.Symbol.ID.Market)) { // per market we keep track of the exchange hours _exchangeHours[securityChange.Symbol.ID.Market] = securityChange.Exchange.Hours; } } } /// <summary> /// Samples portfolio equity, benchmark, and daily performance /// </summary> /// <param name="time">Current UTC time in the AlgorithmManager loop</param> /// <param name="force">Force sampling of equity, benchmark, and performance to be </param> public override void Sample(DateTime time, bool force = false) { UpdatePortfolioValue(time, force); UpdateBenchmarkValue(time, force); base.Sample(time, force); } /// <summary> /// Gets the current portfolio value /// </summary> /// <remarks>Useful so that live trading implementation can freeze the returned value if there is no user exchange open /// so we ignore extended market hours updates</remarks> protected override decimal GetPortfolioValue() { return _portfolioValue; } /// <summary> /// Gets the current benchmark value /// </summary> /// <remarks>Useful so that live trading implementation can freeze the returned value if there is no user exchange open /// so we ignore extended market hours updates</remarks> protected override decimal GetBenchmarkValue() { return _benchmarkValue; } /// <summary> /// True if user exchange are open and we should update portfolio and benchmark value /// </summary> /// <remarks>Useful so that live trading implementation can freeze the returned value if there is no user exchange open /// so we ignore extended market hours updates</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool UserExchangeIsOpen(DateTime utcDateTime) { if (_sampleChartAlways || _exchangeHours.Count == 0) { return true; } if (_lastChartSampleLogicCheck.Day == utcDateTime.Day && _lastChartSampleLogicCheck.Hour == utcDateTime.Hour && _lastChartSampleLogicCheck.Minute == utcDateTime.Minute) { // we cache the value for a minute return _userExchangeIsOpen; } _lastChartSampleLogicCheck = utcDateTime; foreach (var exchangeHour in _exchangeHours.Values) { if (exchangeHour.IsOpen(utcDateTime.ConvertFromUtc(exchangeHour.TimeZone), false)) { // one of the users exchanges is open _userExchangeIsOpen = true; return true; } } // no user exchange is open _userExchangeIsOpen = false; return false; } private static void DictionarySafeAdd<T>(Dictionary<string, T> dictionary, string key, T value, string dictionaryName) { if (dictionary.ContainsKey(key)) { // TODO: GH issue 3609 Log.Debug($"LiveTradingResultHandler.DictionarySafeAdd(): dictionary {dictionaryName} already contains key {key}"); } else { dictionary.Add(key, value); } } /// <summary> /// Will launch a task which will call the API and update the algorithm status every minute /// </summary> private void UpdateAlgorithmStatus() { if (!ExitTriggered && !_cancellationTokenSource.IsCancellationRequested) // just in case { // wait until after we're warmed up to start sending running status each minute if (!Algorithm.IsWarmingUp) { _api.SetAlgorithmStatus(_job.AlgorithmId, AlgorithmStatus.Running); } Task.Delay(TimeSpan.FromMinutes(1), _cancellationTokenSource.Token).ContinueWith(_ => UpdateAlgorithmStatus()); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void UpdateBenchmarkValue(DateTime time, bool force) { if (force || UserExchangeIsOpen(time)) { _benchmarkValue = base.GetBenchmarkValue(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void UpdatePortfolioValue(DateTime time, bool force) { if (force || UserExchangeIsOpen(time)) { _portfolioValue = base.GetPortfolioValue(); } } private Dictionary<string, Holding> GetHoldings(bool onlyInvested = false) { var holdings = new Dictionary<string, Holding>(); foreach (var kvp in Algorithm.Securities // we send non internal, non canonical and tradable securities. When securities are removed they are marked as non tradable .Where(pair => pair.Value.IsTradable && !pair.Value.IsInternalFeed() && !pair.Key.IsCanonical() && (!onlyInvested || pair.Value.Invested)) .OrderBy(x => x.Key.Value)) { var security = kvp.Value; DictionarySafeAdd(holdings, security.Symbol.Value, new Holding(security), "holdings"); } return holdings; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Windows.Forms; using Microsoft.WindowsAPICodePack.DirectX.Direct2D1; using Microsoft.WindowsAPICodePack.DirectX.DirectWrite; using DXGI = Microsoft.WindowsAPICodePack.DirectX.Graphics; using FontFamily=Microsoft.WindowsAPICodePack.DirectX.DirectWrite.FontFamily; using FontStyle=Microsoft.WindowsAPICodePack.DirectX.DirectWrite.FontStyle; namespace D2DPaint { public class FontEnumComboBox : ComboBox { #region Fields private readonly CultureInfo enUSCulture = new CultureInfo("en-US"); private D2DFactory d2DFactory; private DWriteFactory dwriteFactory; private DCRenderTarget dcRenderTarget; private SolidColorBrush brush; List<string> primaryNames = new List<string>(); private Dictionary<string, TextLayout> layouts; private float maxHeight; #endregion #region Properties private float dropDownFontSize = 18; /// <summary> /// Gets or sets the size of the font used in the drop down. /// </summary> /// <value>The size of the drop down font.</value> [DefaultValue(18f)] public float DropDownFontSize { get { return dropDownFontSize; } set { dropDownFontSize = value; } } /// <summary> /// Gets or sets a value indicating whether all items should be of the same height (the height of the tallest font) or whether they should use the minimum size required for each font. /// </summary> /// <value><c>true</c> if item height should be fixed; otherwise, <c>false</c>.</value> [DefaultValue(true)] public bool FixedItemHeight { get; set; } #endregion #region FontEnumComboBox() public FontEnumComboBox() { FixedItemHeight = true; } #endregion #region Initialize() public void Initialize() { d2DFactory = D2DFactory.CreateFactory(D2DFactoryType.Multithreaded); dwriteFactory = DWriteFactory.CreateFactory(); InitializeRenderTarget(); FillFontFamilies(); if (FixedItemHeight) DropDownHeight = (int)maxHeight * 10; DrawMode = DrawMode.OwnerDrawVariable; MeasureItem += FontEnumComboBox_MeasureItem; DrawItem += FontEnumComboBox_DrawItem; } #endregion #region InitializeRenderTarget() private void InitializeRenderTarget() { if (dcRenderTarget == null) { var props = new RenderTargetProperties { PixelFormat = new PixelFormat( Microsoft.WindowsAPICodePack.DirectX.Graphics.Format.B8G8R8A8UNorm, AlphaMode.Ignore), Usage = RenderTargetUsages.GdiCompatible }; dcRenderTarget = d2DFactory.CreateDCRenderTarget(props); brush = dcRenderTarget.CreateSolidColorBrush( new ColorF( ForeColor.R / 256f, ForeColor.G / 256f, ForeColor.B / 256f, 1)); } } #endregion #region FillFontFamilies() private void FillFontFamilies() { maxHeight = 0; primaryNames = new List<string>(); layouts = new Dictionary<string, TextLayout>(); foreach (FontFamily family in dwriteFactory.SystemFontFamilyCollection) { AddFontFamily(family); } primaryNames.Sort(); Items.Clear(); Items.AddRange(primaryNames.ToArray()); } #endregion #region AddFontFamily() private void AddFontFamily(FontFamily family) { string familyName; CultureInfo familyCulture; // First try getting a name in the user's language. familyCulture = CultureInfo.CurrentUICulture; family.FamilyNames.TryGetValue(familyCulture, out familyName); if (familyName == null) { // Fall back to en-US culture. This is somewhat arbitrary, but most fonts have English // strings so this at least yields predictable fallback behavior in most cases. familyCulture = enUSCulture; family.FamilyNames.TryGetValue(familyCulture, out familyName); } if (familyName == null) { // As a last resort, use the first name we find. This will just be the name associated // with whatever locale name sorts first alphabetically. foreach (KeyValuePair<CultureInfo, string> entry in family.FamilyNames) { familyCulture = entry.Key; familyName = entry.Value; } } if (familyName == null) return; //add info to list of structs used as a cache of text layouts var displayFormats = new List<TextLayout>(); var format = dwriteFactory.CreateTextFormat( family.Fonts[0].IsSymbolFont ? Font.FontFamily.Name : familyName, DropDownFontSize, FontWeight.Normal, FontStyle.Normal, FontStretch.Normal, familyCulture); format.WordWrapping = WordWrapping.NoWrap; var layout = dwriteFactory.CreateTextLayout( familyName, format, 10000, 10000); DropDownWidth = Math.Max(DropDownWidth, (int)layout.Metrics.Width); maxHeight = Math.Max(maxHeight, layout.Metrics.Height); displayFormats.Add(layout); //add name to list primaryNames.Add(familyName); layouts.Add(familyName, layout); } #endregion #region FontEnumComboBox_MeasureItem() void FontEnumComboBox_MeasureItem(object sender, MeasureItemEventArgs e) { //initialize the DC Render Target and a brush before first use InitializeRenderTarget(); var fontName = (string)Items[e.Index]; e.ItemWidth = (int)layouts[fontName].Metrics.Width + 10; e.ItemHeight = FixedItemHeight ? (int)maxHeight : (int)layouts[fontName].Metrics.Height; } #endregion #region FontEnumComboBox_DrawItem() void FontEnumComboBox_DrawItem(object sender, DrawItemEventArgs e) { //initialize the DC Render Target and a brush before first use InitializeRenderTarget(); //draw the background of the combo item e.DrawBackground(); //set section of the DC to draw on var subRect = new Rect( e.Bounds.Left, e.Bounds.Top, e.Bounds.Right, e.Bounds.Bottom); //bind the render target with the DC dcRenderTarget.BindDC(e.Graphics.GetHdc(), subRect); //draw the text using D2D/DWrite dcRenderTarget.BeginDraw(); var fontName = (string)Items[e.Index]; //if ((e.State & DrawItemState.Selected & ~DrawItemState.NoFocusRect) != DrawItemState.None) dcRenderTarget.DrawTextLayout( new Point2F(5, (e.Bounds.Height - layouts[fontName].Metrics.Height) / 2), layouts[fontName], brush, DrawTextOptions.Clip); dcRenderTarget.EndDraw(); //release the DC e.Graphics.ReleaseHdc(); //drow focus rect for a focused item e.DrawFocusRectangle(); } #endregion #region Dispose() protected override void Dispose(bool disposing) { if (disposing) { //dispose of all layouts while (layouts.Keys.Count > 0) foreach (string key in layouts.Keys) { layouts[key].Dispose(); layouts.Remove(key); break; } if (brush != null) brush.Dispose(); brush = null; if (dcRenderTarget != null) dcRenderTarget.Dispose(); dcRenderTarget = null; if (dwriteFactory != null) dwriteFactory.Dispose(); dwriteFactory = null; if (d2DFactory != null) d2DFactory.Dispose(); d2DFactory = null; } base.Dispose(disposing); } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:08:55 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // Bart Adriaanse | 30/11/2013 | Added Amersfoort definition, the proper name for dutch datum // | | Note: please look for DutchRD in Pojected.NationalGrids // ************************************************************************************************* #pragma warning disable 1591 namespace DotSpatial.Projections.GeographicCategories { /// <summary> /// Europe /// </summary> public class Europe : CoordinateSystemCategory { #region Private Variables public readonly ProjectionInfo ATFParis; public readonly ProjectionInfo Amersfoort; public readonly ProjectionInfo Albanian1987; public readonly ProjectionInfo Belge1950Brussels; public readonly ProjectionInfo Belge1972; public readonly ProjectionInfo Bern1898; public readonly ProjectionInfo Bern1898Bern; public readonly ProjectionInfo Bern1938; public readonly ProjectionInfo CH1903; public readonly ProjectionInfo Datum73; public readonly ProjectionInfo DatumLisboaBessel; public readonly ProjectionInfo DatumLisboaHayford; public readonly ProjectionInfo DealulPiscului1933Romania; public readonly ProjectionInfo DealulPiscului1970Romania; public readonly ProjectionInfo DeutscheHauptdreiecksnetz; public readonly ProjectionInfo DutchRD; public readonly ProjectionInfo ETRF1989; public readonly ProjectionInfo ETRS1989; public readonly ProjectionInfo EUREFFIN; public readonly ProjectionInfo Estonia1937; public readonly ProjectionInfo Estonia1992; public readonly ProjectionInfo Estonia1997; public readonly ProjectionInfo European1979; public readonly ProjectionInfo EuropeanDatum1950; public readonly ProjectionInfo EuropeanDatum1987; public readonly ProjectionInfo Greek; public readonly ProjectionInfo GreekAthens; public readonly ProjectionInfo GreekGeodeticRefSystem1987; public readonly ProjectionInfo Hermannskogel; public readonly ProjectionInfo Hjorsey1955; public readonly ProjectionInfo HungarianDatum1972; public readonly ProjectionInfo IRENET95; public readonly ProjectionInfo ISN1993; public readonly ProjectionInfo Kartastokoordinaattijarjestelma; public readonly ProjectionInfo LKS1992; public readonly ProjectionInfo LKS1994; public readonly ProjectionInfo Lisbon; public readonly ProjectionInfo Lisbon1890; public readonly ProjectionInfo Lisbon1890Lisbon; public readonly ProjectionInfo LisbonLisbon; public readonly ProjectionInfo Luxembourg1930; public readonly ProjectionInfo MGIFerro; public readonly ProjectionInfo Madrid1870Madrid; public readonly ProjectionInfo MilitarGeographischeInstitut; public readonly ProjectionInfo MonteMario; public readonly ProjectionInfo MonteMarioRome; public readonly ProjectionInfo NGO1948; public readonly ProjectionInfo NGO1948Oslo; public readonly ProjectionInfo NTFParis; public readonly ProjectionInfo NorddeGuerreParis; public readonly ProjectionInfo NouvelleTriangulationFrancaise; public readonly ProjectionInfo OSGB1936; public readonly ProjectionInfo OSGB1970SN; public readonly ProjectionInfo OSNI1952; public readonly ProjectionInfo OSSN1980; public readonly ProjectionInfo Pulkovo1942; public readonly ProjectionInfo Pulkovo1942Adj1958; public readonly ProjectionInfo Pulkovo1942Adj1983; public readonly ProjectionInfo Pulkovo1995; public readonly ProjectionInfo Qornoq; public readonly ProjectionInfo RGF1993; public readonly ProjectionInfo RT1990; public readonly ProjectionInfo RT38; public readonly ProjectionInfo RT38Stockholm; public readonly ProjectionInfo ReseauNationalBelge1950; public readonly ProjectionInfo ReseauNationalBelge1972; public readonly ProjectionInfo Reykjavik1900; public readonly ProjectionInfo Roma1940; public readonly ProjectionInfo S42Hungary; public readonly ProjectionInfo SJTSK; public readonly ProjectionInfo SWEREF99; public readonly ProjectionInfo SwissTRF1995; public readonly ProjectionInfo TM65; public readonly ProjectionInfo TM75; #endregion #region Constructors /// <summary> /// Creates a new instance of Europe /// </summary> public Europe() { Albanian1987 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); Amersfoort = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +towgs84=565.2369,50.0087,465.658,-0.406857330322398,0.350732676542563,-1.8703473836068,4.0812 +no_defs "); ATFParis = ProjectionInfo.FromProj4String("+proj=longlat +a=6376523 +b=6355862.933255573 +pm=2.337229166666667 +no_defs "); Belge1950Brussels = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +pm=4.367975 +no_defs "); Belge1972 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); Bern1898 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); Bern1898Bern = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +pm=7.439583333333333 +no_defs "); Bern1938 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); CH1903 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); Datum73 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); DatumLisboaBessel = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); DatumLisboaHayford = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); DealulPiscului1933Romania = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); DealulPiscului1970Romania = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); DeutscheHauptdreiecksnetz = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); DutchRD = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +towgs84=565.2369,50.0087,465.658,-0.406857330322398,0.350732676542563,-1.8703473836068,4.0812 +no_defs "); Estonia1937 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); Estonia1992 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); Estonia1997 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); ETRF1989 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=WGS84 +no_defs "); ETRS1989 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); EUREFFIN = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); European1979 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); EuropeanDatum1950 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); EuropeanDatum1987 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); Greek = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); GreekAthens = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +pm=23.7163375 +no_defs "); GreekGeodeticRefSystem1987 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); Hermannskogel = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); Hjorsey1955 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); HungarianDatum1972 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS67 +no_defs "); IRENET95 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); ISN1993 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); Kartastokoordinaattijarjestelma = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); Lisbon = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); LisbonLisbon = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +pm=-9.131906111111112 +no_defs "); Lisbon1890 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); Lisbon1890Lisbon = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +pm=-9.131906111111112 +no_defs "); LKS1992 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); LKS1994 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); Luxembourg1930 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); Madrid1870Madrid = ProjectionInfo.FromProj4String("+proj=longlat +a=6378298.3 +b=6356657.142669561 +pm=-3.687938888888889 +no_defs "); MGIFerro = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +pm=-17.66666666666667 +no_defs "); MilitarGeographischeInstitut = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); MonteMario = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); MonteMarioRome = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +pm=12.45233333333333 +no_defs "); NGO1948 = ProjectionInfo.FromProj4String("+proj=longlat +a=6377492.018 +b=6356173.508712696 +no_defs "); NGO1948Oslo = ProjectionInfo.FromProj4String("+proj=longlat +a=6377492.018 +b=6356173.508712696 +pm=10.72291666666667 +no_defs "); NorddeGuerreParis = ProjectionInfo.FromProj4String("+proj=longlat +a=6376523 +b=6355862.933255573 +pm=2.337229166666667 +no_defs "); NouvelleTriangulationFrancaise = ProjectionInfo.FromProj4String("+proj=longlat +a=6378249.2 +b=6356514.999904194 +no_defs "); NTFParis = ProjectionInfo.FromProj4String("+proj=longlat +a=6378249.2 +b=6356514.999904194 +pm=2.337229166666667 +no_defs "); OSSN1980 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=airy +no_defs "); OSGB1936 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=airy +no_defs "); OSGB1970SN = ProjectionInfo.FromProj4String("+proj=longlat +ellps=airy +no_defs "); OSNI1952 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=airy +no_defs "); Pulkovo1942 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); Pulkovo1942Adj1958 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); Pulkovo1942Adj1983 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); Pulkovo1995 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); Qornoq = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); ReseauNationalBelge1950 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); ReseauNationalBelge1972 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); Reykjavik1900 = ProjectionInfo.FromProj4String("+proj=longlat +a=6377019.27 +b=6355762.5391 +no_defs "); RGF1993 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); Roma1940 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); RT1990 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); RT38 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); RT38Stockholm = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +pm=18.05827777777778 +no_defs "); S42Hungary = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); SJTSK = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); SWEREF99 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); SwissTRF1995 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); TM65 = ProjectionInfo.FromProj4String("+proj=longlat +a=6377340.189 +b=6356034.447938534 +no_defs "); TM75 = ProjectionInfo.FromProj4String("+proj=longlat +a=6377340.189 +b=6356034.447938534 +no_defs "); Albanian1987.GeographicInfo.Name = "GCS_Albanian_1987"; ATFParis.GeographicInfo.Name = "GCS_ATF_Paris"; Belge1950Brussels.GeographicInfo.Name = "GCS_Belge_1950_Brussels"; Belge1972.GeographicInfo.Name = "GCS_Belge_1972"; Bern1898.GeographicInfo.Name = "GCS_Bern_1898"; Bern1898Bern.GeographicInfo.Name = "GCS_Bern_1898_Bern"; Bern1938.GeographicInfo.Name = "GCS_Bern_1938"; CH1903.GeographicInfo.Name = "GCS_CH1903"; Datum73.GeographicInfo.Name = "GCS_Datum_73"; DatumLisboaBessel.GeographicInfo.Name = "GCS_Datum_Lisboa_Bessel"; DatumLisboaHayford.GeographicInfo.Name = "GCS_Datum_Lisboa_Hayford"; DealulPiscului1933Romania.GeographicInfo.Name = "GCS_Dealul_Piscului_1933"; DealulPiscului1970Romania.GeographicInfo.Name = "GCS_Dealul_Piscului_1970"; DeutscheHauptdreiecksnetz.GeographicInfo.Name = "GCS_Deutsches_Hauptdreiecksnetz"; Estonia1937.GeographicInfo.Name = "GCS_Estonia_1937"; Estonia1992.GeographicInfo.Name = "GCS_Estonia_1992"; Estonia1997.GeographicInfo.Name = "GCS_Estonia_1997"; ETRF1989.GeographicInfo.Name = "GCS_ETRF_1989"; ETRS1989.GeographicInfo.Name = "GCS_ETRS_1989"; EUREFFIN.GeographicInfo.Name = "GCS_EUREF_FIN"; European1979.GeographicInfo.Name = "GCS_European_1979"; EuropeanDatum1950.GeographicInfo.Name = "GCS_European_1950"; EuropeanDatum1987.GeographicInfo.Name = "GCS_European_1987"; Greek.GeographicInfo.Name = "GCS_Greek"; GreekAthens.GeographicInfo.Name = "GCS_Greek_Athens"; GreekGeodeticRefSystem1987.GeographicInfo.Name = "GCS_GGRS_1987"; Hermannskogel.GeographicInfo.Name = "GCS_Hermannskogel"; Hjorsey1955.GeographicInfo.Name = "GCS_Hjorsey_1955"; HungarianDatum1972.GeographicInfo.Name = "GCS_Hungarian_1972"; IRENET95.GeographicInfo.Name = "GCS_IRENET95"; ISN1993.GeographicInfo.Name = "GCS_ISN_1993"; Kartastokoordinaattijarjestelma.GeographicInfo.Name = "GCS_KKJ"; Lisbon.GeographicInfo.Name = "GCS_Lisbon"; LisbonLisbon.GeographicInfo.Name = "GCS_Lisbon_Lisbon"; Lisbon1890.GeographicInfo.Name = "GCS_Lisbon_1890"; Lisbon1890Lisbon.GeographicInfo.Name = "GCS_Lisbon_1890_Lisbon"; LKS1992.GeographicInfo.Name = "GCS_LKS_1992"; LKS1994.GeographicInfo.Name = "GCS_LKS_1994"; Luxembourg1930.GeographicInfo.Name = "GCS_Luxembourg_1930"; Madrid1870Madrid.GeographicInfo.Name = "GCS_Madrid_1870_Madrid"; MGIFerro.GeographicInfo.Name = "GCS_MGI_Ferro"; MilitarGeographischeInstitut.GeographicInfo.Name = "GCS_MGI"; MonteMario.GeographicInfo.Name = "GCS_Monte_Mario"; MonteMarioRome.GeographicInfo.Name = "GCS_Monte_Mario_Rome"; NGO1948.GeographicInfo.Name = "GCS_NGO_1948"; NGO1948Oslo.GeographicInfo.Name = "GCS_NGO_1948_Oslo"; NorddeGuerreParis.GeographicInfo.Name = "GCS_Nord_de_Guerre_Paris"; NouvelleTriangulationFrancaise.GeographicInfo.Name = "GCS_NTF"; NTFParis.GeographicInfo.Name = "GCS_NTF_Paris"; OSSN1980.GeographicInfo.Name = "GCS_OS_SN_1980"; OSGB1936.GeographicInfo.Name = "GCS_OSGB_1936"; OSGB1970SN.GeographicInfo.Name = "GCS_OSGB_1970_SN"; OSNI1952.GeographicInfo.Name = "GCS_OSNI_1952"; Pulkovo1942.GeographicInfo.Name = "GCS_Pulkovo_1942"; Pulkovo1942Adj1958.GeographicInfo.Name = "GCS_Pulkovo_1942_Adj_1958"; Pulkovo1942Adj1983.GeographicInfo.Name = "GCS_Pulkovo_1942_Adj_1983"; Pulkovo1995.GeographicInfo.Name = "GCS_Pulkovo_1995"; Qornoq.GeographicInfo.Name = "GCS_Qornoq"; ReseauNationalBelge1950.GeographicInfo.Name = "GCS_Belge_1950"; ReseauNationalBelge1972.GeographicInfo.Name = "GCS_Belge_1972"; Reykjavik1900.GeographicInfo.Name = "GCS_Reykjavik_1900"; RGF1993.GeographicInfo.Name = "GCS_RGF_1993"; Roma1940.GeographicInfo.Name = "GCS_Roma_1940"; RT1990.GeographicInfo.Name = "GCS_RT_1990"; RT38.GeographicInfo.Name = "GCS_RT38"; RT38Stockholm.GeographicInfo.Name = "GCS_RT38_Stockholm"; S42Hungary.GeographicInfo.Name = "GCS_S42_Hungary"; SJTSK.GeographicInfo.Name = "GCS_S_JTSK"; SWEREF99.GeographicInfo.Name = "GCS_SWEREF99"; SwissTRF1995.GeographicInfo.Name = "GCS_Swiss_TRF_1995"; TM65.GeographicInfo.Name = "GCS_TM65"; TM75.GeographicInfo.Name = "GCS_TM75"; Albanian1987.GeographicInfo.Datum.Name = "D_Albanian_1987"; ATFParis.GeographicInfo.Datum.Name = "D_ATF"; Belge1950Brussels.GeographicInfo.Datum.Name = "D_Belge_1950"; Belge1972.GeographicInfo.Datum.Name = "D_Belge_1972"; Bern1898.GeographicInfo.Datum.Name = "D_Bern_1898"; Bern1898Bern.GeographicInfo.Datum.Name = "D_Bern_1898"; Bern1938.GeographicInfo.Datum.Name = "D_Bern_1938"; CH1903.GeographicInfo.Datum.Name = "D_CH1903"; Datum73.GeographicInfo.Datum.Name = "D_Datum_73"; DatumLisboaBessel.GeographicInfo.Datum.Name = "D_Datum_Lisboa_Bessel"; DatumLisboaHayford.GeographicInfo.Datum.Name = "D_Datum_Lisboa_Hayford"; DealulPiscului1933Romania.GeographicInfo.Datum.Name = "D_Dealul_Piscului_1933"; DealulPiscului1970Romania.GeographicInfo.Datum.Name = "D_Dealul_Piscului_1970"; DeutscheHauptdreiecksnetz.GeographicInfo.Datum.Name = "D_Deutsches_Hauptdreiecksnetz"; Estonia1937.GeographicInfo.Datum.Name = "D_Estonia_1937"; Estonia1992.GeographicInfo.Datum.Name = "D_Estonia_1992"; Estonia1997.GeographicInfo.Datum.Name = "D_Estonia_1997"; ETRF1989.GeographicInfo.Datum.Name = "D_ETRF_1989"; ETRS1989.GeographicInfo.Datum.Name = "D_ETRS_1989"; EUREFFIN.GeographicInfo.Datum.Name = "D_ETRS_1989"; European1979.GeographicInfo.Datum.Name = "D_European_1979"; EuropeanDatum1950.GeographicInfo.Datum.Name = "D_European_1950"; EuropeanDatum1987.GeographicInfo.Datum.Name = "D_European_1987"; Greek.GeographicInfo.Datum.Name = "D_Greek"; GreekAthens.GeographicInfo.Datum.Name = "D_Greek"; GreekGeodeticRefSystem1987.GeographicInfo.Datum.Name = "D_GGRS_1987"; Hermannskogel.GeographicInfo.Datum.Name = "D_Hermannskogel"; Hjorsey1955.GeographicInfo.Datum.Name = "D_Hjorsey_1955"; HungarianDatum1972.GeographicInfo.Datum.Name = "D_Hungarian_1972"; IRENET95.GeographicInfo.Datum.Name = "D_IRENET95"; ISN1993.GeographicInfo.Datum.Name = "D_Islands_Network_1993"; Kartastokoordinaattijarjestelma.GeographicInfo.Datum.Name = "D_KKJ"; Lisbon.GeographicInfo.Datum.Name = "D_Lisbon"; LisbonLisbon.GeographicInfo.Datum.Name = "D_Lisbon"; Lisbon1890.GeographicInfo.Datum.Name = "D_Lisbon_1890"; Lisbon1890Lisbon.GeographicInfo.Datum.Name = "D_Lisbon_1890"; LKS1992.GeographicInfo.Datum.Name = "D_Latvia_1992"; LKS1994.GeographicInfo.Datum.Name = "D_Lithuania_1994"; Luxembourg1930.GeographicInfo.Datum.Name = "D_Luxembourg_1930"; Madrid1870Madrid.GeographicInfo.Datum.Name = "D_Madrid_1870"; MGIFerro.GeographicInfo.Datum.Name = "D_MGI"; MilitarGeographischeInstitut.GeographicInfo.Datum.Name = "D_MGI"; MonteMario.GeographicInfo.Datum.Name = "D_Monte_Mario"; MonteMarioRome.GeographicInfo.Datum.Name = "D_Monte_Mario"; NGO1948.GeographicInfo.Datum.Name = "D_NGO_1948"; NGO1948Oslo.GeographicInfo.Datum.Name = "D_NGO_1948"; NorddeGuerreParis.GeographicInfo.Datum.Name = "D_Nord_de_Guerre"; NouvelleTriangulationFrancaise.GeographicInfo.Datum.Name = "D_NTF"; NTFParis.GeographicInfo.Datum.Name = "D_NTF"; OSSN1980.GeographicInfo.Datum.Name = "D_OS_SN_1980"; OSGB1936.GeographicInfo.Datum.Name = "D_OSGB_1936"; OSGB1970SN.GeographicInfo.Datum.Name = "D_OSGB_1970_SN"; OSNI1952.GeographicInfo.Datum.Name = "D_OSNI_1952"; Pulkovo1942.GeographicInfo.Datum.Name = "D_Pulkovo_1942"; Pulkovo1942Adj1958.GeographicInfo.Datum.Name = "D_Pulkovo_1942_Adj_1958"; Pulkovo1942Adj1983.GeographicInfo.Datum.Name = "D_Pulkovo_1942_Adj_1983"; Pulkovo1995.GeographicInfo.Datum.Name = "D_Pulkovo_1995"; Qornoq.GeographicInfo.Datum.Name = "D_Qornoq"; ReseauNationalBelge1950.GeographicInfo.Datum.Name = "D_Belge_1950"; ReseauNationalBelge1972.GeographicInfo.Datum.Name = "D_Belge_1972"; Reykjavik1900.GeographicInfo.Datum.Name = "D_Reykjavik_1900"; RGF1993.GeographicInfo.Datum.Name = "D_RGF_1993"; Roma1940.GeographicInfo.Datum.Name = "D_Roma_1940"; RT1990.GeographicInfo.Datum.Name = "D_RT_1990"; RT38.GeographicInfo.Datum.Name = "D_Stockholm_1938"; RT38Stockholm.GeographicInfo.Datum.Name = "D_Stockholm_1938"; S42Hungary.GeographicInfo.Datum.Name = "D_S42_Hungary"; SJTSK.GeographicInfo.Datum.Name = "D_S_JTSK"; SWEREF99.GeographicInfo.Datum.Name = "D_SWEREF99"; SwissTRF1995.GeographicInfo.Datum.Name = "D_Swiss_TRF_1995"; TM65.GeographicInfo.Datum.Name = "D_TM65"; TM75.GeographicInfo.Datum.Name = "D_TM75"; } #endregion } } #pragma warning restore 1591
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; namespace RedditSharp { /// <inheritdoc /> public class WebAgent : IWebAgent { private const string OAuthDomainUrl = "oauth.reddit.com"; private static HttpClient _httpClient; /// <summary> /// Additional values to append to the default RedditSharp user agent. /// </summary> public static string DefaultUserAgent { get; set; } = "RedditSharp"; /// <summary> /// web protocol "http", "https" /// </summary> public static string Protocol { get; set; } /// <summary> /// The root domain RedditSharp uses to address Reddit. /// www.reddit.com by default /// </summary> public static string RootDomain { get; set; } /// <summary> /// Global default RateLimitManager /// </summary> public static IRateLimiter DefaultRateLimiter { get; private set; } /// <summary> /// RateLimitManager for this Reddit instance. /// </summary> public IRateLimiter RateLimiter { get; set; } /// <inheritdoc /> public string AccessToken { get; set; } /// <summary> /// String to override default useragent for this instance /// </summary> public string UserAgent { get; set; } /// <summary> /// Append the library to the end of the User-Agent string. Default is true. /// </summary> public bool AppendLibraryToUA { get; set; } = true; private static readonly bool IsMono = Type.GetType("Mono.Runtime") != null; private static bool IsOAuth => RootDomain == "oauth.reddit.com"; static WebAgent() { //Static constructors are dumb, no likey -Meepster23 DefaultUserAgent = string.IsNullOrWhiteSpace( DefaultUserAgent ) ? "" : DefaultUserAgent ; Protocol = string.IsNullOrWhiteSpace(Protocol) ? "https" : Protocol; RootDomain = string.IsNullOrWhiteSpace(RootDomain) ? "www.reddit.com" : RootDomain; DefaultRateLimiter = new RateLimitManager(); _httpClient = new HttpClient(); } /// <summary> /// Creates WebAgent with default rate limiter and default useragent. /// </summary> public WebAgent() { UserAgent = DefaultUserAgent; RateLimiter = WebAgent.DefaultRateLimiter; } /// <summary> /// Intializes a WebAgent with a specified access token and optional <see cref="RateLimitManager"/>. Sets the default url to the oauth api address /// </summary> /// <param name="accessToken">Valid access token</param> /// <param name="rateLimiter"><see cref="RateLimitManager"/> that controls the rate limit for this instance of the WebAgent. Defaults to the shared, static rate limiter.</param> /// <param name="userAgent">Optional userAgent string to override default UserAgent</param> public WebAgent( string accessToken, IRateLimiter rateLimiter = null, string userAgent = "") { RootDomain = OAuthDomainUrl; AccessToken = accessToken; if(rateLimiter == null) { RateLimiter = WebAgent.DefaultRateLimiter; } else { RateLimiter = rateLimiter; } if (string.IsNullOrEmpty(userAgent)) { UserAgent = DefaultUserAgent; } else { UserAgent = userAgent; } } /// <inheritdoc /> public virtual async Task<JToken> ExecuteRequestAsync(Func<HttpRequestMessage> request) { if (request == null) throw new ArgumentNullException(nameof(request)); const int maxTries = 20; HttpResponseMessage response; var tries = 0; do { await RateLimiter.CheckRateLimitAsync(IsOAuth).ConfigureAwait(false); response = await _httpClient.SendAsync(request()).ConfigureAwait(false); await RateLimiter.ReadHeadersAsync(response); ++tries; } while( // only retry if 500, 502, 503, or 504 (response.StatusCode == System.Net.HttpStatusCode.InternalServerError || response.StatusCode == System.Net.HttpStatusCode.BadGateway || response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable || response.StatusCode == System.Net.HttpStatusCode.GatewayTimeout) && tries < maxTries ); if (!response.IsSuccessStatusCode) throw new RedditHttpException(response.StatusCode); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); JToken json; if (!string.IsNullOrEmpty(result)) { json = JToken.Parse(result); try { if (json["json"] != null) { json = json["json"]; //get json object if there is a root node } if (json["errors"] != null) { switch (json["errors"].ToString()) { case "404": throw new Exception("File Not Found"); case "403": throw new Exception("Restricted"); case "invalid_grant": //Refresh authtoken //AccessToken = authProvider.GetRefreshToken(); //ExecuteRequest(request); break; default: throw new Exception($"Error return by reddit: {json["errors"][0][0].ToString()}"); } } } catch { } } else { json = JToken.Parse($"{{'method':'{response.RequestMessage.Method}','uri':'{response.RequestMessage.RequestUri.AbsoluteUri}','status':'{response.StatusCode.ToString()}'}}"); } return json; } /// <inheritdoc /> public virtual HttpRequestMessage CreateRequest(string url, string method) { bool prependDomain; // IsWellFormedUristring returns true on Mono for some reason when using a string like "/api/me" if (IsMono) prependDomain = !url.StartsWith("http://") && !url.StartsWith("https://"); else prependDomain = !Uri.IsWellFormedUriString(url, UriKind.Absolute); Uri uri; if (prependDomain) uri = new Uri(string.Format("{0}://{1}{2}", Protocol, RootDomain, url)); else uri = new Uri(url); return CreateRequest(uri, method); } /// <inheritdoc /> protected virtual HttpRequestMessage CreateRequest(Uri uri, string method) { var request = new HttpRequestMessage() { RequestUri = uri }; if (IsOAuth)// use OAuth request.Headers.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);//Must be included in OAuth calls request.Method = new HttpMethod(method); //request.Headers.UserAgent.ParseAdd(UserAgent); var userAgentString = AppendLibraryToUA ? $"{UserAgent} - with RedditSharp by meepster23" : UserAgent; request.Headers.TryAddWithoutValidation("User-Agent", userAgentString); return request; } /// <inheritdoc /> public Task<JToken> Get(string url) => ExecuteRequestAsync(() => CreateRequest(url, "GET")); /// <inheritdoc /> public Task<JToken> Post(string url, object data, params string[] additionalFields) { return ExecuteRequestAsync(() => { var request = CreateRequest(url, "POST"); WritePostBody(request, data, additionalFields); return request; }); } /// <inheritdoc /> public Task<JToken> Put(string url, object data) { return ExecuteRequestAsync(() => { var request = CreateRequest(url, "PUT"); WritePostBody(request, data); return request; }); } /// <inheritdoc /> public virtual void WritePostBody(HttpRequestMessage request, object data, params string[] additionalFields) { var type = data.GetType(); var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var content = new List<KeyValuePair<string, string>>(); foreach (var property in properties) { var attr = property.GetCustomAttributes(typeof(RedditAPINameAttribute), false).FirstOrDefault() as RedditAPINameAttribute; string name = attr == null ? property.Name : attr.Name; var entry = Convert.ToString(property.GetValue(data, null)); content.Add(new KeyValuePair<string,string>(name, entry)); } for (int i = 0; i < additionalFields.Length; i += 2) { var entry = Convert.ToString(additionalFields[i + 1]); content.Add(new KeyValuePair<string, string>(additionalFields[i], entry)); } //new FormUrlEncodedContent has a limit on length which can cause issues; request.Content = new StringContent(string.Join("&",content.Select(c=>c.Key + "=" + System.Net.WebUtility.UrlEncode(c.Value))), System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); } /// <inheritdoc /> public Task<HttpResponseMessage> GetResponseAsync(HttpRequestMessage message) { return _httpClient.SendAsync(message); } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.27.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * TaskQueue API Version v1beta1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'>TaskQueue API</a> * <tr><th>API Version<td>v1beta1 * <tr><th>API Rev<td>20160428 (483) * <tr><th>API Docs * <td><a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'> * https://developers.google.com/appengine/docs/python/taskqueue/rest</a> * <tr><th>Discovery Name<td>taskqueue * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using TaskQueue API can be found at * <a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'>https://developers.google.com/appengine/docs/python/taskqueue/rest</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Taskqueue.v1beta1 { /// <summary>The Taskqueue Service.</summary> public class TaskqueueService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public TaskqueueService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public TaskqueueService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { taskqueues = new TaskqueuesResource(this); tasks = new TasksResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "taskqueue"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/taskqueue/v1beta1/projects/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "taskqueue/v1beta1/projects/"; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://www.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the TaskQueue API.</summary> public class Scope { /// <summary>Manage your Tasks and Taskqueues</summary> public static string Taskqueue = "https://www.googleapis.com/auth/taskqueue"; /// <summary>Consume Tasks from your Taskqueues</summary> public static string TaskqueueConsumer = "https://www.googleapis.com/auth/taskqueue.consumer"; } private readonly TaskqueuesResource taskqueues; /// <summary>Gets the Taskqueues resource.</summary> public virtual TaskqueuesResource Taskqueues { get { return taskqueues; } } private readonly TasksResource tasks; /// <summary>Gets the Tasks resource.</summary> public virtual TasksResource Tasks { get { return tasks; } } } ///<summary>A base abstract class for Taskqueue requests.</summary> public abstract class TaskqueueBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new TaskqueueBaseServiceRequest instance.</summary> protected TaskqueueBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Taskqueue parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "taskqueues" collection of methods.</summary> public class TaskqueuesResource { private const string Resource = "taskqueues"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TaskqueuesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Get detailed information about a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The id of the /// taskqueue to get the properties of.</param> public virtual GetRequest Get(string project, string taskqueue) { return new GetRequest(service, project, taskqueue); } /// <summary>Get detailed information about a TaskQueue.</summary> public class GetRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.TaskQueue> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string project, string taskqueue) : base(service) { Project = project; Taskqueue = taskqueue; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The id of the taskqueue to get the properties of.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>Whether to get stats. Optional.</summary> [Google.Apis.Util.RequestParameterAttribute("getStats", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> GetStats { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "getStats", new Google.Apis.Discovery.Parameter { Name = "getStats", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "tasks" collection of methods.</summary> public class TasksResource { private const string Resource = "tasks"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TasksResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Delete a task from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// to delete a task from.</param> /// <param name="task">The id of the task to delete.</param> public virtual DeleteRequest Delete(string project, string taskqueue, string task) { return new DeleteRequest(service, project, taskqueue, task); } /// <summary>Delete a task from a TaskQueue.</summary> public class DeleteRequest : TaskqueueBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, string task) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue to delete a task from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The id of the task to delete.</summary> [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Get a particular task from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// in which the task belongs.</param> /// <param name="task">The task to get properties of.</param> public virtual GetRequest Get(string project, string taskqueue, string task) { return new GetRequest(service, project, taskqueue, task); } /// <summary>Get a particular task from a TaskQueue.</summary> public class GetRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.Task> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, string task) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue in which the task belongs.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The task to get properties of.</summary> [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Lease 1 or more tasks from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// to lease a task from.</param> /// <param name="numTasks">The number of tasks to lease.</param> /// <param /// name="leaseSecs">The lease in seconds.</param> public virtual LeaseRequest Lease(string project, string taskqueue, int numTasks, int leaseSecs) { return new LeaseRequest(service, project, taskqueue, numTasks, leaseSecs); } /// <summary>Lease 1 or more tasks from a TaskQueue.</summary> public class LeaseRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.Tasks> { /// <summary>Constructs a new Lease request.</summary> public LeaseRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, int numTasks, int leaseSecs) : base(service) { Project = project; Taskqueue = taskqueue; NumTasks = numTasks; LeaseSecs = leaseSecs; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue to lease a task from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The number of tasks to lease.</summary> [Google.Apis.Util.RequestParameterAttribute("numTasks", Google.Apis.Util.RequestParameterType.Query)] public virtual int NumTasks { get; private set; } /// <summary>The lease in seconds.</summary> [Google.Apis.Util.RequestParameterAttribute("leaseSecs", Google.Apis.Util.RequestParameterType.Query)] public virtual int LeaseSecs { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "lease"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/lease"; } } /// <summary>Initializes Lease parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "numTasks", new Google.Apis.Discovery.Parameter { Name = "numTasks", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "leaseSecs", new Google.Apis.Discovery.Parameter { Name = "leaseSecs", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>List Tasks in a TaskQueue</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The id of the /// taskqueue to list tasks from.</param> public virtual ListRequest List(string project, string taskqueue) { return new ListRequest(service, project, taskqueue); } /// <summary>List Tasks in a TaskQueue</summary> public class ListRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.Tasks2> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string project, string taskqueue) : base(service) { Project = project; Taskqueue = taskqueue; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The id of the taskqueue to list tasks from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Taskqueue.v1beta1.Data { public class Task : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Time (in seconds since the epoch) at which the task was enqueued.</summary> [Newtonsoft.Json.JsonPropertyAttribute("enqueueTimestamp")] public virtual System.Nullable<long> EnqueueTimestamp { get; set; } /// <summary>Name of the task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind of object returned, in this case set to task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Time (in seconds since the epoch) at which the task lease will expire. This value is 0 if the task /// isnt currently leased out to a worker.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leaseTimestamp")] public virtual System.Nullable<long> LeaseTimestamp { get; set; } /// <summary>A bag of bytes which is the task payload. The payload on the JSON side is always Base64 /// encoded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("payloadBase64")] public virtual string PayloadBase64 { get; set; } /// <summary>Name of the queue that the task is in.</summary> [Newtonsoft.Json.JsonPropertyAttribute("queueName")] public virtual string QueueName { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class TaskQueue : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ACLs that are applicable to this TaskQueue object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("acl")] public virtual TaskQueue.AclData Acl { get; set; } /// <summary>Name of the taskqueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind of REST object returned, in this case taskqueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The number of times we should lease out tasks before giving up on them. If unset we lease them out /// forever until a worker deletes the task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("maxLeases")] public virtual System.Nullable<int> MaxLeases { get; set; } /// <summary>Statistics for the TaskQueue object in question.</summary> [Newtonsoft.Json.JsonPropertyAttribute("stats")] public virtual TaskQueue.StatsData Stats { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>ACLs that are applicable to this TaskQueue object.</summary> public class AclData { /// <summary>Email addresses of users who are "admins" of the TaskQueue. This means they can control the /// queue, eg set ACLs for the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("adminEmails")] public virtual System.Collections.Generic.IList<string> AdminEmails { get; set; } /// <summary>Email addresses of users who can "consume" tasks from the TaskQueue. This means they can /// Dequeue and Delete tasks from the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("consumerEmails")] public virtual System.Collections.Generic.IList<string> ConsumerEmails { get; set; } /// <summary>Email addresses of users who can "produce" tasks into the TaskQueue. This means they can Insert /// tasks into the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("producerEmails")] public virtual System.Collections.Generic.IList<string> ProducerEmails { get; set; } } /// <summary>Statistics for the TaskQueue object in question.</summary> public class StatsData { /// <summary>Number of tasks leased in the last hour.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leasedLastHour")] public virtual System.Nullable<long> LeasedLastHour { get; set; } /// <summary>Number of tasks leased in the last minute.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leasedLastMinute")] public virtual System.Nullable<long> LeasedLastMinute { get; set; } /// <summary>The timestamp (in seconds since the epoch) of the oldest unfinished task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("oldestTask")] public virtual System.Nullable<long> OldestTask { get; set; } /// <summary>Number of tasks in the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("totalTasks")] public virtual System.Nullable<int> TotalTasks { get; set; } } } public class Tasks : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The actual list of tasks returned as a result of the lease operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Task> Items { get; set; } /// <summary>The kind of object returned, a list of tasks.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class Tasks2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The actual list of tasks currently active in the TaskQueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Task> Items { get; set; } /// <summary>The kind of object returned, a list of tasks.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using Microsoft.SqlServer.Types; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.Unity; namespace Geospatial { /// <summary> /// RStar-Tree node /// </summary> /// <typeparam name="T"></typeparam> public class RTreeNode<T> { /// <summary> /// The children of a node /// </summary> public List<RTreeNode<T>> Children; /// <summary> /// The bounding box for this node if this is a parent node, if not is RTreeInfoNode it is the actual geography /// </summary> protected IGeography geography; /// <summary> /// Default tree initialization /// </summary> private int P = 32; private int M = 50; private int m = 20; /// <summary> /// This is to control the boundingbox calculation. If new child is added the BB needs to be recalculated, otherwise not /// </summary> private bool dirtyFlag = true; /// <summary> /// Is a node has leaves(RTreeInfoNode) under it /// </summary> public bool HasLeaves { get; set; } /// <summary> /// The parent of this node /// </summary> public RTreeNode<T> Parent { get; set; } /// <summary> /// If a node needs splitting in case it has gronw too much /// </summary> public bool NeedSplit { get { return this.Children.Count > this.M; } } /// <summary> /// If a node needs condensing if too many items were deleted /// </summary> public bool NeedCondense { get { return this.Children.Count < this.m; } } /// <summary> /// Create a new node giving its parent /// </summary> /// <param name="parent">The parent of this node</param> public RTreeNode(RTreeNode<T> parent) { this.Children = new List<RTreeNode<T>>(); this.HasLeaves = false; this.Parent = parent; } /// <summary> /// Create a new node given geography and parent /// </summary> /// <param name="geography">The node's geography</param> /// <param name="parent">The node's parent</param> public RTreeNode(IGeography geography, RTreeNode<T> parent) : this(parent) { this.geography = geography; } /// <summary> /// Split a node if needed /// </summary> /// <param name="llNode">The new node containing the splited children</param> /// <returns>True if this node needs splitting, false otherwise</returns> public bool SplitIfNeeded(out RTreeNode<T> llNode) { if (this.NeedSplit) { llNode = this.Split(); return true; } llNode = null; return false; } /// <summary> /// Add the new splitted node into the tree again /// </summary> /// <param name="tree">The tree to add the new splitted node</param> /// <param name="llNode">The splitted node</param> /// <returns>Return the tree new root in case root needed splitting</returns> public RTreeNode<T> AdjustNodeAfterSplit(RTree<T> tree, RTreeNode<T> llNode) { RTreeNode<T> newRoot = tree.Root; if (tree.Root == this) { newRoot = new RTreeNode<T>(tree.Degree, this); newRoot.AddNode(this); newRoot.AddNode(llNode); } else { this.Parent.AddNode(llNode); RTreeNode<T> newLLNode = null; if (this.Parent.SplitIfNeeded(out newLLNode)) { this.Parent.AdjustNodeAfterSplit(tree, newLLNode); } } return newRoot; } /// <summary> /// Create a new node /// </summary> /// <param name="M">The tree degree</param> /// <param name="geography">The geography for this new node</param> /// <param name="parent">The parent of this node</param> public RTreeNode(int M, IGeography geography, RTreeNode<T> parent) : this(geography, parent) { this.M = M; this.m = (int)(0.4*(M+1)); } /// <summary> /// Create a new node /// </summary> /// <param name="M">The tree degree</param> /// <param name="parent">The node parent</param> public RTreeNode(int M, RTreeNode<T> parent) : this(M, null, parent) { } public RTreeNode<T> Split() { Axis axisToSplit = this.ChooseSplitAxis(); int splitIndex = this.ChooseSplitIndex(axisToSplit); RTreeNode<T> ll = new RTreeNode<T>(this.M, null); ll.HasLeaves = this.HasLeaves; int llNodeCount = this.Children.Count - splitIndex; for (int index = splitIndex; index < splitIndex + llNodeCount; index++) { ll.Children.Add(this.Children[index]); this.Children[index].Parent = ll; } this.Children.RemoveRange(splitIndex, llNodeCount); this.dirtyFlag = true; return ll; } /// <summary> /// Choose which axis to split this node /// </summary> /// <returns>Latitude or Longitude axis</returns> public Axis ChooseSplitAxis() { double latitudeMarginValue = Double.MaxValue; double longitudeMarginValue = Double.MaxValue; // Sort BoudingBoxes on Latitude Axis this.SortChildrenOnAxis(Axis.Latitude); latitudeMarginValue = this.ComputeMinimalMargin(); this.SortChildrenOnAxis(Axis.Longitude); longitudeMarginValue = this.ComputeMinimalMargin(); if (latitudeMarginValue < longitudeMarginValue) { return Axis.Latitude; } else { return Axis.Longitude; } } /// <summary> /// Sort all children based on the splitting axis /// </summary> /// <param name="axis">Latitude or Longitude axis</param> public void SortChildrenOnAxis(Axis axis) { if (axis == Axis.Latitude) { this.Children.Sort(delegate(RTreeNode<T> a, RTreeNode<T> b) { int result = a.Geography.LowerLatitude.CompareTo(b.Geography.LowerLatitude); return result == 0 ? a.Geography.LowerLongitude.CompareTo(b.Geography.LowerLongitude) : result; }); } else { this.Children.Sort(delegate(RTreeNode<T> a, RTreeNode<T> b) { int result = a.Geography.LowerLongitude.CompareTo(b.Geography.LowerLongitude); return result == 0 ? a.Geography.LowerLatitude.CompareTo(b.Geography.LowerLatitude) : result; }); } } /// <summary> /// Choose the split index to split the node /// </summary> /// <param name="axis">The axis to split the node</param> /// <returns>The index in which the split must be done</returns> public int ChooseSplitIndex(Axis axis) { if (axis == Axis.Latitude) { this.SortChildrenOnAxis(Axis.Latitude); } else { this.SortChildrenOnAxis(Axis.Longitude); } int minSplitIndex = this.m; int splitIndex = 1; double minOverlap = Double.MaxValue; double minArea = Double.MaxValue; IGeography firstSet = this.Children[0].Geography; for (splitIndex = 1; splitIndex < this.m; splitIndex++) { firstSet = firstSet.Union(this.Children[splitIndex].Geography); } IGeography secondSet = null; for (int i = splitIndex; i < this.Children.Count; i++) { if (secondSet == null) { secondSet = this.Children[i].Geography; } else { secondSet = secondSet.Union(this.Children[i].Geography); } } IGeography firstSetBB = firstSet; IGeography secondSetBB = secondSet; double overlap = this.ComputeAreaOverlap(firstSetBB, secondSetBB); if (overlap == minOverlap) { double area = firstSetBB.Area() + secondSetBB.Area(); if (area < minArea) { minArea = area; minSplitIndex = splitIndex; } } else if (overlap < minOverlap) { minOverlap = overlap; minArea = firstSetBB.Area() + secondSetBB.Area(); } for (; splitIndex < (M+1) - this.m; splitIndex++) { firstSet = firstSet.Union(this.Children[splitIndex].Geography); secondSet = null; for (int i = splitIndex+1; i < this.Children.Count; i++) { if (secondSet == null) { secondSet = this.Children[i].Geography; } else { secondSet = secondSet.Union(this.Children[i].Geography); } } firstSetBB = firstSet; secondSetBB = secondSet; overlap = this.ComputeAreaOverlap(firstSetBB, secondSetBB); if (overlap == minOverlap) { double area = firstSetBB.Area() + secondSetBB.Area(); if (area < minArea) { minArea = area; minSplitIndex = splitIndex; } } else if (overlap < minOverlap) { minOverlap = overlap; minArea = firstSetBB.Area() + secondSetBB.Area(); } } return minSplitIndex; } /// <summary> /// Compute the area of overlap between two geographies /// </summary> /// <param name="firstSetBB">The geography</param> /// <param name="secondSetBB">The other geography</param> /// <returns>The overlapping area between two geographies</returns> public double ComputeAreaOverlap(IGeography firstSetBB, IGeography secondSetBB) { return firstSetBB.Intersection(secondSetBB).Area(); } /// <summary> /// Compute the minimal margin of this node /// </summary> /// <returns>The minimum margin</returns> public double ComputeMinimalMargin() { double minAxialMargin = Double.MaxValue; IGeography unionGeometry = this.Children[0].Geography; for (int i = 1; i < this.m; i++) { unionGeometry = unionGeometry.Union(this.Children[i].Geography); } minAxialMargin = Math.Min(minAxialMargin, this.ComputeMargin(unionGeometry)); for (int i = m; i < M - m; i++) { unionGeometry = unionGeometry.Union(this.Children[i].Geography); minAxialMargin = Math.Min(minAxialMargin, this.ComputeMargin(unionGeometry)); } return minAxialMargin; } /// <summary> /// Build the node geography bounding box /// </summary> /// <returns>The node bounding box</returns> public IGeography BuildNodeGeography() { IGeography unionGeography = null; for (int i = 0; i < this.Children.Count; i++) { if (unionGeography == null) { unionGeography = this.Children[i].Geography; } else { unionGeography = unionGeography.Union(this.Children[i].Geography); } } return unionGeography.GeographyBoundingBox(); } /// <summary> /// Compute this node bounding box margin /// </summary> /// <param name="unionGeography"></param> /// <returns>The margin for this node BB</returns> public double ComputeMargin(IGeography unionGeography) { IGeography pointA; IGeography pointB; IGeography pointC; pointA = GeographyOperations.CreatePoint(unionGeography.LowerLatitude, unionGeography.LowerLongitude); pointB = GeographyOperations.CreatePoint(unionGeography.UpperLatitude, unionGeography.LowerLongitude); pointC = GeographyOperations.CreatePoint(unionGeography.UpperLatitude, unionGeography.UpperLongitude); return pointA.Distance(pointB) + pointB.Distance(pointC); } /// <summary> /// The geography for this node /// </summary> public IGeography Geography { get { if (this.dirtyFlag) { this.geography = this.BuildNodeGeography(); this.dirtyFlag = false; } return this.geography; } } /// <summary> /// Verify if this node is pointing to leaves /// </summary> /// <returns>True if it has leaves, false otherwise</returns> public bool PointingToLeafNodes() { return this.Children[0].HasLeaves; } /// <summary> /// Add a new node as children /// </summary> /// <param name="node">The node to be added</param> public void AddNode(RTreeNode<T> node) { this.dirtyFlag = true; this.Children.Add(node); node.Parent = this; } /// <summary> /// Get a list of ordered geographies by enlargement area if item was to be added to them /// </summary> /// <param name="item">The item to be added</param> /// <returns>Ordered list of geographies by enlarment area</returns> public List<Tuple<double, IGeography, RTreeNode<T>>> GetOrderedEnlargementByArea(IGeography item) { List<Tuple<double, IGeography, RTreeNode<T>>> orderedEnlargement = new List<Tuple<double, IGeography, RTreeNode<T>>>(); foreach (RTreeNode<T> child in this.Children) { IGeography originalBB = child.Geography; IGeography enlargedBB = originalBB.Union(item); double enlargmentDifference = enlargedBB.Area() - originalBB.Area(); orderedEnlargement.Add(new Tuple<double, IGeography, RTreeNode<T>>(enlargmentDifference, enlargedBB, child)); } orderedEnlargement.Sort(delegate(Tuple<double, IGeography, RTreeNode<T>> a, Tuple<double, IGeography, RTreeNode<T>> b) { return a.Item1.CompareTo(b.Item1); }); return orderedEnlargement; } /// <summary> /// Choose minimal overlap cost between all the enlarment areas /// </summary> /// <param name="orderedEnlargement">The ordered list of enlargement</param> /// <returns>The node with the minimal overlaping cost if enlarged</returns> public RTreeNode<T> ChooseMinimumOverlapCost(List<Tuple<double, IGeography, RTreeNode<T>>> orderedEnlargement) { RTreeNode<T> minimumChild = null; double minimumOverlap = Double.MaxValue; double minimumAreaEnlargement = Double.MaxValue; for (int orderedIndex = 0; orderedIndex < Math.Min(this.P, orderedEnlargement.Count); orderedIndex++) { foreach (RTreeNode<T> child in this.Children) { IGeography overlap = orderedEnlargement[orderedIndex].Item2.Intersection(child.Geography); double overlapArea = overlap.Area(); if (overlapArea <= minimumOverlap && orderedEnlargement[orderedIndex].Item1 < minimumAreaEnlargement) { minimumOverlap = overlapArea; minimumChild = orderedEnlargement[orderedIndex].Item3; minimumAreaEnlargement = orderedEnlargement[orderedIndex].Item1; } } } return minimumChild; } /// <summary> /// The minimal area cost of enlargement /// </summary> /// <param name="orderedEnlargement">The ordered list of enlargement</param> /// <returns>The minimal area</returns> public RTreeNode<T> ChooseMinimumAreaCost(List<Tuple<double, IGeography, RTreeNode<T>>> orderedEnlargement) { return orderedEnlargement[0].Item3; } /// <summary> /// Choose a leaf to add a new item /// </summary> /// <param name="item">The new item to be added</param> /// <returns>The node where the new item should be added</returns> public RTreeNode<T> ChooseLeaf(IGeography item) { RTreeNode<T> N = this; while (!N.HasLeaves) { List<Tuple<double, IGeography, RTreeNode<T>>> orderedAreas = N.GetOrderedEnlargementByArea(item); if (N.PointingToLeafNodes()) { N = N.ChooseMinimumOverlapCost(orderedAreas); } else { N = N.ChooseMinimumAreaCost(orderedAreas); } } return N; } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using Caps = OpenSim.Framework.Capabilities.Caps; using OSDMap = OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.OptionalModules.ViewerSupport { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicMenu")] public class DynamicMenuModule : INonSharedRegionModule, IDynamicMenuModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private class MenuItemData { public string Title; public UUID AgentID; public InsertLocation Location; public UserMode Mode; public CustomMenuHandler Handler; } private Dictionary<UUID, List<MenuItemData>> m_menuItems = new Dictionary<UUID, List<MenuItemData>>(); private Scene m_scene; public string Name { get { return "DynamicMenuModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { } public void Close() { } public void AddRegion(Scene scene) { m_scene = scene; scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.RegisterModuleInterface<IDynamicMenuModule>(this); } public void RegionLoaded(Scene scene) { ISimulatorFeaturesModule featuresModule = m_scene.RequestModuleInterface<ISimulatorFeaturesModule>(); if (featuresModule != null) featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest; } public void RemoveRegion(Scene scene) { } private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features) { OSD menus = new OSDMap(); if (features.ContainsKey("menus")) menus = features["menus"]; OSDMap agent = new OSDMap(); OSDMap world = new OSDMap(); OSDMap tools = new OSDMap(); OSDMap advanced = new OSDMap(); OSDMap admin = new OSDMap(); if (((OSDMap)menus).ContainsKey("agent")) agent = (OSDMap)((OSDMap)menus)["agent"]; if (((OSDMap)menus).ContainsKey("world")) world = (OSDMap)((OSDMap)menus)["world"]; if (((OSDMap)menus).ContainsKey("tools")) tools = (OSDMap)((OSDMap)menus)["tools"]; if (((OSDMap)menus).ContainsKey("advanced")) advanced = (OSDMap)((OSDMap)menus)["advanced"]; if (((OSDMap)menus).ContainsKey("admin")) admin = (OSDMap)((OSDMap)menus)["admin"]; if (m_menuItems.ContainsKey(UUID.Zero)) { foreach (MenuItemData d in m_menuItems[UUID.Zero]) { if (d.Mode == UserMode.God && (!m_scene.Permissions.IsGod(agentID))) continue; OSDMap loc = null; switch (d.Location) { case InsertLocation.Agent: loc = agent; break; case InsertLocation.World: loc = world; break; case InsertLocation.Tools: loc = tools; break; case InsertLocation.Advanced: loc = advanced; break; case InsertLocation.Admin: loc = admin; break; } if (loc == null) continue; loc[d.Title] = OSD.FromString(d.Title); } } if (m_menuItems.ContainsKey(agentID)) { foreach (MenuItemData d in m_menuItems[agentID]) { if (d.Mode == UserMode.God && (!m_scene.Permissions.IsGod(agentID))) continue; OSDMap loc = null; switch (d.Location) { case InsertLocation.Agent: loc = agent; break; case InsertLocation.World: loc = world; break; case InsertLocation.Tools: loc = tools; break; case InsertLocation.Advanced: loc = advanced; break; case InsertLocation.Admin: loc = admin; break; } if (loc == null) continue; loc[d.Title] = OSD.FromString(d.Title); } } ((OSDMap)menus)["agent"] = agent; ((OSDMap)menus)["world"] = world; ((OSDMap)menus)["tools"] = tools; ((OSDMap)menus)["advanced"] = advanced; ((OSDMap)menus)["admin"] = admin; features["menus"] = menus; } private void OnRegisterCaps(UUID agentID, Caps caps) { string capUrl = "/CAPS/" + UUID.Random() + "/"; capUrl = "/CAPS/" + UUID.Random() + "/"; caps.RegisterHandler("CustomMenuAction", new MenuActionHandler(capUrl, "CustomMenuAction", agentID, this, m_scene)); } internal void HandleMenuSelection(string action, UUID agentID, List<uint> selection) { if (m_menuItems.ContainsKey(agentID)) { foreach (MenuItemData d in m_menuItems[agentID]) { if (d.Title == action) d.Handler(action, agentID, selection); } } if (m_menuItems.ContainsKey(UUID.Zero)) { foreach (MenuItemData d in m_menuItems[UUID.Zero]) { if (d.Title == action) d.Handler(action, agentID, selection); } } } public void AddMenuItem(string title, InsertLocation location, UserMode mode, CustomMenuHandler handler) { AddMenuItem(UUID.Zero, title, location, mode, handler); } public void AddMenuItem(UUID agentID, string title, InsertLocation location, UserMode mode, CustomMenuHandler handler) { if (!m_menuItems.ContainsKey(agentID)) m_menuItems[agentID] = new List<MenuItemData>(); m_menuItems[agentID].Add(new MenuItemData() { Title = title, AgentID = agentID, Location = location, Mode = mode, Handler = handler }); } public void RemoveMenuItem(string action) { foreach (KeyValuePair<UUID,List< MenuItemData>> kvp in m_menuItems) { List<MenuItemData> pendingDeletes = new List<MenuItemData>(); foreach (MenuItemData d in kvp.Value) { if (d.Title == action) pendingDeletes.Add(d); } foreach (MenuItemData d in pendingDeletes) kvp.Value.Remove(d); } } } public class MenuActionHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private UUID m_agentID; private Scene m_scene; private DynamicMenuModule m_module; public MenuActionHandler(string path, string name, UUID agentID, DynamicMenuModule module, Scene scene) :base("POST", path, name, agentID.ToString()) { m_agentID = agentID; m_scene = scene; m_module = module; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader reader = new StreamReader(request); string requestBody = reader.ReadToEnd(); OSD osd = OSDParser.DeserializeLLSDXml(requestBody); string action = ((OSDMap)osd)["action"].AsString(); OSDArray selection = (OSDArray)((OSDMap)osd)["selection"]; List<uint> sel = new List<uint>(); for (int i = 0 ; i < selection.Count ; i++) sel.Add(selection[i].AsUInteger()); Util.FireAndForget(x => { m_module.HandleMenuSelection(action, m_agentID, sel); }); Encoding encoding = Encoding.UTF8; return encoding.GetBytes(OSDParser.SerializeLLSDXmlString(new OSD())); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.WebParts.WebPartVerb.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls.WebParts { public partial class WebPartVerb : System.Web.UI.IStateManager { #region Methods and constructors protected virtual new void LoadViewState (Object savedState) { } protected virtual new Object SaveViewState () { return default(Object); } void System.Web.UI.IStateManager.LoadViewState (Object savedState) { } Object System.Web.UI.IStateManager.SaveViewState () { return default(Object); } void System.Web.UI.IStateManager.TrackViewState () { } protected virtual new void TrackViewState () { } public WebPartVerb (string id, WebPartEventHandler serverClickHandler) { Contract.Ensures (!string.IsNullOrEmpty(id)); } public WebPartVerb (string id, WebPartEventHandler serverClickHandler, string clientClickHandler) { Contract.Ensures (!string.IsNullOrEmpty(id)); Contract.Ensures (!string.IsNullOrEmpty(clientClickHandler)); } public WebPartVerb (string id, string clientClickHandler) { Contract.Ensures (!string.IsNullOrEmpty(id)); Contract.Ensures (!string.IsNullOrEmpty(clientClickHandler)); } #endregion #region Properties and indexers public virtual new bool Checked { get { return default(bool); } set { } } public string ClientClickHandler { get { return default(string); } } public virtual new string Description { get { return default(string); } set { } } public virtual new bool Enabled { get { return default(bool); } set { } } public string ID { get { return default(string); } } public virtual new string ImageUrl { get { return default(string); } set { } } protected virtual new bool IsTrackingViewState { get { return default(bool); } } public WebPartEventHandler ServerClickHandler { get { return default(WebPartEventHandler); } } bool System.Web.UI.IStateManager.IsTrackingViewState { get { return default(bool); } } public virtual new string Text { get { return default(string); } set { } } protected System.Web.UI.StateBag ViewState { get { Contract.Ensures (Contract.Result<System.Web.UI.StateBag>() != null); return default(System.Web.UI.StateBag); } } public virtual new bool Visible { get { return default(bool); } set { } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; namespace InControl { public class UnityInputDeviceManager : InputDeviceManager { float deviceRefreshTimer = 0.0f; const float deviceRefreshInterval = 1.0f; List<UnityInputDeviceProfile> deviceProfiles = new List<UnityInputDeviceProfile>(); bool keyboardDevicesAttached = false; string joystickHash = ""; public UnityInputDeviceManager() { AutoDiscoverDeviceProfiles(); RefreshDevices(); } public override void Update( ulong updateTick, float deltaTime ) { deviceRefreshTimer += deltaTime; if (string.IsNullOrEmpty( joystickHash ) || deviceRefreshTimer >= deviceRefreshInterval) { deviceRefreshTimer = 0.0f; if (joystickHash != JoystickHash) { Logger.LogInfo( "Change in Unity attached joysticks detected; refreshing device list." ); RefreshDevices(); } } } void RefreshDevices() { AttachKeyboardDevices(); DetectAttachedJoystickDevices(); DetectDetachedJoystickDevices(); joystickHash = JoystickHash; } void AttachDevice( UnityInputDevice device ) { devices.Add( device ); InputManager.AttachDevice( device ); } void AttachKeyboardDevices() { int deviceProfileCount = deviceProfiles.Count; for (int i = 0; i < deviceProfileCount; i++) { var deviceProfile = deviceProfiles[i]; if (deviceProfile.IsNotJoystick && deviceProfile.IsSupportedOnThisPlatform) { AttachKeyboardDeviceWithConfig( deviceProfile ); } } } void AttachKeyboardDeviceWithConfig( UnityInputDeviceProfile config ) { if (keyboardDevicesAttached) { return; } var keyboardDevice = new UnityInputDevice( config ); AttachDevice( keyboardDevice ); keyboardDevicesAttached = true; } void DetectAttachedJoystickDevices() { try { var joystickNames = Input.GetJoystickNames(); for (int i = 0; i < joystickNames.Length; i++) { DetectAttachedJoystickDevice( i + 1, joystickNames[i] ); } } catch (Exception e) { Logger.LogError( e.Message ); Logger.LogError( e.StackTrace ); } } void DetectAttachedJoystickDevice( int unityJoystickId, string unityJoystickName ) { if (unityJoystickName == "WIRED CONTROLLER" || unityJoystickName == " WIRED CONTROLLER") { // Ignore Steam controller for now. return; } if (unityJoystickName.IndexOf( "webcam", StringComparison.OrdinalIgnoreCase ) != -1) { // Unity thinks some webcams are joysticks. >_< return; } // PS4 controller works properly as of Unity 4.5 if (InputManager.UnityVersion <= new VersionInfo( 4, 5 )) { if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer) { if (unityJoystickName == "Unknown Wireless Controller") { // Ignore PS4 controller in Bluetooth mode on Mac since it connects but does nothing. return; } } } // As of Unity 4.6.3p1, empty strings on windows represent disconnected devices. if (InputManager.UnityVersion >= new VersionInfo( 4, 6, 3 )) { if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) { if (String.IsNullOrEmpty( unityJoystickName )) { return; } } } var matchedDeviceProfile = deviceProfiles.Find( config => config.HasJoystickName( unityJoystickName ) ); if (matchedDeviceProfile == null) { matchedDeviceProfile = deviceProfiles.Find( config => config.HasLastResortRegex( unityJoystickName ) ); } UnityInputDeviceProfile deviceProfile = null; if (matchedDeviceProfile == null) { deviceProfile = new UnityUnknownDeviceProfile( unityJoystickName ); deviceProfiles.Add( deviceProfile ); } else { deviceProfile = matchedDeviceProfile; } int deviceCount = devices.Count; for (int i = 0; i < deviceCount; i++) { var device = devices[i]; var unityDevice = device as UnityInputDevice; if (unityDevice != null && unityDevice.IsConfiguredWith( deviceProfile, unityJoystickId )) { Logger.LogInfo( "Device \"" + unityJoystickName + "\" is already configured with " + deviceProfile.Name ); return; } } if (!deviceProfile.IsHidden) { var joystickDevice = new UnityInputDevice( deviceProfile, unityJoystickId ); AttachDevice( joystickDevice ); if (matchedDeviceProfile == null) { Logger.LogWarning( "Device " + unityJoystickId + " with name \"" + unityJoystickName + "\" does not match any known profiles." ); } else { Logger.LogInfo( "Device " + unityJoystickId + " matched profile " + deviceProfile.GetType().Name + " (" + deviceProfile.Name + ")" ); } } else { Logger.LogInfo( "Device " + unityJoystickId + " matching profile " + deviceProfile.GetType().Name + " (" + deviceProfile.Name + ")" + " is hidden and will not be attached." ); } } void DetectDetachedJoystickDevices() { var joystickNames = Input.GetJoystickNames(); for (int i = devices.Count - 1; i >= 0; i--) { var inputDevice = devices[i] as UnityInputDevice; if (inputDevice.Profile.IsNotJoystick) { continue; } if (joystickNames.Length < inputDevice.JoystickId || !inputDevice.Profile.HasJoystickOrRegexName( joystickNames[inputDevice.JoystickId - 1] )) { devices.Remove( inputDevice ); InputManager.DetachDevice( inputDevice ); Logger.LogInfo( "Detached device: " + inputDevice.Profile.Name ); } } } void AutoDiscoverDeviceProfiles() { foreach (var typeName in UnityInputDeviceProfileList.Profiles) { var deviceProfile = (UnityInputDeviceProfile) Activator.CreateInstance( Type.GetType( typeName ) ); if (deviceProfile.IsSupportedOnThisPlatform) { // Logger.LogInfo( "Found profile: " + deviceProfile.GetType().Name + " (" + deviceProfile.Name + ")" ); deviceProfiles.Add( deviceProfile ); } } } static string JoystickHash { get { var joystickNames = Input.GetJoystickNames(); return joystickNames.Length + ": " + String.Join( ", ", joystickNames ); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Events; namespace Prism.Tests.Events { [TestClass] public class PubSubEventFixture { [TestMethod] public void CanSubscribeAndRaiseEvent() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); bool published = false; pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, true, delegate { return true; }); pubSubEvent.Publish(null); Assert.IsTrue(published); } [TestMethod] public void CanSubscribeAndRaiseCustomEvent() { var customEvent = new TestablePubSubEvent<Payload>(); Payload payload = new Payload(); var action = new ActionHelper(); customEvent.Subscribe(action.Action); customEvent.Publish(payload); Assert.AreSame(action.ActionArg<Payload>(), payload); } [TestMethod] public void CanHaveMultipleSubscribersAndRaiseCustomEvent() { var customEvent = new TestablePubSubEvent<Payload>(); Payload payload = new Payload(); var action1 = new ActionHelper(); var action2 = new ActionHelper(); customEvent.Subscribe(action1.Action); customEvent.Subscribe(action2.Action); customEvent.Publish(payload); Assert.AreSame(action1.ActionArg<Payload>(), payload); Assert.AreSame(action2.ActionArg<Payload>(), payload); } [TestMethod] public void SubscribeTakesExecuteDelegateThreadOptionAndFilter() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); var action = new ActionHelper(); pubSubEvent.Subscribe(action.Action); pubSubEvent.Publish("test"); Assert.AreEqual("test", action.ActionArg<string>()); } [TestMethod] public void FilterEnablesActionTarget() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); var goodFilter = new MockFilter { FilterReturnValue = true }; var actionGoodFilter = new ActionHelper(); var badFilter = new MockFilter { FilterReturnValue = false }; var actionBadFilter = new ActionHelper(); pubSubEvent.Subscribe(actionGoodFilter.Action, ThreadOption.PublisherThread, true, goodFilter.FilterString); pubSubEvent.Subscribe(actionBadFilter.Action, ThreadOption.PublisherThread, true, badFilter.FilterString); pubSubEvent.Publish("test"); Assert.IsTrue(actionGoodFilter.ActionCalled); Assert.IsFalse(actionBadFilter.ActionCalled); } [TestMethod] public void SubscribeDefaultsThreadOptionAndNoFilter() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); SynchronizationContext calledSyncContext = null; var myAction = new ActionHelper() { ActionToExecute = () => calledSyncContext = SynchronizationContext.Current }; pubSubEvent.Subscribe(myAction.Action); pubSubEvent.Publish("test"); Assert.AreEqual(SynchronizationContext.Current, calledSyncContext); } [TestMethod] public void ShouldUnsubscribeFromPublisherThread() { var PubSubEvent = new TestablePubSubEvent<string>(); var actionEvent = new ActionHelper(); PubSubEvent.Subscribe( actionEvent.Action, ThreadOption.PublisherThread); Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action)); PubSubEvent.Unsubscribe(actionEvent.Action); Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action)); } [TestMethod] public void UnsubscribeShouldNotFailWithNonSubscriber() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); Action<string> subscriber = delegate { }; pubSubEvent.Unsubscribe(subscriber); } [TestMethod] public void ShouldUnsubscribeFromBackgroundThread() { var PubSubEvent = new TestablePubSubEvent<string>(); var actionEvent = new ActionHelper(); PubSubEvent.Subscribe( actionEvent.Action, ThreadOption.BackgroundThread); Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action)); PubSubEvent.Unsubscribe(actionEvent.Action); Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action)); } [TestMethod] public void ShouldUnsubscribeFromUIThread() { var PubSubEvent = new TestablePubSubEvent<string>(); PubSubEvent.SynchronizationContext = new SynchronizationContext(); var actionEvent = new ActionHelper(); PubSubEvent.Subscribe( actionEvent.Action, ThreadOption.UIThread); Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action)); PubSubEvent.Unsubscribe(actionEvent.Action); Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action)); } [TestMethod] public void ShouldUnsubscribeASingleDelegate() { var PubSubEvent = new TestablePubSubEvent<string>(); int callCount = 0; var actionEvent = new ActionHelper() { ActionToExecute = () => callCount++ }; PubSubEvent.Subscribe(actionEvent.Action); PubSubEvent.Subscribe(actionEvent.Action); PubSubEvent.Publish(null); Assert.AreEqual<int>(2, callCount); callCount = 0; PubSubEvent.Unsubscribe(actionEvent.Action); PubSubEvent.Publish(null); Assert.AreEqual<int>(1, callCount); } [TestMethod] public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAlive() { var PubSubEvent = new TestablePubSubEvent<string>(); ExternalAction externalAction = new ExternalAction(); PubSubEvent.Subscribe(externalAction.ExecuteAction); PubSubEvent.Publish("testPayload"); Assert.AreEqual("testPayload", externalAction.PassedValue); WeakReference actionEventReference = new WeakReference(externalAction); externalAction = null; GC.Collect(); Assert.IsFalse(actionEventReference.IsAlive); PubSubEvent.Publish("testPayload"); } [TestMethod] public void ShouldNotExecuteOnGarbageCollectedFilterReferenceWhenNotKeepAlive() { var PubSubEvent = new TestablePubSubEvent<string>(); bool wasCalled = false; var actionEvent = new ActionHelper() { ActionToExecute = () => wasCalled = true }; ExternalFilter filter = new ExternalFilter(); PubSubEvent.Subscribe(actionEvent.Action, ThreadOption.PublisherThread, false, filter.AlwaysTrueFilter); PubSubEvent.Publish("testPayload"); Assert.IsTrue(wasCalled); wasCalled = false; WeakReference filterReference = new WeakReference(filter); filter = null; GC.Collect(); Assert.IsFalse(filterReference.IsAlive); PubSubEvent.Publish("testPayload"); Assert.IsFalse(wasCalled); } [TestMethod] public void CanAddSubscriptionWhileEventIsFiring() { var PubSubEvent = new TestablePubSubEvent<string>(); var emptyAction = new ActionHelper(); var subscriptionAction = new ActionHelper { ActionToExecute = (() => PubSubEvent.Subscribe( emptyAction.Action)) }; PubSubEvent.Subscribe(subscriptionAction.Action); Assert.IsFalse(PubSubEvent.Contains(emptyAction.Action)); PubSubEvent.Publish(null); Assert.IsTrue((PubSubEvent.Contains(emptyAction.Action))); } [TestMethod] public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferences() { var PubSubEvent = new TestablePubSubEvent<string>(); bool published = false; PubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, false, delegate { return true; }); GC.Collect(); PubSubEvent.Publish(null); Assert.IsTrue(published); } [TestMethod] public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAlive() { var PubSubEvent = new TestablePubSubEvent<string>(); var externalAction = new ExternalAction(); PubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true); WeakReference actionEventReference = new WeakReference(externalAction); externalAction = null; GC.Collect(); GC.Collect(); Assert.IsTrue(actionEventReference.IsAlive); PubSubEvent.Publish("testPayload"); Assert.AreEqual("testPayload", ((ExternalAction)actionEventReference.Target).PassedValue); } [TestMethod] public void RegisterReturnsTokenThatCanBeUsedToUnsubscribe() { var PubSubEvent = new TestablePubSubEvent<string>(); var emptyAction = new ActionHelper(); var token = PubSubEvent.Subscribe(emptyAction.Action); PubSubEvent.Unsubscribe(token); Assert.IsFalse(PubSubEvent.Contains(emptyAction.Action)); } [TestMethod] public void ContainsShouldSearchByToken() { var PubSubEvent = new TestablePubSubEvent<string>(); var emptyAction = new ActionHelper(); var token = PubSubEvent.Subscribe(emptyAction.Action); Assert.IsTrue(PubSubEvent.Contains(token)); PubSubEvent.Unsubscribe(emptyAction.Action); Assert.IsFalse(PubSubEvent.Contains(token)); } [TestMethod] public void SubscribeDefaultsToPublisherThread() { var PubSubEvent = new TestablePubSubEvent<string>(); Action<string> action = delegate { }; var token = PubSubEvent.Subscribe(action, true); Assert.AreEqual(1, PubSubEvent.BaseSubscriptions.Count); Assert.AreEqual(typeof(EventSubscription<string>), PubSubEvent.BaseSubscriptions.ElementAt(0).GetType()); } public class ExternalFilter { public bool AlwaysTrueFilter(string value) { return true; } } public class ExternalAction { public string PassedValue; public void ExecuteAction(string value) { PassedValue = value; } } class TestablePubSubEvent<TPayload> : PubSubEvent<TPayload> { public ICollection<IEventSubscription> BaseSubscriptions { get { return base.Subscriptions; } } } public class Payload { } } public class ActionHelper { public bool ActionCalled; public Action ActionToExecute = null; private object actionArg; public T ActionArg<T>() { return (T)actionArg; } public void Action(PubSubEventFixture.Payload arg) { Action((object)arg); } public void Action(string arg) { Action((object)arg); } public void Action(object arg) { actionArg = arg; ActionCalled = true; if (ActionToExecute != null) { ActionToExecute.Invoke(); } } } public class MockFilter { public bool FilterReturnValue; public bool FilterString(string arg) { return FilterReturnValue; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Diagnostics; using Axiom.Core; using Axiom.Graphics; using Axiom.MathLib; using Axiom.Configuration; namespace Multiverse.Tools.ToolTemplate { public partial class Form1 : Form { protected readonly float oneMeter = 1000.0f; protected Root engine; protected Camera camera; protected Viewport viewport; protected SceneManager scene; protected RenderWindow window; protected bool quit = false; protected float time = 0; protected bool displayWireFrame = false; protected bool displayTerrainTiles = true; protected bool displayTerrainStitches = true; protected bool displayOcean = true; protected bool spinCamera = false; Multiverse.Generator.Generator terrainGenerator; public Form1() { InitializeComponent(); terrainGenerator = new Multiverse.Generator.Generator(); } #region Axiom Initialization Code protected bool Setup() { // get a reference to the engine singleton engine = new Root("EngineConfig.xml", "AxiomEngine.log"); // add event handlers for frame events engine.FrameStarted += new FrameEvent(OnFrameStarted); engine.FrameEnded += new FrameEvent(OnFrameEnded); // allow for setting up resource gathering SetupResources(); //show the config dialog and collect options if (!ConfigureAxiom()) { // shutting right back down engine.Shutdown(); return false; } ChooseSceneManager(); CreateCamera(); CreateViewports(); // set default mipmap level TextureManager.Instance.DefaultNumMipMaps = 5; // call the overridden CreateScene method CreateScene(); return true; } protected void SetupResources() { EngineConfig config = new EngineConfig(); // load the config file // relative from the location of debug and releases executables config.ReadXml("EngineConfig.xml"); // interrogate the available resource paths foreach (EngineConfig.FilePathRow row in config.FilePath) { string fullPath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + row.src; ResourceManager.AddCommonArchive(fullPath, row.type); } } protected bool ConfigureAxiom() { // HACK: Temporary RenderSystem renderSystem = Root.Instance.RenderSystems[0]; Root.Instance.RenderSystem = renderSystem; Root.Instance.Initialize(false); window = Root.Instance.CreateRenderWindow("Main Window", axiomPictureBox.Width, axiomPictureBox.Height, false, "externalWindow", axiomPictureBox, "useNVPerfHUD", true); Root.Instance.Initialize(false); return true; } protected void ChooseSceneManager() { scene = Root.Instance.SceneManagers.GetSceneManager(SceneType.ExteriorClose); } protected void CreateCamera() { camera = scene.CreateCamera("PlayerCam"); camera.Position = new Vector3(128 * oneMeter, 200 * oneMeter, 128 * oneMeter); camera.LookAt(new Vector3(0, 0, -300 * oneMeter)); camera.Near = 1 * oneMeter; camera.Far = 10000 * oneMeter; } protected virtual void CreateViewports() { Debug.Assert(window != null, "Attempting to use a null RenderWindow."); // create a new viewport and set it's background color viewport = window.AddViewport(camera, 0, 0, 1.0f, 1.0f, 100); viewport.BackgroundColor = ColorEx.Black; } #endregion Axiom Initialization Code #region Application Startup Code public bool Start() { if (!Setup()) { return false; } // start the engines rendering loop engine.StartRendering(); return true; } #endregion Application Startup Code #region Scene Setup protected void GenerateScene() { ((Axiom.SceneManagers.Multiverse.SceneManager)scene).SetWorldParams(terrainGenerator, null, 256, 4); scene.LoadWorldGeometry(""); Axiom.SceneManagers.Multiverse.WorldManager.Instance.ShowOcean = displayOcean; Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawTiles = displayTerrainTiles; Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawStitches = displayTerrainStitches; scene.AmbientLight = new ColorEx(0.8f, 0.8f, 0.8f); Light light = scene.CreateLight("MainLight"); light.Type = LightType.Directional; Vector3 lightDir = new Vector3(-80 * oneMeter, -70 * oneMeter, -80 * oneMeter); lightDir.Normalize(); light.Direction = lightDir; light.Position = -lightDir; light.Diffuse = ColorEx.White; light.SetAttenuation(1000 * oneMeter, 1, 0, 0); return; } private void Regenerate() { GenerateScene(); } protected void CreateScene() { viewport.BackgroundColor = ColorEx.White; viewport.OverlaysEnabled = false; GenerateScene(); scene.SetFog(FogMode.Linear, ColorEx.White, .008f, 0, 1000 * oneMeter); return; } #endregion Scene Setup #region Axiom Frame Event Handlers protected void OnFrameEnded(object source, FrameEventArgs e) { return; } protected void OnFrameStarted(object source, FrameEventArgs e) { if (quit) { Root.Instance.QueueEndRendering(); return; } float scaleMove = 100 * e.TimeSinceLastFrame * oneMeter; time += e.TimeSinceLastFrame; Axiom.SceneManagers.Multiverse.WorldManager.Instance.Time = time; if (spinCamera) { float rot = 20 * e.TimeSinceLastFrame; camera.Yaw(rot); } //// reset acceleration zero //camAccel = Vector3.Zero; //// set the scaling of camera motion //cameraScale = 100 * e.TimeSinceLastFrame; //if (moveForward) //{ // camAccel.z = -1.0f; //} //if (moveBack) //{ // camAccel.z = 1.0f; //} //if (moveLeft) //{ // camAccel.x = -0.5f; //} //if (moveRight) //{ // camAccel.x = 0.5f; //} //// handle rotation of the camera with the mouse //if (mouseRotate) //{ // float deltaX = mouseX - lastMouseX; // float deltaY = mouseY - lastMouseY; // camera.Yaw(-deltaX * mouseRotationScale); // camera.Pitch(-deltaY * mouseRotationScale); //} //// update last mouse position //lastMouseX = mouseX; //lastMouseY = mouseY; //if (humanSpeed) //{ // camVelocity = camAccel * 7.0f * oneMeter; // camera.MoveRelative(camVelocity * e.TimeSinceLastFrame); //} //else //{ // camVelocity += (camAccel * scaleMove * camSpeed); // // move the camera based on the accumulated movement vector // camera.MoveRelative(camVelocity * e.TimeSinceLastFrame); // // Now dampen the Velocity - only if user is not accelerating // if (camAccel == Vector3.Zero) // { // float decel = 1 - (6 * e.TimeSinceLastFrame); // if (decel < 0) // { // decel = 0; // } // camVelocity *= decel; // } //} //if (followTerrain || (result.worldFragment.SingleIntersection.y + (2.0f * oneMeter)) > camera.Position.y) //{ // // adjust new camera position to be a fixed distance above the ground // camera.Position = new Vector3(camera.Position.x, result.worldFragment.SingleIntersection.y + (2.0f * oneMeter), camera.Position.z); //} } #endregion Axiom Frame Event Handlers private bool DisplayWireFrame { get { return displayWireFrame; } set { displayWireFrame = value; if (displayWireFrame) { camera.SceneDetail = SceneDetailLevel.Wireframe; } else { camera.SceneDetail = SceneDetailLevel.Solid; } } } private bool DisplayOcean { get { return displayOcean; } set { displayOcean = value; Axiom.SceneManagers.Multiverse.WorldManager.Instance.ShowOcean = displayOcean; } } private bool DisplayTerrainTiles { get { return displayTerrainTiles; } set { displayTerrainTiles = value; Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawTiles = displayTerrainTiles; } } private bool DisplayTerrainStitches { get { return displayTerrainStitches; } set { displayTerrainStitches = value; Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawStitches = displayTerrainStitches; } } private bool SpinCamera { get { return spinCamera; } set { spinCamera = value; } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { quit = true; } private void wireFrameToolStripMenuItem_Click(object sender, EventArgs e) { DisplayWireFrame = !DisplayWireFrame; } private void viewToolStripMenuItem1_DropDownOpening(object sender, EventArgs e) { wireFrameToolStripMenuItem.Checked = DisplayWireFrame; displayOceanToolStripMenuItem.Checked = DisplayOcean; displayTerrainStitchesToolStripMenuItem.Checked = DisplayTerrainStitches; displayTerrainTilesToolStripMenuItem.Checked = DisplayTerrainTiles; spinCameraToolStripMenuItem.Checked = SpinCamera; } private void displayOceanToolStripMenuItem_Click(object sender, EventArgs e) { DisplayOcean = !DisplayOcean; } private void displayTerrainTilesToolStripMenuItem_Click(object sender, EventArgs e) { DisplayTerrainTiles = !DisplayTerrainTiles; } private void displayTerrainStitchesToolStripMenuItem_Click(object sender, EventArgs e) { DisplayTerrainStitches = !DisplayTerrainStitches; } private void spinCameraToolStripMenuItem_Click(object sender, EventArgs e) { SpinCamera = !SpinCamera; } private void toolStripButton1_Click(object sender, EventArgs e) { SpinCamera = !SpinCamera; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public static class JoinTests { private const int KeyFactor = 8; public static IEnumerable<object[]> JoinUnorderedData(int[] counts) { foreach (int leftCount in counts) { foreach (int rightCount in counts) { yield return new object[] { leftCount, rightCount }; } } } public static IEnumerable<object[]> JoinData(int[] counts) { // When dealing with joins, if there aren't multiple matches the ordering of the second operand is immaterial. foreach (object[] parms in Sources.Ranges(counts, i => counts)) { yield return parms; } } public static IEnumerable<object[]> JoinMultipleData(int[] counts) { foreach (object[] parms in UnorderedSources.BinaryRanges(counts, counts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } public static IEnumerable<object[]> JoinOrderedLeftUnorderedRightData(int[] counts) { foreach (object[] parms in UnorderedSources.BinaryRanges(counts, counts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]), parms[3] }; } } // // Join // [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor)); foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y))) { Assert.Equal(p.Key * KeyFactor, p.Value); seen.Add(p.Key); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Join_Unordered_Longrunning() { Join_Unordered(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); int seen = 0; foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * KeyFactor, p.Value); } Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinData), new[] { 512, 1024 })] public static void Join_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { Join(left, leftCount, rightCount); } [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered_NotPipelined(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor)); Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(), p => { Assert.Equal(p.Key * KeyFactor, p.Value); seen.Add(p.Key); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Join_Unordered_NotPipelined_Longrunning() { Join_Unordered_NotPipelined(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); int seen = 0; Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * KeyFactor, p.Value); }); Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinData), new[] { 512, 1024 })] public static void Join_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { Join_NotPipelined(left, leftCount, rightCount); } [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered_Multiple(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor)); IntegerRangeSet seenInner = new IntegerRangeSet(0, Math.Min(leftCount * KeyFactor, rightCount)); Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)), p => { Assert.Equal(p.Key, p.Value / KeyFactor); seenInner.Add(p.Value); if (p.Value % KeyFactor == 0) seenOuter.Add(p.Key); }); seenOuter.AssertComplete(); seenInner.AssertComplete(); } [Fact] [OuterLoop] public static void Join_Unordered_Multiple_Longrunning() { Join_Unordered_Multiple(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)), p => { Assert.Equal(p.Key, p.Value / KeyFactor); Assert.Equal(seen++, p.Value); }); Assert.Equal(Math.Min(leftCount * KeyFactor, rightCount), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] public static void Join_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_Multiple(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithOrderedRight : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y % KeyFactor, (x, y) => KeyValuePair.Create(x, y)); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left, right % KeyFactor); Assert.Equal(left + seenRightCount * KeyFactor, right); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { return Math.Min(KeyFactor, Math.Min(rightCount, leftCount)); } } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] public static void Join_Multiple_LeftWithOrderingColisions(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithOrderedRight validator = new LeftOrderingCollisionTestWithOrderedRight(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] public static void Join_Multiple_LeftWithOrderingColisions_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_Multiple_LeftWithOrderingColisions(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithUnorderedRight : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y % KeyFactor, (x, y) => KeyValuePair.Create(x, y)).Distinct(); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left, right % KeyFactor); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { return Math.Min(KeyFactor, Math.Min(rightCount, leftCount)); } } [Theory] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] public static void Join_Multiple_LeftWithOrderingColisions_UnorderedRight(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithUnorderedRight validator = new LeftOrderingCollisionTestWithUnorderedRight(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 256, 512 })] public static void Join_Multiple_LeftWithOrderingColisions_UnorderedRight_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_Multiple_LeftWithOrderingColisions_UnorderedRight(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered_CustomComparator(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeCounter seenOuter = new IntegerRangeCounter(0, leftCount); IntegerRangeCounter seenInner = new IntegerRangeCounter(0, rightCount); Assert.All(leftQuery.Join(rightQuery, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)), p => { Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor); seenOuter.Add(p.Key); seenInner.Add(p.Value); }); if (leftCount == 0 || rightCount == 0) { seenOuter.AssertEncountered(0); seenInner.AssertEncountered(0); } else { int Cartesian(int key, int other) => (other + (KeyFactor - 1) - key % KeyFactor) / KeyFactor; Assert.All(seenOuter, kv => Assert.Equal(Cartesian(kv.Key, rightCount), kv.Value)); Assert.All(seenInner, kv => Assert.Equal(Cartesian(kv.Key, leftCount), kv.Value)); } } [Fact] [OuterLoop] public static void Join_Unordered_CustomComparator_Longrunning() { Join_Unordered_CustomComparator(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seenOuter = 0; int previousOuter = -1; int seenInner = Math.Max(previousOuter % KeyFactor, rightCount - KeyFactor + previousOuter % KeyFactor); Assert.All(leftQuery.Join(rightQuery, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)), p => { if (p.Key != previousOuter) { Assert.Equal(seenOuter, p.Key); Assert.Equal(p.Key % 8, p.Value); // If there aren't sufficient elements in the RHS (< 8), the LHS skips an entry at the end of the mod cycle. seenOuter = Math.Min(leftCount, seenOuter + (p.Key % KeyFactor + 1 == rightCount ? KeyFactor - p.Key % KeyFactor : 1)); Assert.Equal(Math.Max(previousOuter % KeyFactor, rightCount - KeyFactor + previousOuter % KeyFactor), seenInner); previousOuter = p.Key; seenInner = (p.Key % KeyFactor) - KeyFactor; } Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor); Assert.Equal(seenInner += KeyFactor, p.Value); }); Assert.Equal(rightCount == 0 ? 0 : leftCount, seenOuter); Assert.Equal(Math.Max(previousOuter % KeyFactor, rightCount - KeyFactor + previousOuter % KeyFactor), seenInner); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] public static void Join_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_CustomComparator(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithOrderedRightAndCustomComparator : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left % KeyFactor, right % KeyFactor); Assert.Equal(left % KeyFactor + seenRightCount * KeyFactor, right); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { if (rightCount >= KeyFactor) { return leftCount; } else { return leftCount / KeyFactor * rightCount + Math.Min(leftCount % KeyFactor, rightCount); } } } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] public static void Join_CustomComparator_LeftWithOrderingColisions(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithOrderedRightAndCustomComparator validator = new LeftOrderingCollisionTestWithOrderedRightAndCustomComparator(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] public static void Join_CustomComparator_LeftWithOrderingColisions_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_CustomComparator_LeftWithOrderingColisions(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithUnorderedRightAndCustomComparator : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)).Distinct(); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left % KeyFactor, right % KeyFactor); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { if (rightCount >= KeyFactor) { return leftCount; } else { return leftCount / KeyFactor * rightCount + Math.Min(leftCount % KeyFactor, rightCount); } } } [Theory] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] public static void Join_CustomComparator_LeftWithOrderingColisions_UnorderedRight(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithUnorderedRightAndCustomComparator validator = new LeftOrderingCollisionTestWithUnorderedRightAndCustomComparator(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 256 })] public static void Join_CustomComparator_LeftWithOrderingColisions_UnorderedRight_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_CustomComparator_LeftWithOrderingColisions_UnorderedRight(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(JoinData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_InnerJoin_Ordered(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); ParallelQuery<int> middleQuery = ParallelEnumerable.Range(0, leftCount).AsOrdered(); int seen = 0; Assert.All(leftQuery.Join(middleQuery.Join(rightQuery, x => x * KeyFactor / 2, y => y, (x, y) => KeyValuePair.Create(x, y)), z => z * 2, p => p.Key, (x, p) => KeyValuePair.Create(x, p)), pOuter => { KeyValuePair<int, int> pInner = pOuter.Value; Assert.Equal(seen++, pOuter.Key); Assert.Equal(pOuter.Key * 2, pInner.Key); Assert.Equal(pOuter.Key * KeyFactor, pInner.Value); }); Assert.Equal(Math.Min((leftCount + 1) / 2, (rightCount + (KeyFactor - 1)) / KeyFactor), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinData), new[] { 512, 1024 })] public static void Join_InnerJoin_Ordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { Join_InnerJoin_Ordered(left, leftCount, rightCount); } [Fact] public static void Join_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i)); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void Join_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Join(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (l, r) => l)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Join(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (l, r) => l)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Join(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (l, r) => l)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Join(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (l, r) => l)); } [Fact] public static void Join_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("outer", () => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null)); AssertExtensions.Throws<ArgumentNullException>("outer", () => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null, EqualityComparer<int>.Default)); } private abstract class LeftOrderingCollisionTest { protected ParallelQuery<int> ReorderLeft(ParallelQuery<int> left) { return left.AsUnordered().OrderBy(x => x % 2); } protected abstract ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right); protected abstract void ValidateRightValue(int left, int right, int seenRightCount); protected abstract int GetExpectedSeenLeftCount(int leftCount, int rightCount); public void Validate(ParallelQuery<int> left, int leftCount, ParallelQuery<int> right, int rightCount) { HashSet<int> seenLeft = new HashSet<int>(); HashSet<int> seenRight = new HashSet<int>(); int currentLeft = -1; bool seenOdd = false; Assert.All(Join(left, right), p => { try { if (currentLeft != p.Key) { try { if (p.Key % 2 == 1) { seenOdd = true; } else { Assert.False(seenOdd, "Key out of order! " + p.Key.ToString()); } Assert.True(seenLeft.Add(p.Key), "Key already seen! " + p.Key.ToString()); if (currentLeft != -1) { Assert.Equal((rightCount / KeyFactor) + (((rightCount % KeyFactor) > (currentLeft % KeyFactor)) ? 1 : 0), seenRight.Count); } } finally { currentLeft = p.Key; seenRight.Clear(); } } ValidateRightValue(p.Key, p.Value, seenRight.Count); Assert.True(seenRight.Add(p.Value), "Value already seen! " + p.Value.ToString()); } catch (Exception ex) { throw new Exception(string.Format("Key: {0}, Value: {1}", p.Key, p.Value), ex); } finally { seenRight.Add(p.Value); } }); Assert.Equal((rightCount / KeyFactor) + (((rightCount % KeyFactor) > (currentLeft % KeyFactor)) ? 1 : 0), seenRight.Count); Assert.Equal(GetExpectedSeenLeftCount(leftCount, rightCount), seenLeft.Count); } } } }
#region License // // Dasher // // Copyright 2015-2017 Drew Noakes // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/dasher // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Dasher.TypeProviders; using Dasher.Utils; namespace Dasher.Contracts.Types { /// <summary> /// Contract to use when writing a value having union type. /// </summary> public sealed class UnionWriteContract : ByRefContract, IWriteContract { internal static bool CanProcess(Type type) => Union.IsUnionType(type); /// <summary> /// Details of a member type within a union, for writing. /// </summary> public struct Member { /// <summary> /// The ID used in serialised format that identifies this member type. /// </summary> public string Id { get; } /// <summary> /// The contract to use when writing this member type's value. /// </summary> public IWriteContract Contract { get; } internal Member(string id, IWriteContract contract) { Id = id; Contract = contract; } } /// <summary> /// The members that comprise this union type. /// </summary> public IReadOnlyList<Member> Members { get; } internal UnionWriteContract(Type type, ContractCollection contractCollection) { if (!CanProcess(type)) throw new ArgumentException($"Type {type} must be a union.", nameof(type)); Members = Union.GetTypes(type) .Select(t => new Member(UnionEncoding.GetTypeName(t), contractCollection.GetOrAddWriteContract(t))) .OrderBy(m => m.Id, StringComparer.OrdinalIgnoreCase) .ToArray(); } private UnionWriteContract(IReadOnlyList<Member> members) => Members = members; internal UnionWriteContract(XElement element, Func<string, IWriteContract> resolveContract, ICollection<Action> bindActions) { var members = new List<Member>(); bindActions.Add(() => { foreach (var field in element.Elements(nameof(Member))) { var id = field.Attribute(nameof(Member.Id))?.Value; var contract = field.Attribute(nameof(Member.Contract))?.Value; if (string.IsNullOrWhiteSpace(id)) throw new ContractParseException($"\"{element.Name}\" element must have a non-empty \"{nameof(Member.Id)}\" attribute."); if (string.IsNullOrWhiteSpace(contract)) throw new ContractParseException($"\"{element.Name}\" element must have a non-empty \"{nameof(Member.Contract)}\" attribute."); members.Add(new Member(id, resolveContract(contract))); } }); Members = members; } /// <inheritdoc /> public override bool Equals(Contract other) { return other is UnionWriteContract o && o.Members.SequenceEqual(Members, (a, b) => a.Id == b.Id && a.Contract.Equals(b.Contract)); } /// <inheritdoc /> protected override int ComputeHashCode() { unchecked { var hash = 0; foreach (var member in Members) { hash <<= 5; hash ^= member.Id.GetHashCode(); hash <<= 3; hash ^= member.Contract.GetHashCode(); } return hash; } } /// <inheritdoc /> public override IEnumerable<Contract> Children => Members.Select(m => m.Contract).Cast<Contract>(); internal override XElement ToXml() { if (Id == null) throw new InvalidOperationException("\"Id\" property cannot be null."); return new XElement("UnionWrite", new XAttribute("Id", Id), Members.Select(m => new XElement("Member", new XAttribute("Id", m.Id), new XAttribute("Contract", m.Contract.ToReferenceString())))); } /// <inheritdoc /> public IWriteContract CopyTo(ContractCollection collection) { return collection.GetOrCreate(this, () => new UnionWriteContract(Members.Select(m => new Member(m.Id, m.Contract.CopyTo(collection))).ToList())); } } /// <summary> /// Contract to use when reading a value having union type. /// </summary> public sealed class UnionReadContract : ByRefContract, IReadContract { internal static bool CanProcess(Type type) => UnionWriteContract.CanProcess(type); /// <summary> /// Details of a member type within a union, for reading. /// </summary> public struct Member { /// <summary> /// The ID used in serialised format that identifies this member type. /// </summary> public string Id { get; } /// <summary> /// The contract to use when reading this member type's value. /// </summary> public IReadContract Contract { get; } internal Member(string id, IReadContract contract) { Id = id; Contract = contract; } } /// <summary> /// The members that comprise this union type. /// </summary> public IReadOnlyList<Member> Members { get; } internal UnionReadContract(Type type, ContractCollection contractCollection) { if (!CanProcess(type)) throw new ArgumentException($"Type {type} must be a union.", nameof(type)); Members = Union.GetTypes(type) .Select(t => new Member(UnionEncoding.GetTypeName(t), contractCollection.GetOrAddReadContract(t))) .OrderBy(m => m.Id, StringComparer.OrdinalIgnoreCase) .ToArray(); } private UnionReadContract(IReadOnlyList<Member> members) => Members = members; internal UnionReadContract(XElement element, Func<string, IReadContract> resolveContract, ICollection<Action> bindActions) { var members = new List<Member>(); bindActions.Add(() => { foreach (var field in element.Elements(nameof(Member))) { var id = field.Attribute(nameof(Member.Id))?.Value; var contract = field.Attribute(nameof(Member.Contract))?.Value; if (string.IsNullOrWhiteSpace(id)) throw new ContractParseException($"\"{element.Name}\" element must have a non-empty \"{nameof(Member.Id)}\" attribute."); if (string.IsNullOrWhiteSpace(contract)) throw new ContractParseException($"\"{element.Name}\" element must have a non-empty \"{nameof(Member.Contract)}\" attribute."); members.Add(new Member(id, resolveContract(contract))); } }); Members = members; } /// <inheritdoc /> public bool CanReadFrom(IWriteContract writeContract, bool strict) { // TODO write EmptyContract test for this case if (writeContract is EmptyContract) return true; if (!(writeContract is UnionWriteContract ws)) return false; var readMembers = Members; var writeMembers = ws.Members; var ir = 0; var iw = 0; while (iw < writeMembers.Count) { if (ir == readMembers.Count) return false; var rm = readMembers[ir]; var wm = writeMembers[iw]; var cmp = StringComparer.OrdinalIgnoreCase.Compare(rm.Id, wm.Id); if (cmp == 0) { // match if (!rm.Contract.CanReadFrom(wm.Contract, strict)) return false; // step both forwards ir++; iw++; } else if (cmp < 0) { // read member comes before write member -- read type contains an extra member if (strict) return false; // skip the read member only iw++; } else { return false; } } if (ir != readMembers.Count && strict) return false; return true; } /// <inheritdoc /> public override bool Equals(Contract other) { return other is UnionReadContract o && o.Members.SequenceEqual(Members, (a, b) => a.Id == b.Id && a.Contract.Equals(b.Contract)); } /// <inheritdoc /> protected override int ComputeHashCode() { unchecked { var hash = 0; foreach (var member in Members) { hash <<= 5; hash ^= member.Id.GetHashCode(); hash <<= 3; hash ^= member.Contract.GetHashCode(); } return hash; } } /// <inheritdoc /> public override IEnumerable<Contract> Children => Members.Select(m => m.Contract).Cast<Contract>(); internal override XElement ToXml() { if (Id == null) throw new InvalidOperationException("\"Id\" property cannot be null."); return new XElement("UnionRead", new XAttribute("Id", Id), Members.Select(m => new XElement("Member", new XAttribute("Id", m.Id), new XAttribute("Contract", m.Contract.ToReferenceString())))); } /// <inheritdoc /> public IReadContract CopyTo(ContractCollection collection) { return collection.GetOrCreate(this, () => new UnionReadContract(Members.Select(m => new Member(m.Id, m.Contract.CopyTo(collection))).ToList())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; #if !netstandard using Internal.Runtime.CompilerServices; #endif namespace System.Runtime.CompilerServices { /// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask"/>.</summary> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable { /// <summary>The wrapped <see cref="Task"/>.</summary> private readonly ValueTask _value; /// <summary>Initializes the awaitable.</summary> /// <param name="value">The wrapped <see cref="ValueTask"/>.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(in ValueTask value) => _value = value; /// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable"/> instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value); /// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable"/>.</summary> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter { /// <summary>The value being awaited.</summary> private readonly ValueTask _value; /// <summary>Initializes the awaiter.</summary> /// <param name="value">The value to be awaited.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(in ValueTask value) => _value = value; /// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable"/> has completed.</summary> public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _value.IsCompleted; } /// <summary>Gets the result of the ValueTask.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public void GetResult() => _value.ThrowIfCompletedUnsuccessfully(); /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary> public void OnCompleted(Action continuation) { object obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary> public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) { TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } } } /// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask{TResult}"/>.</summary> /// <typeparam name="TResult">The type of the result produced.</typeparam> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable<TResult> { /// <summary>The wrapped <see cref="ValueTask{TResult}"/>.</summary> private readonly ValueTask<TResult> _value; /// <summary>Initializes the awaitable.</summary> /// <param name="value">The wrapped <see cref="ValueTask{TResult}"/>.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(in ValueTask<TResult> value) => _value = value; /// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable{TResult}"/> instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value); /// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter { /// <summary>The value being awaited.</summary> private readonly ValueTask<TResult> _value; /// <summary>Initializes the awaiter.</summary> /// <param name="value">The value to be awaited.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(in ValueTask<TResult> value) => _value = value; /// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable{TResult}"/> has completed.</summary> public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _value.IsCompleted; } /// <summary>Gets the result of the ValueTask.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public TResult GetResult() => _value.Result; /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void OnCompleted(Action continuation) { object obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) { TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CustomerAsset</c> resource.</summary> public sealed partial class CustomerAssetName : gax::IResourceName, sys::IEquatable<CustomerAssetName> { /// <summary>The possible contents of <see cref="CustomerAssetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c>. /// </summary> CustomerAssetFieldType = 1, } private static gax::PathTemplate s_customerAssetFieldType = new gax::PathTemplate("customers/{customer_id}/customerAssets/{asset_id_field_type}"); /// <summary>Creates a <see cref="CustomerAssetName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CustomerAssetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerAssetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerAssetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerAssetName"/> with the pattern /// <c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomerAssetName"/> constructed from the provided ids.</returns> public static CustomerAssetName FromCustomerAssetFieldType(string customerId, string assetId, string fieldTypeId) => new CustomerAssetName(ResourceNameType.CustomerAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerAssetName"/> with pattern /// <c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerAssetName"/> with pattern /// <c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c>. /// </returns> public static string Format(string customerId, string assetId, string fieldTypeId) => FormatCustomerAssetFieldType(customerId, assetId, fieldTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerAssetName"/> with pattern /// <c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerAssetName"/> with pattern /// <c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c>. /// </returns> public static string FormatCustomerAssetFieldType(string customerId, string assetId, string fieldTypeId) => s_customerAssetFieldType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerAssetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customerAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerAssetName"/> if successful.</returns> public static CustomerAssetName Parse(string customerAssetName) => Parse(customerAssetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerAssetName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CustomerAssetName"/> if successful.</returns> public static CustomerAssetName Parse(string customerAssetName, bool allowUnparsed) => TryParse(customerAssetName, allowUnparsed, out CustomerAssetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerAssetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customerAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerAssetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerAssetName, out CustomerAssetName result) => TryParse(customerAssetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerAssetName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerAssetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerAssetName, bool allowUnparsed, out CustomerAssetName result) { gax::GaxPreconditions.CheckNotNull(customerAssetName, nameof(customerAssetName)); gax::TemplatedResourceName resourceName; if (s_customerAssetFieldType.TryParseName(customerAssetName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAssetFieldType(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerAssetName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private CustomerAssetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetId = null, string customerId = null, string fieldTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; AssetId = assetId; CustomerId = customerId; FieldTypeId = fieldTypeId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerAssetName"/> class from the component parts of pattern /// <c>customers/{customer_id}/customerAssets/{asset_id}~{field_type}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> public CustomerAssetName(string customerId, string assetId, string fieldTypeId) : this(ResourceNameType.CustomerAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Asset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>FieldType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FieldTypeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAssetFieldType: return s_customerAssetFieldType.Expand(CustomerId, $"{AssetId}~{FieldTypeId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CustomerAssetName); /// <inheritdoc/> public bool Equals(CustomerAssetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerAssetName a, CustomerAssetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerAssetName a, CustomerAssetName b) => !(a == b); } public partial class CustomerAsset { /// <summary> /// <see cref="CustomerAssetName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CustomerAssetName ResourceNameAsCustomerAssetName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerAssetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="AssetName"/>-typed view over the <see cref="Asset"/> resource name property.</summary> internal AssetName AssetAsAssetName { get => string.IsNullOrEmpty(Asset) ? null : AssetName.Parse(Asset, allowUnparsed: true); set => Asset = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Windows; namespace System { public class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private bool _beginUpdateStarted = false; protected void BeginUpdate() { _beginUpdateStarted = true; } protected void EndUpdate() { _beginUpdateStarted = false; OnPropertyChanged(allPropertiesArgs); } protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) { if (_beginUpdateStarted) return; // http://stackoverflow.com/questions/2553333/wpf-databinding-thread-safety // In WPF .NET 3.5 INotifyPropertyChanged is thread safe VerifyProperty(args.PropertyName); // In multi-thread approach this.PropertyChanged can change its value between [PropertyChanged == null] and [PropertyChanged(...)] // Make a temporary copy of the event to avoid possibility of // a race condition if the last subscriber unsubscribes // immediately after the null check and before the event is raised. var handler = this.PropertyChanged; handler?.Invoke(this, args); //http://10rem.net/blog/2012/01/10/threading-considerations-for-binding-and-change-notification-in-silverlight-5 //Deployment.Current.Dispatcher.CheckAccess() } public void OnPropertyChanged(string propertyName) { var propertyArgs = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(propertyArgs); // Always run OnPropertyChanged(string propertyName) -> DbRecord.IsChanged //if (PropertyChanged == null) // return; } protected bool OnPropertyChanged<T>(ref T propVal, T newVal, PropertyChangedEventArgs propArgs) { if (!object.Equals(propVal, newVal)) { propVal = newVal; OnPropertyChanged(propArgs); return true; } return false; } protected bool OnPropertyChanged<T>(ref T propVal, T newVal, string propName) { if (!object.Equals(propVal, newVal)) { propVal = newVal; OnPropertyChanged(propName); return true; } return false; } [Conditional("DEBUG")] [DebuggerStepThrough] private void VerifyProperty(string propertyName) { var type = this.GetType(); if (type.GetProperty(propertyName) == null) { string msg = string.Format("'{0}' is not a public property of {1}", propertyName, type.FullName); Debug.WriteLine(msg); throw new Exception(msg); } } private static PropertyChangedEventArgs allPropertiesArgs = new PropertyChangedEventArgs(null); [Obsolete] public virtual void NotifyAllPropertiesChanged() { NotifyPropertyChanged(allPropertiesArgs); } [Obsolete] public virtual void NotifyPropertyChanged(PropertyChangedEventArgs args) { OnPropertyChanged(args); } [Obsolete] protected void NotifyPropertyChanged(string propertyName) { OnPropertyChanged(propertyName); } [Obsolete] protected bool NotifyPropertyChanged<T>(ref T propVal, T newVal, string propName) { return OnPropertyChanged(ref propVal, newVal, propName); } [Obsolete] protected void NotifyPropertyChanged<T>(Expression<Func<T>> propertyExpresssion) { var propName = GetPropertyMemberName(propertyExpresssion); NotifyPropertyChanged(propName); } [Obsolete] public virtual bool NotifyPropertyChanged<T>(ref T propVal, T newVal, PropertyChangedEventArgs args) { return OnPropertyChanged<T>(ref propVal, newVal, args); } [Obsolete] protected bool NotifyPropertyChanged<T>(ref T propVal, T newVal, Expression<Func<T>> propertyExpresssion) { return NotifyPropertyChanged(ref propVal, newVal, GetPropertyMemberName(propertyExpresssion)); } [Obsolete("Use nameof() keyword")] public void OnPropertyChanged<T>(Expression<Func<T>> propertyExpresssion) { var propName = GetPropertyMemberName(propertyExpresssion); OnPropertyChanged(propName); } [Obsolete] private static string GetPropertyMemberName(LambdaExpression propertyExpresssion) { if (propertyExpresssion == null) throw new ArgumentNullException("Property access expression cannot be null."); var memberExpression = propertyExpresssion.Body as MemberExpression; if (memberExpression == null) { var unaryExpression = propertyExpresssion.Body as UnaryExpression; if (unaryExpression != null) { memberExpression = unaryExpression.Operand as MemberExpression; } } if ((memberExpression != null) ) //&& (memberExpression.Member.MemberType == MemberTypes.Property)) { return memberExpression.Member.Name; } throw new ArgumentException("The expression is not a property access expression: " + propertyExpresssion.ToString()); } [Obsolete] public static string GetPropertyName<T>(Expression<Func<T, object>> propertyExpresssion) { return GetPropertyMemberName(propertyExpresssion); } [Obsolete] protected string TypePropertyName<T>(Expression<Func<T>> propertyExpresssion) { return this.GetType().Name + "." + GetPropertyMemberName(propertyExpresssion); } /// <summary> /// Use it to ininitialize static PropertyChangedEventArgs. It is about 10 times faster than /// calling everytime OnPropertyChanged(() => MyProperty); /// </summary> /// <typeparam name="T"></typeparam> /// <param name="propertyExpresssion"></param> /// <returns></returns> [Obsolete] public static PropertyChangedEventArgs GetPropertyArgs<T>(Expression<Func<T, object>> propertyExpresssion) { return new PropertyChangedEventArgs(GetPropertyMemberName(propertyExpresssion)); } } /* C# 5.0 + .NET 3.5 namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class CallerMemberNameAttribute : Attribute { } } public class Data : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } } */ public class EditableObject : ObservableObject, IEditableObject //, IClientChangeTracking, INotifyDataErrorInfo, IDataErrorInfo { // AcceptChanges(), RejectChanges(), HasChanges and GetObjectGraphChanges() protected Dictionary<string, object> PropsBackup = new Dictionary<string, object>(); private IEnumerable<PropertyInfo> GetProperties() { return this.GetType().GetProperties().Where(p => p.IsEditableValue()); } virtual public void BeginEdit() { PropsBackup.Clear(); foreach (var pi in GetProperties()) { PropsBackup[pi.Name] = pi.GetValue(this, null); } } virtual public void CancelEdit() { if (PropsBackup.Count < 1) throw new Exception(string.Format("{0}.BeginEdit() not invoked.", this.GetType().Name)); foreach (var pi in GetProperties()) { var thisVal = pi.GetValue(this, null); var bacVal = PropsBackup[pi.Name]; if (!object.Equals(thisVal, bacVal)) { pi.SetValue(this, PropsBackup[pi.Name], null); OnPropertyChanged(pi.Name); } } PropsBackup.Clear(); } virtual public void EndEdit() { if (PropsBackup.Count < 1) throw new Exception(string.Format("{0}.BeginEdit() not invoked.", this.GetType().Name)); // Nothing to do PropsBackup.Clear(); } } public class Presenter : ObservableObject { public Presenter() { IsInDesignMode = Application.Current != null; //IsInDesignMode = DesignerProperties.GetIsInDesignMode(new DependencyObject()); //Windows.ApplicationModel.DesignMode.DesignModeEnabled } /// <summary> /// <UserControl.Resources> /// <ViewModels:MockXViewModel x:Key="DesignViewModel"/> /// </UserControl.Resources> /// <Grid DataContext="{Binding Source={StaticResource DesignViewModel}}" /> /// </summary> // http://stackoverflow.com/questions/1889966/what-approaches-are-available-to-dummy-design-time-data-in-wpf public bool IsInDesignMode { get; private set; } public string DisplayName { get; set; } public virtual void RefreshData() { } private static PropertyChangedEventArgs ErrorMessageArgs = new PropertyChangedEventArgs(nameof(ErrorMessage)); private static PropertyChangedEventArgs HasErrorArgs = new PropertyChangedEventArgs(nameof(HasError)); private static PropertyChangedEventArgs HasNoErrorArgs = new PropertyChangedEventArgs(nameof(HasNoError)); public string ErrorMessage { get; private set; } public bool HasError { get { return !string.IsNullOrEmpty(ErrorMessage); } } public bool HasNoError { get { return !HasError; } } protected void SetError(string errMessage) { if (!object.Equals(this.ErrorMessage, errMessage)) { ErrorMessage = errMessage; OnPropertyChanged(ErrorMessageArgs); OnPropertyChanged(HasErrorArgs); OnPropertyChanged(HasNoErrorArgs); } } protected void SetErrorFmt(string errMessage, params object[] args) { this.SetError(string.Format(errMessage, args)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MongoDB.Driver; namespace MongoDbActionsPlugin { /// <summary> /// Helper class to connect to a MongoDB instance/cluster /// /// ** Usage Example ** /// 1. In the application startup/initialization, call MongoDbContext.Configure (...) to set the global connection settings /// /// 2. Call MongoDbContext.GetDatabase ("My Database Name") to get a thread safe instance of MongoDatabase /// /// </summary> public class MongoDbContext { /// <remarks> /// /// ** Connection String ** /// format example: /// /// mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] /// /// ** OPTIONS ** /// * w /// -1 : The driver will not acknowledge write operations and will suppress all network or socket errors. /// 0 : The driver will not acknowledge write operations, but will pass or handle any network and socket errors that it receives to the client. /// 1 : Provides basic acknowledgment of write operations, a standalone mongod instance, or the primary for replica sets, acknowledge all write operations /// majority /// n /// tags /// /// * ssl /// true: Initiate the connection with SSL. /// false: Initiate the connection without SSL. /// The default value is false. /// /// * connectTimeoutMS /// The time in milliseconds to attempt a connection before timing out. /// The default is never to timeout, though different drivers might vary. See the driver documentation. /// /// * socketTimeoutMS /// The time in milliseconds to attempt a send or receive on a socket before the attempt times out. /// The default is never to timeout, though different drivers might vary. See the driver documentation. /// /// * journal /// true / false /// /// * readPreference /// primaryPreferred - will try to read from primary (but if primary is offline, will read from the secondary nodes) /// secondaryPreferred - will try to read from a secondary node (but if offline, will read from the primary node) /// (OBS.: All writes go to the Primary) /// /// </remarks> private static string _globalConnectionString = String.Empty; private static Lazy<MongoClient> _mongoDbInstance = new Lazy<MongoClient> (OpenConnection); private static MongoServer _server = null; /// <summary> /// Configures the global connection string for a MongoDB instance/cluster. /// </summary> /// <param name="login">The login.</param> /// <param name="password">The password.</param> /// <param name="addresses">List of addresses. Format: host1[:port1][,host2[:port2],...[,hostN[:portN]]]</param> /// <param name="safeMode">The safe mode. True to receive write confirmation from mongo.</param> /// <param name="readOnSecondary">The read on secondary. True to direct read operations to cluster secondary nodes (secondaryPreferred), else try to read from primary (primaryPreferred).</param> /// <param name="connectionTimeoutMilliseconds">The time to attempt a connection before timing out.</param> /// <param name="socketTimeoutMilliseconds">The time to attempt a send or receive on a socket before the attempt times out.</param> /// <param name="databaseName">Database name required to authenticate against a specific database [optional].</param> /// <param name="readPreferenceTags">The read preference tags. List of a comma-separated list of colon-separated key-value pairs. Ex.: { {dc:ny,rack:1}, { dc:ny } } </param> public static void Configure (string login, string password, string addresses, bool safeMode = true, bool readOnSecondary = false, int connectionTimeoutMilliseconds = 30000, int socketTimeoutMilliseconds = 90000, string databaseName = null, IEnumerable<string> readPreferenceTags = null) { // prepares the connection string string connectionString = BuildConnectionString (login, password, safeMode, readOnSecondary, addresses, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, databaseName, readPreferenceTags); // set the new connection string Configure (connectionString); } /// <summary> /// Configures the global connection string for a MongoDB instance/cluster. /// </summary> /// <param name="connectionString">The connection string builder.</param> public static void Configure (MongoUrlBuilder connectionString) { if (connectionString.ConnectTimeout.TotalSeconds < 30) connectionString.ConnectTimeout = TimeSpan.FromSeconds (30); if (connectionString.SocketTimeout.TotalSeconds < 90) connectionString.SocketTimeout = TimeSpan.FromSeconds (90); connectionString.MaxConnectionIdleTime = TimeSpan.FromSeconds (30); // set the new connection string Configure (connectionString.ToString ()); } /// <summary> /// Configures the global connection string for a MongoDB instance/cluster. /// </summary> /// <param name="connectionString">The connection string.</param> public static void Configure (string connectionString) { // if there is any change, reconnect if (_globalConnectionString != connectionString) { _globalConnectionString = connectionString; Dispose (); } } /// <summary> /// Releases MongoDb resources.<para/> /// Obs.: the last Connection String is kept, so if any request is made, the resources will be recreated and the connection opened. /// </summary> public static void Dispose () { _server = null; _mongoDbInstance = new Lazy<MongoClient> (OpenConnection); } /// <summary> /// Forcefully closes all connections from the connection pool.<para/> /// Not recommended, since can cause some connection instability issues. /// </summary> public static void ForceDisconnect () { if (_server != null) { _server.Disconnect (); } } /// <summary> /// Builds the connection string for MongoDB. /// </summary> /// <param name="login">The login.</param> /// <param name="password">The password.</param> /// <param name="addresses">List of addresses. Format: host1[:port1][,host2[:port2],...[,hostN[:portN]]]</param> /// <param name="databaseName">Database name required to authenticate against a specific database [optional].</param> /// <returns></returns> public static string BuildConnectionString (string login, string password, string addresses, string databaseName = null) { return BuildConnectionString (login, password, true, false, addresses, 30000, 90000, databaseName); } static string[] urlPrefix = new string[] { "mongodb://" }; /// <summary> /// Builds the connection string for MongoDB. /// </summary> /// <param name="login">The login.</param> /// <param name="password">The password.</param> /// <param name="safeMode">The safe mode. True to receive write confirmation from mongo.</param> /// <param name="readOnSecondary">The read on secondary. True to direct read operations to cluster secondary nodes (secondaryPreferred), else try to read from primary (primaryPreferred).</param> /// <param name="addresses">List of addresses. Format: host1[:port1][,host2[:port2],...[,hostN[:portN]]]</param> /// <param name="connectionTimeoutMilliseconds">The time to attempt a connection before timing out.</param> /// <param name="socketTimeoutMilliseconds">The time to attempt a send or receive on a socket before the attempt times out.</param> /// <param name="databaseName">Database name required to authenticate against a specific database [optional].</param> /// <param name="readPreferenceTags">The read preference tags. List of a comma-separated list of colon-separated key-value pairs. Ex.: { {dc:ny,rack:1}, { dc:ny } } </param> public static string BuildConnectionString (string login, string password, bool safeMode, bool readOnSecondary, string addresses, int connectionTimeoutMilliseconds, int socketTimeoutMilliseconds, string databaseName = null, IEnumerable<string> readPreferenceTags = null) { var cb = new MongoDB.Driver.MongoUrlBuilder ("mongodb://" + addresses.Replace ("mongodb://", "")); cb.Username = login; cb.Password = password; cb.ConnectionMode = MongoDB.Driver.ConnectionMode.Automatic; cb.W = safeMode ? WriteConcern.W1.W : WriteConcern.Unacknowledged.W; if (connectionTimeoutMilliseconds < 15000) connectionTimeoutMilliseconds = 15000; if (socketTimeoutMilliseconds < 15000) socketTimeoutMilliseconds = 15000; cb.ConnectTimeout = TimeSpan.FromMilliseconds (connectionTimeoutMilliseconds); cb.SocketTimeout = TimeSpan.FromMilliseconds (socketTimeoutMilliseconds); cb.MaxConnectionIdleTime = TimeSpan.FromSeconds (30); cb.ReadPreference = new ReadPreference (); cb.ReadPreference.ReadPreferenceMode = readOnSecondary ? ReadPreferenceMode.SecondaryPreferred : ReadPreferenceMode.PrimaryPreferred; if (readPreferenceTags != null) { foreach (var tag in readPreferenceTags.Where (i => i != null && i.IndexOf (':') > 0).Select (i => i.Split (':')).Select (i => new ReplicaSetTag (i[0], i[1]))) cb.ReadPreference.AddTagSet (new ReplicaSetTagSet ().Add (tag)); } // generate final connection string return cb.ToString (); } private static MongoClient OpenConnection () { // TODO: set serialization options (a design decision to use UtcNow or Local time zone). // Its is recommended to use UtcNow as the DateTime default in the database, and only convert to local whenever the data is displayed to the user. // To use Local time zone, uncomment the line bellow: // MongoDB.Bson.Serialization.BsonSerializer.RegisterSerializer (typeof (DateTime), new MongoDB.Bson.Serialization.Serializers.DateTimeSerializer (MongoDB.Bson.Serialization.Options.DateTimeSerializationOptions.LocalInstance)); // create mongo client MongoClient client = new MongoClient (_globalConnectionString); return client; } public static MongoClient Client { get { return _mongoDbInstance.Value; } } public static MongoServer Server { get { if (_server == null) _server = Client.GetServer (); return _server; } } /// <summary> /// Gets the MongoDb server instance. /// </summary> /// <returns></returns> public static MongoServer GetServer () { return Client.GetServer (); } /// <summary> /// Gets the MongoDb server instance using the provided connection string. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns></returns> public static MongoServer GetServer (MongoUrlBuilder connectionString) { if (connectionString.ConnectTimeout.TotalSeconds < 30) connectionString.ConnectTimeout = TimeSpan.FromSeconds (30); if (connectionString.SocketTimeout.TotalSeconds < 90) connectionString.SocketTimeout = TimeSpan.FromSeconds (90); connectionString.MaxConnectionIdleTime = TimeSpan.FromSeconds (30); return GetServer (connectionString.ToString ()); } /// <summary> /// Gets the MongoDb server instance using the provided connection string. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns></returns> public static MongoServer GetServer (string connectionString) { MongoClient client = new MongoClient (connectionString); return client.GetServer (); } /// <summary> /// Gets a database instance that is thread safe. <para/> /// Uses the static connection string set by <seealso cref="Configure"/> static method. /// </summary> /// <param name="dbName">Name of the db.</param> /// <returns></returns> public static MongoDatabase GetDatabase (string dbName) { return Server.GetDatabase (dbName); } /// <summary> /// Gets the database instance that is thread safe using the provided connection string. /// </summary> /// <param name="dbName">Name of the db.</param> /// <param name="connectionString">The connection string to the MongoDB instance/cluster.</param> /// <returns></returns> public static MongoDatabase GetDatabase (string dbName, MongoUrlBuilder connectionString) { return GetDatabase (dbName, connectionString.ToString ()); } /// <summary> /// Gets the database instance that is thread safe using the provided connection string. /// </summary> /// <param name="dbName">Name of the db.</param> /// <param name="connectionString">The connection string to the MongoDB instance/cluster.</param> /// <returns></returns> public static MongoDatabase GetDatabase (string dbName, string connectionString) { MongoClient client = new MongoClient (connectionString); return client.GetServer ().GetDatabase (dbName); } } /// <summary> /// Some MongoDb helpers methods /// </summary> public static class MongoExtensions { /// <summary> /// Insert an item, retrying in case of connection errors.. /// </summary> /// <typeparam name="T">The type of the item.</typeparam> /// <param name="col">The collection.</param> /// <param name="item">The item.</param> /// <param name="retryCount">The retry count in case of connection errors.</param> /// <param name="throwOnError">Throws an exception on error.</param> /// <param name="ignoreDuplicates">If the insert fails because of duplicated id, then returns as success.</param> /// <returns></returns> public static bool SafeInsert<T> (this MongoCollection col, T item, int retryCount = 2, bool throwOnError = false, bool ignoreDuplicates = false) { int done = 0; // try to update/insert and // retry n times in case of connection errors do { try { if (col.Insert (item).Ok) return true; } catch (MongoDuplicateKeyException dup) { // duplicate id exception (no use to retry) if (ignoreDuplicates) return true; if (throwOnError) throw; break; } catch (WriteConcernException wcEx) { // duplicate id exception (no use to retry) if (wcEx.CommandResult != null && wcEx.CommandResult.Code.HasValue && (wcEx.CommandResult.Code.Value == 11000 || wcEx.CommandResult.Code.Value == 11001)) { if (throwOnError) throw; else return ignoreDuplicates; } // retry limit if (throwOnError && done > (retryCount - 1)) throw; } // System.IO.IOException ex catch { if (throwOnError && done > (retryCount - 1)) throw; } } while (++done < retryCount); // if we got here, the operation have failled return false; } /// <summary> /// Update or insert an item, retrying in case of connection errors. /// </summary> /// <typeparam name="T">The type of the item.</typeparam> /// <param name="col">The collection.</param> /// <param name="item">The item.</param> /// <param name="retryCount">The retry count in case of connection errors.</param> /// <param name="throwOnError">Throws an exception on error.</param> /// <returns></returns> public static bool SafeSave<T> (this MongoCollection col, T item, int retryCount = 2, bool throwOnError = false) { int done = 0; // try to update/insert and // retry n times in case of connection errors do { try { if (col.Save (item).Ok) return true; } // System.IO.IOException ex // WriteConcernException wcEx catch (System.Exception exAll) { if (throwOnError && done > (retryCount - 1)) throw; } } while (++done < retryCount); // if we got here, the operation have failled return false; } /// <summary> /// Execute insert batch, retrying in case of connection errors. /// </summary> /// <typeparam name="T">The type of the item.</typeparam> /// <param name="col">The collection</param> /// <param name="items">list of items.</param> /// <param name="retryCount">The retry count in case of connection errors.</param> /// <param name="throwOnError">Throws an exception on error.</param> /// <param name="ignoreDuplicates">If the insert fails because of duplicated id, then returns as success.</param> /// <returns></returns> public static bool SafeInsertBatch<T> (this MongoCollection col, IList<T> items, int retryCount = 2, bool throwOnError = false, bool ignoreDuplicates = false) { // try to insertbatch try { col.InsertBatch (items); } catch (Exception ex) { // in case of a insertbatch faillure, // update or insert each item individually if (ignoreDuplicates) { for (int i = 0; i < items.Count; i++) { if (!col.SafeInsert (items[i], retryCount, throwOnError, ignoreDuplicates)) { // in case of another faillure, give up saving items return false; } } } else { for (int i = 0; i < items.Count; i++) { if (!col.SafeSave (items[i], retryCount, throwOnError)) { // in case of another faillure, give up saving items return false; } } } } return true; } } }
// 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; namespace WebsitePanel.Portal { public partial class HostingPlansQuotas : WebsitePanelControlBase { DataSet dsQuotas = null; public bool IsPlan = true; protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { ToggleQuotaControls(); } } public void BindPackageQuotas(int packageId) { try { dsQuotas = ES.Services.Packages.GetPackageQuotasForEdit(packageId); dlGroups.DataSource = dsQuotas.Tables[0]; dlGroups.DataBind(); } catch (Exception ex) { Response.Write(ex.ToString()); } ToggleQuotaControls(); } public void BindPlanQuotas(int packageId, int planId, int serverId) { try { dsQuotas = ES.Services.Packages.GetHostingPlanQuotas(packageId, planId, serverId); dlGroups.DataSource = dsQuotas.Tables[0]; dlGroups.DataBind(); } catch (Exception ex) { Response.Write(ex.ToString()); } ToggleQuotaControls(); } private void ToggleQuotaControls() { foreach (RepeaterItem item in dlGroups.Items) { CheckBox chkEnabled = (CheckBox)item.FindControl("chkEnabled"); CheckBox chkCountDiskspace = (CheckBox)item.FindControl("chkCountDiskspace"); CheckBox chkCountBandwidth = (CheckBox)item.FindControl("chkCountBandwidth"); chkCountDiskspace.Enabled = chkEnabled.Checked && IsPlan; chkCountBandwidth.Enabled = chkEnabled.Checked && IsPlan; // iterate quotas Control quotaPanel = item.FindControl("QuotaPanel"); quotaPanel.Visible = chkEnabled.Checked; DataList dlQuotas = (DataList)item.FindControl("dlQuotas"); foreach (DataListItem quotaItem in dlQuotas.Items) { if (!chkEnabled.Checked) { QuotaEditor quotaEditor = (QuotaEditor)quotaItem.FindControl("quotaEditor"); quotaEditor.QuotaValue = 0; } } // hide group if quotas == 0 Control groupPanel = item.FindControl("GroupPanel"); groupPanel.Visible = (IsPlan || dlQuotas.Items.Count > 0); } } List<HostingPlanGroupInfo> groups; List<HostingPlanQuotaInfo> quotas; public HostingPlanGroupInfo[] Groups { get { if (groups == null) CollectFormData(); return groups.ToArray(); } } public HostingPlanQuotaInfo[] Quotas { get { if (quotas == null) CollectFormData(); return quotas.ToArray(); } } public void CollectFormData() { groups = new List<HostingPlanGroupInfo>(); quotas = new List<HostingPlanQuotaInfo>(); // gather info foreach (RepeaterItem item in dlGroups.Items) { Literal litGroupId = (Literal)item.FindControl("groupId"); CheckBox chkEnabled = (CheckBox)item.FindControl("chkEnabled"); CheckBox chkCountDiskspace = (CheckBox)item.FindControl("chkCountDiskspace"); CheckBox chkCountBandwidth = (CheckBox)item.FindControl("chkCountBandwidth"); if (!chkEnabled.Checked) continue; // disabled group HostingPlanGroupInfo group = new HostingPlanGroupInfo(); group.GroupId = Utils.ParseInt(litGroupId.Text, 0); group.Enabled = chkEnabled.Checked; group.CalculateDiskSpace = chkCountDiskspace.Checked; group.CalculateBandwidth = chkCountBandwidth.Checked; groups.Add(group); // iterate quotas DataList dlQuotas = (DataList)item.FindControl("dlQuotas"); foreach (DataListItem quotaItem in dlQuotas.Items) { QuotaEditor quotaEditor = (QuotaEditor)quotaItem.FindControl("quotaEditor"); HostingPlanQuotaInfo quota = new HostingPlanQuotaInfo(); quota.QuotaId = quotaEditor.QuotaId; quota.QuotaValue = quotaEditor.QuotaValue; quotas.Add(quota); } } } /* public void SavePlanQuotas(int planId) { CollectFormData(); // update plan quotas ES.Packages.UpdateHostingPlanQuotas(planId, groups.ToArray(), quotas.ToArray()); } public void SavePackageQuotas(int packageId) { CollectFormData(); // update plan quotas ES.Packages.UpdatePackageQuotas(packageId, groups.ToArray(), quotas.ToArray()); } * */ public DataView GetGroupQuotas(int groupId) { return new DataView(dsQuotas.Tables[1], "GroupID=" + groupId.ToString(), "", DataViewRowState.CurrentRows); } public string GetSharedLocalizedStringNotEmpty(string resourceKey, object resourceDescription) { string result = GetSharedLocalizedString("Quota." + resourceKey); if (string.IsNullOrEmpty(result)) { result = resourceKey; string resourceDescriptionString = resourceDescription as string; if (!string.IsNullOrEmpty(resourceDescriptionString)) { result = resourceDescriptionString; } else if (result.IndexOf('.') > 0 && result.Substring(result.IndexOf('.')).Length > 1) { // drop Quota name prefix // HeliconZoo.python -> python result = result.Substring(result.IndexOf('.')+1); } } return result; } } }
/* * Swagger Petstore * * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using System.IO; using System.Web; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; using RestSharp; namespace IO.Swagger.Client { /// <summary> /// API client is mainly responsible for making the HTTP call to the API backend. /// </summary> public partial class ApiClient { private JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; /// <summary> /// Allows for extending request processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> partial void InterceptRequest(IRestRequest request); /// <summary> /// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> /// <param name="response">The RestSharp response object</param> partial void InterceptResponse(IRestRequest request, IRestResponse response); /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration and base path (http://petstore.swagger.io/v2). /// </summary> public ApiClient() { Configuration = Configuration.Default; RestClient = new RestClient("http://petstore.swagger.io/v2"); } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default base path (http://petstore.swagger.io/v2). /// </summary> /// <param name="config">An instance of Configuration.</param> public ApiClient(Configuration config = null) { if (config == null) Configuration = Configuration.Default; else Configuration = config; RestClient = new RestClient("http://petstore.swagger.io/v2"); } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration. /// </summary> /// <param name="basePath">The base path.</param> public ApiClient(String basePath = "http://petstore.swagger.io/v2") { if (String.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); RestClient = new RestClient(basePath); Configuration = Configuration.Default; } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The default API client.</value> [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")] public static ApiClient Default; /// <summary> /// Gets or sets the Configuration. /// </summary> /// <value>An instance of the Configuration.</value> public Configuration Configuration { get; set; } /// <summary> /// Gets or sets the RestClient. /// </summary> /// <value>An instance of the RestClient</value> public RestClient RestClient { get; set; } // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = new RestRequest(path, method); // add path parameter, if any foreach(var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); // add header parameter, if any foreach(var param in headerParams) request.AddHeader(param.Key, param.Value); // add query parameter, if any foreach(var param in queryParams) request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach(var param in formParams) request.AddParameter(param.Key, param.Value); // add file parameter, if any foreach(var param in fileParams) { request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); } if (postBody != null) // http body (model or byte[]) parameter { if (postBody.GetType() == typeof(String)) { request.AddParameter("application/json", postBody, ParameterType.RequestBody); } else if (postBody.GetType() == typeof(byte[])) { request.AddParameter(contentType, postBody, ParameterType.RequestBody); } } return request; } /// <summary> /// Makes the HTTP request (Sync). /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <param name="contentType">Content Type of the request</param> /// <returns>Object</returns> public Object CallApi( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); // set timeout RestClient.Timeout = Configuration.Timeout; // set user agent RestClient.UserAgent = Configuration.UserAgent; InterceptRequest(request); var response = RestClient.Execute(request); InterceptResponse(request, response); return (Object) response; } /// <summary> /// Makes the asynchronous HTTP request. /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <param name="contentType">Content type.</param> /// <returns>The Task instance.</returns> public async System.Threading.Tasks.Task<Object> CallApiAsync( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); InterceptRequest(request); var response = await RestClient.ExecuteTaskAsync(request); InterceptResponse(request, response); return (Object)response; } /// <summary> /// Escape string (url-encoded). /// </summary> /// <param name="str">String to be escaped.</param> /// <returns>Escaped string.</returns> public string EscapeString(string str) { return UrlEncode(str); } /// <summary> /// Create FileParameter based on Stream. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="stream">Input stream.</param> /// <returns>FileParameter.</returns> public FileParameter ParameterToFile(string name, Stream stream) { if (stream is FileStream) return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); else return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); } /// <summary> /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// </summary> /// <param name="obj">The parameter (header, path, query, form).</param> /// <returns>Formatted string.</returns> public string ParameterToString(object obj) { if (obj is DateTime) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); else if (obj is DateTimeOffset) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); foreach (var param in (IList)obj) { if (flattenedString.Length > 0) flattenedString.Append(","); flattenedString.Append(param); } return flattenedString.ToString(); } else return Convert.ToString (obj); } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> public object Deserialize(IRestResponse response, Type type) { IList<Parameter> headers = response.Headers; if (type == typeof(byte[])) // return byte array { return response.RawBytes; } if (type == typeof(Stream)) { if (headers != null) { var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) ? Path.GetTempPath() : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); File.WriteAllBytes(fileName, response.RawBytes); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(response.RawBytes); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { return ConvertType(response.Content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Serialize an input (model) into JSON string /// </summary> /// <param name="obj">Object.</param> /// <returns>JSON string.</returns> public String Serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Select the Content-Type header's value from the given content-type array: /// if JSON exists in the given array, use it; /// otherwise use the first one defined in 'consumes' /// </summary> /// <param name="contentTypes">The Content-Type array to select from.</param> /// <returns>The Content-Type header to use.</returns> public String SelectHeaderContentType(String[] contentTypes) { if (contentTypes.Length == 0) return null; if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return contentTypes[0]; // use the first content type specified in 'consumes' } /// <summary> /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; /// otherwise use all of them (joining into a string) /// </summary> /// <param name="accepts">The accepts array to select from.</param> /// <returns>The Accept header to use.</returns> public String SelectHeaderAccept(String[] accepts) { if (accepts.Length == 0) return null; if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return String.Join(",", accepts); } /// <summary> /// Encode string in base64 format. /// </summary> /// <param name="text">String to be encoded.</param> /// <returns>Encoded string.</returns> public static string Base64Encode(string text) { return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); } /// <summary> /// Dynamically cast the object into target type. /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast /// </summary> /// <param name="source">Object to be casted</param> /// <param name="dest">Target type</param> /// <returns>Casted object</returns> public static dynamic ConvertType(dynamic source, Type dest) { return Convert.ChangeType(source, dest); } /// <summary> /// Convert stream to byte array /// Credit/Ref: http://stackoverflow.com/a/221941/677735 /// </summary> /// <param name="input">Input stream to be converted</param> /// <returns>Byte array</returns> public static byte[] ReadAsBytes(Stream input) { byte[] buffer = new byte[16*1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } /// <summary> /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// </summary> /// <param name="input">String to be URL encoded</param> /// <returns>Byte array</returns> public static string UrlEncode(string input) { const int maxLength = 32766; if (input == null) { throw new ArgumentNullException("input"); } if (input.Length <= maxLength) { return Uri.EscapeDataString(input); } StringBuilder sb = new StringBuilder(input.Length * 2); int index = 0; while (index < input.Length) { int length = Math.Min(input.Length - index, maxLength); string subString = input.Substring(index, length); sb.Append(Uri.EscapeDataString(subString)); index += subString.Length; } return sb.ToString(); } /// <summary> /// Sanitize filename by removing the path /// </summary> /// <param name="filename">Filename</param> /// <returns>Filename</returns> public static string SanitizeFilename(string filename) { Match match = Regex.Match(filename, @".*[/\\](.*)$"); if (match.Success) { return match.Groups[1].Value; } else { return filename; } } } }
using System; using Csla; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERCLevel; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H05_SubContinent_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="H05_SubContinent_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="H04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class H05_SubContinent_ReChild : BusinessBase<H05_SubContinent_ReChild> { #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="H05_SubContinent_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="H05_SubContinent_ReChild"/> object.</returns> internal static H05_SubContinent_ReChild NewH05_SubContinent_ReChild() { return DataPortal.CreateChild<H05_SubContinent_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="H05_SubContinent_ReChild"/> object, based on given parameters. /// </summary> /// <param name="subContinent_ID2">The SubContinent_ID2 parameter of the H05_SubContinent_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="H05_SubContinent_ReChild"/> object.</returns> internal static H05_SubContinent_ReChild GetH05_SubContinent_ReChild(int subContinent_ID2) { return DataPortal.FetchChild<H05_SubContinent_ReChild>(subContinent_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H05_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 H05_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="H05_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="H05_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 = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IH05_SubContinent_ReChildDal>(); var data = dal.Fetch(subContinent_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Loads a <see cref="H05_SubContinent_ReChild"/> object from the given <see cref="H05_SubContinent_ReChildDto"/>. /// </summary> /// <param name="data">The H05_SubContinent_ReChildDto to use.</param> private void Fetch(H05_SubContinent_ReChildDto data) { // Value properties LoadProperty(SubContinent_Child_NameProperty, data.SubContinent_Child_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="H05_SubContinent_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H04_SubContinent parent) { var dto = new H05_SubContinent_ReChildDto(); dto.Parent_SubContinent_ID = parent.SubContinent_ID; dto.SubContinent_Child_Name = SubContinent_Child_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IH05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="H05_SubContinent_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(H04_SubContinent parent) { if (!IsDirty) return; var dto = new H05_SubContinent_ReChildDto(); dto.Parent_SubContinent_ID = parent.SubContinent_ID; dto.SubContinent_Child_Name = SubContinent_Child_Name; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IH05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="H05_SubContinent_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(H04_SubContinent parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IH05_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 } }
using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Diagnostics; namespace Lucene.Net.Analysis { /* * 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 Automaton = Lucene.Net.Util.Automaton.Automaton; using State = Lucene.Net.Util.Automaton.State; using Transition = Lucene.Net.Util.Automaton.Transition; // TODO: maybe also toFST? then we can translate atts into FST outputs/weights /// <summary> /// Consumes a <see cref="TokenStream"/> and creates an <see cref="Automaton"/> /// where the transition labels are UTF8 bytes (or Unicode /// code points if unicodeArcs is true) from the <see cref="ITermToBytesRefAttribute"/>. /// Between tokens we insert /// <see cref="POS_SEP"/> and for holes we insert <see cref="HOLE"/>. /// /// @lucene.experimental /// </summary> public class TokenStreamToAutomaton { //backing variables private bool preservePositionIncrements; private bool unicodeArcs; /// <summary> /// Sole constructor. </summary> public TokenStreamToAutomaton() { this.preservePositionIncrements = true; } /// <summary> /// Whether to generate holes in the automaton for missing positions, <c>true</c> by default. </summary> public virtual bool PreservePositionIncrements { get { return this.preservePositionIncrements; // LUCENENET specific - properties should always have a getter } set { this.preservePositionIncrements = value; } } /// <summary> /// Whether to make transition labels Unicode code points instead of UTF8 bytes, /// <c>false</c> by default /// </summary> public virtual bool UnicodeArcs { get { return this.unicodeArcs; // LUCENENET specific - properties should always have a getter } set { this.unicodeArcs = value; } } private class Position : RollingBuffer.IResettable { // Any tokens that ended at our position arrive to this state: internal State arriving; // Any tokens that start at our position leave from this state: internal State leaving; public void Reset() { arriving = null; leaving = null; } } private class Positions : RollingBuffer<Position> { public Positions() : base(NewPosition) { } protected override Position NewInstance() { return NewPosition(); } private static Position NewPosition() { return new Position(); } } /// <summary> /// Subclass &amp; implement this if you need to change the /// token (such as escaping certain bytes) before it's /// turned into a graph. /// </summary> protected internal virtual BytesRef ChangeToken(BytesRef @in) { return @in; } /// <summary> /// We create transition between two adjacent tokens. </summary> public const int POS_SEP = 0x001f; /// <summary> /// We add this arc to represent a hole. </summary> public const int HOLE = 0x001e; /// <summary> /// Pulls the graph (including <see cref="IPositionLengthAttribute"/> /// from the provided <see cref="TokenStream"/>, and creates the corresponding /// automaton where arcs are bytes (or Unicode code points /// if unicodeArcs = true) from each term. /// </summary> public virtual Automaton ToAutomaton(TokenStream @in) { var a = new Automaton(); bool deterministic = true; var posIncAtt = @in.AddAttribute<IPositionIncrementAttribute>(); var posLengthAtt = @in.AddAttribute<IPositionLengthAttribute>(); var offsetAtt = @in.AddAttribute<IOffsetAttribute>(); var termBytesAtt = @in.AddAttribute<ITermToBytesRefAttribute>(); BytesRef term = termBytesAtt.BytesRef; @in.Reset(); // Only temporarily holds states ahead of our current // position: RollingBuffer<Position> positions = new Positions(); int pos = -1; Position posData = null; int maxOffset = 0; while (@in.IncrementToken()) { int posInc = posIncAtt.PositionIncrement; if (!preservePositionIncrements && posInc > 1) { posInc = 1; } Debug.Assert(pos > -1 || posInc > 0); if (posInc > 0) { // New node: pos += posInc; posData = positions.Get(pos); Debug.Assert(posData.leaving == null); if (posData.arriving == null) { // No token ever arrived to this position if (pos == 0) { // OK: this is the first token posData.leaving = a.GetInitialState(); } else { // this means there's a hole (eg, StopFilter // does this): posData.leaving = new State(); AddHoles(a.GetInitialState(), positions, pos); } } else { posData.leaving = new State(); posData.arriving.AddTransition(new Transition(POS_SEP, posData.leaving)); if (posInc > 1) { // A token spanned over a hole; add holes // "under" it: AddHoles(a.GetInitialState(), positions, pos); } } positions.FreeBefore(pos); } else { // note: this isn't necessarily true. its just that we aren't surely det. // we could optimize this further (e.g. buffer and sort synonyms at a position) // but thats probably overkill. this is cheap and dirty deterministic = false; } int endPos = pos + posLengthAtt.PositionLength; termBytesAtt.FillBytesRef(); BytesRef termUTF8 = ChangeToken(term); int[] termUnicode = null; Position endPosData = positions.Get(endPos); if (endPosData.arriving == null) { endPosData.arriving = new State(); } State state = posData.leaving; int termLen = termUTF8.Length; if (unicodeArcs) { string utf16 = termUTF8.Utf8ToString(); termUnicode = new int[utf16.CodePointCount(0, utf16.Length)]; termLen = termUnicode.Length; for (int cp, i = 0, j = 0; i < utf16.Length; i += Character.CharCount(cp)) { termUnicode[j++] = cp = Character.CodePointAt(utf16, i); } } else { termLen = termUTF8.Length; } for (int byteIDX = 0; byteIDX < termLen; byteIDX++) { State nextState = byteIDX == termLen - 1 ? endPosData.arriving : new State(); int c; if (unicodeArcs) { c = termUnicode[byteIDX]; } else { c = termUTF8.Bytes[termUTF8.Offset + byteIDX] & 0xff; } state.AddTransition(new Transition(c, nextState)); state = nextState; } maxOffset = Math.Max(maxOffset, offsetAtt.EndOffset); } @in.End(); State endState = null; if (offsetAtt.EndOffset > maxOffset) { endState = new State(); endState.Accept = true; } pos++; while (pos <= positions.MaxPos) { posData = positions.Get(pos); if (posData.arriving != null) { if (endState != null) { posData.arriving.AddTransition(new Transition(POS_SEP, endState)); } else { posData.arriving.Accept = true; } } pos++; } //toDot(a); a.IsDeterministic = deterministic; return a; } // for debugging! /* private static void toDot(Automaton a) throws IOException { final String s = a.toDot(); Writer w = new OutputStreamWriter(new FileOutputStream("/tmp/out.dot")); w.write(s); w.Dispose(); System.out.println("TEST: saved to /tmp/out.dot"); } */ private static void AddHoles(State startState, RollingBuffer<Position> positions, int pos) { Position posData = positions.Get(pos); Position prevPosData = positions.Get(pos - 1); while (posData.arriving == null || prevPosData.leaving == null) { if (posData.arriving == null) { posData.arriving = new State(); posData.arriving.AddTransition(new Transition(POS_SEP, posData.leaving)); } if (prevPosData.leaving == null) { if (pos == 1) { prevPosData.leaving = startState; } else { prevPosData.leaving = new State(); } if (prevPosData.arriving != null) { prevPosData.arriving.AddTransition(new Transition(POS_SEP, prevPosData.leaving)); } } prevPosData.leaving.AddTransition(new Transition(HOLE, posData.arriving)); pos--; if (pos <= 0) { break; } posData = prevPosData; prevPosData = positions.Get(pos - 1); } } } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Should; using Volta.Core.Infrastructure.Framework.IO.FileStore; namespace Volta.Tests.Integration.Infrastructure.Framework.IO.FileStore { [TestFixture] public class FileSystemFileRepositoryTests { private static readonly string RepositoryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); private readonly Core.Infrastructure.Framework.IO.FileStore.FileStore _repo = new Core.Infrastructure.Framework.IO.FileStore.FileStore(RepositoryPath); private const string FileContents = "This is a file!"; private Stream _fileStream; [SetUp] public void Setup() { if (Directory.Exists(RepositoryPath)) Directory.Delete(RepositoryPath, true); Directory.CreateDirectory(RepositoryPath); _fileStream = new MemoryStream(Encoding.ASCII.GetBytes(FileContents)); } [TearDown] public void TearDown() { if (Directory.Exists(RepositoryPath)) Directory.Delete(RepositoryPath, true); } [Test] public void Should_Save_String_File_And_Open_It() { var id = _repo.Save(FileContents, Lifespan.Permanent); var contents = _repo.Open(id); contents.ReadAllText().ShouldEqual(FileContents); } [Test] public void Should_Save_Permanent_File_And_Open_It() { var id = _repo.Save(_fileStream, Lifespan.Permanent); var contents = _repo.Open(id); contents.ReadAllText().ShouldEqual(FileContents); } [Test] public void Should_Save_Transient_File_And_Open_It() { var id = _repo.Save(_fileStream, Lifespan.Transient); var contents = _repo.Open(id); contents.ReadAllText().ShouldEqual(FileContents); } [Test] public void Should_Generate_Import_Path() { var fileInfo = _repo.Create(Lifespan.Transient); fileInfo.Path.Directory().DirectoryExists().ShouldBeTrue(); fileInfo.Path.FileExists().ShouldBeFalse(); fileInfo.Path.Filename().IsNullOrEmpty().ShouldBeFalse(); } [Test] public void Should_Import_Transient_File() { var fileInfo = _repo.Create(Lifespan.Transient); File.WriteAllText(fileInfo.Path, FileContents); var id = _repo.Import(fileInfo.Path, Lifespan.Transient); id.ShouldNotEqual(Guid.Empty); fileInfo.Path.FileExists().ShouldBeFalse(); _repo.Open(id).ReadAllText().ShouldEqual(FileContents); } [Test] public void Should_Import_Permanent_File() { var fileInfo = _repo.Create(Lifespan.Transient); File.WriteAllText(fileInfo.Path, FileContents); var id = _repo.Import(fileInfo.Path, Lifespan.Permanent); id.ShouldNotEqual(Guid.Empty); fileInfo.Path.FileExists().ShouldBeFalse(); _repo.Open(id).ReadAllText().ShouldEqual(FileContents); } [Test] public void Should_Export_Permanent_File() { var id = _repo.Save(_fileStream, Lifespan.Permanent); var path = _repo.GetPath(id); path.FileExists().ShouldBeTrue(); path.ReadAllText().ShouldEqual(FileContents); } [Test] public void Should_Export_Transient_File() { var id = _repo.Save(_fileStream, Lifespan.Transient); var path = _repo.GetPath(id); path.FileExists().ShouldBeTrue(); path.ReadAllText().ShouldEqual(FileContents); } [Test] public void Should_Make_File_Permanent() { var id = _repo.Save(_fileStream, Lifespan.Transient); var transientPath = _repo.GetPath(id); transientPath.FileExists().ShouldBeTrue(); _repo.SetLifespan(id, Lifespan.Permanent); var permanentPath = _repo.GetPath(id); transientPath.ShouldNotEqual(permanentPath); transientPath.FileExists().ShouldBeFalse(); permanentPath.FileExists().ShouldBeTrue(); } [Test] public void Should_Make_File_Transient() { var id = _repo.Save(_fileStream, Lifespan.Permanent); var permanentPath = _repo.GetPath(id); permanentPath.FileExists().ShouldBeTrue(); _repo.SetLifespan(id, Lifespan.Transient); var transientPath = _repo.GetPath(id); transientPath.ShouldNotEqual(permanentPath); permanentPath.FileExists().ShouldBeFalse(); transientPath.FileExists().ShouldBeTrue(); } [Test] public void Transient_File_Should_Exist() { var id = _repo.Save(_fileStream, Lifespan.Transient); _repo.Exists(id).ShouldBeTrue(); _repo.GetPath(id).FileExists().ShouldBeTrue(); } [Test] public void Permanent_File_Should_Exist() { var id = _repo.Save(_fileStream, Lifespan.Permanent); _repo.Exists(id).ShouldBeTrue(); _repo.GetPath(id).FileExists().ShouldBeTrue(); } [Test] public void File_Should_Not_Exist() { _repo.Exists(Guid.NewGuid()).ShouldBeFalse(); } [Test] public void Get_Permanent_File_Info() { var id = _repo.Save(_fileStream, Lifespan.Permanent); var info = _repo.GetInfo(id); info.Size.ShouldEqual(FileContents.Length); info.Lifespan.ShouldEqual(Lifespan.Permanent); (info.Created > DateTime.Now.AddSeconds(-5)).ShouldBeTrue(); (info.Created < DateTime.Now.AddSeconds(5)).ShouldBeTrue(); } [Test] public void Get_Transient_File_Info() { var id = _repo.Save(_fileStream, Lifespan.Transient); var info = _repo.GetInfo(id); info.Size.ShouldEqual(FileContents.Length); info.Lifespan.ShouldEqual(Lifespan.Transient); (info.Created > DateTime.Now.AddSeconds(-5)).ShouldBeTrue(); (info.Created < DateTime.Now.AddSeconds(5)).ShouldBeTrue(); } [Test] public void Should_Delete_Permanent_File() { var id = _repo.Save(_fileStream, Lifespan.Permanent); _repo.Exists(id).ShouldBeTrue(); _repo.Delete(id); _repo.Exists(id).ShouldBeFalse(); } [Test] public void Should_Delete_Transient_File() { var id = _repo.Save(_fileStream, Lifespan.Transient); _repo.Exists(id).ShouldBeTrue(); _repo.Delete(id); _repo.Exists(id).ShouldBeFalse(); } [Test] public void Should_Purge_All_Transient_Files() { var permanentId1 = _repo.Save(FileContents.ToStream(), Lifespan.Permanent); var transientId1 = _repo.Save(FileContents.ToStream(), Lifespan.Transient); var permanentId2 = _repo.Save(FileContents.ToStream(), Lifespan.Permanent); var transientId3 = _repo.Save(FileContents.ToStream(), Lifespan.Transient); _repo.Exists(permanentId1).ShouldBeTrue(); _repo.Exists(transientId1).ShouldBeTrue(); _repo.Exists(permanentId2).ShouldBeTrue(); _repo.Exists(transientId3).ShouldBeTrue(); _repo.PurgeTransientFiles(TimeSpan.MinValue); _repo.Exists(permanentId1).ShouldBeTrue(); _repo.Exists(transientId1).ShouldBeFalse(); _repo.Exists(permanentId2).ShouldBeTrue(); _repo.Exists(transientId3).ShouldBeFalse(); } [Test] public void Should_Purge_Older_Transient_Files() { var permanentId1 = _repo.Save(FileContents.ToStream(), Lifespan.Permanent); var transientId1 = _repo.Save(FileContents.ToStream(), Lifespan.Transient); var permanentId2 = _repo.Save(FileContents.ToStream(), Lifespan.Permanent); var transientId3 = _repo.Save(FileContents.ToStream(), Lifespan.Transient); _repo.Exists(permanentId1).ShouldBeTrue(); _repo.Exists(transientId1).ShouldBeTrue(); _repo.Exists(permanentId2).ShouldBeTrue(); _repo.Exists(transientId3).ShouldBeTrue(); _repo.PurgeTransientFiles(TimeSpan.FromSeconds(30)); _repo.Exists(permanentId1).ShouldBeTrue(); _repo.Exists(transientId1).ShouldBeTrue(); _repo.Exists(permanentId2).ShouldBeTrue(); _repo.Exists(transientId3).ShouldBeTrue(); } } static class FluentExtensions { public static string ReadAllText(this Stream stream) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } public static bool FileExists(this string path) { return File.Exists(path); } public static bool FileIsEmpty(this string path) { return new System.IO.FileInfo(path).Length == 0; } public static string ReadAllText(this string path) { return File.ReadAllText(path); } public static string Filename(this string path) { return Path.GetFileName(path); } public static string Directory(this string path) { return Path.GetDirectoryName(path); } public static bool DirectoryExists(this string path) { return System.IO.Directory.Exists(path); } public static bool IsNullOrEmpty(this string value) { return string.IsNullOrEmpty(value); } public static Stream ToStream(this string value) { return new MemoryStream(Encoding.ASCII.GetBytes(value)); } } }
using UnityEngine; using System.Collections; //Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors //This line should always be present at the top of scripts which use %Pathfinding using Pathfinding; public class AstarAI : MonoBehaviour { //The point to move to private Vector3 targetPosition; public GameObject target; private GameObject tempTarget; private float clockTick; private Seeker seeker; private GameObject[] systems; private GameObject[] players; private CharacterController controller; private bool newPath; private GameObject player; private Transform playerTrans; private Vector3 playerLoc; private bool exploring; private bool systemTarget; private float closest; private int count; private bool playerFound; private GameObject[] targets; private bool targetAquired; private bool targetLocked; //The calculated path public Path path; //The AI's speed per second public float speed = 100; //The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextWaypointDistance = 3; //The waypoint we are currently moving towards private int currentWaypoint = 0; public void Start () { systems = GameObject.FindGameObjectsWithTag ("SystemSpawn"); players = GameObject.FindGameObjectsWithTag ("Player"); targets = new GameObject[24]; count = 0; foreach (GameObject o in systems) { targets [count] = o; count++; } foreach (GameObject o in players) { targets [count] = o; count++; } count = 0; closest = 100000f; targetPosition = new Vector3 (0, 0, 0); target = null; systemTarget = false; clockTick = 0; exploring = true; targetAquired = false; seeker = GetComponent<Seeker> (); controller = GetComponent<CharacterController> (); decision (); } public void pathCalc () { //Start a new path to the targetPosition, return the result to the OnPathComplete function seeker.StartPath (transform.position, targetPosition, OnPathComplete); } public void OnPathComplete (Path p) { Debug.Log ("Yey, we got a path back. Did it have an error? " + p.error); if (!p.error) { path = p; //Reset the waypoint counter currentWaypoint = 0; newPath = true; } } public void FixedUpdate () { if (path == null) { return; } if (exploring) { if ((path.vectorPath.Count - currentWaypoint) < 2) { if (systemTarget) { foreach (GameObject o in systems) { if (o.transform.position.magnitude == target.transform.position.magnitude) { Debug.Log("found " + target); o.GetComponent<SystemSpawn> ().enemyFound = true; } } } } if (newPath) { if (clockTick == 10) { decision (); } else { clockTick++; } } } else { if ((path.vectorPath.Count - currentWaypoint) < 1) { if (targetAquired) { //attack the target //if the target hits 0 health targetAquired goes false. } else { if (newPath) { if (clockTick == 10) { decision (); } else { clockTick++; } } } } } if (currentWaypoint < path.vectorPath.Count) { //Direction to the next waypoint //Debug.Log ("" + path.vectorPath.Count + " and : " + currentWaypoint); Vector3 dir = (path.vectorPath [currentWaypoint] - transform.position).normalized; dir *= speed * Time.fixedDeltaTime; controller.SimpleMove (dir); //Check if we are close enough to the next waypoint //If we are, proceed to follow the next waypoint if (Vector3.Distance (transform.position, path.vectorPath [currentWaypoint]) < nextWaypointDistance) { currentWaypoint++; return; } } } public void decision (){ newPath = false; clockTick = 0; count = 0; if (exploring) { closest = 10000; foreach (GameObject o in systems) { SystemSpawn g = o.GetComponent<SystemSpawn> (); if (g.enemyFound) { Debug.Log ("here"); count++; if (count > 4) { exploring = false; Debug.Log ("GOING AGGRESSIVE!!!!!!!"); } } else { if ((Mathf.Abs (o.transform.position.magnitude - gameObject.transform.position.magnitude)) < closest) { Debug.Log ("" + o + " is closest, it is " + (Mathf.Abs (o.transform.position.magnitude - gameObject.transform.position.magnitude)) + " units away."); closest = (Mathf.Abs (o.transform.position.magnitude - gameObject.transform.position.magnitude)); targetPosition = o.transform.position; target = o; systemTarget = true; } } } foreach (GameObject o in players) { if ((Mathf.Abs (o.transform.position.magnitude - gameObject.transform.position.magnitude)) < closest) { Debug.Log ("" + o + " is closest, it is " + (Mathf.Abs (o.transform.position.magnitude - gameObject.transform.position.magnitude)) + " units away."); closest = (Mathf.Abs (o.transform.position.magnitude - gameObject.transform.position.magnitude)); targetPosition = o.transform.position; target = o; systemTarget = false; playerFound = true; } } Debug.Log ("" + target + " is closest"); targetPosition = target.transform.position; pathCalc (); } else { if (targetAquired) { } else { int Thetarget = 0; if (playerFound) { Thetarget = Random.Range (0, 23); if (Thetarget < 20) { while (!targets[Thetarget].GetComponent<SystemSpawn>().enemyFound) { Thetarget = Random.Range (0, 19); //if Thetarget has 0 health already, choose a new target } } } else { Thetarget = Random.Range (0, count - 1); //While Thetarget has 0 health, choose a new target. } if (Thetarget > 19) { systemTarget = false; } targetAquired = true; target = targets [Thetarget]; pathCalc (); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using ManagedBass; using ManagedBass.Mix; using osu.Framework.Bindables; using osu.Framework.Development; using osu.Framework.Extensions.EnumExtensions; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Statistics; namespace osu.Framework.Audio.Mixing.Bass { /// <summary> /// Mixes together multiple <see cref="IAudioChannel"/> into one output via BASSmix. /// </summary> internal class BassAudioMixer : AudioMixer, IBassAudio { /// <summary> /// The handle for this mixer. /// </summary> public int Handle { get; private set; } /// <summary> /// The list of effects which are currently active in the BASS mix. /// </summary> internal readonly List<EffectWithHandle> ActiveEffects = new List<EffectWithHandle>(); /// <summary> /// The list of channels which are currently active in the BASS mix. /// </summary> private readonly List<IBassAudioChannel> activeChannels = new List<IBassAudioChannel>(); private const int frequency = 44100; /// <summary> /// Creates a new <see cref="BassAudioMixer"/>. /// </summary> /// <param name="globalMixer"><inheritdoc /></param> /// <param name="identifier">An identifier displayed on the audio mixer visualiser.</param> public BassAudioMixer(AudioMixer? globalMixer, string identifier) : base(globalMixer, identifier) { EnqueueAction(createMixer); } public override BindableList<IEffectParameter> Effects { get; } = new BindableList<IEffectParameter>(); protected override void AddInternal(IAudioChannel channel) { Debug.Assert(CanPerformInline); if (!(channel is IBassAudioChannel bassChannel)) return; if (Handle == 0 || bassChannel.Handle == 0) return; if (!bassChannel.MixerChannelPaused) ChannelPlay(bassChannel); } protected override void RemoveInternal(IAudioChannel channel) { Debug.Assert(CanPerformInline); if (!(channel is IBassAudioChannel bassChannel)) return; if (Handle == 0 || bassChannel.Handle == 0) return; if (activeChannels.Remove(bassChannel)) removeChannelFromBassMix(bassChannel); } /// <summary> /// Plays a channel. /// </summary> /// <remarks>See: <see cref="ManagedBass.Bass.ChannelPlay"/>.</remarks> /// <param name="channel">The channel to play.</param> /// <param name="restart">Restart playback from the beginning?</param> /// <returns> /// If successful, <see langword="true"/> is returned, else <see langword="false"/> is returned. /// Use <see cref="ManagedBass.Bass.LastError"/> to get the error code. /// </returns> public bool ChannelPlay(IBassAudioChannel channel, bool restart = false) { if (Handle == 0 || channel.Handle == 0) return false; AddChannelToBassMix(channel); BassMix.ChannelRemoveFlag(channel.Handle, BassFlags.MixerChanPause); return true; } /// <summary> /// Pauses a channel. /// </summary> /// <remarks>See: <see cref="ManagedBass.Bass.ChannelPause"/>.</remarks> /// <param name="channel">The channel to pause.</param> /// <param name="flushMixer">Set to <c>true</c> to make the pause take effect immediately. /// <para> /// This will change the timing of <see cref="ChannelGetPosition"/>, so should be used sparingly. /// </para> /// </param> /// <returns> /// If successful, <see langword="true"/> is returned, else <see langword="false"/> is returned. /// Use <see cref="ManagedBass.Bass.LastError"/> to get the error code. /// </returns> public bool ChannelPause(IBassAudioChannel channel, bool flushMixer = false) { bool result = BassMix.ChannelAddFlag(channel.Handle, BassFlags.MixerChanPause); if (flushMixer) flush(); return result; } /// <summary> /// Checks if a channel is active (playing) or stalled. /// </summary> /// <remarks>See: <see cref="ManagedBass.Bass.ChannelIsActive"/>.</remarks> /// <param name="channel">The channel to get the state of.</param> /// <returns><see cref="ManagedBass.PlaybackState"/> indicating the state of the channel.</returns> public PlaybackState ChannelIsActive(IBassAudioChannel channel) { // The audio channel's state tells us whether it's stalled or stopped. var state = ManagedBass.Bass.ChannelIsActive(channel.Handle); // The channel is always in a playing state unless stopped or stalled as it's a decoding channel. Retrieve the true playing state from the mixer channel. if (state == PlaybackState.Playing) state = BassMix.ChannelFlags(channel.Handle, BassFlags.Default, BassFlags.Default).HasFlagFast(BassFlags.MixerChanPause) ? PlaybackState.Paused : state; return state; } /// <summary> /// Retrieves the playback position of a channel. /// </summary> /// <remarks>See: <see cref="ManagedBass.Bass.ChannelGetPosition"/>.</remarks> /// <param name="channel">The channel to retrieve the position of.</param> /// <param name="mode">How to retrieve the position.</param> /// <returns> /// If an error occurs, -1 is returned, use <see cref="ManagedBass.Bass.LastError"/> to get the error code. /// If successful, the position is returned. /// </returns> public long ChannelGetPosition(IBassAudioChannel channel, PositionFlags mode = PositionFlags.Bytes) => BassMix.ChannelGetPosition(channel.Handle); /// <summary> /// Sets the playback position of a channel. /// </summary> /// <remarks>See: <see cref="ManagedBass.Bass.ChannelSetPosition"/>.</remarks> /// <param name="channel">The <see cref="IBassAudioChannel"/> to set the position of.</param> /// <param name="position">The position, in units determined by the <paramref name="mode"/>.</param> /// <param name="mode">How to set the position.</param> /// <returns> /// If successful, then <see langword="true"/> is returned, else <see langword="false"/> is returned. /// Use <see cref="P:ManagedBass.Bass.LastError"/> to get the error code. /// </returns> public bool ChannelSetPosition(IBassAudioChannel channel, long position, PositionFlags mode = PositionFlags.Bytes) { // All BASS channels enter a stopped state once they reach the end. // Non-decoding channels remain in the stopped state when seeked afterwards, however decoding channels are put back into a playing state which causes audio to play. // Thus, on seek, in order to reproduce the expectations set out by non-decoding channels, manually pause the mixer channel when the decoding channel is stopped. if (ChannelIsActive(channel) == PlaybackState.Stopped) ChannelPause(channel, true); bool result = BassMix.ChannelSetPosition(channel.Handle, position, mode); // Perform a flush so that ChannelGetPosition() immediately returns the new value. flush(); return result; } /// <summary> /// Retrieves the level (peak amplitude) of a channel. /// </summary> /// <remarks>See: <see cref="ManagedBass.Bass.ChannelGetLevel(int, float[], float, LevelRetrievalFlags)"/>.</remarks> /// <param name="channel">The <see cref="IBassAudioChannel"/> to get the levels of.</param> /// <param name="levels">The array in which the levels are to be returned.</param> /// <param name="length">How much data (in seconds) to look at to get the level (limited to 1 second).</param> /// <param name="flags">What levels to retrieve.</param> /// <returns><c>true</c> if successful, false otherwise.</returns> public bool ChannelGetLevel(IBassAudioChannel channel, [In, Out] float[] levels, float length, LevelRetrievalFlags flags) => BassMix.ChannelGetLevel(channel.Handle, levels, length, flags) != -1; /// <summary> /// Retrieves the immediate sample data (or an FFT representation of it) of a channel. /// </summary> /// <remarks>See: <see cref="ManagedBass.Bass.ChannelGetData(int, float[], int)"/>.</remarks> /// <param name="channel">The <see cref="IBassAudioChannel"/> to retrieve the data of.</param> /// <param name="buffer">float[] to write the data to.</param> /// <param name="length">Number of bytes wanted, and/or <see cref="T:ManagedBass.DataFlags"/>.</param> /// <returns>If an error occurs, -1 is returned, use <see cref="P:ManagedBass.Bass.LastError"/> to get the error code. /// <para>When requesting FFT data, the number of bytes read from the channel (to perform the FFT) is returned.</para> /// <para>When requesting sample data, the number of bytes written to buffer will be returned (not necessarily the same as the number of bytes read when using the <see cref="F:ManagedBass.DataFlags.Float"/> or DataFlags.Fixed flag).</para> /// <para>When using the <see cref="F:ManagedBass.DataFlags.Available"/> flag, the number of bytes in the channel's buffer is returned.</para> /// </returns> public int ChannelGetData(IBassAudioChannel channel, float[] buffer, int length) => BassMix.ChannelGetData(channel.Handle, buffer, length); /// <summary> /// Sets up a synchroniser on a mixer source channel. /// </summary> /// <remarks>See: <see cref="ManagedBass.Mix.BassMix.ChannelSetSync(int, SyncFlags, long, SyncProcedure, IntPtr)"/>.</remarks> /// <param name="channel">The <see cref="IBassAudioChannel"/> to set up the synchroniser for.</param> /// <param name="type">The type of sync.</param> /// <param name="parameter">The sync parameters, depending on the sync type.</param> /// <param name="procedure">The callback function which should be invoked with the sync.</param> /// <param name="user">User instance data to pass to the callback function.</param> /// <returns>If successful, then the new synchroniser's handle is returned, else 0 is returned. Use <see cref="P:ManagedBass.Bass.LastError" /> to get the error code.</returns> public int ChannelSetSync(IBassAudioChannel channel, SyncFlags type, long parameter, SyncProcedure procedure, IntPtr user = default) => BassMix.ChannelSetSync(channel.Handle, type, parameter, procedure, user); /// <summary> /// Removes a synchroniser from a mixer source channel. /// </summary> /// <param name="channel">The <see cref="IBassAudioChannel"/> to remove the synchroniser for.</param> /// <param name="sync">Handle of the synchroniser to remove (return value of a previous <see cref="M:ManagedBass.Mix.BassMix.ChannelSetSync(System.Int32,ManagedBass.SyncFlags,System.Int64,ManagedBass.SyncProcedure,System.IntPtr)" /> call).</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="P:ManagedBass.Bass.LastError" /> to get the error code.</returns> public bool ChannelRemoveSync(IBassAudioChannel channel, int sync) => BassMix.ChannelRemoveSync(channel.Handle, sync); /// <summary> /// Frees a channel's resources. /// </summary> /// <param name="channel">The <see cref="IBassAudioChannel"/> to free.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="P:ManagedBass.Bass.LastError" /> to get the error code.</returns> public bool StreamFree(IBassAudioChannel channel) { Remove(channel, false); return ManagedBass.Bass.StreamFree(channel.Handle); } public void UpdateDevice(int deviceIndex) { if (Handle == 0) createMixer(); else ManagedBass.Bass.ChannelSetDevice(Handle, deviceIndex); } protected override void UpdateState() { for (int i = 0; i < activeChannels.Count; i++) { var channel = activeChannels[i]; if (channel.IsActive) continue; activeChannels.RemoveAt(i--); removeChannelFromBassMix(channel); } FrameStatistics.Add(StatisticsCounterType.MixChannels, activeChannels.Count); base.UpdateState(); } private void createMixer() { if (Handle != 0) return; // Make sure that bass is initialised before trying to create a mixer. // If not, this will be called again when the device is initialised via UpdateDevice(). if (!ManagedBass.Bass.GetDeviceInfo(ManagedBass.Bass.CurrentDevice, out var deviceInfo) || !deviceInfo.IsInitialized) return; Handle = BassMix.CreateMixerStream(frequency, 2, BassFlags.MixerNonStop); if (Handle == 0) return; // Lower latency is valued more for the time since we are not using complex DSP effects. Disable buffering on the mixer channel in order for data to be produced immediately. ManagedBass.Bass.ChannelSetAttribute(Handle, ChannelAttribute.Buffer, 0); // Register all channels that were previously played prior to the mixer being loaded. var toAdd = activeChannels.ToArray(); activeChannels.Clear(); foreach (var channel in toAdd) AddChannelToBassMix(channel); Effects.BindCollectionChanged(onEffectsChanged, true); ManagedBass.Bass.ChannelPlay(Handle); } /// <summary> /// Adds a channel to the native BASS mix. /// </summary> public void AddChannelToBassMix(IBassAudioChannel channel) { Debug.Assert(Handle != 0); Debug.Assert(channel.Handle != 0); BassFlags flags = BassFlags.MixerChanBuffer | BassFlags.MixerChanNoRampin; if (channel.MixerChannelPaused) flags |= BassFlags.MixerChanPause; if (BassMix.MixerAddChannel(Handle, channel.Handle, flags)) activeChannels.Add(channel); } /// <summary> /// Removes a channel from the native BASS mix. /// </summary> private void removeChannelFromBassMix(IBassAudioChannel channel) { Debug.Assert(Handle != 0); Debug.Assert(channel.Handle != 0); channel.MixerChannelPaused = BassMix.ChannelHasFlag(channel.Handle, BassFlags.MixerChanPause); BassMix.MixerRemoveChannel(channel.Handle); } private void onEffectsChanged(object? sender, NotifyCollectionChangedEventArgs e) => EnqueueAction(() => { switch (e.Action) { case NotifyCollectionChangedAction.Add: { Debug.Assert(e.NewItems != null); // Work around BindableList sending initial event start with index -1. int startIndex = Math.Max(0, e.NewStartingIndex); ActiveEffects.InsertRange(startIndex, e.NewItems.OfType<IEffectParameter>().Select(eff => new EffectWithHandle(eff))); applyEffects(startIndex, ActiveEffects.Count - 1); break; } case NotifyCollectionChangedAction.Move: { EffectWithHandle effect = ActiveEffects[e.OldStartingIndex]; ActiveEffects.RemoveAt(e.OldStartingIndex); ActiveEffects.Insert(e.NewStartingIndex, effect); applyEffects(Math.Min(e.OldStartingIndex, e.NewStartingIndex), ActiveEffects.Count - 1); break; } case NotifyCollectionChangedAction.Remove: { Debug.Assert(e.OldItems != null); for (int i = 0; i < e.OldItems.Count; i++) removeEffect(ActiveEffects[e.OldStartingIndex + i]); ActiveEffects.RemoveRange(e.OldStartingIndex, e.OldItems.Count); applyEffects(e.OldStartingIndex, ActiveEffects.Count - 1); break; } case NotifyCollectionChangedAction.Replace: { Debug.Assert(e.NewItems != null); EffectWithHandle oldEffect = ActiveEffects[e.NewStartingIndex]; EffectWithHandle newEffect = new EffectWithHandle((IEffectParameter)e.NewItems[0].AsNonNull()) { Handle = oldEffect.Handle }; ActiveEffects[e.NewStartingIndex] = newEffect; // If the effect types don't match, the old effect has to be removed altogether. Otherwise, the new parameters can be applied onto the existing handle. if (oldEffect.Effect.FXType != newEffect.Effect.FXType) removeEffect(oldEffect); applyEffects(e.NewStartingIndex, e.NewStartingIndex); break; } case NotifyCollectionChangedAction.Reset: { foreach (var effect in ActiveEffects) removeEffect(effect); ActiveEffects.Clear(); break; } } void removeEffect(EffectWithHandle effect) { Debug.Assert(effect.Handle != 0); ManagedBass.Bass.ChannelRemoveFX(Handle, effect.Handle); effect.Handle = 0; } void applyEffects(int startIndex, int endIndex) { for (int i = startIndex; i <= endIndex; i++) { var effect = ActiveEffects[i]; // Effects with greatest priority are stored at the front of the list. effect.Priority = -i; if (effect.Handle != 0) { // Todo: Temporary bypass to attempt to fix failing test runs. if (!DebugUtils.IsNUnitRunning) ManagedBass.Bass.FXSetPriority(effect.Handle, effect.Priority); } else effect.Handle = ManagedBass.Bass.ChannelSetFX(Handle, effect.Effect.FXType, effect.Priority); ManagedBass.Bass.FXSetParameters(effect.Handle, effect.Effect); } } }); /// <summary> /// Flushes the mixer, causing pause and seek events to take effect immediately. /// </summary> /// <remarks> /// This will change the timing of <see cref="ChannelGetPosition"/>, so should be used sparingly. /// </remarks> private void flush() { if (Handle != 0) ManagedBass.Bass.ChannelSetPosition(Handle, 0); } protected override void Dispose(bool disposing) { base.Dispose(disposing); // Move all contained channels back to the default mixer. foreach (var channel in activeChannels.ToArray()) Remove(channel); if (Handle != 0) { ManagedBass.Bass.StreamFree(Handle); Handle = 0; } } internal class EffectWithHandle { public int Handle { get; set; } public int Priority { get; set; } public readonly IEffectParameter Effect; public EffectWithHandle(IEffectParameter effect) { Effect = effect; } } } }
// 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; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.AccessControl; using System.Text; namespace Microsoft.Win32 { /// <summary>Registry encapsulation. To get an instance of a RegistryKey use the Registry class's static members then call OpenSubKey.</summary> internal sealed partial class RegistryKey : IDisposable { public static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); public static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); public static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); public static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); public static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); public static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); /// <summary>Names of keys. This array must be in the same order as the HKEY values listed above.</summary> private static readonly string[] s_hkeyNames = new string[] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG" }; // MSDN defines the following limits for registry key names & values: // Key Name: 255 characters // Value name: 16,383 Unicode characters // Value: either 1 MB or current available memory, depending on registry format. private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; private volatile SafeRegistryHandle _hkey; private volatile string _keyName; private volatile bool _remoteKey; private volatile StateFlags _state; private volatile RegistryView _regView = RegistryView.Default; /// <summary> /// Creates a RegistryKey. This key is bound to hkey, if writable is <b>false</b> then no write operations will be allowed. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view) : this(hkey, writable, false, false, false, view) { } /// <summary> /// Creates a RegistryKey. /// This key is bound to hkey, if writable is <b>false</b> then no write operations /// will be allowed. If systemkey is set then the hkey won't be released /// when the object is GC'ed. /// The remoteKey flag when set to true indicates that we are dealing with registry entries /// on a remote machine and requires the program making these calls to have full trust. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) { ValidateKeyView(view); _hkey = hkey; _keyName = ""; _remoteKey = remoteKey; _regView = view; if (systemkey) { _state |= StateFlags.SystemKey; } if (writable) { _state |= StateFlags.WriteAccess; } if (isPerfData) { _state |= StateFlags.PerfData; } } public void Flush() { FlushCore(); } public void Dispose() { if (_hkey != null) { if (!IsSystemKey()) { try { _hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { _hkey = null; } } else if (IsPerfDataKey()) { ClosePerfDataKey(); } } } /// <summary>Creates a new subkey, or opens an existing one.</summary> /// <param name="subkey">Name or path to subkey to create or open.</param> /// <returns>The subkey, or <b>null</b> if the operation failed.</returns> [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] public RegistryKey CreateSubKey(string subkey) { return CreateSubKey(subkey, IsWritable()); } public RegistryKey CreateSubKey(string subkey, bool writable) { return CreateSubKeyInternal(subkey, writable, RegistryOptions.None); } public RegistryKey CreateSubKey(string subkey, bool writable, RegistryOptions options) { return CreateSubKeyInternal(subkey, writable, options); } private RegistryKey CreateSubKeyInternal(string subkey, bool writable, RegistryOptions registryOptions) { ValidateKeyOptions(registryOptions); ValidateKeyName(subkey); EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash // only keys opened under read mode is not writable if (!_remoteKey) { RegistryKey key = InternalOpenSubKey(subkey, writable); if (key != null) { // Key already exits return key; } } return CreateSubKeyInternalCore(subkey, writable, registryOptions); } public void DeleteValue(string name, bool throwOnMissingValue) { EnsureWriteable(); DeleteValueCore(name, throwOnMissingValue); } public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) { ValidateKeyView(view); return OpenBaseKeyCore(hKey, view); } /// <summary> /// Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with /// read-only access. /// </summary> /// <returns>the Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey OpenSubKey(string name, bool writable) => OpenSubKey(name, GetRegistryKeyRights(writable)); public RegistryKey OpenSubKey(string name, RegistryRights rights) { ValidateKeyName(name); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash return InternalOpenSubKeyCore(name, rights, throwOnPermissionFailure: true); } /// <summary> /// This required no security checks. This is to get around the Deleting SubKeys which only require /// write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks /// </summary> private RegistryKey InternalOpenSubKey(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); return InternalOpenSubKeyCore(name, GetRegistryKeyRights(writable), throwOnPermissionFailure: false); } /// <summary>Returns a subkey with read only permissions.</summary> /// <param name="name">Name or path of subkey to open.</param> /// <returns>The Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey OpenSubKey(string name) { return OpenSubKey(name, false); } /// <summary>Retrieves the count of subkeys.</summary> /// <returns>A count of subkeys.</returns> public int SubKeyCount { get { return InternalSubKeyCount(); } } public RegistryView View { get { EnsureNotDisposed(); return _regView; } } public SafeRegistryHandle Handle { get { EnsureNotDisposed(); return IsSystemKey() ? SystemKeyHandle : _hkey; } } public static RegistryKey FromHandle(SafeRegistryHandle handle) { return FromHandle(handle, RegistryView.Default); } public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) { if (handle == null) throw new ArgumentNullException(nameof(handle)); ValidateKeyView(view); return new RegistryKey(handle, writable: true, view: view); } private int InternalSubKeyCount() { EnsureNotDisposed(); return InternalSubKeyCountCore(); } /// <summary>Retrieves an array of strings containing all the subkey names.</summary> /// <returns>All subkey names.</returns> public string[] GetSubKeyNames() { return InternalGetSubKeyNames(); } private string[] InternalGetSubKeyNames() { int subkeys = InternalSubKeyCount(); return subkeys > 0 ? InternalGetSubKeyNamesCore(subkeys) : Array.Empty<string>(); } /// <summary>Retrieves the count of values.</summary> /// <returns>A count of values.</returns> public int ValueCount { get { EnsureNotDisposed(); return InternalValueCountCore(); } } /// <summary>Retrieves an array of strings containing all the value names.</summary> /// <returns>All value names.</returns> public string[] GetValueNames() { int values = ValueCount; return values > 0 ? GetValueNamesCore(values) : Array.Empty<string>(); } /// <summary>Retrieves the specified value. <b>null</b> is returned if the value doesn't exist</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <returns>The data associated with the value.</returns> public object GetValue(string name) { return InternalGetValue(name, null, false, true); } /// <summary>Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist.</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// The default values for RegistryKeys are OS-dependent. NT doesn't /// have them by default, but they can exist and be of any type. On /// Win95, the default value is always an empty key of type REG_SZ. /// Win98 supports default values of any type, but defaults to REG_SZ. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <param name="defaultValue">Value to return if <i>name</i> doesn't exist.</param> /// <returns>The data associated with the value.</returns> public object GetValue(string name, object defaultValue) { return InternalGetValue(name, defaultValue, false, true); } public object GetValue(string name, object defaultValue, RegistryValueOptions options) { if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); } bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); return InternalGetValue(name, defaultValue, doNotExpand, checkSecurity: true); } public object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity) { if (checkSecurity) { EnsureNotDisposed(); } // Name can be null! It's the most common use of RegQueryValueEx return InternalGetValueCore(name, defaultValue, doNotExpand); } public RegistryValueKind GetValueKind(string name) { EnsureNotDisposed(); return GetValueKindCore(name); } public string Name { get { EnsureNotDisposed(); return _keyName; } } //The actual api is SetValue(string name, object value, RegistryValueKind valueKind) but we only need to set Strings // so this is a cut-down version that supports on that. internal void SetValue(string name, string value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (name != null && name.Length > MaxValueLength) throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); EnsureWriteable(); SetValueCore(name, value); } /// <summary>Retrieves a string representation of this key.</summary> /// <returns>A string representing the key.</returns> public override string ToString() { EnsureNotDisposed(); return _keyName; } private static string FixupName(string name) { Debug.Assert(name != null, "[FixupName]name!=null"); if (name.IndexOf('\\') == -1) { return name; } StringBuilder sb = new StringBuilder(name); FixupPath(sb); int temp = sb.Length - 1; if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash { sb.Length = temp; } return sb.ToString(); } private static void FixupPath(StringBuilder path) { Debug.Assert(path != null); int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; int i = 1; while (i < length - 1) { if (path[i] == '\\') { i++; while (i < length && path[i] == '\\') { path[i] = markerChar; i++; fixup = true; } } i++; } if (fixup) { i = 0; int j = 0; while (i < length) { if (path[i] == markerChar) { i++; continue; } path[j] = path[i]; i++; j++; } path.Length += j - i; } } private void EnsureNotDisposed() { } private void EnsureWriteable() { } private static void ValidateKeyName(string name) { } private static void ValidateKeyOptions(RegistryOptions options) { } private static void ValidateKeyView(RegistryView view) { } private static RegistryRights GetRegistryKeyRights(bool isWritable) { return isWritable ? RegistryRights.ReadKey | RegistryRights.WriteKey : RegistryRights.ReadKey; } /// <summary>Retrieves the current state of the dirty property.</summary> /// <remarks>A key is marked as dirty if any operation has occurred that modifies the contents of the key.</remarks> /// <returns><b>true</b> if the key has been modified.</returns> private bool IsDirty() => (_state & StateFlags.Dirty) != 0; private bool IsSystemKey() => (_state & StateFlags.SystemKey) != 0; private bool IsWritable() => (_state & StateFlags.WriteAccess) != 0; private bool IsPerfDataKey() => (_state & StateFlags.PerfData) != 0; private void SetDirty() => _state |= StateFlags.Dirty; [Flags] private enum StateFlags { /// <summary>Dirty indicates that we have munged data that should be potentially written to disk.</summary> Dirty = 0x0001, /// <summary>SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" or "closed".</summary> SystemKey = 0x0002, /// <summary>Access</summary> WriteAccess = 0x0004, /// <summary>Indicates if this key is for HKEY_PERFORMANCE_DATA</summary> PerfData = 0x0008 } /** * Closes this key, flushes it to disk if the contents have been modified. */ public void Close() { Dispose(true); } private void Dispose(bool disposing) { if (_hkey != null) { if (!IsSystemKey()) { try { _hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { _hkey = null; } } else if (disposing && IsPerfDataKey()) { // System keys should never be closed. However, we want to call RegCloseKey // on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources // (i.e. when disposing is true) so that we release the PERFLIB cache and cause it // to be refreshed (by re-reading the registry) when accessed subsequently. // This is the only way we can see the just installed perf counter. // NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race condition in closing // the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources // in this situation the down level OSes are not. We have a small window between // the dispose below and usage elsewhere (other threads). This is By Design. // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary. Interop.mincore.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA); } } } internal static RegistryKey GetBaseKey(IntPtr hKey) { return GetBaseKey(hKey, RegistryView.Default); } internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) { int index = ((int)hKey) & 0x0FFFFFFF; bool isPerf = hKey == HKEY_PERFORMANCE_DATA; // only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA. SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf); RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view); key._keyName = s_hkeyNames[index]; return key; } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Action Link Template ///<para>SObject Name: ActionLinkTemplate</para> ///<para>Custom Object: False</para> ///</summary> public class SfActionLinkTemplate : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "ActionLinkTemplate"; } } ///<summary> /// Action Link Template ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Action Link Group Template ID /// <para>Name: ActionLinkGroupTemplateId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "actionLinkGroupTemplateId")] [Updateable(false), Createable(true)] public string ActionLinkGroupTemplateId { get; set; } ///<summary> /// ReferenceTo: ActionLinkGroupTemplate /// <para>RelationshipName: ActionLinkGroupTemplate</para> ///</summary> [JsonProperty(PropertyName = "actionLinkGroupTemplate")] [Updateable(false), Createable(false)] public SfActionLinkGroupTemplate ActionLinkGroupTemplate { get; set; } ///<summary> /// Label Key /// <para>Name: LabelKey</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "labelKey")] public string LabelKey { get; set; } ///<summary> /// HTTP Method /// <para>Name: Method</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "method")] public string Method { get; set; } ///<summary> /// Action Type /// <para>Name: LinkType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "linkType")] public string LinkType { get; set; } ///<summary> /// Position /// <para>Name: Position</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "position")] public int? Position { get; set; } ///<summary> /// Confirmation Required /// <para>Name: IsConfirmationRequired</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isConfirmationRequired")] public bool? IsConfirmationRequired { get; set; } ///<summary> /// Default Link in Group /// <para>Name: IsGroupDefault</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isGroupDefault")] public bool? IsGroupDefault { get; set; } ///<summary> /// User Visibility /// <para>Name: UserVisibility</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userVisibility")] public string UserVisibility { get; set; } ///<summary> /// Custom User Alias /// <para>Name: UserAlias</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "userAlias")] public string UserAlias { get; set; } ///<summary> /// Label /// <para>Name: Label</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "label")] public string Label { get; set; } ///<summary> /// Action URL /// <para>Name: ActionUrl</para> /// <para>SF Type: textarea</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "actionUrl")] public string ActionUrl { get; set; } ///<summary> /// HTTP Request Body /// <para>Name: RequestBody</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "requestBody")] public string RequestBody { get; set; } ///<summary> /// HTTP Headers /// <para>Name: Headers</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "headers")] public string Headers { get; set; } } }
// // Button.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Xwt.Drawing; using System.ComponentModel; namespace Xwt { [BackendType (typeof(IButtonBackend))] public class Button: Widget { EventHandler clicked; ButtonStyle style = ButtonStyle.Normal; ButtonType type = ButtonType.Normal; Image image; string label; bool useMnemonic = true; ContentPosition imagePosition = ContentPosition.Left; protected new class WidgetBackendHost: Widget.WidgetBackendHost, IButtonEventSink { protected override void OnBackendCreated () { base.OnBackendCreated (); ((IButtonBackend)Backend).SetButtonStyle (((Button)Parent).style); } public void OnClicked () { ((Button)Parent).OnClicked (EventArgs.Empty); } } public Button () { } public Button (string label) { VerifyConstructorCall (this); Label = label; } public Button (Image img, string label) { VerifyConstructorCall (this); Label = label; Image = img; } public Button (Image img) { VerifyConstructorCall (this); Image = img; } protected override BackendHost CreateBackendHost () { return new WidgetBackendHost (); } protected override void Dispose (bool disposing) { base.Dispose (disposing); if(image != null) image.Dispose (); } IButtonBackend Backend { get { return (IButtonBackend) BackendHost.Backend; } } [DefaultValue ("")] public string Label { get { return label ?? ""; } set { label = value; Backend.SetContent (label, UseMnemonic, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition); OnPreferredSizeChanged (); } } public bool IsToggled { get { return Backend.IsToggled; } set { Backend.IsToggled = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Xwt.Button"/> uses a mnemonic. /// </summary> /// <value><c>true</c> if it uses a mnemonic; otherwise, <c>false</c>.</value> /// <remarks> /// When set to true, the character after the first underscore character in the Label property value is /// interpreted as the mnemonic for that Label. /// </remarks> [DefaultValue(true)] public bool UseMnemonic { get { return useMnemonic; } set { if (useMnemonic == value) return; Backend.SetContent (label, value, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition); useMnemonic = value; } } [DefaultValue (null)] public Image Image { get { return image; } set { image = value; Backend.SetContent (label, UseMnemonic, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition); OnPreferredSizeChanged (); } } [DefaultValue (ContentPosition.Left)] public ContentPosition ImagePosition { get { return imagePosition; } set { imagePosition = value; Backend.SetContent (label, UseMnemonic, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition); OnPreferredSizeChanged (); } } [DefaultValue (ButtonStyle.Normal)] public ButtonStyle Style { get { return style; } set { style = value; Backend.SetButtonStyle (style); OnPreferredSizeChanged (); } } [DefaultValue (ButtonType.Normal)] public ButtonType Type { get { return type; } set { type = value; Backend.SetButtonType (type); OnPreferredSizeChanged (); } } public Color LabelColor { get { return Backend.LabelColor; } set { Backend.LabelColor = value; } } public bool IsDefault { get { return Backend.IsDefault; } set { Backend.IsDefault = value; } } [MappedEvent(ButtonEvent.Clicked)] protected virtual void OnClicked (EventArgs e) { if (clicked != null) clicked (this, e); } public event EventHandler Clicked { add { BackendHost.OnBeforeEventAdd (ButtonEvent.Clicked, clicked); clicked += value; } remove { clicked -= value; BackendHost.OnAfterEventRemove (ButtonEvent.Clicked, clicked); } } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using MvcTemplate.Components.Notifications; using MvcTemplate.Components.Security; using NSubstitute; using System; using System.Collections.Generic; using System.Security.Claims; using System.Text.Json; using Xunit; namespace MvcTemplate.Controllers.Tests { public class AControllerTests : ControllerTests { private ActionExecutingContext context; private AController controller; private String controllerName; private ActionContext action; private String? areaName; public AControllerTests() { controller = Substitute.ForPartsOf<AController>(); controller.Url = Substitute.For<IUrlHelper>(); controller.ControllerContext.RouteData = new RouteData(); controller.TempData = Substitute.For<ITempDataDictionary>(); controller.Authorization.Returns(Substitute.For<IAuthorization>()); controller.ControllerContext.HttpContext = Substitute.For<HttpContext>(); controller.HttpContext.RequestServices.GetService(typeof(IAuthorization)).Returns(Substitute.For<IAuthorization>()); areaName = controller.RouteData.Values["area"] as String; controllerName = (String)controller.RouteData.Values["controller"]!; action = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()); context = new ActionExecutingContext(action, new List<IFilterMetadata>(), new Dictionary<String, Object>(), controller); } public override void Dispose() { controller.Dispose(); } [Fact] public void AController_CreatesEmptyAlerts() { Assert.Empty(controller.Alerts); } [Fact] public void NotFoundView_ReturnsNotFoundView() { ViewResult actual = controller.NotFoundView(); Assert.Equal(StatusCodes.Status404NotFound, controller.Response.StatusCode); Assert.Equal($"~/Views/{nameof(Home)}/{nameof(Home.NotFound)}.cshtml", actual.ViewName); } [Fact] public void NotEmptyView_NullModel_ReturnsNotFoundView() { ViewResult expected = NotFoundView(controller); ViewResult actual = controller.NotEmptyView(null); Assert.Same(expected, actual); } [Fact] public void NotEmptyView_ReturnsModelView() { Object expected = new(); Object actual = Assert.IsType<ViewResult>(controller.NotEmptyView(expected)).Model; Assert.Same(expected, actual); } [Fact] public void RedirectToLocal_NotLocalUrl_RedirectsToDefault() { controller.Url.IsLocalUrl("T").Returns(false); Object expected = RedirectToDefault(controller); Object actual = controller.RedirectToLocal("T"); Assert.Same(expected, actual); } [Fact] public void RedirectToLocal_IsLocalUrl_RedirectsToLocal() { controller.Url.IsLocalUrl("/").Returns(true); String actual = Assert.IsType<RedirectResult>(controller.RedirectToLocal("/")).Url; String expected = "/"; Assert.Equal(expected, actual); } [Fact] public void RedirectToDefault_Route() { RedirectToActionResult actual = controller.RedirectToDefault(); Assert.Equal(nameof(Home.Index), actual.ActionName); Assert.Equal(nameof(Home), actual.ControllerName); Assert.Equal("", actual.RouteValues["area"]); Assert.Single(actual.RouteValues); } [Fact] public void IsAuthorizedFor_ReturnsAuthorizationResult() { controller.Authorization.IsGrantedFor(controller.CurrentAccountId, "Area/Controller/Action").Returns(true); Assert.True(controller.IsAuthorizedFor("Area/Controller/Action")); } [Fact] public void RedirectToAction_Action_Controller_Route_NotAuthorized_RedirectsToDefault() { controller.IsAuthorizedFor($"{areaName}/Controller/Action").Returns(false); Object expected = RedirectToDefault(controller); Object actual = controller.RedirectToAction("Action", "Controller", new { id = 1 }); Assert.Same(expected, actual); } [Fact] public void RedirectToAction_Action_NullController_NullRoute_RedirectsToAction() { controller.IsAuthorizedFor($"{areaName}/{controllerName}/Action").Returns(true); RedirectToActionResult actual = controller.RedirectToAction("Action", null, null); Assert.Equal(controllerName, actual.ControllerName); Assert.Equal("Action", actual.ActionName); Assert.Null(actual.RouteValues); } [Fact] public void RedirectToAction_Action_Controller_NullRoute_RedirectsToAction() { controller.IsAuthorizedFor($"{areaName}/Controller/Action").Returns(true); RedirectToActionResult actual = controller.RedirectToAction("Action", "Controller", null); Assert.Equal("Controller", actual.ControllerName); Assert.Equal("Action", actual.ActionName); Assert.Null(actual.RouteValues); } [Fact] public void RedirectToAction_Action_Controller_Route_RedirectsToAction() { controller.IsAuthorizedFor("Area/Controller/Action").Returns(true); RedirectToActionResult actual = controller.RedirectToAction("Action", "Controller", new { area = "Area", id = 1 }); Assert.Equal("Controller", actual.ControllerName); Assert.Equal("Area", actual.RouteValues["area"]); Assert.Equal("Action", actual.ActionName); Assert.Equal(1, actual.RouteValues["id"]); Assert.Equal(2, actual.RouteValues.Count); } [Fact] public void OnActionExecuting_SetsAuthorization() { controller = Substitute.ForPartsOf<AController>(); controller.ControllerContext.HttpContext = Substitute.For<HttpContext>(); controller.HttpContext.RequestServices.GetService(typeof(IAuthorization)).Returns(Substitute.For<IAuthorization>()); controller.OnActionExecuting(context); Object expected = controller.HttpContext.RequestServices.GetRequiredService<IAuthorization>(); Object actual = controller.Authorization; Assert.Same(expected, actual); } [Theory] [InlineData("", 0)] [InlineData("1", 1)] public void OnActionExecuting_SetsCurrentAccountId(String identifier, Int64 accountId) { controller.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Returns(new Claim(ClaimTypes.NameIdentifier, identifier)); controller.OnActionExecuting(context); Int64? actual = controller.CurrentAccountId; Int64? expected = accountId; Assert.Equal(expected, actual); } [Fact] public void OnActionExecuted_JsonResult_NoAlerts() { JsonResult result = new("Value"); controller.Alerts.AddError("Test"); controller.TempData["Alerts"] = null; controller.OnActionExecuted(new ActionExecutedContext(action, new List<IFilterMetadata>(), controller) { Result = result }); Assert.Null(controller.TempData["Alerts"]); } [Fact] public void OnActionExecuted_NullTempDataAlerts_SetsTempDataAlerts() { controller.Alerts.AddError("Test"); controller.TempData["Alerts"] = null; controller.OnActionExecuted(new ActionExecutedContext(action, new List<IFilterMetadata>(), controller)); Object expected = JsonSerializer.Serialize(controller.Alerts); Object actual = controller.TempData["Alerts"]; Assert.Equal(expected, actual); } [Fact] public void OnActionExecuted_MergesTempDataAlerts() { Alerts alerts = new(); alerts.AddError("Test1"); controller.TempData["Alerts"] = JsonSerializer.Serialize(alerts); controller.Alerts.AddError("Test2"); alerts.AddError("Test2"); controller.OnActionExecuted(new ActionExecutedContext(action, new List<IFilterMetadata>(), controller)); Object expected = JsonSerializer.Serialize(alerts); Object actual = controller.TempData["Alerts"]; Assert.Equal(expected, actual); } } }
//------------------------------------------------------------------------------ // <copyright file="Transfer_RequestOptions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Diagnostics; using System.Net; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.File; using Microsoft.WindowsAzure.Storage.RetryPolicies; using Microsoft.WindowsAzure.Storage.Table; /// <summary> /// Defines default RequestOptions for every type of transfer job. /// </summary> internal static class Transfer_RequestOptions { /// <summary> /// Stores the default client retry count in x-ms error. /// </summary> private const int DefaultRetryCountXMsError = 10; /// <summary> /// Stores the default client retry count in non x-ms error. /// </summary> private const int DefaultRetryCountOtherError = 3; /// <summary> /// Stores the default maximum execution time across all potential retries. /// </summary> private static readonly TimeSpan DefaultMaximumExecutionTime = TimeSpan.FromSeconds(900); /// <summary> /// Stores the default server timeout. /// </summary> private static readonly TimeSpan DefaultServerTimeout = TimeSpan.FromSeconds(300); /// <summary> /// Stores the default back-off. /// Increases exponentially used with ExponentialRetry: 3, 9, 21, 45, 93, 120, 120, 120, ... /// </summary> private static TimeSpan retryPoliciesDefaultBackoff = TimeSpan.FromSeconds(3.0); /// <summary> /// Gets the default <see cref="BlobRequestOptions"/>. /// </summary> /// <value>The default <see cref="BlobRequestOptions"/></value> public static BlobRequestOptions DefaultBlobRequestOptions { get { IRetryPolicy defaultRetryPolicy = new TransferRetryPolicy( retryPoliciesDefaultBackoff, DefaultRetryCountXMsError, DefaultRetryCountOtherError); return new BlobRequestOptions() { MaximumExecutionTime = DefaultMaximumExecutionTime, RetryPolicy = defaultRetryPolicy, ServerTimeout = DefaultServerTimeout, UseTransactionalMD5 = true }; } } /// <summary> /// Gets the default <see cref="FileRequestOptions"/>. /// </summary> /// <value>The default <see cref="FileRequestOptions"/></value> public static FileRequestOptions DefaultFileRequestOptions { get { IRetryPolicy defaultRetryPolicy = new TransferRetryPolicy( retryPoliciesDefaultBackoff, DefaultRetryCountXMsError, DefaultRetryCountOtherError); return new FileRequestOptions() { MaximumExecutionTime = DefaultMaximumExecutionTime, RetryPolicy = defaultRetryPolicy, ServerTimeout = DefaultServerTimeout, UseTransactionalMD5 = true }; } } /// <summary> /// Gets the default <see cref="TableRequestOptions"/>. /// </summary> /// <value>The default <see cref="TableRequestOptions"/></value> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "It will be called in TableDataMovement project.")] public static TableRequestOptions DefaultTableRequestOptions { get { IRetryPolicy defaultRetryPolicy = new TransferRetryPolicy( retryPoliciesDefaultBackoff, DefaultRetryCountXMsError, DefaultRetryCountOtherError); return new TableRequestOptions { MaximumExecutionTime = DefaultMaximumExecutionTime, RetryPolicy = defaultRetryPolicy, ServerTimeout = DefaultServerTimeout, PayloadFormat = TablePayloadFormat.Json }; } } /// <summary> /// Define retry policy used in blob transfer. /// </summary> private class TransferRetryPolicy : IExtendedRetryPolicy { /// <summary> /// Prefix of Azure Storage response keys. /// </summary> private const string XMsPrefix = "x-ms"; /// <summary> /// Max retry count in non x-ms error. /// </summary> private int maxAttemptsOtherError; /// <summary> /// ExponentialRetry retry policy object. /// </summary> private ExponentialRetry retryPolicy; /// <summary> /// Indicate whether has met x-ms once or more. /// </summary> private bool gotXMsError = false; /// <summary> /// Initializes a new instance of the <see cref="TransferRetryPolicy"/> class. /// </summary> /// <param name="deltaBackoff">Back-off in ExponentialRetry retry policy.</param> /// <param name="maxAttemptsXMsError">Max retry count when meets x-ms error.</param> /// <param name="maxAttemptsOtherError">Max retry count when meets non x-ms error.</param> public TransferRetryPolicy(TimeSpan deltaBackoff, int maxAttemptsXMsError, int maxAttemptsOtherError) { Debug.Assert( maxAttemptsXMsError >= maxAttemptsOtherError, "We should retry more times when meets x-ms errors than the other errors."); this.retryPolicy = new ExponentialRetry(deltaBackoff, maxAttemptsXMsError); this.maxAttemptsOtherError = maxAttemptsOtherError; } /// <summary> /// Initializes a new instance of the <see cref="TransferRetryPolicy"/> class. /// </summary> /// <param name="retryPolicy">ExponentialRetry object.</param> /// <param name="maxAttemptsInOtherError">Max retry count when meets non x-ms error.</param> private TransferRetryPolicy(ExponentialRetry retryPolicy, int maxAttemptsInOtherError) { this.retryPolicy = retryPolicy; this.maxAttemptsOtherError = maxAttemptsInOtherError; } /// <summary> /// Generates a new retry policy for the current request attempt. /// </summary> /// <returns>An IRetryPolicy object that represents the retry policy for the current request attempt.</returns> public IRetryPolicy CreateInstance() { return new TransferRetryPolicy( this.retryPolicy.CreateInstance() as ExponentialRetry, this.maxAttemptsOtherError); } /// <summary> /// Determines whether the operation should be retried and the interval until the next retry. /// </summary> /// <param name="retryContext"> /// A RetryContext object that indicates the number of retries, the results of the last request, /// and whether the next retry should happen in the primary or secondary location, and specifies the location mode.</param> /// <param name="operationContext">An OperationContext object for tracking the current operation.</param> /// <returns> /// A RetryInfo object that indicates the location mode, /// and whether the next retry should happen in the primary or secondary location. /// If null, the operation will not be retried. </returns> public RetryInfo Evaluate(RetryContext retryContext, OperationContext operationContext) { if (null == retryContext) { throw new ArgumentNullException("retryContext"); } if (null == operationContext) { throw new ArgumentNullException("operationContext"); } RetryInfo retryInfo = this.retryPolicy.Evaluate(retryContext, operationContext); if (null != retryInfo) { if (this.ShouldRetry(retryContext.CurrentRetryCount, retryContext.LastRequestResult.Exception)) { return retryInfo; } } return null; } /// <summary> /// Determines if the operation should be retried and how long to wait until the next retry. /// </summary> /// <param name="currentRetryCount">The number of retries for the given operation.</param> /// <param name="statusCode">The status code for the last operation.</param> /// <param name="lastException">An Exception object that represents the last exception encountered.</param> /// <param name="retryInterval">The interval to wait until the next retry.</param> /// <param name="operationContext">An OperationContext object for tracking the current operation.</param> /// <returns>True if the operation should be retried; otherwise, false.</returns> public bool ShouldRetry( int currentRetryCount, int statusCode, Exception lastException, out TimeSpan retryInterval, OperationContext operationContext) { if (!this.retryPolicy.ShouldRetry(currentRetryCount, statusCode, lastException, out retryInterval, operationContext)) { return false; } return this.ShouldRetry(currentRetryCount, lastException); } /// <summary> /// Determines if the operation should be retried. /// This function uses http header to determine whether the error is returned from Windows Azure. /// If it's from Windows Azure (with <c>x-ms</c> in header), the request will retry 10 times at most. /// Otherwise, the request will retry 3 times at most. /// </summary> /// <param name="currentRetryCount">The number of retries for the given operation.</param> /// <param name="lastException">An Exception object that represents the last exception encountered.</param> /// <returns>True if the operation should be retried; otherwise, false.</returns> private bool ShouldRetry( int currentRetryCount, Exception lastException) { if (this.gotXMsError) { return true; } StorageException storageException = lastException as StorageException; if (null != storageException) { WebException webException = storageException.InnerException as WebException; if (null != webException) { if (WebExceptionStatus.ConnectionClosed == webException.Status) { return true; } HttpWebResponse response = webException.Response as HttpWebResponse; if (null != response) { if (null != response.Headers) { if (null != response.Headers.AllKeys) { for (int i = 0; i < response.Headers.AllKeys.Length; ++i) { if (response.Headers.AllKeys[i].StartsWith(XMsPrefix, StringComparison.OrdinalIgnoreCase)) { this.gotXMsError = true; return true; } } } } } } } if (currentRetryCount < this.maxAttemptsOtherError) { return true; } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNearestIntegerScalarSingle() { var test = new SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle testClass) { var result = Sse41.RoundToNearestIntegerScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToNearestIntegerScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToNearestIntegerScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse41.RoundToNearestIntegerScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__RoundToNearestIntegerScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToNearestIntegerScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(right[0], MidpointRounding.AwayFromZero))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNearestIntegerScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // AttachmentInternal.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // 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 (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using Couchbase.Lite; using Couchbase.Lite.Internal; using Sharpen; using System.Collections.Generic; using System.IO; using System; using System.Diagnostics; using System.Linq; using System.IO.Compression; using Couchbase.Lite.Util; namespace Couchbase.Lite.Internal { internal enum AttachmentEncoding { None, GZIP } internal sealed class AttachmentInternal { private IEnumerable<byte> _data; private const string TAG = "AttachmentInternal"; public long Length { get; set; } public long EncodedLength { get; set; } public AttachmentEncoding Encoding { get; set; } public int RevPos { get; set; } public Database Database { get; set; } public string Name { get; private set; } public string ContentType { get; private set; } public BlobKey BlobKey { get { return _blobKey; } set { _digest = null; _blobKey = value; } } private BlobKey _blobKey; public string Digest { get { if (_digest != null) { return _digest; } if (_blobKey != null) { return _blobKey.Base64Digest(); } return null; } } private string _digest; // only if inline or stored in db blob-store public IEnumerable<byte> EncodedContent { get { if (_data != null) { return _data; } if (Database == null || Database.Attachments == null) { return null; } return Database.Attachments.BlobForKey(_blobKey); } } public IEnumerable<byte> Content { get { var data = EncodedContent; switch (Encoding) { case AttachmentEncoding.None: break; case AttachmentEncoding.GZIP: data = data.Decompress(); break; } if (data == null) { Log.W(TAG, "Unable to decode attachment!"); } return data; } } public Stream ContentStream { get { if (Encoding == AttachmentEncoding.None) { return Database.Attachments.BlobStreamForKey(_blobKey); } var ms = new MemoryStream(_data.ToArray()); return new GZipStream(ms, CompressionMode.Decompress, true); } } // only if already stored in db blob-store public Uri ContentUrl { get { string path = Database.Attachments.PathForKey(_blobKey); return path != null ? new Uri(path) : null; } } public bool IsValid { get { if (Encoding != AttachmentEncoding.None) { if (EncodedLength == 0 && Length > 0) { return false; } } else if (EncodedLength > 0) { return false; } if (RevPos == 0) { return false; } #if DEBUG if(_blobKey == null) { return false; } #endif return true; } } public AttachmentInternal(string name, string contentType) { Debug.Assert(name != null); Name = name; ContentType = contentType; } public AttachmentInternal(string name, IDictionary<string, object> info) : this(name, info.GetCast<string>("content_type")) { Length = info.GetCast<long>("length"); EncodedLength = info.GetCast<long>("encoded_length"); _digest = info.GetCast<string>("digest"); if (_digest != null) { BlobKey = new BlobKey(_digest); } string encodingString = info.GetCast<string>("encoding"); if (encodingString != null) { if (encodingString.Equals("gzip")) { Encoding = AttachmentEncoding.GZIP; } else { throw new CouchbaseLiteException(StatusCode.BadEncoding); } } var data = info.Get("data"); if (data != null) { // If there's inline attachment data, decode and store it: if (data is string) { _data = Convert.FromBase64String((string)data); } else { _data = data as IEnumerable<byte>; } if (_data == null) { throw new CouchbaseLiteException(StatusCode.BadEncoding); } SetPossiblyEncodedLength(_data.LongCount()); } else if (info.GetCast<bool>("stub", false)) { // This item is just a stub; validate and skip it if(info.ContainsKey("revpos")) { var revPos = info.GetCast<int>("revpos"); if (revPos <= 0) { throw new CouchbaseLiteException(StatusCode.BadAttachment); } RevPos = revPos; } } else if (info.GetCast<bool>("follows", false)) { // I can't handle this myself; my caller will look it up from the digest if (Digest == null) { throw new CouchbaseLiteException(StatusCode.BadAttachment); } if(info.ContainsKey("revpos")) { var revPos = info.GetCast<int>("revpos"); if (revPos <= 0) { throw new CouchbaseLiteException(StatusCode.BadAttachment); } RevPos = revPos; } } else { throw new CouchbaseLiteException(StatusCode.BadAttachment); } } public IDictionary<string, object> AsStubDictionary() { var retVal = new NonNullDictionary<string, object> { { "stub", true }, { "digest", Digest }, { "content_type", ContentType }, { "revpos", RevPos }, { "length", Length } }; if (EncodedLength > 0) { retVal["encoded_length"] = EncodedLength; } switch (Encoding) { case AttachmentEncoding.GZIP: retVal["encoding"] = "gzip"; break; case AttachmentEncoding.None: break; } return retVal; } public void SetPossiblyEncodedLength(long length) { if (Encoding != AttachmentEncoding.None) { EncodedLength = length; } else { Length = length; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace System { internal static partial class SR { internal static string GetString(string value) { return value; } internal static string GetString(string format, params object[] args) { return SR.Format(format, args); } } } namespace System.Data.Common { internal static class ADP { // The class ADP defines the exceptions that are specific to the Adapters. // The class contains functions that take the proper informational variables and then construct // the appropriate exception with an error string obtained from the resource framework. // The exception is then returned to the caller, so that the caller may then throw from its // location so that the catcher of the exception will have the appropriate call stack. // This class is used so that there will be compile time checking of error messages. internal static Exception ExceptionWithStackTrace(Exception e) { try { throw e; } catch (Exception caught) { return caught; } } // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx) // Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features private static Task<bool> s_trueTask = null; internal static Task<bool> TrueTask { get { if (s_trueTask == null) { s_trueTask = Task.FromResult<bool>(true); } return s_trueTask; } } private static Task<bool> s_falseTask = null; internal static Task<bool> FalseTask { get { if (s_falseTask == null) { s_falseTask = Task.FromResult<bool>(false); } return s_falseTask; } } private static readonly bool s_isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); internal static bool IsWindows { get { return s_isWindows; } } // // COM+ exceptions // internal static ArgumentException Argument(string error) { ArgumentException e = new ArgumentException(error); return e; } internal static ArgumentException Argument(string error, Exception inner) { ArgumentException e = new ArgumentException(error, inner); return e; } internal static ArgumentException Argument(string error, string parameter) { ArgumentException e = new ArgumentException(error, parameter); return e; } internal static ArgumentNullException ArgumentNull(string parameter) { ArgumentNullException e = new ArgumentNullException(parameter); return e; } internal static ArgumentNullException ArgumentNull(string parameter, string error) { ArgumentNullException e = new ArgumentNullException(parameter, error); return e; } internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) { ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName); return e; } internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) { ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message); return e; } internal static IndexOutOfRangeException IndexOutOfRange(int value) { IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture)); return e; } internal static IndexOutOfRangeException IndexOutOfRange(string error) { IndexOutOfRangeException e = new IndexOutOfRangeException(error); return e; } internal static IndexOutOfRangeException IndexOutOfRange() { IndexOutOfRangeException e = new IndexOutOfRangeException(); return e; } internal static InvalidCastException InvalidCast(string error) { return InvalidCast(error, null); } internal static InvalidCastException InvalidCast(string error, Exception inner) { InvalidCastException e = new InvalidCastException(error, inner); return e; } internal static InvalidOperationException InvalidOperation(string error) { InvalidOperationException e = new InvalidOperationException(error); return e; } internal static TimeoutException TimeoutException(string error) { TimeoutException e = new TimeoutException(error); return e; } internal static InvalidOperationException InvalidOperation(string error, Exception inner) { InvalidOperationException e = new InvalidOperationException(error, inner); return e; } internal static NotSupportedException NotSupported() { NotSupportedException e = new NotSupportedException(); return e; } internal static NotSupportedException NotSupported(string error) { NotSupportedException e = new NotSupportedException(error); return e; } internal static OverflowException Overflow(string error) { return Overflow(error, null); } internal static OverflowException Overflow(string error, Exception inner) { OverflowException e = new OverflowException(error, inner); return e; } internal static PlatformNotSupportedException DbTypeNotSupported(string dbType) { PlatformNotSupportedException e = new PlatformNotSupportedException(SR.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType)); return e; } internal static InvalidCastException InvalidCast() { InvalidCastException e = new InvalidCastException(); return e; } internal static IOException IO(string error) { IOException e = new IOException(error); return e; } internal static IOException IO(string error, Exception inner) { IOException e = new IOException(error, inner); return e; } internal static InvalidOperationException DataAdapter(string error) { return InvalidOperation(error); } private static InvalidOperationException Provider(string error) { return InvalidOperation(error); } internal static ObjectDisposedException ObjectDisposed(object instance) { ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name); return e; } internal static InvalidOperationException MethodCalledTwice(string method) { InvalidOperationException e = new InvalidOperationException(SR.GetString(SR.ADP_CalledTwice, method)); return e; } internal static ArgumentException InvalidMultipartName(string property, string value) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidMultipartName, SR.GetString(property), value)); return e; } internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidMultipartNameQuoteUsage, SR.GetString(property), value)); return e; } internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidMultipartNameToManyParts, SR.GetString(property), value, limit)); return e; } internal static void CheckArgumentNull(object value, string parameterName) { if (null == value) { throw ArgumentNull(parameterName); } } internal static bool IsCatchableExceptionType(Exception e) { return !((e is NullReferenceException) || (e is SecurityException)); } internal static bool IsCatchableOrSecurityExceptionType(Exception e) { // a 'catchable' exception is defined by what it is not. // since IsCatchableExceptionType defined SecurityException as not 'catchable' // this method will return true for SecurityException has being catchable. // the other way to write this method is, but then SecurityException is checked twice // return ((e is SecurityException) || IsCatchableExceptionType(e)); Debug.Assert(e != null, "Unexpected null exception!"); // Most of the exception types above will cause the process to fail fast // So they are no longer needed in this check return !(e is NullReferenceException); } // Invalid Enumeration internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) { return ADP.ArgumentOutOfRange(SR.GetString(SR.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name); } // IDbCommand.CommandType internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value) { #if DEBUG switch (value) { case CommandType.Text: case CommandType.StoredProcedure: case CommandType.TableDirect: Debug.Assert(false, "valid CommandType " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(CommandType), (int)value); } // IDbConnection.BeginTransaction, OleDbTransaction.Begin internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) { #if DEBUG switch (value) { case IsolationLevel.Unspecified: case IsolationLevel.Chaos: case IsolationLevel.ReadUncommitted: case IsolationLevel.ReadCommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: Debug.Fail("valid IsolationLevel " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(IsolationLevel), (int)value); } // IDataParameter.Direction internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) { #if DEBUG switch (value) { case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: Debug.Assert(false, "valid ParameterDirection " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); } // IDbCommand.UpdateRowSource internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) { #if DEBUG switch (value) { case UpdateRowSource.None: case UpdateRowSource.OutputParameters: case UpdateRowSource.FirstReturnedRecord: case UpdateRowSource.Both: Debug.Assert(false, "valid UpdateRowSource " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value); } // // DbConnectionOptions, DataAccess // internal static ArgumentException ConnectionStringSyntax(int index) { return Argument(SR.GetString(SR.ADP_ConnectionStringSyntax, index)); } internal static ArgumentException KeywordNotSupported(string keyword) { return Argument(SR.GetString(SR.ADP_KeywordNotSupported, keyword)); } internal static ArgumentException InvalidMinMaxPoolSizeValues() { return ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues)); } internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) { return ADP.Argument(SR.GetString(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); } // // DbConnection // internal static InvalidOperationException NoConnectionString() { return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString)); } internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "") { return NotImplemented.ByDesignWithMessage(methodName); } private static string ConnectionStateMsg(ConnectionState state) { switch (state) { case (ConnectionState.Closed): case (ConnectionState.Connecting | ConnectionState.Broken): return SR.GetString(SR.ADP_ConnectionStateMsg_Closed); case (ConnectionState.Connecting): return SR.GetString(SR.ADP_ConnectionStateMsg_Connecting); case (ConnectionState.Open): return SR.GetString(SR.ADP_ConnectionStateMsg_Open); case (ConnectionState.Open | ConnectionState.Executing): return SR.GetString(SR.ADP_ConnectionStateMsg_OpenExecuting); case (ConnectionState.Open | ConnectionState.Fetching): return SR.GetString(SR.ADP_ConnectionStateMsg_OpenFetching); default: return SR.GetString(SR.ADP_ConnectionStateMsg, state.ToString()); } } // // : DbConnectionOptions, DataAccess, SqlClient // internal static Exception InvalidConnectionOptionValue(string key) { return InvalidConnectionOptionValue(key, null); } internal static Exception InvalidConnectionOptionValueLength(string key, int limit) { return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit)); } internal static Exception InvalidConnectionOptionValue(string key, Exception inner) { return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValue, key), inner); } internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) { return Argument(SR.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); } internal static Exception WrongType(Type got, Type expected) { return Argument(SR.GetString(SR.SQL_WrongType, got.ToString(), expected.ToString())); } // // DbConnectionPool and related // internal static Exception PooledOpenTimeout() { return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout)); } internal static Exception NonPooledOpenTimeout() { return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout)); } // // Generic Data Provider Collection // internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) { return Argument(SR.GetString(SR.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); } internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) { return ArgumentNull(parameter, SR.GetString(SR.ADP_CollectionNullValue, collection.Name, itemType.Name)); } internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) { return IndexOutOfRange(SR.GetString(SR.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture))); } internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) { return IndexOutOfRange(SR.GetString(SR.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name)); } internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) { return InvalidCast(SR.GetString(SR.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name)); } internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) { return Argument(SR.GetString(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); } internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection) { return Argument(SR.GetString(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); } // // DbProviderException // internal static InvalidOperationException TransactionConnectionMismatch() { return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch)); } internal static InvalidOperationException TransactionRequired(string method) { return Provider(SR.GetString(SR.ADP_TransactionRequired, method)); } internal static Exception CommandTextRequired(string method) { return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method)); } internal static InvalidOperationException ConnectionRequired(string method) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method)); } internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); } internal static Exception OpenReaderExists() { return OpenReaderExists(null); } internal static Exception OpenReaderExists(Exception e) { return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e); } // // DbDataReader // internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method) { return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method)); } internal static Exception NegativeParameter(string parameterName) { return InvalidOperation(SR.GetString(SR.ADP_NegativeParameter, parameterName)); } internal static Exception InvalidSeekOrigin(string parameterName) { return ArgumentOutOfRange(SR.GetString(SR.ADP_InvalidSeekOrigin), parameterName); } // // SqlMetaData, SqlTypes, SqlClient // internal static Exception InvalidMetaDataValue() { return ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue)); } internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) { return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture))); } // // : IDbCommand // internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "") { return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property); } internal static Exception UninitializedParameterSize(int index, Type dataType) { return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); } internal static Exception PrepareParameterType(DbCommand cmd) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name)); } internal static Exception PrepareParameterSize(DbCommand cmd) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name)); } internal static Exception PrepareParameterScale(DbCommand cmd, string type) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type)); } internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) { return InvalidOperation(SR.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); } // // : ConnectionUtil // internal static Exception ConnectionIsDisabled(Exception InnerException) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionIsDisabled), InnerException); } internal static Exception ClosedConnectionError() { return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError)); } internal static Exception ConnectionAlreadyOpen(ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); } internal static Exception OpenConnectionPropertySet(string property, ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); } internal static Exception EmptyDatabaseName() { return Argument(SR.GetString(SR.ADP_EmptyDatabaseName)); } internal enum ConnectionError { BeginGetConnectionReturnsNull, GetConnectionReturnsNull, ConnectionOptionsMissing, CouldNotSwitchToClosedPreviouslyOpenedState, } internal static Exception InternalConnectionError(ConnectionError internalError) { return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError)); } internal enum InternalErrorCode { UnpooledObjectHasOwner = 0, UnpooledObjectHasWrongOwner = 1, PushingObjectSecondTime = 2, PooledObjectHasOwner = 3, PooledObjectInPoolMoreThanOnce = 4, CreateObjectReturnedNull = 5, NewObjectCannotBePooled = 6, NonPooledObjectUsedMoreThanOnce = 7, AttemptingToPoolOnRestrictedToken = 8, // ConnectionOptionsInUse = 9, ConvertSidToStringSidWReturnedNull = 10, // UnexpectedTransactedObject = 11, AttemptingToConstructReferenceCollectionOnStaticObject = 12, AttemptingToEnlistTwice = 13, CreateReferenceCollectionReturnedNull = 14, PooledObjectWithoutPool = 15, UnexpectedWaitAnyResult = 16, SynchronousConnectReturnedPending = 17, CompletedConnectReturnedPending = 18, NameValuePairNext = 20, InvalidParserState1 = 21, InvalidParserState2 = 22, InvalidParserState3 = 23, InvalidBuffer = 30, UnimplementedSMIMethod = 40, InvalidSmiCall = 41, SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50, SqlDependencyProcessDispatcherFailureCreateInstance = 51, SqlDependencyProcessDispatcherFailureAppDomain = 52, SqlDependencyCommandHashIsNotAssociatedWithNotification = 53, UnknownTransactionFailure = 60, } internal static Exception InternalError(InternalErrorCode internalError) { return InvalidOperation(SR.GetString(SR.ADP_InternalProviderError, (int)internalError)); } internal static Exception InvalidConnectRetryCountValue() { return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryCountValue)); } internal static Exception InvalidConnectRetryIntervalValue() { return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue)); } // // : DbDataReader // internal static Exception DataReaderClosed([CallerMemberName] string method = "") { return InvalidOperation(SR.GetString(SR.ADP_DataReaderClosed, method)); } internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) { return ArgumentOutOfRange(SR.GetString(SR.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName); } internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) { return ArgumentOutOfRange(SR.GetString(SR.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName); } internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) { return IndexOutOfRange(SR.GetString(SR.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidDataLength(long length) { return IndexOutOfRange(SR.GetString(SR.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); } internal static InvalidOperationException AsyncOperationPending() { return InvalidOperation(SR.GetString(SR.ADP_PendingAsyncOperation)); } // // : Stream // internal static Exception StreamClosed([CallerMemberName] string method = "") { return InvalidOperation(SR.GetString(SR.ADP_StreamClosed, method)); } internal static IOException ErrorReadingFromStream(Exception internalException) { return IO(SR.GetString(SR.SqlMisc_StreamErrorMessage), internalException); } internal static ArgumentException InvalidDataType(string typeName) { return Argument(SR.GetString(SR.ADP_InvalidDataType, typeName)); } internal static ArgumentException UnknownDataType(Type dataType) { return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName)); } internal static ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype) { return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); } internal static ArgumentException InvalidOffsetValue(int value) { return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException InvalidSizeValue(int value) { return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException ParameterValueOutOfRange(Decimal value) { return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); } internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value) { return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString())); } internal static ArgumentException VersionDoesNotSupportDataType(string typeName) { return Argument(SR.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName)); } internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { Debug.Assert(null != value, "null value on conversion failure"); Debug.Assert(null != inner, "null inner on conversion failure"); Exception e; string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); if (inner is ArgumentException) { e = new ArgumentException(message, inner); } else if (inner is FormatException) { e = new FormatException(message, inner); } else if (inner is InvalidCastException) { e = new InvalidCastException(message, inner); } else if (inner is OverflowException) { e = new OverflowException(message, inner); } else { e = inner; } return e; } // // : IDataParameterCollection // internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection) { return CollectionIndexInt32(index, collection.GetType(), collection.Count); } internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType) { return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType()); } internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType) { return CollectionNullValue(parameter, collection.GetType(), parameterType); } internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue) { return CollectionInvalidType(collection.GetType(), parameterType, invalidValue); } // // : IDbTransaction // internal static Exception ParallelTransactionsNotSupported(DbConnection obj) { return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); } internal static Exception TransactionZombied(DbTransaction obj) { return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name)); } // global constant strings internal const string Parameter = "Parameter"; internal const string ParameterName = "ParameterName"; internal const string ParameterSetPosition = "set_Position"; internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; internal const int DecimalMaxPrecision = 29; internal const int DecimalMaxPrecision28 = 28; // there are some cases in Odbc where we need that ... internal const int DefaultCommandTimeout = 30; internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout; internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections // security issue, don't rely upon public static readonly values - AS/URT 109635 internal static readonly String StrEmpty = ""; // String.Empty internal const int CharSize = sizeof(char); internal static void TimerCurrent(out long ticks) { ticks = DateTime.UtcNow.ToFileTimeUtc(); } internal static long TimerCurrent() { return DateTime.UtcNow.ToFileTimeUtc(); } internal static long TimerFromSeconds(int seconds) { long result = checked((long)seconds * TimeSpan.TicksPerSecond); return result; } internal static long TimerFromMilliseconds(long milliseconds) { long result = checked(milliseconds * TimeSpan.TicksPerMillisecond); return result; } internal static bool TimerHasExpired(long timerExpire) { bool result = TimerCurrent() > timerExpire; return result; } internal static long TimerRemaining(long timerExpire) { long timerNow = TimerCurrent(); long result = checked(timerExpire - timerNow); return result; } internal static long TimerRemainingMilliseconds(long timerExpire) { long result = TimerToMilliseconds(TimerRemaining(timerExpire)); return result; } internal static long TimerRemainingSeconds(long timerExpire) { long result = TimerToSeconds(TimerRemaining(timerExpire)); return result; } internal static long TimerToMilliseconds(long timerValue) { long result = timerValue / TimeSpan.TicksPerMillisecond; return result; } private static long TimerToSeconds(long timerValue) { long result = timerValue / TimeSpan.TicksPerSecond; return result; } internal static string MachineName() { return Environment.MachineName; } internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) { StringBuilder resultString = new StringBuilder(); if (string.IsNullOrEmpty(quotePrefix) == false) { resultString.Append(quotePrefix); } // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar". if (string.IsNullOrEmpty(quoteSuffix) == false) { resultString.Append(unQuotedString.Replace(quoteSuffix, quoteSuffix + quoteSuffix)); resultString.Append(quoteSuffix); } else { resultString.Append(unQuotedString); } return resultString.ToString(); } // { "a", "a", "a" } -> { "a", "a1", "a2" } // { "a", "a", "a1" } -> { "a", "a2", "a1" } // { "a", "A", "a" } -> { "a", "A1", "a2" } // { "a", "A", "a1" } -> { "a", "A2", "a1" } internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray) { Dictionary<string, int> hash = new Dictionary<string, int>(columnNameArray.Length); int startIndex = columnNameArray.Length; // lowest non-unique index for (int i = columnNameArray.Length - 1; 0 <= i; --i) { string columnName = columnNameArray[i]; if ((null != columnName) && (0 < columnName.Length)) { columnName = columnName.ToLowerInvariant(); int index; if (hash.TryGetValue(columnName, out index)) { startIndex = Math.Min(startIndex, index); } hash[columnName] = i; } else { columnNameArray[i] = ADP.StrEmpty; startIndex = i; } } int uniqueIndex = 1; for (int i = startIndex; i < columnNameArray.Length; ++i) { string columnName = columnNameArray[i]; if (0 == columnName.Length) { // generate a unique name columnNameArray[i] = "Column"; uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex); } else { columnName = columnName.ToLowerInvariant(); if (i != hash[columnName]) { GenerateUniqueName(hash, ref columnNameArray[i], i, 1); } } } } private static int GenerateUniqueName(Dictionary<string, int> hash, ref string columnName, int index, int uniqueIndex) { for (; ; ++uniqueIndex) { string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture); string lowerName = uniqueName.ToLowerInvariant(); if (!hash.ContainsKey(lowerName)) { columnName = uniqueName; hash.Add(lowerName, index); break; } } return uniqueIndex; } internal static int DstCompare(string strA, string strB) { // this is null safe return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions); } internal static bool IsDirection(DbParameter value, ParameterDirection condition) { #if DEBUG IsDirectionValid(condition); #endif return (condition == (condition & value.Direction)); } #if DEBUG private static void IsDirectionValid(ParameterDirection value) { switch (value) { // @perfnote: Enum.IsDefined case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: break; default: throw ADP.InvalidParameterDirection(value); } } #endif internal static bool IsNull(object value) { if ((null == value) || (DBNull.Value == value)) { return true; } INullable nullable = (value as INullable); return ((null != nullable) && nullable.IsNull); } internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) { if ((value == null) || (value == DBNull.Value)) { isNull = true; isSqlType = false; } else { INullable nullable = (value as INullable); if (nullable != null) { isNull = nullable.IsNull; // Duplicated from DataStorage.cs // For back-compat, SqlXml is not in this list isSqlType = ((value is SqlBinary) || (value is SqlBoolean) || (value is SqlByte) || (value is SqlBytes) || (value is SqlChars) || (value is SqlDateTime) || (value is SqlDecimal) || (value is SqlDouble) || (value is SqlGuid) || (value is SqlInt16) || (value is SqlInt32) || (value is SqlInt64) || (value is SqlMoney) || (value is SqlSingle) || (value is SqlString)); } else { isNull = false; isSqlType = false; } } } private static Version s_systemDataVersion; internal static Version GetAssemblyVersion() { // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time if (s_systemDataVersion == null) { s_systemDataVersion = new Version(ThisAssembly.InformationalVersion); } return s_systemDataVersion; } internal static readonly string[] AzureSqlServerEndpoints = {SR.GetString(SR.AZURESQL_GenericEndpoint), SR.GetString(SR.AZURESQL_GermanEndpoint), SR.GetString(SR.AZURESQL_UsGovEndpoint), SR.GetString(SR.AZURESQL_ChinaEndpoint)}; // This method assumes dataSource parameter is in TCP connection string format. internal static bool IsAzureSqlServerEndpoint(string dataSource) { // remove server port int i = dataSource.LastIndexOf(','); if (i >= 0) { dataSource = dataSource.Substring(0, i); } // check for the instance name i = dataSource.LastIndexOf('\\'); if (i >= 0) { dataSource = dataSource.Substring(0, i); } // trim redundant whitespace dataSource = dataSource.Trim(); // check if servername end with any azure endpoints for (i = 0; i < AzureSqlServerEndpoints.Length; i++) { if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } }
// 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.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ProductSubscriptionsOperations operations. /// </summary> internal partial class ProductSubscriptionsOperations : IServiceOperations<ApiManagementClient>, IProductSubscriptionsOperations { /// <summary> /// Initializes a new instance of the ProductSubscriptionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProductSubscriptionsOperations(ApiManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApiManagementClient /// </summary> public ApiManagementClient Client { get; private set; } /// <summary> /// Lists the collection of subscriptions to the specified product. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='productId'> /// Product identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SubscriptionContract>>> ListWithHttpMessagesAsync(string resourceGroupName, string serviceName, string productId, ODataQuery<SubscriptionContract> odataQuery = default(ODataQuery<SubscriptionContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (productId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "productId"); } if (productId != null) { if (productId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "productId", 256); } if (productId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "productId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(productId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "productId", "^[^*#&+:<>?]+$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("productId", productId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/products/{productId}/subscriptions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{productId}", System.Uri.EscapeDataString(productId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SubscriptionContract>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SubscriptionContract>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the collection of subscriptions to the specified product. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SubscriptionContract>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SubscriptionContract>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<SubscriptionContract>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Paket.Bootstrapper.HelperProxies; namespace Paket.Bootstrapper.DownloadStrategies { internal class NugetDownloadStrategy : DownloadStrategy { internal class NugetApiHelper { private readonly string packageName; private readonly string nugetSource; const string NugetSourceAppSettingsKey = "NugetSource"; const string DefaultNugetSource = "https://www.nuget.org/api/v2"; const string GetPackageVersionTemplate = "{0}/package-versions/{1}"; const string GetLatestFromNugetUrlTemplate = "{0}/package/{1}"; const string GetSpecificFromNugetUrlTemplate = "{0}/package/{1}/{2}"; public NugetApiHelper(string packageName, string nugetSource) { this.packageName = packageName; this.nugetSource = nugetSource ?? ConfigurationManager.AppSettings[NugetSourceAppSettingsKey] ?? DefaultNugetSource; } internal string GetAllPackageVersions(bool includePrerelease) { var request = String.Format(GetPackageVersionTemplate, nugetSource, packageName); const string withPrereleases = "?includePrerelease=true"; if (includePrerelease) request += withPrereleases; return request; } internal string GetLatestPackage() { return String.Format(GetLatestFromNugetUrlTemplate, nugetSource, packageName); } internal string GetSpecificPackageVersion(string version) { return String.Format(GetSpecificFromNugetUrlTemplate, nugetSource, packageName, version); } } private IWebRequestProxy WebRequestProxy { get; set; } private IFileSystemProxy FileSystemProxy { get; set; } private string Folder { get; set; } private string NugetSource { get; set; } private bool AsTool { get; set; } private const string PaketNugetPackageName = "Paket"; private const string PaketBootstrapperNugetPackageName = "Paket.Bootstrapper"; public NugetDownloadStrategy(IWebRequestProxy webRequestProxy, IFileSystemProxy fileSystemProxy, string folder, string nugetSource, bool asTool = false) { WebRequestProxy = webRequestProxy; FileSystemProxy = fileSystemProxy; Folder = folder; NugetSource = nugetSource; AsTool = asTool; } public override string Name { get { return "Nuget"; } } public override bool CanDownloadHashFile { get { return false; } } protected override string GetLatestVersionCore(bool ignorePrerelease) { IEnumerable<string> allVersions = null; if (FileSystemProxy.DirectoryExists(NugetSource)) { var paketPrefix = "paket."; allVersions = FileSystemProxy. EnumerateFiles(NugetSource, "paket.*.nupkg", SearchOption.TopDirectoryOnly). Select(x => Path.GetFileNameWithoutExtension(x)). // If the specified character isn't a digit, then the file // likely contains the bootstrapper or paket.core Where(x => x.Length > paketPrefix.Length && Char.IsDigit(x[paketPrefix.Length])). Select(x => x.Substring(paketPrefix.Length)); } else { var apiHelper = new NugetApiHelper(PaketNugetPackageName, NugetSource); var versionRequestUrl = apiHelper.GetAllPackageVersions(!ignorePrerelease); var versions = WebRequestProxy.DownloadString(versionRequestUrl); allVersions = versions. Trim('[', ']'). Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries). Select(x => x.Trim('"')); } var latestVersion = allVersions. Select(SemVer.Create). Where(x => !ignorePrerelease || (x.PreRelease == null)). OrderBy(x => x). LastOrDefault(x => !String.IsNullOrWhiteSpace(x.Original)); return latestVersion != null ? latestVersion.Original : String.Empty; } protected override void DownloadVersionCore(string latestVersion, string target, PaketHashFile hashfile) { var apiHelper = new NugetApiHelper(PaketNugetPackageName, NugetSource); const string paketNupkgFile = "paket.latest.nupkg"; const string paketNupkgFileTemplate = "paket.{0}.nupkg"; var paketDownloadUrl = apiHelper.GetLatestPackage(); var paketFile = paketNupkgFile; if (!String.IsNullOrWhiteSpace(latestVersion)) { paketDownloadUrl = apiHelper.GetSpecificPackageVersion(latestVersion); paketFile = String.Format(paketNupkgFileTemplate, latestVersion); } var randomFullPath = Path.Combine(Folder, Path.GetRandomFileName()); FileSystemProxy.CreateDirectory(randomFullPath); var paketPackageFile = Path.Combine(randomFullPath, paketFile); if (FileSystemProxy.DirectoryExists(NugetSource)) { if (String.IsNullOrWhiteSpace(latestVersion)) latestVersion = GetLatestVersion(false); var sourcePath = Path.Combine(NugetSource, String.Format(paketNupkgFileTemplate, latestVersion)); ConsoleImpl.WriteInfo("Starting download from {0}", sourcePath); FileSystemProxy.CopyFile(sourcePath, paketPackageFile); } else { ConsoleImpl.WriteInfo("Starting download from {0}", paketDownloadUrl); try { WebRequestProxy.DownloadFile(paketDownloadUrl, paketPackageFile); } catch (WebException webException) { if (webException.Status == WebExceptionStatus.ProtocolError && !string.IsNullOrEmpty(latestVersion)) { var response = (HttpWebResponse) webException.Response; if (response.StatusCode == HttpStatusCode.NotFound) { throw new WebException(String.Format("Version {0} wasn't found (404)",latestVersion), webException); } if (response.StatusCode == HttpStatusCode.BadRequest) { // For cases like "The package version is not a valid semantic version" throw new WebException(String.Format("Unable to get version '{0}': {1}",latestVersion,response.StatusDescription), webException); } } Console.WriteLine(webException.ToString()); throw; } } if (this.AsTool) { var installAsTool = new InstallKind.InstallAsTool(FileSystemProxy); installAsTool.Run(randomFullPath, target, latestVersion); } else { FileSystemProxy.ExtractToDirectory(paketPackageFile, randomFullPath); var paketSourceFile = Path.Combine(randomFullPath, "tools", "paket.exe"); FileSystemProxy.CopyFile(paketSourceFile, target, true); } FileSystemProxy.DeleteDirectory(randomFullPath, true); } protected override void SelfUpdateCore(string latestVersion) { string target = Assembly.GetExecutingAssembly().Location; var localVersion = FileSystemProxy.GetLocalFileVersion(target); if (localVersion.StartsWith(latestVersion)) { ConsoleImpl.WriteInfo("Bootstrapper is up to date. Nothing to do."); return; } var apiHelper = new NugetApiHelper(PaketBootstrapperNugetPackageName, NugetSource); const string paketNupkgFile = "paket.bootstrapper.latest.nupkg"; const string paketNupkgFileTemplate = "paket.bootstrapper.{0}.nupkg"; var getLatestFromNugetUrl = apiHelper.GetLatestPackage(); var paketDownloadUrl = getLatestFromNugetUrl; var paketFile = paketNupkgFile; if (!String.IsNullOrWhiteSpace(latestVersion)) { paketDownloadUrl = apiHelper.GetSpecificPackageVersion(latestVersion); paketFile = String.Format(paketNupkgFileTemplate, latestVersion); } var randomFullPath = Path.Combine(Folder, Path.GetRandomFileName()); FileSystemProxy.CreateDirectory(randomFullPath); var paketPackageFile = Path.Combine(randomFullPath, paketFile); if (FileSystemProxy.DirectoryExists(NugetSource)) { if (String.IsNullOrWhiteSpace(latestVersion)) latestVersion = GetLatestVersion(false); var sourcePath = Path.Combine(NugetSource, String.Format(paketNupkgFileTemplate, latestVersion)); ConsoleImpl.WriteInfo("Starting download from {0}", sourcePath); FileSystemProxy.CopyFile(sourcePath, paketPackageFile); } else { ConsoleImpl.WriteInfo("Starting download from {0}", paketDownloadUrl); WebRequestProxy.DownloadFile(paketDownloadUrl, paketPackageFile); } FileSystemProxy.ExtractToDirectory(paketPackageFile, randomFullPath); var paketSourceFile = Path.Combine(randomFullPath, "tools", "paket.bootstrapper.exe"); var renamedPath = BootstrapperHelper.GetTempFile("oldBootstrapper"); try { FileSystemProxy.MoveFile(target, renamedPath); FileSystemProxy.MoveFile(paketSourceFile, target); ConsoleImpl.WriteInfo("Self update of bootstrapper was successful."); } catch (Exception) { ConsoleImpl.WriteInfo("Self update failed. Resetting bootstrapper."); FileSystemProxy.MoveFile(renamedPath, target); throw; } FileSystemProxy.DeleteDirectory(randomFullPath, true); } protected override PaketHashFile DownloadHashFileCore(string latestVersion) { // TODO: implement get hash file return null; } } }
using System; using System.Text; using MonoBrick; using System.Collections.Generic; namespace MonoBrick.EV3 { /// <summary> /// Encoded Parameter format /// </summary> [Flags] public enum ParameterFormat : byte { #pragma warning disable Short = 0x00, Long = 0x80 #pragma warning restore } /// <summary> /// Encoded Parameter type /// </summary> [Flags] public enum ParameterType : byte { #pragma warning disable Constant = 0x00, Variable = 0x40 #pragma warning restore } /// <summary> /// Encoded Parameter sign when using short constant format /// </summary> [Flags] enum ShortSign : byte { #pragma warning disable Positive = 0x00, Negative = 0x20 #pragma warning restore } /// <summary> /// Encoded Parameter type when using long constant format /// </summary> [Flags] public enum ConstantParameterType : byte { #pragma warning disable Value = 0x00, Label = 0x20 #pragma warning restore } /// <summary> /// Encoded Parameter scope when using long variable format /// </summary> [Flags] public enum VariableScope : byte { #pragma warning disable Local = 0x00, Global = 0x20, #pragma warning restore } /// <summary> /// Encoded Parameter type when using long variable format /// </summary> [Flags] public enum VariableType : byte { #pragma warning disable Value = 0x00, Handle = 0x10 #pragma warning restore } /// <summary> /// Encoded Parameter following when using long format /// </summary> [Flags] enum FollowType : byte { #pragma warning disable OneByte = 0x01, TwoBytes = 0x02, FourBytes = 0x03, TerminatedString = 0x00, TerminatedString2 = 0x04 #pragma warning restore } /// <summary> /// Program slots used by the EV3 /// </summary> public enum ProgramSlots{ /// <summary> /// Program slot reserved for executing the user interface /// </summary> Gui = 0, /// <summary> /// Program slot used to execute user projects, apps and tools /// </summary> User = 1, /// <summary> /// Program slot used for direct commands coming from c_com /// </summary> Cmd = 2, /// <summary> /// Program slot used for direct commands coming from c_ui /// </summary> Term = 3, /// <summary> /// Program slot used to run the debug ui /// </summary> Debug = 4, /// <summary> /// ONLY VALID IN opPROGRAM_STOP /// </summary> Current = -1 } /// <summary> /// The daisychain layer /// </summary> public enum DaisyChainLayer{ /// <summary> /// The EV3 /// </summary> EV3 = 0, /// <summary> /// First EV3 in the Daisychain /// </summary> First = 1, /// <summary> /// Second EV3 in the Daisychain /// </summary> Second = 2, /// <summary> /// Third EV3 in the Daisychain /// </summary> Third = 3, } /// <summary> /// EV3 command type. /// </summary> public enum CommandType{ /// <summary> /// Direct command /// </summary> DirectCommand = 0x00, /// <summary> /// System command. /// </summary> SystemCommand = 0x01, /// <summary> /// Direct command reply. /// </summary> DirectReply = 0x02, /// <summary> /// System command reply. /// </summary> SystemReply = 0x03, /// <summary> /// Direct reply with error. /// </summary> DirectReplyWithError = 0x04, /// <summary> /// System reply with error. /// </summary> SystemReplyWithError = 0x05 } /// <summary> /// EV3 system commands /// </summary> public enum SystemCommand { #pragma warning disable None = 0x00, BeginDownload = 0x92, ContinueDownload = 0x93, BeginUpload = 0x94, ContinueUpload = 0x95, BeginGetFile = 0x96, ContinueGetFile = 0x97, CloseFileHandle = 0x98, ListFiles = 0x99, ContinueListFiles = 0x9a, CreateDir = 0x9b, DeleteFile = 0x9c, ListOpenHandles = 0x9d, WriteMailbox = 0x9e, BluetoothPin = 0x9f, EnterFirmwareUpdate = 0xa0 #pragma warning restore } /// <summary> /// EV3 byte codes /// </summary> public enum ByteCodes{ #pragma warning disable //VM ProgramStop = 0x02, ProgramStart = 0x03, //Move InitBytes = 0x2F, //VM Info = 0x7C, String = 0x7D, MemoryWrite = 0x7E, MemoryRead = 0x7F, //Sound Sound = 0x94, SoundTest = 095, SoundReady = 0x96, //Input InputSample = 0x97, InputDeviceList = 0x98, InputDevice = 0x99, InputRead = 0x9a, InputTest = 0x9b, InputReady = 0x9c, InputReadSI = 0x9d, InputReadExt = 0x9e, InputWrite = 0x9f, //output OutputGetType = 0xa0, OutputSetType = 0xa1, OutputReset = 0xa2, OutputStop = 0xA3, OutputPower = 0xA4, OutputSpeed = 0xA5, OutputStart = 0xA6, OutputPolarity = 0xA7, OutputRead = 0xA8, OutputTest = 0xA9, OutputReady = 0xAA, OutputPosition = 0xAB, OutputStepPower = 0xAC, OutputTimePower = 0xAD, OutputStepSpeed = 0xAE, OutputTimeSpeed = 0xAF, OutputStepSync = 0xB0, OutputTimeSync = 0xB1, OutputClrCount = 0xB2, OutputGetCount = 0xB3, //Memory File = 0xC0, Array = 0xc1, ArrayWrite = 0xc2, ArrayRead = 0xc3, ArrayAppend = 0xc4, MemoryUsage = 0xc5, FileName = 0xc6, //Mailbox MailboxOpen = 0xD8, MailboxWrite = 0xD9, MailboxRead = 0xDA, MailboxTest = 0xDB, MailboxReady = 0xDC, MailboxClose = 0xDD, #pragma warning restore } /// <summary> /// EV3 sound sub codes /// </summary> public enum SoundSubCodes{ #pragma warning disable Break = 0, Tone = 1, Play = 2, Repeat = 3, Service = 4 #pragma warning restore } /// <summary> /// EV3 input sub codes. /// </summary> public enum InputSubCodes{ #pragma warning disable GetFormat = 2, CalMinMax = 3, CalDefault = 4, GetTypeMode = 5, GetSymbol = 6, CalMin = 7, CalMax = 8, Setup = 9, ClearAll = 10, GetRaw = 11, GetConnection = 12, StopAll = 13, GetName = 21, GetModeName = 22, SetRaw = 23, GetFigures = 24, GetChanges = 25, ClrChanges = 26, ReadyPCT = 27, ReadyRaw = 28, ReadySI = 29, GetMinMax = 30, GetBumps = 31 #pragma warning disable } /// <summary> /// EV3 file sub codes. /// </summary> public enum FileSubCodes{ #pragma warning disable OpenAppend = 0, OpenRead = 1, OpenWrite = 2, ReadValue = 3, WriteValue = 4, ReadText = 5, WriteText = 6, Close = 7, LoadImage = 8, GetHandle = 9, LoadPicture = 10, GetPool = 11, Unload = 12, GetFolders = 13, GetIcon = 14, GetSubfolderName = 15, WriteLog = 16, CLoseLog = 17, GetImage = 18, GetItem = 19, GetCacheFiles = 20, PutCacheFile = 21, GetCacheFile = 22, DelCacheFile = 23, DelSubfolder = 24, GetLogName = 25, GetCacheName = 26, OpenLog = 27, ReadBytes = 28, WriteBytes = 29, Remove = 30, Move = 31, #pragma warning restore } /// <summary> /// Memory sub codes /// </summary> public enum MemorySubCodes{ #pragma warning disable Delete = 0, Create8 = 1, Create16 = 2, Create32 = 3, CreateTEF = 4, Resize = 5, Fill = 6, Copy = 7, Init8 = 8, Init16 = 9, Init32 = 10, InitF = 11, Size = 12, #pragma warning restore } /// <summary> /// Class for creating a EV3 system command. /// </summary> public class Command: BrickCommand{ private SystemCommand systemCommand; private CommandType commandType; private UInt16 sequenceNumber; /// <summary> /// The short value maximum size /// </summary> public const sbyte ShortValueMax = 31; /// <summary> /// The short value minimum size /// </summary> public const sbyte ShortValueMin = -32; /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.Command"/> class. /// </summary> /// <param name="data">Data.</param> public Command(byte [] data){ if(data.Length < 4){ throw new System.ArgumentException("Invalid EV3 Command"); } for(int i = 0; i < data.Length; i++){ dataArr.Add(data[i]); } this.sequenceNumber = (UInt16)(0x0000 | dataArr[0] | (dataArr[1] << 2)); try{ commandType = (CommandType) (data[2] & 0x7f); if(commandType == CommandType.SystemCommand){ systemCommand = (SystemCommand) data[3]; } else{ systemCommand = SystemCommand.None; } } catch(BrickException){ throw new System.ArgumentException("Invalid EV3 Command"); } replyRequired = !Convert.ToBoolean(data[2]&0x80); } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.Command"/> class as a system command /// </summary> /// <param name="systemCommand">System command.</param> /// <param name="sequenceNumber">Sequence number.</param> /// <param name="reply">If set to <c>true</c> reply will be send from brick</param> public Command(SystemCommand systemCommand, UInt16 sequenceNumber, bool reply) { this.systemCommand = systemCommand; this.commandType = CommandType.SystemCommand; this.sequenceNumber = sequenceNumber; this.Append(sequenceNumber); if (reply){ replyRequired = true; dataArr.Add((byte)commandType); } else{ replyRequired = false; dataArr.Add((byte)((byte) commandType | 0x80)); } dataArr.Add((byte)systemCommand); } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.Command"/> class as a direct command /// </summary> /// <param name="byteCode">Bytecode to use for the direct command</param> /// <param name="globalVariables">Global variables.</param> /// <param name="localVariables">Number of global variables</param> /// <param name="sequenceNumber">Number of local variables</param> /// <param name="reply">If set to <c>true</c> reply will be send from the brick</param> public Command(ByteCodes byteCode, int globalVariables, int localVariables, UInt16 sequenceNumber, bool reply): this(globalVariables, localVariables, sequenceNumber, reply){ this.Append(byteCode); } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.Command"/> as a direct command /// </summary> /// <param name="globalVariables">Global bytes.</param> /// <param name="localVariables">Number of global variables</param> /// <param name="sequenceNumber">Number of local variables</param> /// <param name="reply">If set to <c>true</c> reply will be send from brick</param> public Command(int globalVariables, int localVariables, UInt16 sequenceNumber, bool reply) { this.systemCommand = SystemCommand.None; this.commandType = CommandType.DirectCommand; this.sequenceNumber = sequenceNumber; this.Append(sequenceNumber); if (reply){ replyRequired = true; dataArr.Add((byte)commandType); } else{ replyRequired = false; dataArr.Add((byte)((byte) commandType | 0x80)); } byte firstByte = (byte)(globalVariables & 0xFF); byte secondByte = (byte)((localVariables << 2) | (globalVariables >> 8)); this.Append(firstByte); this.Append(secondByte); } /// <summary> /// Gets the EV3 system command. /// </summary> /// <value>The system command.</value> public SystemCommand SystemCommandType{ get{return systemCommand;} } /// <summary> /// Gets the EV3 command type /// </summary> /// <value>The type of the command.</value> public CommandType CommandType { get{return commandType;} } /// <summary> /// Gets the sequence number /// </summary> /// <value>The sequence number.</value> public UInt16 SequenceNumber { get{return sequenceNumber;} } /// <summary> /// Append a sensor type value /// </summary> /// <param name="type">Sensor type to append</param> public void Append (SensorType type) { Append((byte) type, ParameterFormat.Short); } /// <summary> /// Append a sensor mode value /// </summary> /// <param name="mode">Sensor mode to append</param> public void Append (SensorMode mode) { Append((byte) mode, ParameterFormat.Short); } /// <summary> /// Append a byte code value /// </summary> /// <param name="byteCode">Byte code to append</param> public void Append(ByteCodes byteCode){ Append((byte) byteCode); } /// <summary> /// Append a file sub code /// </summary> /// <param name="code">Code to append.</param> public void Append(FileSubCodes code){ Append((sbyte) code, ParameterFormat.Short); } /// <summary> /// Append a file sub code /// </summary> /// <param name="code">Code to append.</param> public void Append(SoundSubCodes code){ Append((sbyte) code, ParameterFormat.Short); } /// <summary> /// Append a daisy chain layer /// </summary> /// <param name="chain">Daisy chain layer to append</param> public void Append(DaisyChainLayer chain){ Append((sbyte) chain, ParameterFormat.Short); } /// <summary> /// Append a input sub code /// </summary> /// <param name="subCode">Sub code to append</param> public void Append (InputSubCodes subCode) { Append((sbyte) subCode, ParameterFormat.Short); } /// <summary> /// Append a memory sub code /// </summary> /// <param name="subCode">Sub code to append</param> public void Append (MemorySubCodes subCode) { Append((sbyte) subCode, ParameterFormat.Short); } /// <summary> /// Append a sensor port /// </summary> /// <param name="port">Sensor port to append</param> public void Append (SensorPort port) { Append((sbyte) port, ParameterFormat.Short); } /// <summary> /// Append a motor port /// </summary> /// <param name="port">Motor port to append</param> public void Append(MotorPort port){ Append((sbyte) port, ParameterFormat.Short); } /// <summary> /// Append a output bit field /// </summary> /// <param name="bitField">Bit field to append</param> public void Append (OutputBitfield bitField) { Append((sbyte) bitField, ParameterFormat.Short); } /// <summary> /// Append a constant parameter encoded byte in either short or long format. Note that if format is long parameter constant type will be a value /// </summary> /// <param name="value">Value to append</param> /// <param name="format">Use either short or long format</param> public void Append (byte value, ParameterFormat format) { if(format == ParameterFormat.Short){ if(value > (byte) ShortValueMax){ value = (byte) ShortValueMax; } byte b = (byte)((byte)format | (byte) ParameterType.Constant | (byte)(value & ((byte)0x1f)) | (byte)ShortSign.Positive); Append (b); } else{ byte b = (byte)((byte)format | (byte) ParameterType.Constant | (byte) ConstantParameterType.Value | (byte)FollowType.OneByte); Append (b); Append (value); } } /// <summary> /// Append a constant parameter encoded byte in either short or long format. Note that if format is long parameter constant type will be a value /// </summary> /// <param name="value">Value to append</param> /// <param name="format">Use either short or long format</param> public void Append(sbyte value, ParameterFormat format) { if(format == ParameterFormat.Short){ byte b = 0x00; if(value <0 ){ if(value < ShortValueMin){ value = ShortValueMin; } b = (byte)((byte)format | (byte) ParameterType.Constant | (byte)(value & ((byte)0x1f))); b = (byte)((byte)ShortSign.Negative | b); } else{ if(value > ShortValueMax){ value = ShortValueMax; } b = (byte)((byte)format | (byte) ParameterType.Constant | (byte)(value & ((byte)0x1f))); b = (byte)((byte)ShortSign.Positive | b); } Append (b); } else{ byte b = (byte)((byte)format | (byte) ParameterType.Constant | (byte) ConstantParameterType.Value | (byte)FollowType.OneByte); Append (b); Append (value); } } /// <summary> /// Append a constant parameter encoded /// </summary> /// <param name="value">byte to append</param> /// <param name="type">User either value or lable type</param> public void Append(sbyte value, ConstantParameterType type) { Append(type, FollowType.OneByte); Append (value); } /// <summary> /// Append a constant parameter encoded /// </summary> /// <param name="value">byte to append</param> /// <param name="type">User either value or lable type</param> public void Append(byte value, ConstantParameterType type) { Append(type, FollowType.OneByte); Append (value); } /// <summary> /// Append a constant parameter encoded /// </summary> /// <param name="value">Int16 to append</param> /// <param name="type">User either value or lable type</param> public void Append(Int16 value , ConstantParameterType type){ Append(type, FollowType.TwoBytes); Append (value); } /// <summary> /// Append a constant parameter encoded /// </summary> /// <param name="value">Int32 to append</param> /// <param name="type">User either value or lable type</param> public void Append(Int32 value, ConstantParameterType type){ Append(type, FollowType.FourBytes); Append(value); } /// <summary> /// Append a constant parameter encoded /// </summary> /// <param name="value">UInt32 to append</param> /// <param name="type">User either value or lable type</param> public void Append(UInt32 value, ConstantParameterType type){ Append(type, FollowType.FourBytes); Append(value); } /// <summary> /// Append a constant parameter encoded /// </summary> /// <param name="value">Float to append</param> /// <param name="type">User either value or lable type</param> public void Append(float value, ConstantParameterType type){ Append(type, FollowType.FourBytes); Append(value); } /// <summary> /// Append a constant parameter encoded /// </summary> /// <param name="s">String to append</param> /// <param name="type">User either value or lable type</param> public void Append(string s, ConstantParameterType type){ Append(type, FollowType.TerminatedString2); Append (s); } /// <summary> /// Append a variable parameter encoded byte in short format /// </summary> /// <param name="value">Value to append</param> /// <param name="scope">Select either global or local scope</param> public void Append(byte value, VariableScope scope) { byte b = (byte)((byte)ParameterFormat.Short| (byte) ParameterType.Variable | (byte) scope | (byte)(value & ((byte)0x1f))); Append (b); } private void Append(VariableScope scopeType, VariableType variableType, FollowType followType){ byte b = (byte)((byte)ParameterFormat.Long| (byte) ParameterType.Variable | (byte) scopeType | (byte)variableType | (byte)followType); Append (b); } /// <summary> /// Append a variable parameter encoded byte in long format /// </summary> /// <param name="value">Value to append</param> /// <param name="scope">Select either global or local scope</param> /// <param name="type">Select either value or handle scope</param> public void Append (byte value, VariableScope scope, VariableType type) { Append(scope, type, FollowType.OneByte); Append (value); } /// <summary> /// Append a variable parameter encoded Int16 /// </summary> /// <param name="value">Value to append</param> /// <param name="scope">Select either global or local scope</param> /// <param name="type">Select either value or handle scope</param> public void Append(Int16 value , VariableScope scope, VariableType type){ Append(scope, type, FollowType.TwoBytes); Append (value); } /// <summary> /// Append a variable parameter encoded Int32 /// </summary> /// <param name="value">Value to append</param> /// <param name="scope">Select either global or local scope</param> /// <param name="type">Select either value or handle scope</param> public void Append(Int32 value, VariableScope scope, VariableType type){ Append(scope, type, FollowType.FourBytes); Append(value); } /// <summary> /// Append a variable parameter encoded string /// </summary> /// <param name="s">String to append</param> /// <param name="scope">Select either global or local scope</param> /// <param name="type">Select either value or handle scope</param> public void Append(string s, VariableScope scope, VariableType type){ Append(scope, type, FollowType.TerminatedString2); Append (s); } /// <summary> /// Append the specified longType and followType. /// </summary> /// <param name="longType">Long type.</param> /// <param name="followType">Follow type.</param> private void Append(ConstantParameterType longType, FollowType followType){ byte b = (byte)((byte)ParameterFormat.Long| (byte) ParameterType.Constant | (byte) longType | (byte)followType); Append (b); } internal void Print(){ byte[] arr = Data; for(int i = 0; i < Length; i++){ Console.WriteLine("Command["+i+"]: " + arr[i].ToString("X")); } } } /// <summary> /// Class for creating a EV3 reply /// </summary> public class Reply: BrickReply { /// <summary> /// Gets a value indicating whether this instance has error. /// </summary> /// <value> /// <c>true</c> if this instance has error; otherwise, <c>false</c>. /// </value> public bool HasError{ get{ CommandType type = (CommandType)dataArray[2]; if(type == CommandType.DirectReply || type == CommandType.SystemReply){ return false; } return true; } } /// <summary> /// Gets the type of error. /// </summary> /// <value> /// The type of error /// </value> internal ErrorType ErrorType{ get{ return Error.ToErrorType(ErrorCode); } } /// <summary> /// Gets the error code. /// </summary> /// <value> /// The error code /// </value> public byte ErrorCode { get { if (HasError) { if(CommandType == CommandType.SystemReplyWithError){ if(dataArray.Length >=5){ byte error = dataArray[4]; if(Enum.IsDefined(typeof(EV3.BrickError),(int) error)){ return error; } } } return (byte)BrickError.UnknownError; } return 0;//no error } } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.Reply"/> class. /// </summary> public Reply () { } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.Reply"/> class. /// </summary> /// <param name='data'> /// The byte array to be used for the reply /// </param> public Reply(byte[] data){ dataArray = data; if(data.Length < 4){ throw new System.ArgumentException("Invalid EV3 Reply"); } if(!Enum.IsDefined(typeof (CommandType),data[2])){ throw new System.ArgumentException("Invalid EV3 Reply"); } CommandType type = (CommandType)data[2]; if(type == CommandType.SystemReply){ if(!Enum.IsDefined(typeof(SystemCommand),data[3])){ throw new System.ArgumentException("Invalid EV3 Reply"); } } if( type == CommandType.SystemCommand || type == CommandType.SystemCommand){ throw new System.ArgumentException("Invalid EV3 Reply"); } } /// <summary> /// Gets the EV3 system command. /// </summary> /// <value>The system command.</value> public SystemCommand SystemCommandType{ get{ if(CommandType == CommandType.SystemReply){ return (SystemCommand) dataArray[3]; } return SystemCommand.None; } } /// <summary> /// Gets the EV3 command type /// </summary> /// <value>The type of the command.</value> public CommandType CommandType { get{return (CommandType) dataArray[2];} } /// <summary> /// Gets the sequence number. /// </summary> /// <value>The sequence number.</value> public UInt16 SequenceNumber { get{return (UInt16)(0x0000 | dataArray[0] | (dataArray[1] << 2));} } /// <summary> /// Gets the command byte as string. /// </summary> /// <value> /// The command byte as string /// </value> public string CommandTypeAsString{ get{return BrickCommand.AddSpacesToString(CommandType.ToString()); } } internal void print(){ Console.WriteLine("Command: " + CommandType.ToString()); Console.WriteLine("Length: " + Length); Console.WriteLine("Errorcode: " + ErrorCode); for(int i = 0; i < Length; i++){ Console.WriteLine("Reply["+i+"]: " + dataArray[i].ToString("X")); } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.AutoMapper; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.UI; using Microsoft.AspNetCore.Hosting; using Repairis.Authorization; using Repairis.Authorization.Users; using Repairis.Authorization.Roles; using Repairis.Users.Dto; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Repairis.Configuration; using Repairis.Email; using Repairis.Sms; namespace Repairis.Users { [AbpAuthorize(PermissionNames.Pages_Users)] public class UserAppService : RepairisAppServiceBase, IUserAppService { private readonly IRepository<User, long> _userRepository; private readonly IRepository<CustomerInfo, long> _customerInfoRepository; private readonly IRepository<EmployeeInfo, long> _employeeInfoRepository; private readonly IEmailService _emailService; private readonly ISmsService _smsService; private readonly IPermissionManager _permissionManager; private readonly IPasswordHasher<User> _passwordHasher; private readonly UserRegistrationManager _userRegistrationManager; private readonly CompanySettings _companySettings; public UserAppService( IRepository<User, long> userRepository, IPermissionManager permissionManager, IPasswordHasher<User> passwordHasher, UserRegistrationManager userRegistrationManager, IRepository<CustomerInfo, long> customerInfoRepository, IRepository<EmployeeInfo, long> employeeInfoRepository, IEmailService emailService, ISmsService smsService, CompanySettings companySettings) { _userRepository = userRepository; _permissionManager = permissionManager; _passwordHasher = passwordHasher; _userRegistrationManager = userRegistrationManager; _customerInfoRepository = customerInfoRepository; _employeeInfoRepository = employeeInfoRepository; _emailService = emailService; _smsService = smsService; _companySettings = companySettings; } public async Task ProhibitPermission(ProhibitPermissionInput input) { var user = await UserManager.GetUserByIdAsync(input.UserId); var permission = _permissionManager.GetPermission(input.PermissionName); await UserManager.ProhibitPermissionAsync(user, permission); } //Example for primitive method parameters. public async Task RemoveFromRole(long userId, string roleName) { var user = await UserManager.FindByIdAsync(userId.ToString()); await UserManager.RemoveFromRoleAsync(user, roleName); } public async Task<ListResultDto<UserListDto>> GetUsers() { var users = await _userRepository.GetAllListAsync(); return new ListResultDto<UserListDto>( ObjectMapper.Map<List<UserListDto>>(users) ); } public async Task CreateUser(CreateUserInput input) { var user = ObjectMapper.Map<User>(input); user.TenantId = AbpSession.TenantId; user.Password = _passwordHasher.HashPassword(user, input.Password); user.IsEmailConfirmed = true; await UserManager.CreateAsync(user); } public async Task<ListResultDto<UserListDto>> GetEmployeesAsync() { var users = await _userRepository.GetAllListAsync(x => x.EmployeeInfo != null); return new ListResultDto<UserListDto>( users.MapTo<List<UserListDto>>() ); } public async Task<ListResultDto<CustomerBasicEntityDto>> GetAllActiveCustomersAsync() { var customers = await _userRepository.GetAllListAsync(x => x.IsActive && x.CustomerInfoId != null); return new ListResultDto<CustomerBasicEntityDto>( customers.MapTo<List<CustomerBasicEntityDto>>() ); } public async Task<CustomerInfo> GetOrCreateCustomerAsync(CustomerInput input) { var user = await _userRepository.GetAllIncluding(x => x.CustomerInfo).Where( x => x.Name.ToUpper() == input.Name.ToUpper() && x.Surname.ToUpper() == input.Surname.ToUpper() && (x.EmailAddress.ToUpper() == input.EmailAddress.ToUpper() ||x.PhoneNumber == input.PhoneNumber)).FirstOrDefaultAsync(); if (user == null) { return await CreateCustomerAsync(input); } if (user.CustomerInfo == null) { var customerInfo = await _customerInfoRepository.InsertAsync(new CustomerInfo { CustomerUserId = user.Id, CustomerType = input.CustomerType, AdditionalInfo = input.AdditionalInfo }); user.CustomerInfoId = customerInfo.Id; await _userRepository.UpdateAsync(user); } return user.CustomerInfo; } public async Task<CustomerFullEntityDto> GetCustomerDtoAsync(long id) { var customer = await _userRepository.GetAsync(id); if (customer?.CustomerInfo == null) { throw new UserFriendlyException(L("CustomerNotFound")); } return customer.MapTo<CustomerFullEntityDto>(); } [UnitOfWork] public async Task DeleteCustomerAsync(long id) { var customer = await _customerInfoRepository.GetAllIncluding(x => x.CustomerUser).FirstOrDefaultAsync(x => x.Id == id); if (customer == null) { throw new UserFriendlyException(L("CustomerNotFound")); } customer.CustomerUser.CustomerInfoId = null; await CurrentUnitOfWork.SaveChangesAsync(); await _userRepository.DeleteAsync(customer.CustomerUserId); await _customerInfoRepository.DeleteAsync(customer.Id); } public async Task<CustomerInfo> CreateCustomerAsync(CustomerInput input) { string password = User.CreateRandomPassword(); string login = input.EmailAddress; if (string.IsNullOrEmpty(login)) { login = input.PhoneNumber; } var user = await _userRegistrationManager.RegisterUserAsync(StaticRoleNames.Tenants.Customer, input.Name, input.Surname, input.FatherName, input.PhoneNumber, input.SecondaryPhoneNumber, input.Address, input.EmailAddress, login, password, false); var customerInfo = await _customerInfoRepository.InsertAsync(new CustomerInfo { CustomerUserId = user.Id, CustomerType = input.CustomerType, AdditionalInfo = input.AdditionalInfo }); user.CustomerInfoId = customerInfo.Id; await _userRepository.UpdateAsync(user); string companyName = _companySettings.CompanyName; if (input.EmailAddress != null) { string subject = $"{companyName} {L("NewUserWasCreated")}"; string message = $"{L("WelcomeTo")} {companyName}!\n" + $"{L("YourLogin")}: {login}\n" + $"{L("YourPassword")}: {password}"; await _emailService.SendEmailAsync(input.EmailAddress, subject, message); } if (input.PhoneNumber != null) { string message = $"{companyName} {L("YourLogin")}: {login} {L("YourPassword")}: {password}"; await _smsService.SendSmsAsync(input.PhoneNumber, message); } return customerInfo; } public async Task<ListResultDto<EmployeeBasicEntityDto>> GetAllActiveEmployeesAsync() { var employees = await _userRepository.GetAllListAsync(x => x.IsActive && x.EmployeeInfo != null); return new ListResultDto<EmployeeBasicEntityDto>( employees.MapTo<List<EmployeeBasicEntityDto>>() ); } public async Task<EmployeeFullEntityDto> GetEmployeeDtoAsync(long id) { var employee = await _userRepository.GetAsync(id); if (employee?.EmployeeInfo == null) { throw new UserFriendlyException(L("EmployeeNotFound")); } return employee.MapTo<EmployeeFullEntityDto>(); } public async Task DeleteEmployeeAsync(long id) { var employee = await _employeeInfoRepository.GetAllIncluding(x => x.EmployeeUser).FirstOrDefaultAsync(x => x.Id == id); if (employee == null) { throw new UserFriendlyException(L("EmployeeNotFound")); } employee.EmployeeUser.EmployeeInfoId = null; await CurrentUnitOfWork.SaveChangesAsync(); await _userRepository.DeleteAsync(employee.EmployeeUserId); await _employeeInfoRepository.DeleteAsync(employee.Id); } public async Task<EmployeeInfo> CreateEmployeeAsync(EmployeeInput input) { string login = input.EmailAddress; if (string.IsNullOrEmpty(login)) { login = input.PhoneNumber; } var user = await _userRegistrationManager.RegisterUserAsync(StaticRoleNames.Tenants.Employee, input.Name, input.Surname, input.FatherName, input.PhoneNumber, input.SecondaryPhoneNumber, input.Address, input.EmailAddress, input.PhoneNumber, input.Password, false); var employeeInfo = await _employeeInfoRepository.InsertAsync(new EmployeeInfo { EmployeeUserId = user.Id, SalaryIsFlat = input.SalaryIsFlat, SalaryValue = input.SalaryValue }); user.EmployeeInfoId = employeeInfo.Id; await _userRepository.UpdateAsync(user); string companyName = _companySettings.CompanyName; if (input.EmailAddress != null) { string subject = $"{companyName} {L("NewUserWasCreated")}"; string message = $"{L("WelcomeTo")} {companyName}!\n" + $"{L("YourLogin")}: {login}\n" + $"{L("YourPassword")}: {input.Password}"; await _emailService.SendEmailAsync(input.EmailAddress, subject, message); } if (input.PhoneNumber != null) { string message = $"{companyName} {L("YourLogin")}: {login} {L("YourPassword")}: {input.Password}"; await _smsService.SendSmsAsync(input.PhoneNumber, message); } return employeeInfo; } } }
using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Subjects; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.LogicalTree; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests { public class CarouselTests { [Fact] public void First_Item_Should_Be_Selected_By_Default() { var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = new[] { "Foo", "Bar" } }; target.ApplyTemplate(); Assert.Equal(0, target.SelectedIndex); Assert.Equal("Foo", target.SelectedItem); } [Fact] public void LogicalChild_Should_Be_Selected_Item() { var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = new[] { "Foo", "Bar" } }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Single(target.GetLogicalChildren()); var child = GetContainerTextBlock(target.GetLogicalChildren().Single()); Assert.Equal("Foo", child.Text); } [Fact] public void Should_Remove_NonCurrent_Page_When_IsVirtualized_True() { var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = new[] { "foo", "bar" }, IsVirtualized = true, SelectedIndex = 0, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Single(target.ItemContainerGenerator.Containers); target.SelectedIndex = 1; Assert.Single(target.ItemContainerGenerator.Containers); } [Fact] public void Selected_Item_Changes_To_First_Item_When_Items_Property_Changes() { var items = new ObservableCollection<string> { "Foo", "Bar", "FooBar" }; var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = items, IsVirtualized = false }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(3, target.GetLogicalChildren().Count()); var child = GetContainerTextBlock(target.GetLogicalChildren().First()); Assert.Equal("Foo", child.Text); var newItems = items.ToList(); newItems.RemoveAt(0); target.Items = newItems; child = GetContainerTextBlock(target.GetLogicalChildren().First()); Assert.Equal("Bar", child.Text); } [Fact] public void Selected_Item_Changes_To_First_Item_When_Items_Property_Changes_And_Virtualized() { var items = new ObservableCollection<string> { "Foo", "Bar", "FooBar" }; var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = items, IsVirtualized = true, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Single(target.GetLogicalChildren()); var child = GetContainerTextBlock(target.GetLogicalChildren().Single()); Assert.Equal("Foo", child.Text); var newItems = items.ToList(); newItems.RemoveAt(0); target.Items = newItems; child = GetContainerTextBlock(target.GetLogicalChildren().Single()); Assert.Equal("Bar", child.Text); } [Fact] public void Selected_Item_Changes_To_First_Item_When_Item_Added() { var items = new ObservableCollection<string>(); var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = items, IsVirtualized = false }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(-1, target.SelectedIndex); Assert.Empty(target.GetLogicalChildren()); items.Add("Foo"); Assert.Equal(0, target.SelectedIndex); Assert.Single(target.GetLogicalChildren()); } [Fact] public void Selected_Index_Changes_To_None_When_Items_Assigned_Null() { var items = new ObservableCollection<string> { "Foo", "Bar", "FooBar" }; var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = items, IsVirtualized = false }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(3, target.GetLogicalChildren().Count()); var child = GetContainerTextBlock(target.GetLogicalChildren().First()); Assert.Equal("Foo", child.Text); target.Items = null; var numChildren = target.GetLogicalChildren().Count(); Assert.Equal(0, numChildren); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Selected_Index_Is_Maintained_Carousel_Created_With_Non_Zero_SelectedIndex() { var items = new ObservableCollection<string> { "Foo", "Bar", "FooBar" }; var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = items, IsVirtualized = false, SelectedIndex = 2 }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal("FooBar", target.SelectedItem); var child = GetContainerTextBlock(target.GetVisualDescendants().LastOrDefault()); Assert.IsType<TextBlock>(child); Assert.Equal("FooBar", ((TextBlock)child).Text); } [Fact] public void Selected_Item_Changes_To_Next_First_Item_When_Item_Removed_From_Beggining_Of_List() { var items = new ObservableCollection<string> { "Foo", "Bar", "FooBar" }; var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = items, IsVirtualized = false }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(3, target.GetLogicalChildren().Count()); var child = GetContainerTextBlock(target.GetLogicalChildren().First()); Assert.Equal("Foo", child.Text); items.RemoveAt(0); child = GetContainerTextBlock(target.GetLogicalChildren().First()); Assert.IsType<TextBlock>(child); Assert.Equal("Bar", ((TextBlock)child).Text); } [Fact] public void Selected_Item_Changes_To_First_Item_If_SelectedItem_Is_Removed_From_Middle() { var items = new ObservableCollection<string> { "Foo", "Bar", "FooBar" }; var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), Items = items, IsVirtualized = false }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedIndex = 1; items.RemoveAt(1); Assert.Equal(0, target.SelectedIndex); Assert.Equal("Foo", target.SelectedItem); } private Control CreateTemplate(Carousel control, INameScope scope) { return new CarouselPresenter { Name = "PART_ItemsPresenter", [~CarouselPresenter.IsVirtualizedProperty] = control[~Carousel.IsVirtualizedProperty], [~CarouselPresenter.ItemsProperty] = control[~Carousel.ItemsProperty], [~CarouselPresenter.ItemsPanelProperty] = control[~Carousel.ItemsPanelProperty], [~CarouselPresenter.SelectedIndexProperty] = control[~Carousel.SelectedIndexProperty], [~CarouselPresenter.PageTransitionProperty] = control[~Carousel.PageTransitionProperty], }.RegisterInNameScope(scope); } private static TextBlock GetContainerTextBlock(object control) { var contentPresenter = Assert.IsType<ContentPresenter>(control); contentPresenter.UpdateChild(); return Assert.IsType<TextBlock>(contentPresenter.Child); } [Fact] public void SelectedItem_Validation() { using (UnitTestApplication.Start(TestServices.MockThreadingInterface)) { var target = new Carousel { Template = new FuncControlTemplate<Carousel>(CreateTemplate), IsVirtualized = false }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var exception = new System.InvalidCastException("failed validation"); var textObservable = new BehaviorSubject<BindingNotification>(new BindingNotification(exception, BindingErrorType.DataValidationError)); target.Bind(ComboBox.SelectedItemProperty, textObservable); Assert.True(DataValidationErrors.GetHasErrors(target)); Assert.True(DataValidationErrors.GetErrors(target).SequenceEqual(new[] { exception })); } } } }
using System; using System.Reflection; namespace EasyGenerator.Studio.Utils { /// <summary> /// Summary description for Mapper. /// </summary> public class Mapper { public enum Behaviour { FieldsToFields, FieldsToProperties, PropertiesToFields, PropertiesToProperties, PropertiesPropertiesDataEntity }; public Mapper() { } public static void Map( Object from, Object to ) { Map( from, to, true, Behaviour.FieldsToFields ); } public static void Map( Object from, Object to, Behaviour behaviour ) { Map( from, to, true, behaviour ); } public static void Map( Object from, Object to, bool caseSensitive, Behaviour behaviour ) { switch ( behaviour ) { case Behaviour.FieldsToFields: MapFieldsToFields( from, to, caseSensitive ); break; case Behaviour.FieldsToProperties: MapFieldsToProperties( from, to, caseSensitive ); break; case Behaviour.PropertiesToFields: MapPropertiesToFields( from, to, caseSensitive ); break; case Behaviour.PropertiesToProperties: MapPropertiesToProperties( from, to, caseSensitive ); break; case Behaviour.PropertiesPropertiesDataEntity: MapPropertiesToPropertiesDataEntity( from, to, caseSensitive ); break; } } private static void MapFieldsToFields( Object from, Object to, bool caseSensitive ) { FieldInfo toFieldInfo; try { Type fromType = from.GetType(); Type toType = to.GetType(); foreach( FieldInfo fromFieldInfo in fromType.GetFields() ) { if( caseSensitive ) toFieldInfo = toType.GetField( fromFieldInfo.Name ); else toFieldInfo = toType.GetField( fromFieldInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase ); // if field exists, set caption if( toFieldInfo != null ) { if ( fromFieldInfo.FieldType.IsArray ) { toFieldInfo.SetValue( to, fromFieldInfo.GetValue( from ) ); } else { toFieldInfo.SetValue( to, fromFieldInfo.GetValue( from ) ); } } } } catch { throw; } } private static void MapFieldsToProperties( Object from, Object to, bool caseSensitive ) { PropertyInfo toPropertyInfo; try { Type fromType = from.GetType(); Type toType = to.GetType(); foreach( FieldInfo fromFieldInfo in fromType.GetFields() ) { //PropertyInfo toPropertyInfo; if( caseSensitive ) toPropertyInfo = toType.GetProperty( fromFieldInfo.Name ); else toPropertyInfo = toType.GetProperty( fromFieldInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase ); // if field exists, set caption if( toPropertyInfo != null ) { //if ( fromFieldInfo.FieldType.IsArray ) //{ // throw new NotImplementedException(); //} //else { toPropertyInfo.SetValue( to, fromFieldInfo.GetValue( from ), null ); } } } } catch ( Exception ) { throw; } } private static void MapPropertiesToFields( Object from, Object to, bool caseSensitive ) { FieldInfo toFieldInfo; Type fromType = from.GetType(); Type toType = to.GetType(); try { foreach( PropertyInfo fromPropertyInfo in fromType.GetProperties() ) { if( caseSensitive ) toFieldInfo = toType.GetField( fromPropertyInfo.Name ); else toFieldInfo = toType.GetField( fromPropertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase ); // if field exists, set caption if( toFieldInfo != null ) { toFieldInfo.SetValue( to, fromPropertyInfo.GetValue( from, null ) ); } } } catch ( Exception ) { throw; } } private static void MapPropertiesToProperties( Object from, Object to, bool caseSensitive ) { Type fromType = from.GetType(); Type toType = to.GetType(); foreach( PropertyInfo fromPropertyInfo in fromType.GetProperties() ) { PropertyInfo toPropertyInfo; if( caseSensitive ) toPropertyInfo = toType.GetProperty( fromPropertyInfo.Name ); else toPropertyInfo = toType.GetProperty( fromPropertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase ); // if field exists, set caption if( toPropertyInfo != null ) { if (toPropertyInfo.PropertyType != fromPropertyInfo.PropertyType) continue; /*if ( fromPropertyInfo.PropertyType.IsArray ) { throw new NotImplementedException(); } else*/ { if (toPropertyInfo.CanWrite) toPropertyInfo.SetValue( to, fromPropertyInfo.GetValue( from, null ), null ); } } } } private static void MapPropertiesToPropertiesDataEntity( Object from, Object to, bool caseSensitive ) { Type fromType = from.GetType(); Type toType = to.GetType(); foreach( PropertyInfo fromPropertyInfo in fromType.GetProperties() ) { PropertyInfo toPropertyInfo; if( caseSensitive ) toPropertyInfo = toType.GetProperty( fromPropertyInfo.Name ); else toPropertyInfo = toType.GetProperty( fromPropertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase ); // if field exists, set caption if( toPropertyInfo != null ) { if (toPropertyInfo.Name == "ID") continue; if (toPropertyInfo.PropertyType != fromPropertyInfo.PropertyType) continue; if ( fromPropertyInfo.PropertyType.IsArray ) { throw new NotImplementedException(); } else { if (toPropertyInfo.CanWrite) { object val = fromPropertyInfo.GetValue( from, null ); if (val != null) toPropertyInfo.SetValue( to, fromPropertyInfo.GetValue( from, null ), null ); } } } } } } }
/* * 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. */ #pragma warning disable 649 #pragma warning disable 169 namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Test for task and job adapter. /// </summary> public class TaskAdapterTest : AbstractTaskTest { /// <summary> /// Constructor. /// </summary> public TaskAdapterTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected TaskAdapterTest(bool fork) : base(fork) { } /// <summary> /// Test for task adapter. /// </summary> [Test] public void TestTaskAdapter() { Assert.AreEqual(3, Grid1.GetCluster().GetNodes().Count); HashSet<Guid> allNodes = new HashSet<Guid>(); for (int i = 0; i < 20 && allNodes.Count < GetServerCount(); i++) { HashSet<Guid> res = Grid1.GetCompute().Execute(new TestSplitTask(), 1); Assert.AreEqual(1, res.Count); allNodes.UnionWith(res); } Assert.AreEqual(GetServerCount(), allNodes.Count); HashSet<Guid> res2 = Grid1.GetCompute().Execute<int, Guid, HashSet<Guid>>(typeof(TestSplitTask), 3); Assert.IsTrue(res2.Count > 0); Grid1.GetCompute().Execute(new TestSplitTask(), 100); Assert.AreEqual(GetServerCount(), allNodes.Count); } /// <summary> /// Test for job adapter. /// </summary> [Test] public void TestSerializableJobAdapter() { for (int i = 0; i < 10; i++) { bool res = Grid1.GetCompute().Execute(new TestJobAdapterTask(), true); Assert.IsTrue(res); } } /// <summary> /// Test for job adapter. /// </summary> [Test] public void TestBinarizableJobAdapter() { for (int i = 0; i < 10; i++) { bool res = Grid1.GetCompute().Execute(new TestJobAdapterTask(), false); Assert.IsTrue(res); } } /** <inheritDoc /> */ protected override ICollection<Type> GetBinaryTypes() { return new[] { typeof(BinarizableJob) }; } /// <summary> /// Test task. /// </summary> public class TestSplitTask : ComputeTaskSplitAdapter<int, Guid, HashSet<Guid>> { [InstanceResource] private readonly IIgnite _ignite; /** <inheritDoc /> */ override protected ICollection<IComputeJob<Guid>> Split(int gridSize, int arg) { Assert.AreEqual(_ignite.GetCluster().GetNodes().Count(x => !x.IsClient), gridSize); int jobsNum = arg; Assert.IsTrue(jobsNum > 0); var jobs = new List<IComputeJob<Guid>>(jobsNum); for (int i = 0; i < jobsNum; i++) jobs.Add(new NodeIdJob()); return jobs; } /** <inheritDoc /> */ override public HashSet<Guid> Reduce(IList<IComputeJobResult<Guid>> results) { HashSet<Guid> nodes = new HashSet<Guid>(); foreach (var res in results) { Guid id = res.Data; Assert.NotNull(id); nodes.Add(id); } return nodes; } } /// <summary> /// Test task. /// </summary> public class TestJobAdapterTask : ComputeTaskSplitAdapter<bool, bool, bool> { /** <inheritDoc /> */ override protected ICollection<IComputeJob<bool>> Split(int gridSize, bool arg) { bool serializable = arg; ICollection<IComputeJob<bool>> jobs = new List<IComputeJob<bool>>(1); if (serializable) jobs.Add(new SerializableJob(100, "str")); else jobs.Add(new BinarizableJob(100, "str")); return jobs; } /** <inheritDoc /> */ override public bool Reduce(IList<IComputeJobResult<bool>> results) { Assert.AreEqual(1, results.Count); Assert.IsTrue(results[0].Data); return true; } } /// <summary> /// Test job. /// </summary> [Serializable] public class NodeIdJob : IComputeJob<Guid> { [InstanceResource] private IIgnite _grid = null; /** <inheritDoc /> */ public Guid Execute() { Assert.NotNull(_grid); return _grid.GetCluster().GetLocalNode().Id; } /** <inheritDoc /> */ public void Cancel() { // No-op. } } /// <summary> /// Test serializable job. /// </summary> [Serializable] public class SerializableJob : ComputeJobAdapter<bool> { [InstanceResource] private IIgnite _grid = null; public SerializableJob(params object[] args) : base(args) { // No-op. } /** <inheritDoc /> */ override public bool Execute() { Assert.IsFalse(IsCancelled()); Cancel(); Assert.IsTrue(IsCancelled()); Assert.NotNull(_grid); int arg1 = GetArgument<int>(0); Assert.AreEqual(100, arg1); string arg2 = GetArgument<string>(1); Assert.AreEqual("str", arg2); return true; } } /// <summary> /// Test binary job. /// </summary> public class BinarizableJob : ComputeJobAdapter<bool> { [InstanceResource] private IIgnite _grid; public BinarizableJob(params object[] args) : base(args) { // No-op. } /** <inheritDoc /> */ override public bool Execute() { Assert.IsFalse(IsCancelled()); Cancel(); Assert.IsTrue(IsCancelled()); Assert.NotNull(_grid); int arg1 = GetArgument<int>(0); Assert.AreEqual(100, arg1); string arg2 = GetArgument<string>(1); Assert.AreEqual("str", arg2); return true; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the LabMetodoScreening class. /// </summary> [Serializable] public partial class LabMetodoScreeningCollection : ActiveList<LabMetodoScreening, LabMetodoScreeningCollection> { public LabMetodoScreeningCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>LabMetodoScreeningCollection</returns> public LabMetodoScreeningCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { LabMetodoScreening o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the LAB_MetodoScreening table. /// </summary> [Serializable] public partial class LabMetodoScreening : ActiveRecord<LabMetodoScreening>, IActiveRecord { #region .ctors and Default Settings public LabMetodoScreening() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public LabMetodoScreening(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public LabMetodoScreening(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public LabMetodoScreening(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("LAB_MetodoScreening", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMetodoScreening = new TableSchema.TableColumn(schema); colvarIdMetodoScreening.ColumnName = "idMetodoScreening"; colvarIdMetodoScreening.DataType = DbType.Int32; colvarIdMetodoScreening.MaxLength = 0; colvarIdMetodoScreening.AutoIncrement = true; colvarIdMetodoScreening.IsNullable = false; colvarIdMetodoScreening.IsPrimaryKey = true; colvarIdMetodoScreening.IsForeignKey = false; colvarIdMetodoScreening.IsReadOnly = false; colvarIdMetodoScreening.DefaultSetting = @""; colvarIdMetodoScreening.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMetodoScreening); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.String; colvarDescripcion.MaxLength = 500; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarBaja = new TableSchema.TableColumn(schema); colvarBaja.ColumnName = "Baja"; colvarBaja.DataType = DbType.Boolean; colvarBaja.MaxLength = 0; colvarBaja.AutoIncrement = false; colvarBaja.IsNullable = false; colvarBaja.IsPrimaryKey = false; colvarBaja.IsForeignKey = false; colvarBaja.IsReadOnly = false; colvarBaja.DefaultSetting = @"((0))"; colvarBaja.ForeignKeyTableName = ""; schema.Columns.Add(colvarBaja); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("LAB_MetodoScreening",schema); } } #endregion #region Props [XmlAttribute("IdMetodoScreening")] [Bindable(true)] public int IdMetodoScreening { get { return GetColumnValue<int>(Columns.IdMetodoScreening); } set { SetColumnValue(Columns.IdMetodoScreening, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("Baja")] [Bindable(true)] public bool Baja { get { return GetColumnValue<bool>(Columns.Baja); } set { SetColumnValue(Columns.Baja, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.LabItemScreeningCollection colLabItemScreeningRecords; public DalSic.LabItemScreeningCollection LabItemScreeningRecords { get { if(colLabItemScreeningRecords == null) { colLabItemScreeningRecords = new DalSic.LabItemScreeningCollection().Where(LabItemScreening.Columns.IdMetodo, IdMetodoScreening).Load(); colLabItemScreeningRecords.ListChanged += new ListChangedEventHandler(colLabItemScreeningRecords_ListChanged); } return colLabItemScreeningRecords; } set { colLabItemScreeningRecords = value; colLabItemScreeningRecords.ListChanged += new ListChangedEventHandler(colLabItemScreeningRecords_ListChanged); } } void colLabItemScreeningRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colLabItemScreeningRecords[e.NewIndex].IdMetodo = IdMetodoScreening; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varDescripcion,bool varBaja) { LabMetodoScreening item = new LabMetodoScreening(); item.Descripcion = varDescripcion; item.Baja = varBaja; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdMetodoScreening,string varDescripcion,bool varBaja) { LabMetodoScreening item = new LabMetodoScreening(); item.IdMetodoScreening = varIdMetodoScreening; item.Descripcion = varDescripcion; item.Baja = varBaja; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdMetodoScreeningColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn BajaColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdMetodoScreening = @"idMetodoScreening"; public static string Descripcion = @"descripcion"; public static string Baja = @"Baja"; } #endregion #region Update PK Collections public void SetPKValues() { if (colLabItemScreeningRecords != null) { foreach (DalSic.LabItemScreening item in colLabItemScreeningRecords) { if (item.IdMetodo != IdMetodoScreening) { item.IdMetodo = IdMetodoScreening; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colLabItemScreeningRecords != null) { colLabItemScreeningRecords.SaveAll(); } } #endregion } }
using System; using System.IO; // ReSharper disable StringIndexOfIsCultureSpecific.1 // ReSharper disable StringLastIndexOfIsCultureSpecific.1 // ReSharper disable StringIndexOfIsCultureSpecific.2 // ReSharper disable ReplaceWithStringIsNullOrEmpty namespace Skewworks.NETMF { /// <summary> /// Class for working with strings /// </summary> public class Strings { /// <summary> /// Return absolute path from relative path /// </summary> /// <param name="baseDirectory">Base (or current) directory to use when assembling absolute path</param> /// <param name="target">Relative path to convert</param> /// <returns>Returns the absolute path</returns> public static string AbsolutePath(string baseDirectory, string target) { // Remove last slash if (baseDirectory.Substring(baseDirectory.Length - 1) == "\\") { baseDirectory = baseDirectory.Substring(0, baseDirectory.Length - 1); } // Check roots if (target.Substring(0, 1) == "\\") { return target; } // Remove up-line while (target.IndexOf("..\\") >= 0) { int i = baseDirectory.LastIndexOf("\\"); // Invalid Path if (i <= 0) { return target; } baseDirectory = baseDirectory.Substring(0, i); target = target.Substring(3); } return NormalizeDirectory(baseDirectory) + target; } /// <summary> /// Ensures the directory ends with a '\' character /// </summary> /// <param name="path">Path to normalize</param> /// <returns>Returns the normalized path</returns> public static string NormalizeDirectory(string path) { if (path.Substring(path.Length - 1) != "\\") { return path + "\\"; } return path; } /// <summary> /// Returns a relative path from an absolute path /// </summary> /// <param name="baseDirectory">Base (or current) directory to use when assembling relative path</param> /// <param name="target">Absolute path to convert</param> /// <returns>Returns the relative path</returns> public static string RelativePath(string baseDirectory, string target) { string sRes = string.Empty; int i; // Check for file only if (target.IndexOf('\\') < 0) { return target; } // Split strings string[] rel1 = NormalizeDirectory(baseDirectory).Split('\\'); string[] rel2 = target.Split('\\'); // Check for different drive if (rel1[1].ToLower() != rel2[1].ToLower()) { return target; } // Find last match int s = 0; int e = (rel1.Length < rel2.Length) ? rel1.Length : rel2.Length; for (i = 2; i < e; i++) { if (rel1[i].ToLower() != rel2[i].ToLower()) { s = i; break; } } // Build up-line if (s < rel1.Length - 1) { for (i = s; i < rel1.Length; i++) { if (rel1[i] != string.Empty) { sRes += "..\\"; } } } // Build down-line if (s < rel2.Length) { for (i = s; i < rel2.Length; i++) { sRes += rel2[i] + "\\"; } } // Check for file if (Path.GetExtension(target) != string.Empty) { sRes = sRes.Substring(0, sRes.Length - 1); } // Return outcome return sRes; } /// <summary> /// Replaces all instances of a string in a string with a new value /// </summary> /// <param name="source">String to be modified</param> /// <param name="toFind">String to find within the source</param> /// <param name="replaceWith">New value to replace all ToFind instances with</param> /// <returns>Returns the modified string</returns> public static string Replace(string source, string toFind, string replaceWith) { int iStart = 0; if (source == string.Empty || source == null || toFind == string.Empty || toFind == null) { return source; } while (true) { int i = source.IndexOf(toFind, iStart); if (i < 0) break; if (i > 0) { source = source.Substring(0, i) + replaceWith + source.Substring(i + toFind.Length); } else { source = replaceWith + source.Substring(i + toFind.Length); } iStart = i + replaceWith.Length; } return source; } /// <summary> /// Returns true if the specified location is inside of a quote set /// </summary> /// <param name="value">String to check</param> /// <param name="position">Location withing the string to check</param> /// <returns>true if the location is inside quotes; else false</returns> public static bool InQuotes(string value, int position) { int qcount = 0; int iStart = 0; while (true) { // Find next instance of a quote int i = value.IndexOf('"', iStart); // If not return our value if (i < 0 || i >= position) { return qcount % 2 != 0; } // Check if it's a qualified quote if (i > 0 && value.Substring(i, 1) != "\\" || i == 0) { qcount++; } iStart = i + 1; } } /// <summary> /// Splits a string by delimiter while accounting for quotes /// </summary> /// <param name="value">String to split</param> /// <param name="delimiter">Character to split by</param> /// <returns>Returns the splitted string</returns> public static string[] SplitComponents(string value, char delimiter) { int iStart = 0; string[] ret = null; while (true) { // Find delimiter int i = value.IndexOf(delimiter, iStart); if (InQuotes(value, i)) { iStart = i + 1; } else { // Separate value string s; if (i < 0) { s = value; } else { s = value.Substring(0, i).Trim(); value = value.Substring(i + 1); } // Add value if (ret == null) { ret = new[] { s }; } else { var tmp = new string[ret.Length + 1]; Array.Copy(ret, tmp, ret.Length); tmp[tmp.Length - 1] = s; ret = tmp; } iStart = 0; } // Break on last value if (i < 0 || value == string.Empty) { break; } } return ret; } /// <summary> /// Tokenizes a line while accounting for quotes /// </summary> /// <param name="command">String to tokenize</param> /// <returns>Returns the tokenized string.</returns> public static string[] Tokenize(string command) { string[] res = SplitComponents(command, ' '); for (int i = 0; i < res.Length; i++) { res[i] = res[i].Trim(); if (res[i].Substring(0, 1) == "\"" && res[i].Substring(res[i].Length - 1) == "\"") { res[i] = res[i].Substring(1, res[i].Length - 2); } } return res; } } } // ReSharper restore StringIndexOfIsCultureSpecific.1 // ReSharper restore StringLastIndexOfIsCultureSpecific.1 // ReSharper restore StringIndexOfIsCultureSpecific.2 // ReSharper restore ReplaceWithStringIsNullOrEmpty
// Delcom Engineering - Copyright 2007 // Delcom Dll CS.Net declaration class file // Constants and Functions declaration // File Date: 01/10/2007 - Verison 0.1 - Preliminary // How to use this Delcom class in your C# code // 1 Copy the DelcomDll.dll file into the directory that the compiled file runs from. // In most cases this is the /debug and /release directories. // 2 Copy this file (DelcomDll.cs) in to the projectname directory. (This is were your source is.) // 3 Add this file to the project. (Right click in the Solution Explorer, Add/Existing item...) // 4 In you main code add the following example code: // /* Example to blink the LED on P1.0 using System; using System.Collections.Generic; using System.Text; namespace CS_NET_DLL { class Program { static void Main(string[] args) { uint hUSB; int Result; StringBuilder DeviceName = new StringBuilder(Delcom.MAXDEVICENAMELEN); // Serach for the first match USB device, For USB IO Chips use Delcom.USBIODS // With Generation 2 HID devices, you can pass a TypeId of 0 to open any Delcom device. Result = Delcom.DelcomGetNthDevice(Delcom.USBDELVI, 0, DeviceName); if(Result == 0 ) { // if not found, exit Console.WriteLine("Device not found!\n"); return; } Console.WriteLine("Delcom C# Example Program."); Console.WriteLine("Device found: "+ DeviceName ); hUSB = Delcom.DelcomOpenDevice(DeviceName, 0); // open the device Delcom.DelcomLEDControl(hUSB, Delcom.GREENLED, Delcom.LEDON); // blink the green led Delcom.DelcomCloseDevice(hUSB); // close the device while (!Console.KeyAvailable) ; // wait for any key } } } */ using System; using System.Text; using System.Runtime.InteropServices; public class Delcom { // Delcom USB Devices public const uint USBIODS = 1; public const uint USBDELVI = 2; public const uint USBNDSPY = 3; // USBDELVI LED MODES public const byte LEDOFF = 0; public const byte LEDON = 1; public const byte LEDFLASH = 2; // USBDELVI LED COlORS public const byte GREENLED = 0; public const byte REDLED = 1; public const byte BLUELED = 2; // Device Name Maximum Length public const int MAXDEVICENAMELEN = 512; // USB Packet Structures // USB Data IO Packact [StructLayout(LayoutKind.Sequential, Pack=1)] public struct PacketStructure { public byte Recipient; public byte DeviceModel; public byte MajorCmd; public byte MinorCmd; public byte DataLSB; public byte DataMSB; public byte Length; [ MarshalAs( UnmanagedType.ByValArray, SizeConst = 8 )] public byte[] DATA ; //Data 1 .. 8 } // Return data struture [StructLayout(LayoutKind.Sequential, Pack=1)] public struct DataExtStructure { [ MarshalAs( UnmanagedType.ByValArray, SizeConst = 8 )] public byte[] DATA ; //Data 1 .. 8 } // Delcom DLL Fucnctions - See the DelcomDLL.pdf for documentation // http://www.delcom-eng.com/productdetails.asp?PartNumber=890510 // Gets the DelcomDLL verison [DllImport("delcomdll.dll", EntryPoint="DelcomGetDLLVersion")] public static extern float DelcomGetDLLVersion(); // Sets the verbose controll - used for debugging [DllImport("delcomdll.dll", EntryPoint="DelcomVerboseControl")] public static extern int DelcomVerboseControl(uint Mode, StringBuilder caption); // Gets the DLL date [DllImport("delcomdll.dll", EntryPoint="DelcomGetDLLDate")] public static extern int DelcomGetDLLDate(StringBuilder DateString); // Generic Functions //Gets DeviceCount [DllImport("delcomdll.dll", EntryPoint="DelcomGetDeviceCount")] public static extern int DelcomGetDeviceCount(uint ProductType); // Gets Nth Device [DllImport("delcomdll.dll", EntryPoint="DelcomGetNthDevice")] public static extern int DelcomGetNthDevice(uint ProductType, uint NthDevice, StringBuilder DeviceName); // Open Device [DllImport("delcomdll.dll", EntryPoint="DelcomOpenDevice")] public static extern uint DelcomOpenDevice(StringBuilder DeviceName, int Mode ); // Close Device [DllImport("delcomdll.dll", EntryPoint="DelcomCloseDevice")] public static extern int DelcomCloseDevice(uint DeviceHandle); // Read USB Device Version [DllImport("delcomdll.dll", EntryPoint="DelcomReadDeviceVersion")] public static extern int DelcomReadDeviceVersion(uint DeviceHandle ); // Read USB Device SerialNumber [DllImport("delcomdll.dll", EntryPoint="DelcomReadDeviceSerialNum")] public static extern int DelcomReadDeviceSerialNum(StringBuilder DeviceName, uint DeviceHandle); // Send USB Packet [DllImport("delcomdll.dll", EntryPoint="DelcomSendPacket")] public static extern int DelcomSendPacket(uint DeviceHandle, ref PacketStructure PacketOut, out PacketStructure PacketIn); // USBDELVI - Visual Indicator Functions // Set LED Functions [DllImport("delcomdll.dll", EntryPoint="DelcomLEDControl")] public static extern int DelcomLEDControl(uint DeviceHandle, int Color, int Mode); // Set LED Freq/Duty functions [DllImport("delcomdll.dll", EntryPoint="DelcomLoadLedFreqDuty")] public static extern int DelcomLoadLedFreqDuty(uint DeviceHandle, byte Color, byte Low, byte High); // Set Auto Confirm Mode [DllImport("delcomdll.dll", EntryPoint="DelcomEnableAutoConfirm")] public static extern int DelcomEnableAutoConfirm(uint DeviceHandle, int Mode ); // Set Auto Clear Mode [DllImport("delcomdll.dll", EntryPoint="DelcomEnableAutoClear(")] public static extern int DelcomEnableAutoClear(uint DeviceHandle, int Mode); // Set Buzzer Function [DllImport("delcomdll.dll", EntryPoint="DelcomBuzzer")] public static extern int DelcomBuzzer(uint DeviceHandle, byte Mode , byte Freq, byte Repeat, byte OnTime, byte OffTime); // Set LED Phase Delay [DllImport("delcomdll.dll", EntryPoint="DelcomLoadInitialPhaseDelay")] public static extern int DelcomLoadInitialPhaseDelay(uint DeviceHandle, byte Color, byte Delay); // Set Led Sync Functions [DllImport("delcomdll.dll", EntryPoint="DelcomSyncLeds")] public static extern int DelcomSyncLeds(uint DeviceHandle ); // Set LED PreScalar Functions [DllImport("delcomdll.dll", EntryPoint="DelcomLoadPreScalar")] public static extern int DelcomLoadPreScalar(uint DeviceHandle, byte PreScalar); // Get Button Status [DllImport("delcomdll.dll", EntryPoint="DelcomGetButtonStatus")] public static extern int DelcomGetButtonStatus(uint DeviceHandle); // Set LED Power [DllImport("delcomdll.dll", EntryPoint="DelcomLEDPower")] public static extern int DelcomLEDPower(uint DeviceHandle, int Color, int Power); // USBIODS - USB IO Functions // Set Ports [DllImport("delcomdll.dll", EntryPoint="DelcomWritePin")] public static extern int DelcomWritePin(uint DeviceHandle, byte Port, byte Pin, byte Value); // Set Ports [DllImport("delcomdll.dll", EntryPoint="DelcomWritePorts")] public static extern int DelcomWritePorts(uint DeviceHandle, byte Port0, byte Port1); // Get Ports [DllImport("delcomdll.dll", EntryPoint="DelcomReadPorts")] public static extern int DelcomReadPorts(uint DeviceHandle, out byte Port0 , out byte Port1 ); // Set 64Bit Value [DllImport("delcomdll.dll", EntryPoint="DelcomWrite64Bit")] public static extern int DelcomWrite64Bit(uint DeviceHandle, ref DataExtStructure DataExt); // Get 64Bit Value [DllImport("delcomdll.dll", EntryPoint="DelcomRead64Bit")] public static extern int DelcomRead64Bit(uint DeviceHandle, out DataExtStructure DataExt); // Write I2C Functions [DllImport("delcomdll.dll", EntryPoint="DelcomWriteI2C")] public static extern int DelcomWriteI2C(uint DeviceHandle, byte CmdAdd , byte Length, DataExtStructure DataExt); // Read I2C Functions [DllImport("delcomdll.dll", EntryPoint="DelcomReadI2C")] public static extern int DelcomReadI2C( uint DeviceHandle, byte CmdAdd, byte Length, out DataExtStructure DataExt); // Get I2C Slect Read [DllImport("delcomdll.dll", EntryPoint="DelcomSelReadI2C")] public static extern int DelcomSelReadI2C(uint DeviceHandle, byte SetAddCmd, byte Address, byte ReadCmd, byte Length , out DataExtStructure DataExt); // Read I2C EEPROM Functions [DllImport("delcomdll.dll", EntryPoint="DelcomReadI2CEEPROM")] public static extern int DelcomReadI2CEEPROM( uint DeviceHandle, uint Address, uint size, byte Ctrlcode, out StringBuilder Data); // Write I2C EEPROM Functions [DllImport("delcomdll.dll", EntryPoint="DelcomwriteI2CEEPROM")] public static extern int DelcomWriteI2CEEPROM( uint DeviceHandle, uint Address, uint size, byte Ctrlcode, byte WriteDelay, out StringBuilder Data); // Setup RS232 Mode [DllImport("delcomdll.dll", EntryPoint="DelcomRS232Ctrl")] public static extern int DelcomRS232Ctrl(uint DeviceHandle, int Mode, int Value ); // Write RS232 Function [DllImport("delcomdll.dll", EntryPoint="DelcomWriteRS232")] public static extern int DelcomWriteRS232(uint DeviceHandle , int Length, ref DataExtStructure DataExt); // Read RS232 Function [DllImport("delcomdll.dll", EntryPoint="DelcomReadRS232")] public static extern int DelcomReadRS232(uint DeviceHandle, out DataExtStructure DataExt); // SPI Write Function [DllImport("delcomdll.dll", EntryPoint="DelcomSPIWrite")] public static extern int DelcomSPIWrite(uint DeviceHandle, uint ClockCount, out DataExtStructure DataExt); // SPI SetClock Function [DllImport("delcomdll.dll", EntryPoint="DelcomSPISetClock")] public static extern int DelcomSPISetClock(uint DeviceHandle, uint ClockPeriod ); // SPI Read Function [DllImport("delcomdll.dll", EntryPoint="DelcomSPIRead")] public static extern int DelcomSPIRead(uint DeviceHandle, out DataExtStructure DataExt); // SPI Write8Read64 Function [DllImport("delcomdll.dll", EntryPoint="DelcomSPIWr8Read64")] public static extern int DelcomSPIWr8Read64(uint DeviceHandle, uint WeData, uint ClockCount, out DataExtStructure DataExt); // USBNDSPY Functions // Set Numeric Mode [DllImport("delcomdll.dll", EntryPoint="DelcomNumericMode")] public static extern int DelcomNumericMode(uint DeviceHandle, byte Mode, byte Rate); // Set Numeric Scan Rate [DllImport("delcomdll.dll", EntryPoint="DelcomNumericScanRate")] public static extern int DelcomNumericScanRate(uint DeviceHandle, byte ScanRate); // Setup Numeric Digits [DllImport("delcomdll.dll", EntryPoint="DelcomNumericSetup")] public static extern int DelcomNumericSetup(uint DeviceHandle, byte Digits); // Set Numeric Raw Mode [DllImport("delcomdll.dll", EntryPoint="DelcomNumericRaw")] public static extern int DelcomNumericRaw(uint DeviceHandle, StringBuilder Str); // Set Numeric Integer Mode [DllImport("delcomdll.dll", EntryPoint="DelcomNumericInteger")] public static extern int DelcomNumericInteger(uint DeviceHandle, int Number, int Base); // Set Numeric Hexdecimal Mode [DllImport("delcomdll.dll", EntryPoint="DelcomNumericHexaDecimal")] public static extern int DelcomNumericHexaDecimal(uint DeviceHandle, int Number, int Base); // Set Numeric Double Mode [DllImport("delcomdll.dll", EntryPoint="DelcomNumericDouble(")] public static extern int DelcomNumericDouble(uint DeviceHandle, double Number, int Base); } // end of class
//----------------------------------------------------------------------- // <copyright file="Framing.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.IO; using Akka.Streams.Implementation.Stages; using Akka.Streams.Stage; using Akka.Util; namespace Akka.Streams.Dsl { public static class Framing { /// <summary> /// Creates a Flow that handles decoding a stream of unstructured byte chunks into a stream of frames where the /// incoming chunk stream uses a specific byte-sequence to mark frame boundaries. /// /// The decoded frames will not include the separator sequence. /// /// If there are buffered bytes (an incomplete frame) when the input stream finishes and <paramref name="allowTruncation"/> is set to /// false then this Flow will fail the stream reporting a truncated frame. /// </summary> /// <param name="delimiter">The byte sequence to be treated as the end of the frame.</param> /// <param name="maximumFrameLength">The maximum length of allowed frames while decoding. If the maximum length is exceeded this Flow will fail the stream.</param> /// <param name="allowTruncation">If false, then when the last frame being decoded contains no valid delimiter this Flow fails the stream instead of returning a truncated frame.</param> /// <returns></returns> public static Flow<ByteString, ByteString, NotUsed> Delimiter(ByteString delimiter, int maximumFrameLength, bool allowTruncation = false) { return Flow.Create<ByteString>() .Via(new DelimiterFramingStage(delimiter, maximumFrameLength, allowTruncation)) .Named("DelimiterFraming"); } /// <summary> /// Creates a Flow that decodes an incoming stream of unstructured byte chunks into a stream of frames, assuming that /// incoming frames have a field that encodes their length. /// /// If the input stream finishes before the last frame has been fully decoded this Flow will fail the stream reporting /// a truncated frame. /// </summary> /// <param name="fieldLength">The length of the "Count" field in bytes</param> /// <param name="maximumFramelength">The maximum length of allowed frames while decoding. If the maximum length is exceeded this Flow will fail the stream. This length *includes* the header (i.e the offset and the length of the size field)</param> /// <param name="fieldOffset">The offset of the field from the beginning of the frame in bytes</param> /// <param name="byteOrder">The <see cref="ByteOrder"/> to be used when decoding the field</param> /// <returns></returns> public static Flow<ByteString, ByteString, NotUsed> LengthField(int fieldLength, int maximumFramelength, int fieldOffset = 0, ByteOrder byteOrder = ByteOrder.LittleEndian) { if (fieldLength < 1 || fieldLength > 4) throw new ArgumentException("Length field length must be 1,2,3 or 4"); return Flow.Create<ByteString>() .Transform(() => new LengthFieldFramingStage(fieldLength, maximumFramelength, fieldOffset, byteOrder)) .Named("LengthFieldFraming"); } /// <summary> /// Returns a BidiFlow that implements a simple framing protocol. This is a convenience wrapper over <see cref="LengthField"/> /// and simply attaches a length field header of four bytes (using big endian encoding) to outgoing messages, and decodes /// such messages in the inbound direction. The decoded messages do not contain the header. /// /// This BidiFlow is useful if a simple message framing protocol is needed (for example when TCP is used to send /// individual messages) but no compatibility with existing protocols is necessary. /// /// The encoded frames have the layout /// {{{ /// [4 bytes length field, Big Endian][User Payload] /// }}} /// The length field encodes the length of the user payload excluding the header itself. /// </summary> /// <param name="maximumMessageLength">Maximum length of allowed messages. If sent or received messages exceed the configured limit this BidiFlow will fail the stream. The header attached by this BidiFlow are not included in this limit.</param> /// <returns></returns> public static BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> SimpleFramingProtocol(int maximumMessageLength) { return BidiFlow.FromFlowsMat(SimpleFramingProtocolEncoder(maximumMessageLength), SimpleFramingProtocolDecoder(maximumMessageLength), Keep.Left); } /// <summary> /// Protocol decoder that is used by <see cref="SimpleFramingProtocol"/> /// </summary> public static Flow<ByteString, ByteString, NotUsed> SimpleFramingProtocolDecoder(int maximumMessageLength) { return LengthField(4, maximumMessageLength + 4, 0, ByteOrder.BigEndian).Select(b => b.Drop(4)); } /// <summary> /// Protocol encoder that is used by <see cref="SimpleFramingProtocol"/> /// </summary> public static Flow<ByteString, ByteString, NotUsed> SimpleFramingProtocolEncoder(int maximumMessageLength) { return Flow.Create<ByteString>().Transform(() => new FramingDecoderStage(maximumMessageLength)); } public class FramingException : Exception { public FramingException(string message) : base(message) { } } private static readonly Func<ByteIterator, int, int> BigEndianDecoder = (byteString, length) => { var count = length; var decoded = 0; while (count > 0) { decoded <<= 8; decoded |= byteString.Next() & 0xFF; count--; } return decoded; }; private static readonly Func<ByteIterator, int, int> LittleEndianDecoder = (byteString, length) => { var highestOcted = (length - 1) << 3; var mask = (int) (1L << (length << 3)) - 1; var count = length; var decoded = 0; while (count > 0) { // decoded >>>= 8 on the jvm decoded = (int) ((uint) decoded >> 8); decoded += (byteString.Next() & 0xFF) << highestOcted; count--; } return decoded & mask; }; private sealed class FramingDecoderStage : PushStage<ByteString, ByteString> { private readonly int _maximumMessageLength; public FramingDecoderStage(int maximumMessageLength) { _maximumMessageLength = maximumMessageLength; } public override ISyncDirective OnPush(ByteString element, IContext<ByteString> context) { var messageSize = element.Count; if (messageSize > _maximumMessageLength) return context.Fail(new FramingException($"Maximum allowed message size is {_maximumMessageLength} but tried to send {messageSize} bytes")); var header = ByteString.Create(new[] { Convert.ToByte((messageSize >> 24) & 0xFF), Convert.ToByte((messageSize >> 16) & 0xFF), Convert.ToByte((messageSize >> 8) & 0xFF), Convert.ToByte(messageSize & 0xFF) }); return context.Push(header + element); } } private sealed class DelimiterFramingStage : GraphStage<FlowShape<ByteString, ByteString>> { #region Logic private sealed class Logic : InAndOutGraphStageLogic { private readonly DelimiterFramingStage _stage; private readonly byte _firstSeparatorByte; private ByteString _buffer; private int _nextPossibleMatch; public Logic(DelimiterFramingStage stage) : base (stage.Shape) { _stage = stage; _firstSeparatorByte = stage._separatorBytes.Head; _buffer = ByteString.Empty; SetHandler(stage.In, this); SetHandler(stage.Out, this); } public override void OnPush() { _buffer += Grab(_stage.In); DoParse(); } public override void OnUpstreamFinish() { if (_buffer.IsEmpty) CompleteStage(); else if (IsAvailable(_stage.Out)) DoParse(); // else swallow the termination and wait for pull } public override void OnPull() => DoParse(); private void TryPull() { if (IsClosed(_stage.In)) { if (_stage._allowTruncation) { Push(_stage.Out, _buffer); CompleteStage(); } else FailStage( new FramingException( "Stream finished but there was a truncated final frame in the buffer")); } else Pull(_stage.In); } private void DoParse() { var possibleMatchPosition = -1; for (var i = _nextPossibleMatch; i < _buffer.Count; i++) { if (_buffer[i] == _firstSeparatorByte) { possibleMatchPosition = i; break; } } if (possibleMatchPosition > _stage._maximumLineBytes) FailStage( new FramingException( $"Read {_buffer.Count} bytes which is more than {_stage._maximumLineBytes} without seeing a line terminator")); else if (possibleMatchPosition == -1) { if (_buffer.Count > _stage._maximumLineBytes) FailStage( new FramingException( $"Read {_buffer.Count} bytes which is more than {_stage._maximumLineBytes} without seeing a line terminator")); else { // No matching character, we need to accumulate more bytes into the buffer _nextPossibleMatch = _buffer.Count; TryPull(); } } else if (possibleMatchPosition + _stage._separatorBytes.Count > _buffer.Count) { // We have found a possible match (we found the first character of the terminator // sequence) but we don't have yet enough bytes. We remember the position to // retry from next time. _nextPossibleMatch = possibleMatchPosition; TryPull(); } else if (Equals(_buffer.Slice(possibleMatchPosition, possibleMatchPosition + _stage._separatorBytes.Count), _stage._separatorBytes)) { // Found a match var parsedFrame = _buffer.Slice(0, possibleMatchPosition).Compact(); _buffer = _buffer.Drop(possibleMatchPosition + _stage._separatorBytes.Count).Compact(); _nextPossibleMatch = 0; Push(_stage.Out, parsedFrame); if (IsClosed(_stage.In) && _buffer.IsEmpty) CompleteStage(); } else { // possibleMatchPos was not actually a match _nextPossibleMatch++; DoParse(); } } } #endregion private readonly ByteString _separatorBytes; private readonly int _maximumLineBytes; private readonly bool _allowTruncation; public DelimiterFramingStage(ByteString separatorBytes, int maximumLineBytes, bool allowTruncation) { _separatorBytes = separatorBytes; _maximumLineBytes = maximumLineBytes; _allowTruncation = allowTruncation; Shape = new FlowShape<ByteString, ByteString>(In, Out); } private Inlet<ByteString> In = new Inlet<ByteString>("DelimiterFraming.in"); private Outlet<ByteString> Out = new Outlet<ByteString>("DelimiterFraming.in"); public override FlowShape<ByteString, ByteString> Shape { get; } protected override Attributes InitialAttributes { get; } = DefaultAttributes.DelimiterFraming; protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); public override string ToString() => "DelimiterFraming"; } private sealed class LengthFieldFramingStage : PushPullStage<ByteString, ByteString> { private readonly int _lengthFieldLength; private readonly int _maximumFramelength; private readonly int _lengthFieldOffset; private ByteString _buffer = ByteString.Empty; private readonly int _minimumChunkSize; private int _frameSize; private readonly Func<ByteIterator, int, int> _intDecoder; public LengthFieldFramingStage(int lengthFieldLength, int maximumFramelength, int lengthFieldOffset, ByteOrder byteOrder) { _lengthFieldLength = lengthFieldLength; _maximumFramelength = maximumFramelength; _lengthFieldOffset = lengthFieldOffset; _minimumChunkSize = lengthFieldOffset + lengthFieldLength; _frameSize = int.MaxValue; _intDecoder = byteOrder == ByteOrder.BigEndian ? BigEndianDecoder : LittleEndianDecoder; } public override ISyncDirective OnPush(ByteString element, IContext<ByteString> context) { _buffer += element; return DoParse(context); } public override ISyncDirective OnPull(IContext<ByteString> context) => DoParse(context); public override ITerminationDirective OnUpstreamFinish(IContext<ByteString> context) { return _buffer.NonEmpty ? context.AbsorbTermination() : context.Finish(); } public override void PostStop() => _buffer = null; private ISyncDirective TryPull(IContext<ByteString> context) { if (context.IsFinishing) return context.Fail(new FramingException("Stream finished but there was a truncated final frame in the buffer")); return context.Pull(); } private ISyncDirective DoParse(IContext<ByteString> context) { Func<IContext<ByteString>, ISyncDirective> emitFrame = ctx => { var parsedFrame = _buffer.Take(_frameSize).Compact(); _buffer = _buffer.Drop(_frameSize); _frameSize = int.MaxValue; if (ctx.IsFinishing && _buffer.IsEmpty) return ctx.PushAndFinish(parsedFrame); return ctx.Push(parsedFrame); }; var bufferSize = _buffer.Count; if (bufferSize >= _frameSize) return emitFrame(context); if (bufferSize >= _minimumChunkSize) { var parsedLength = _intDecoder(_buffer.Iterator().Drop(_lengthFieldOffset), _lengthFieldLength); _frameSize = parsedLength + _minimumChunkSize; if (_frameSize > _maximumFramelength) return context.Fail(new FramingException($"Maximum allowed frame size is {_maximumFramelength} but decoded frame header reported size {_frameSize}")); if (bufferSize >= _frameSize) return emitFrame(context); return TryPull(context); } return TryPull(context); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using SRS.Models; namespace SRS.Migrations { [ContextType(typeof(ApplicationDbContext))] partial class CreateIdentitySchema { public override string Id { get { return "00000000000000_CreateIdentitySchema"; } } public override string ProductVersion { get { return "7.0.0-beta5"; } } public override void BuildTargetModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 1); b.Property<string>("Name") .Annotation("OriginalValueIndex", 2); b.Property<string>("NormalizedName") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ProviderKey") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 1); b.Property<string>("ProviderDisplayName") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId") .Annotation("OriginalValueIndex", 0); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 1); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("SRS.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<int>("AccessFailedCount") .Annotation("OriginalValueIndex", 1); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 2); b.Property<string>("Email") .Annotation("OriginalValueIndex", 3); b.Property<bool>("EmailConfirmed") .Annotation("OriginalValueIndex", 4); b.Property<bool>("LockoutEnabled") .Annotation("OriginalValueIndex", 5); b.Property<DateTimeOffset?>("LockoutEnd") .Annotation("OriginalValueIndex", 6); b.Property<string>("NormalizedEmail") .Annotation("OriginalValueIndex", 7); b.Property<string>("NormalizedUserName") .Annotation("OriginalValueIndex", 8); b.Property<string>("PasswordHash") .Annotation("OriginalValueIndex", 9); b.Property<string>("PhoneNumber") .Annotation("OriginalValueIndex", 10); b.Property<bool>("PhoneNumberConfirmed") .Annotation("OriginalValueIndex", 11); b.Property<string>("SecurityStamp") .Annotation("OriginalValueIndex", 12); b.Property<bool>("TwoFactorEnabled") .Annotation("OriginalValueIndex", 13); b.Property<string>("UserName") .Annotation("OriginalValueIndex", 14); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("SRS.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("SRS.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("SRS.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
using YAF.Lucene.Net.Documents; using YAF.Lucene.Net.Documents.Extensions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace YAF.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 = YAF.Lucene.Net.Util.BytesRef; using Counter = YAF.Lucene.Net.Util.Counter; using DocValuesConsumer = YAF.Lucene.Net.Codecs.DocValuesConsumer; using DocValuesFormat = YAF.Lucene.Net.Codecs.DocValuesFormat; using IOUtils = YAF.Lucene.Net.Util.IOUtils; internal sealed class DocValuesProcessor : StoredFieldsConsumer { // TODO: somewhat wasteful we also keep a map here; would // be more efficient if we could "reuse" the map/hash // lookup DocFieldProcessor already did "above" private readonly IDictionary<string, DocValuesWriter> writers = new Dictionary<string, DocValuesWriter>(); private readonly Counter bytesUsed; public DocValuesProcessor(Counter bytesUsed) { this.bytesUsed = bytesUsed; } public override void StartDocument() { } [MethodImpl(MethodImplOptions.NoInlining)] internal override void FinishDocument() { } public override void AddField(int docID, IIndexableField field, FieldInfo fieldInfo) { DocValuesType dvType = field.IndexableFieldType.DocValueType; if (dvType != DocValuesType.NONE) { fieldInfo.DocValuesType = dvType; if (dvType == DocValuesType.BINARY) { AddBinaryField(fieldInfo, docID, field.GetBinaryValue()); } else if (dvType == DocValuesType.SORTED) { AddSortedField(fieldInfo, docID, field.GetBinaryValue()); } else if (dvType == DocValuesType.SORTED_SET) { AddSortedSetField(fieldInfo, docID, field.GetBinaryValue()); } else if (dvType == DocValuesType.NUMERIC) { if (field.NumericType != NumericFieldType.INT64) { throw new System.ArgumentException("illegal type " + field.NumericType + ": DocValues types must be " + NumericFieldType.INT64); } AddNumericField(fieldInfo, docID, field.GetInt64ValueOrDefault()); } else { Debug.Assert(false, "unrecognized DocValues.Type: " + dvType); } } } [MethodImpl(MethodImplOptions.NoInlining)] public override void Flush(SegmentWriteState state) { if (writers.Count > 0) { DocValuesFormat fmt = state.SegmentInfo.Codec.DocValuesFormat; DocValuesConsumer dvConsumer = fmt.FieldsConsumer(state); bool success = false; try { foreach (DocValuesWriter writer in writers.Values) { writer.Finish(state.SegmentInfo.DocCount); writer.Flush(state, dvConsumer); } // TODO: catch missing DV fields here? else we have // null/"" depending on how docs landed in segments? // but we can't detect all cases, and we should leave // this behavior undefined. dv is not "schemaless": its column-stride. writers.Clear(); success = true; } finally { if (success) { IOUtils.Dispose(dvConsumer); } else { IOUtils.DisposeWhileHandlingException(dvConsumer); } } } } internal void AddBinaryField(FieldInfo fieldInfo, int docID, BytesRef value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); BinaryDocValuesWriter binaryWriter; if (writer == null) { binaryWriter = new BinaryDocValuesWriter(fieldInfo, bytesUsed); writers[fieldInfo.Name] = binaryWriter; } else if (!(writer is BinaryDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to binary"); } else { binaryWriter = (BinaryDocValuesWriter)writer; } binaryWriter.AddValue(docID, value); } internal void AddSortedField(FieldInfo fieldInfo, int docID, BytesRef value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); SortedDocValuesWriter sortedWriter; if (writer == null) { sortedWriter = new SortedDocValuesWriter(fieldInfo, bytesUsed); writers[fieldInfo.Name] = sortedWriter; } else if (!(writer is SortedDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to sorted"); } else { sortedWriter = (SortedDocValuesWriter)writer; } sortedWriter.AddValue(docID, value); } internal void AddSortedSetField(FieldInfo fieldInfo, int docID, BytesRef value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); SortedSetDocValuesWriter sortedSetWriter; if (writer == null) { sortedSetWriter = new SortedSetDocValuesWriter(fieldInfo, bytesUsed); writers[fieldInfo.Name] = sortedSetWriter; } else if (!(writer is SortedSetDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to sorted"); } else { sortedSetWriter = (SortedSetDocValuesWriter)writer; } sortedSetWriter.AddValue(docID, value); } internal void AddNumericField(FieldInfo fieldInfo, int docID, long value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); NumericDocValuesWriter numericWriter; if (writer == null) { numericWriter = new NumericDocValuesWriter(fieldInfo, bytesUsed, true); writers[fieldInfo.Name] = numericWriter; } else if (!(writer is NumericDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to numeric"); } else { numericWriter = (NumericDocValuesWriter)writer; } numericWriter.AddValue(docID, value); } private string GetTypeDesc(DocValuesWriter obj) { if (obj is BinaryDocValuesWriter) { return "binary"; } else if (obj is NumericDocValuesWriter) { return "numeric"; } else { Debug.Assert(obj is SortedDocValuesWriter); return "sorted"; } } [MethodImpl(MethodImplOptions.NoInlining)] public override void Abort() { foreach (DocValuesWriter writer in writers.Values) { try { writer.Abort(); } #pragma warning disable 168 catch (Exception t) #pragma warning restore 168 { } } writers.Clear(); } } }
// ------------------------------------------------------------------------------ // 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. 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 WorkbookChartAxisTitleFormatRequest. /// </summary> public partial class WorkbookChartAxisTitleFormatRequest : BaseRequest, IWorkbookChartAxisTitleFormatRequest { /// <summary> /// Constructs a new WorkbookChartAxisTitleFormatRequest. /// </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 WorkbookChartAxisTitleFormatRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookChartAxisTitleFormat using POST. /// </summary> /// <param name="workbookChartAxisTitleFormatToCreate">The WorkbookChartAxisTitleFormat to create.</param> /// <returns>The created WorkbookChartAxisTitleFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> CreateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToCreate) { return this.CreateAsync(workbookChartAxisTitleFormatToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookChartAxisTitleFormat using POST. /// </summary> /// <param name="workbookChartAxisTitleFormatToCreate">The WorkbookChartAxisTitleFormat to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookChartAxisTitleFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> CreateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookChartAxisTitleFormat>(workbookChartAxisTitleFormatToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookChartAxisTitleFormat. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookChartAxisTitleFormat. /// </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<WorkbookChartAxisTitleFormat>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookChartAxisTitleFormat. /// </summary> /// <returns>The WorkbookChartAxisTitleFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookChartAxisTitleFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookChartAxisTitleFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookChartAxisTitleFormat>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookChartAxisTitleFormat using PATCH. /// </summary> /// <param name="workbookChartAxisTitleFormatToUpdate">The WorkbookChartAxisTitleFormat to update.</param> /// <returns>The updated WorkbookChartAxisTitleFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> UpdateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToUpdate) { return this.UpdateAsync(workbookChartAxisTitleFormatToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookChartAxisTitleFormat using PATCH. /// </summary> /// <param name="workbookChartAxisTitleFormatToUpdate">The WorkbookChartAxisTitleFormat to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookChartAxisTitleFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> UpdateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookChartAxisTitleFormat>(workbookChartAxisTitleFormatToUpdate, 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 IWorkbookChartAxisTitleFormatRequest 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 IWorkbookChartAxisTitleFormatRequest Expand(Expression<Func<WorkbookChartAxisTitleFormat, 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 IWorkbookChartAxisTitleFormatRequest 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 IWorkbookChartAxisTitleFormatRequest Select(Expression<Func<WorkbookChartAxisTitleFormat, 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="workbookChartAxisTitleFormatToInitialize">The <see cref="WorkbookChartAxisTitleFormat"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToInitialize) { } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Routing; using OrchardCore.Admin; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Navigation; using OrchardCore.Routing; using OrchardCore.Settings; using OrchardCore.Sitemaps.Cache; using OrchardCore.Sitemaps.Models; using OrchardCore.Sitemaps.Services; using OrchardCore.Sitemaps.ViewModels; namespace OrchardCore.Sitemaps.Controllers { [Admin] public class SitemapIndexController : Controller { private readonly ISitemapHelperService _sitemapService; private readonly IAuthorizationService _authorizationService; private readonly ISitemapIdGenerator _sitemapIdGenerator; private readonly ISitemapManager _sitemapManager; private readonly ISitemapCacheProvider _sitemapCacheProvider; private readonly ISiteService _siteService; private readonly IUpdateModelAccessor _updateModelAccessor; private readonly INotifier _notifier; private readonly IHtmlLocalizer H; private readonly dynamic New; public SitemapIndexController( ISitemapHelperService sitemapService, IAuthorizationService authorizationService, ISitemapIdGenerator sitemapIdGenerator, ISitemapManager sitemapManager, ISitemapCacheProvider sitemapCacheProvider, ISiteService siteService, IUpdateModelAccessor updateModelAccessor, IShapeFactory shapeFactory, IHtmlLocalizer<AdminController> htmlLocalizer, INotifier notifier) { _sitemapService = sitemapService; _authorizationService = authorizationService; _sitemapIdGenerator = sitemapIdGenerator; _sitemapManager = sitemapManager; _sitemapCacheProvider = sitemapCacheProvider; _siteService = siteService; _updateModelAccessor = updateModelAccessor; _notifier = notifier; New = shapeFactory; H = htmlLocalizer; } public async Task<IActionResult> List(SitemapIndexListOptions options, PagerParameters pagerParameters) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps)) { return Forbid(); } var siteSettings = await _siteService.GetSiteSettingsAsync(); var pager = new Pager(pagerParameters, siteSettings.PageSize); // default options if (options == null) { options = new SitemapIndexListOptions(); } var sitemaps = (await _sitemapManager.ListSitemapsAsync()) .OfType<SitemapIndex>(); if (!string.IsNullOrWhiteSpace(options.Search)) { sitemaps = sitemaps.Where(smp => smp.Name.Contains(options.Search)); } var count = sitemaps.Count(); var results = sitemaps .Skip(pager.GetStartIndex()) .Take(pager.PageSize) .ToList(); // Maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Search", options.Search); var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData); var model = new ListSitemapIndexViewModel { SitemapIndexes = results.Select(sm => new SitemapIndexListEntry { SitemapId = sm.SitemapId, Name = sm.Name, Enabled = sm.Enabled }).ToList(), Options = options, Pager = pagerShape }; return View(model); } [HttpPost, ActionName("List")] [FormValueRequired("submit.Filter")] public ActionResult ListFilterPOST(ListSitemapIndexViewModel model) { return RedirectToAction("List", new RouteValueDictionary { { "Options.Search", model.Options.Search } }); } public async Task<IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps)) { return Forbid(); } var sitemaps = await _sitemapManager.ListSitemapsAsync(); var containableSitemaps = sitemaps .Where(s => s.GetType() != typeof(SitemapIndex)) .Select(s => new ContainableSitemapEntryViewModel { SitemapId = s.SitemapId, Name = s.Name, IsChecked = false }) .OrderBy(s => s.Name) .ToArray(); var model = new CreateSitemapIndexViewModel { ContainableSitemaps = containableSitemaps }; return View(model); } [HttpPost] public async Task<IActionResult> Create(CreateSitemapIndexViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps)) { return Forbid(); } var sitemap = new SitemapIndex { SitemapId = _sitemapIdGenerator.GenerateUniqueId() }; var indexSource = new SitemapIndexSource { Id = _sitemapIdGenerator.GenerateUniqueId() }; sitemap.SitemapSources.Add(indexSource); if (ModelState.IsValid) { await _sitemapService.ValidatePathAsync(model.Path, _updateModelAccessor.ModelUpdater); } // Path validation may invalidate model state. if (ModelState.IsValid) { sitemap.Name = model.Name; sitemap.Enabled = model.Enabled; sitemap.Path = model.Path; indexSource.ContainedSitemapIds = model.ContainableSitemaps .Where(m => m.IsChecked) .Select(m => m.SitemapId) .ToArray(); await _sitemapManager.SaveSitemapAsync(sitemap.SitemapId, sitemap); _notifier.Success(H["Sitemap index created successfully"]); return View(model); } // If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> Edit(string sitemapId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps)) { return Forbid(); } var sitemaps = await _sitemapManager.ListSitemapsAsync(); var sitemap = sitemaps.FirstOrDefault(s => s.SitemapId == sitemapId); var indexSource = sitemap.SitemapSources.FirstOrDefault() as SitemapIndexSource; var containableSitemaps = sitemaps .Where(s => s.GetType() != typeof(SitemapIndex)) .Select(s => new ContainableSitemapEntryViewModel { SitemapId = s.SitemapId, Name = s.Name, IsChecked = indexSource.ContainedSitemapIds.Any(id => id == s.SitemapId) }) .OrderBy(s => s.Name) .ToArray(); var model = new EditSitemapIndexViewModel { SitemapId = sitemap.SitemapId, Name = sitemap.Name, Enabled = sitemap.Enabled, Path = sitemap.Path, SitemapIndexSource = indexSource, ContainableSitemaps = containableSitemaps }; return View(model); } [HttpPost] public async Task<IActionResult> Edit(EditSitemapIndexViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps)) { return Forbid(); } var sitemap = await _sitemapManager.LoadSitemapAsync(model.SitemapId); if (sitemap == null) { return NotFound(); } var indexSource = sitemap.SitemapSources.FirstOrDefault() as SitemapIndexSource; model.SitemapIndexSource = indexSource; if (ModelState.IsValid) { await _sitemapService.ValidatePathAsync(model.Path, _updateModelAccessor.ModelUpdater, sitemap.SitemapId); } // Path validation may invalidate model state. if (ModelState.IsValid) { sitemap.Name = model.Name; sitemap.Enabled = model.Enabled; sitemap.Path = model.Path; indexSource.ContainedSitemapIds = model.ContainableSitemaps .Where(m => m.IsChecked) .Select(m => m.SitemapId) .ToArray(); await _sitemapManager.SaveSitemapAsync(sitemap.SitemapId, sitemap); // Always clear sitemap index cache when updated. await _sitemapCacheProvider.ClearSitemapCacheAsync(sitemap.Path); _notifier.Success(H["Sitemap index updated successfully"]); return View(model); } // If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> Delete(string sitemapId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps)) { return Forbid(); } var sitemap = await _sitemapManager.LoadSitemapAsync(sitemapId); if (sitemap == null) { return NotFound(); } // Clear sitemap cache when deleted. await _sitemapCacheProvider.ClearSitemapCacheAsync(sitemap.Path); await _sitemapManager.DeleteSitemapAsync(sitemapId); _notifier.Success(H["Sitemap index deleted successfully"]); return RedirectToAction(nameof(List)); } [HttpPost] public async Task<IActionResult> Toggle(string sitemapId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps)) { return Forbid(); } var sitemap = await _sitemapManager.LoadSitemapAsync(sitemapId); if (sitemap == null) { return NotFound(); } sitemap.Enabled = !sitemap.Enabled; await _sitemapManager.SaveSitemapAsync(sitemap.SitemapId, sitemap); await _sitemapCacheProvider.ClearSitemapCacheAsync(sitemap.Path); _notifier.Success(H["Sitemap index menu toggled successfully"]); return RedirectToAction(nameof(List)); } } }
// 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. namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM March 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; // // Calendar ID Values. This is used to get data from calendar.nlp. // The order of calendar ID means the order of data items in the table. // internal const int CAL_GREGORIAN = 1 ; // Gregorian (localized) calendar internal const int CAL_GREGORIAN_US = 2 ; // Gregorian (U.S.) calendar internal const int CAL_JAPAN = 3 ; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4 ; // Taiwan Era calendar internal const int CAL_KOREA = 5 ; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6 ; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7 ; // Thai calendar internal const int CAL_HEBREW = 8 ; // Hebrew (Lunar) calendar internal const int CAL_GREGORIAN_ME_FRENCH = 9 ; // Gregorian Middle East French calendar internal const int CAL_GREGORIAN_ARABIC = 10; // Gregorian Arabic calendar internal const int CAL_GREGORIAN_XLIT_ENGLISH = 11; // Gregorian Transliterated English calendar internal const int CAL_GREGORIAN_XLIT_FRENCH = 12; internal const int CAL_JULIAN = 13; internal const int CAL_JAPANESELUNISOLAR = 14; internal const int CAL_CHINESELUNISOLAR = 15; internal const int CAL_SAKA = 16; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_CHN = 17; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_KOR = 18; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_ROKUYOU = 19; // reserved to match Office but not implemented in our code internal const int CAL_KOREANLUNISOLAR = 20; internal const int CAL_TAIWANLUNISOLAR = 21; internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; internal int m_currentEraValue = -1; [System.Runtime.Serialization.OptionalField(VersionAdded = 2)] private bool m_isReadOnly = false; // The minimum supported DateTime range for the calendar. [System.Runtime.InteropServices.ComVisible(false)] public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. [System.Runtime.InteropServices.ComVisible(false)] public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual int ID { get { return (-1); } } /// // Return the Base calendar ID for calendars that didn't have defined data in calendarData // internal virtual int BaseCalendarID { get { return ID; } } // Returns the type of the calendar. // [System.Runtime.InteropServices.ComVisible(false)] public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public bool IsReadOnly { get { return (m_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of ICloneable. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual Object Clone() { object o = MemberwiseClone(); ((Calendar) o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState(true); return (clonedCalendar); } internal void VerifyWritable() { if (m_isReadOnly) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); } } internal void SetReadOnlyState(bool readOnly) { m_isReadOnly = readOnly; } /*=================================CurrentEraValue========================== **Action: This is used to convert CurretEra(0) to an appropriate era value. **Returns: **Arguments: **Exceptions: **Notes: ** The value is from calendar.nlp. ============================================================================*/ internal virtual int CurrentEraValue { get { // The following code assumes that the current era value can not be -1. if (m_currentEraValue == -1) { Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0"); m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (m_currentEraValue); } } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Argument_ResultCalendarRange"), minValue, maxValue)); } Contract.EndContractBlock(); } internal DateTime Add(DateTime time, double value, int scale) { // From ECMA CLI spec, Partition III, section 3.27: // // If overflow occurs converting a floating-point type to an integer, or if the floating-point value // being converted to an integer is a NaN, the value returned is unspecified. // // Based upon this, this method should be performing the comparison against the double // before attempting a cast. Otherwise, the result is undefined. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_AddValue")); } long millis = (long)tempMillis; long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return (Add(time, milliseconds, 1)); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays(DateTime time, int days) { return (Add(time, days, MillisPerDay)); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours(DateTime time, int hours) { return (Add(time, hours, MillisPerHour)); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes(DateTime time, int minutes) { return (Add(time, minutes, MillisPerMinute)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public abstract DateTime AddMonths(DateTime time, int months); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, MillisPerSecond); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks(DateTime time, int weeks) { return (AddDays(time, weeks * 7)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public abstract DateTime AddYears(DateTime time, int years); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth(DateTime time); // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public abstract DayOfWeek GetDayOfWeek(DateTime time); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear(DateTime time); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth(int year, int month) { return (GetDaysInMonth(year, month, CurrentEra)); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth(int year, int month, int era); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear(int year) { return (GetDaysInYear(year, CurrentEra)); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear(int year, int era); // Returns the era for the specified DateTime value. public abstract int GetEra(DateTime time); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour(DateTime time) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds(DateTime time) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute(DateTime time) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth(DateTime time); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear(int year) { return (GetMonthsInYear(year, CurrentEra)); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear(int year, int era); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond(DateTime time) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day/7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7; // Calculate the offset (how many days from the start of the year to the start of the week) int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7; if (offset == 0 || offset >= minimumDaysInFirstWeek) { // First of year falls in the first week of the year return 1; } int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7); // starting from first day of the year, how many days do you have to go forward // before getting to the first day of the week? int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7; int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek; if (daysInInitialPartialWeek >= minimumDaysInFirstWeek) { // If the offset is greater than the minimum Days in the first week, it means that // First of year is part of the first week of the year even though it is only a partial week // add another week day += 7; } return (day / 7 + 1); } // it would be nice to make this abstract but we can't since that would break previous implementations protected virtual int DaysInYearBeforeMinSupportedYear { get { return 365; } } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( nameof(firstDayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( nameof(rule), Environment.GetResourceString("ArgumentOutOfRange_Range", CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear(DateTime time); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay(int year, int month, int day) { return (IsLeapDay(year, month, day, CurrentEra)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public abstract bool IsLeapDay(int year, int month, int day, int era); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth(int year, int month) { return (IsLeapMonth(year, month, CurrentEra)); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public abstract bool IsLeapMonth(int year, int month, int era); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetLeapMonth(int year) { return (GetLeapMonth(year, CurrentEra)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) return 0; int monthsCount = GetMonthsInYear(year, era); for (int month=1; month<=monthsCount; month++) { if (IsLeapMonth(year, month, era)) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear(int year) { return (IsLeapYear(year, CurrentEra)); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public abstract bool IsLeapYear(int year, int era); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime)); } internal virtual bool IsValidMonth(int year, int month, int era) { return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era)); } internal virtual bool IsValidDay(int year, int month, int day, int era) { return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era)); } // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year < 100) { return ((TwoDigitYearMax/100 - ( year > TwoDigitYearMax % 100 ? 1 : 0))*100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } return TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } [System.Security.SecuritySafeCritical] // auto-generated internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue) { // Call nativeGetTwoDigitYearMax int twoDigitYearMax = CalendarData.nativeGetTwoDigitYearMax(CalID); if (twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Verse.Tools; namespace Verse { /// <summary> /// Utility class able to scan any type (using reflection) to automatically /// declare its fields to a printer or parser descriptor. /// </summary> public class Linker { #region Events /// <summary> /// Binding error occurred. /// </summary> public event Action<Type, string> Error; #endregion #region Methods / Public / Instance /// <summary> /// Scan entity type and declare fields using given parser descriptor. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="descriptor">Parser descriptor</param> /// <returns>True if binding succeeded, false otherwise</returns> public bool LinkParser<TEntity>(IParserDescriptor<TEntity> descriptor) { return this.LinkParser(descriptor, new Dictionary<Type, object>()); } /// <summary> /// Scan entity type and declare fields using given printer descriptor. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="descriptor">Printer descriptor</param> /// <returns>True if binding succeeded, false otherwise</returns> public bool LinkPrinter<TEntity>(IPrinterDescriptor<TEntity> descriptor) { return this.LinkPrinter(descriptor, new Dictionary<Type, object>()); } #endregion #region Methods / Public / Static /// <summary> /// Shorthand method to create a parser from given schema. This is /// equivalent to creating a new linker, use it on schema's parser /// descriptor and throw exception whenever error event is fired. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="schema">Entity schema</param> /// <returns>Entity parser</returns> public static IParser<TEntity> CreateParser<TEntity>(ISchema<TEntity> schema) { Linker linker; string message; Type type; linker = new Linker(); linker.Error += (t, m) => { message = string.Empty; type = t; }; message = "unknown"; type = typeof (TEntity); if (!linker.LinkParser(schema.ParserDescriptor)) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "can't link parser for type '{0}' (error with type '{1}', {2})", typeof (TEntity), type, message), "schema"); return schema.CreateParser(); } /// <summary> /// Shorthand method to create a printer from given schema. This is /// equivalent to creating a new linker, use it on schema's Printer /// descriptor and throw exception whenever error event is fired. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="schema">Entity schema</param> /// <returns>Entity Printer</returns> public static IPrinter<TEntity> CreatePrinter<TEntity>(ISchema<TEntity> schema) { Linker linker; string message; Type type; linker = new Linker(); linker.Error += (t, m) => { message = string.Empty; type = t; }; message = "unknown"; type = typeof (TEntity); if (!linker.LinkPrinter(schema.PrinterDescriptor)) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "can't link printer for type '{0}' (error with type '{1}', {2})", typeof (TEntity), type, message), "schema"); return schema.CreatePrinter(); } #endregion #region Methods / Private / Instance private bool LinkParser<T>(IParserDescriptor<T> descriptor, Dictionary<Type, object> parents) { Type[] arguments; object assign; TypeFilter filter; Type inner; ParameterInfo[] parameters; Type source; Type type; try { descriptor.IsValue(); return true; } catch (InvalidCastException) // FIXME: hack { } type = typeof (T); parents = new Dictionary<Type, object>(parents); parents[type] = descriptor; // Target type is an array if (type.IsArray) { inner = type.GetElementType(); assign = Linker.MakeAssignArray(inner); return this.LinkParserArray(descriptor, inner, assign, parents); } // Target type implements IEnumerable<> interface filter = new TypeFilter((t, c) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (IEnumerable<>)); foreach (Type iface in type.FindInterfaces(filter, null)) { arguments = iface.GetGenericArguments(); // Found interface, inner elements type is "inner" if (arguments.Length == 1) { inner = arguments[0]; // Search constructor compatible with IEnumerable<> foreach (ConstructorInfo constructor in type.GetConstructors()) { parameters = constructor.GetParameters(); if (parameters.Length != 1) continue; source = parameters[0].ParameterType; if (!source.IsGenericType || source.GetGenericTypeDefinition() != typeof (IEnumerable<>)) continue; arguments = source.GetGenericArguments(); if (arguments.Length != 1 || inner != arguments[0]) continue; assign = Linker.MakeAssignArray(constructor, inner); return this.LinkParserArray(descriptor, inner, assign, parents); } } } // Link public readable and writable instance properties foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (property.GetGetMethod() == null || property.GetSetMethod() == null || property.Attributes.HasFlag(PropertyAttributes.SpecialName)) continue; assign = Linker.MakeAssignField(property); if (!this.LinkParserField(descriptor, property.PropertyType, property.Name, assign, parents)) return false; } // Link public instance fields foreach (FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.Public)) { if (field.Attributes.HasFlag(FieldAttributes.SpecialName)) continue; assign = Linker.MakeAssignField(field); if (!this.LinkParserField(descriptor, field.FieldType, field.Name, assign, parents)) return false; } return true; } private bool LinkParserArray<TEntity>(IParserDescriptor<TEntity> descriptor, Type type, object assign, IDictionary<Type, object> parents) { object recurse; object result; if (parents.TryGetValue(type, out recurse)) { Resolver .Method<Func<IParserDescriptor<TEntity>, ParserAssign<TEntity, IEnumerable<object>>, IParserDescriptor<object>, IParserDescriptor<object>>>((d, a, p) => d.IsArray(a, p), null, new[] { type }) .Invoke(descriptor, new[] { assign, recurse }); } else { recurse = Resolver .Method<Func<IParserDescriptor<TEntity>, ParserAssign<TEntity, IEnumerable<object>>, IParserDescriptor<object>>>((d, a) => d.IsArray(a), null, new[] { type }) .Invoke(descriptor, new[] { assign }); result = Resolver .Method<Func<Linker, IParserDescriptor<object>, Dictionary<Type, object>, bool>>((l, d, p) => l.LinkParser(d, p), null, new[] { type }) .Invoke(this, new object[] { recurse, parents }); if (!(result is bool)) throw new InvalidOperationException("internal error"); if (!(bool)result) return false; } return true; } private bool LinkParserField<TEntity>(IParserDescriptor<TEntity> descriptor, Type type, string name, object assign, IDictionary<Type, object> parents) { object recurse; object result; if (parents.TryGetValue(type, out recurse)) { Resolver .Method<Func<IParserDescriptor<TEntity>, string, ParserAssign<TEntity, object>, IParserDescriptor<object>, IParserDescriptor<object>>>((d, n, a, p) => d.HasField(n, a, p), null, new[] { type }) .Invoke(descriptor, new object[] { name, assign, recurse }); } else { recurse = Resolver .Method<Func<IParserDescriptor<TEntity>, string, ParserAssign<TEntity, object>, IParserDescriptor<object>>>((d, n, a) => d.HasField(n, a), null, new[] { type }) .Invoke(descriptor, new object[] { name, assign }); result = Resolver .Method<Func<Linker, IParserDescriptor<object>, Dictionary<Type, object>, bool>>((l, d, p) => l.LinkParser(d, p), null, new[] { type }) .Invoke(this, new object[] { recurse, parents }); if (!(result is bool)) throw new InvalidOperationException("internal error"); if (!(bool)result) return false; } return true; } private bool LinkPrinter<T>(IPrinterDescriptor<T> descriptor, Dictionary<Type, object> parents) { object access; Type[] arguments; TypeFilter filter; Type inner; Type type; try { descriptor.IsValue(); return true; } catch (InvalidCastException) // FIXME: hack { } type = typeof (T); parents = new Dictionary<Type, object>(parents); parents[type] = descriptor; // Target type is an array if (type.IsArray) { inner = type.GetElementType(); access = Linker.MakeAccessArray(inner); return this.LinkPrinterArray(descriptor, inner, access, parents); } // Target type implements IEnumerable<> interface filter = new TypeFilter((t, c) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (IEnumerable<>)); foreach (Type iface in type.FindInterfaces(filter, null)) { arguments = iface.GetGenericArguments(); // Found interface, inner elements type is "inner" if (arguments.Length == 1) { inner = arguments[0]; access = Linker.MakeAccessArray(inner); return this.LinkPrinterArray(descriptor, inner, access, parents); } } // Link public readable and writable instance properties foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (property.GetGetMethod() == null || property.GetSetMethod() == null || property.Attributes.HasFlag(PropertyAttributes.SpecialName)) continue; access = Linker.MakeAccessField(property); if (!this.LinkPrinterField(descriptor, property.PropertyType, property.Name, access, parents)) return false; } // Link public instance fields foreach (FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.Public)) { if (field.Attributes.HasFlag(FieldAttributes.SpecialName)) continue; access = Linker.MakeAccessField(field); if (!this.LinkPrinterField(descriptor, field.FieldType, field.Name, access, parents)) return false; } return true; } private bool LinkPrinterArray<T>(IPrinterDescriptor<T> descriptor, Type type, object access, IDictionary<Type, object> parents) { object recurse; object result; if (parents.TryGetValue(type, out recurse)) { Resolver .Method<Func<IPrinterDescriptor<T>, Func<T, IEnumerable<object>>, IPrinterDescriptor<object>, IPrinterDescriptor<object>>>((d, a, p) => d.IsArray(a, p), null, new[] { type }) .Invoke(descriptor, new[] { access, recurse }); } else { recurse = Resolver .Method<Func<IPrinterDescriptor<T>, Func<T, IEnumerable<object>>, IPrinterDescriptor<object>>>((d, a) => d.IsArray(a), null, new[] { type }) .Invoke(descriptor, new[] { access }); result = Resolver .Method<Func<Linker, IPrinterDescriptor<object>, Dictionary<Type, object>, bool>>((l, d, p) => l.LinkPrinter(d, p), null, new[] { type }) .Invoke(this, new object[] { recurse, parents }); if (!(result is bool)) throw new InvalidOperationException("internal error"); if (!(bool)result) return false; } return true; } private bool LinkPrinterField<T>(IPrinterDescriptor<T> descriptor, Type type, string name, object access, IDictionary<Type, object> parents) { object recurse; object result; if (parents.TryGetValue(type, out recurse)) { Resolver .Method<Func<IPrinterDescriptor<T>, string, Func<T, object>, IPrinterDescriptor<object>, IPrinterDescriptor<object>>>((d, n, a, p) => d.HasField(n, a, p), null, new[] { type }) .Invoke(descriptor, new object[] { name, access, recurse }); } else { recurse = Resolver .Method<Func<IPrinterDescriptor<T>, string, Func<T, object>, IPrinterDescriptor<object>>>((d, n, a) => d.HasField(n, a), null, new[] { type }) .Invoke(descriptor, new object[] { name, access }); result = Resolver .Method<Func<Linker, IPrinterDescriptor<object>, Dictionary<Type, object>, bool>>((l, d, p) => l.LinkPrinter(d, p), null, new[] { type }) .Invoke(this, new object[] { recurse, parents }); if (!(result is bool)) throw new InvalidOperationException("internal error"); if (!(bool)result) return false; } return true; } private void OnError(Type type, string message) { Action<Type, string> error; error = this.Error; if (error != null) error(type, message); } #endregion #region Methods / Private / Static private static object MakeAccessArray(Type inner) { Type enumerable; ILGenerator generator; DynamicMethod method; enumerable = typeof (IEnumerable<>).MakeGenericType(inner); method = new DynamicMethod(string.Empty, enumerable, new[] { enumerable }, inner.Module, true); generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ret); return method.CreateDelegate(typeof (Func<,>).MakeGenericType(enumerable, enumerable)); } private static object MakeAccessField(FieldInfo field) { ILGenerator generator; DynamicMethod method; method = new DynamicMethod(string.Empty, field.FieldType, new[] { field.DeclaringType }, field.Module, true); generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ret); return method.CreateDelegate(typeof (Func<,>).MakeGenericType(field.DeclaringType, field.FieldType)); } private static object MakeAccessField(PropertyInfo property) { ILGenerator generator; DynamicMethod method; method = new DynamicMethod(string.Empty, property.PropertyType, new[] { property.DeclaringType }, property.Module, true); generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Call, property.GetGetMethod()); generator.Emit(OpCodes.Ret); return method.CreateDelegate(typeof (Func<,>).MakeGenericType(property.DeclaringType, property.PropertyType)); } /// <summary> /// Generate ParserAssign delegate from IEnumerable to any compatible /// object, using a constructor taking the IEnumerable as its argument. /// </summary> /// <param name="constructor">Compatible constructor</param> /// <param name="inner">Inner elements type</param> /// <returns>ParserAssign delegate</returns> private static object MakeAssignArray(ConstructorInfo constructor, Type inner) { Type enumerable; ILGenerator generator; DynamicMethod method; enumerable = typeof (IEnumerable<>).MakeGenericType(inner); method = new DynamicMethod(string.Empty, null, new[] { constructor.DeclaringType.MakeByRefType(), enumerable }, constructor.Module, true); generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Newobj, constructor); if (constructor.DeclaringType.IsValueType) generator.Emit(OpCodes.Stobj, constructor.DeclaringType); else generator.Emit(OpCodes.Stind_Ref); generator.Emit(OpCodes.Ret); return method.CreateDelegate(typeof (ParserAssign<,>).MakeGenericType(constructor.DeclaringType, enumerable)); } /// <summary> /// Generate ParserAssign delegate from IEnumerable to compatible array /// type, using Linq Enumerable.ToArray conversion. /// </summary> /// <param name="inner">Inner elements type</param> /// <returns>ParserAssign delegate</returns> private static object MakeAssignArray(Type inner) { MethodInfo converter; Type enumerable; ILGenerator generator; DynamicMethod method; converter = Resolver.Method<Func<IEnumerable<object>, object[]>>((e) => e.ToArray(), null, new[] { inner }); enumerable = typeof (IEnumerable<>).MakeGenericType(inner); method = new DynamicMethod(string.Empty, null, new[] { inner.MakeArrayType().MakeByRefType(), enumerable }, converter.Module, true); generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Call, converter); generator.Emit(OpCodes.Stind_Ref); generator.Emit(OpCodes.Ret); return method.CreateDelegate(typeof (ParserAssign<,>).MakeGenericType(inner.MakeArrayType(), enumerable)); } private static object MakeAssignField(FieldInfo field) { ILGenerator generator; DynamicMethod method; method = new DynamicMethod(string.Empty, null, new[] { field.DeclaringType.MakeByRefType(), field.FieldType }, field.Module, true); generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); if (!field.DeclaringType.IsValueType) generator.Emit(OpCodes.Ldind_Ref); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Stfld, field); generator.Emit(OpCodes.Ret); return method.CreateDelegate(typeof (ParserAssign<,>).MakeGenericType(field.DeclaringType, field.FieldType)); } private static object MakeAssignField(PropertyInfo property) { ILGenerator generator; DynamicMethod method; method = new DynamicMethod(string.Empty, null, new[] { property.DeclaringType.MakeByRefType(), property.PropertyType }, property.Module, true); generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); if (!property.DeclaringType.IsValueType) generator.Emit(OpCodes.Ldind_Ref); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Call, property.GetSetMethod()); generator.Emit(OpCodes.Ret); return method.CreateDelegate(typeof (ParserAssign<,>).MakeGenericType(property.DeclaringType, property.PropertyType)); } #endregion } }
/* * Copyright 2008 ZXing 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. */ using System; using System.Collections.Generic; using System.Text; using ZXing.Common; namespace ZXing.Datamatrix.Internal { /// <summary> /// <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes /// in one Data Matrix Code. This class decodes the bits back into text.</p> /// /// <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p> /// /// <author>bbrown@google.com (Brian Brown)</author> /// <author>Sean Owen</author> /// </summary> internal static class DecodedBitStreamParser { private enum Mode { PAD_ENCODE, // Not really a mode ASCII_ENCODE, C40_ENCODE, TEXT_ENCODE, ANSIX12_ENCODE, EDIFACT_ENCODE, BASE256_ENCODE } /// <summary> /// See ISO 16022:2006, Annex C Table C.1 /// The C40 Basic Character Set (*'s used for placeholders for the shift values) /// </summary> private static readonly char[] C40_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private static readonly char[] C40_SHIFT2_SET_CHARS = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' }; /// <summary> /// See ISO 16022:2006, Annex C Table C.2 /// The Text Basic Character Set (*'s used for placeholders for the shift values) /// </summary> private static readonly char[] TEXT_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; private static readonly char[] TEXT_SHIFT3_SET_CHARS = { '\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127 }; internal static DecoderResult decode(byte[] bytes) { BitSource bits = new BitSource(bytes); StringBuilder result = new StringBuilder(100); StringBuilder resultTrailer = new StringBuilder(0); List<byte[]> byteSegments = new List<byte[]>(1); Mode mode = Mode.ASCII_ENCODE; do { if (mode == Mode.ASCII_ENCODE) { if (!decodeAsciiSegment(bits, result, resultTrailer, out mode)) return null; } else { switch (mode) { case Mode.C40_ENCODE: if (!decodeC40Segment(bits, result)) return null; break; case Mode.TEXT_ENCODE: if (!decodeTextSegment(bits, result)) return null; break; case Mode.ANSIX12_ENCODE: if (!decodeAnsiX12Segment(bits, result)) return null; break; case Mode.EDIFACT_ENCODE: if (!decodeEdifactSegment(bits, result)) return null; break; case Mode.BASE256_ENCODE: if (!decodeBase256Segment(bits, result, byteSegments)) return null; break; default: return null; } mode = Mode.ASCII_ENCODE; } } while (mode != Mode.PAD_ENCODE && bits.available() > 0); if (resultTrailer.Length > 0) { result.Append(resultTrailer.ToString()); } return new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, null); } /// <summary> /// See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 /// </summary> private static bool decodeAsciiSegment(BitSource bits, StringBuilder result, StringBuilder resultTrailer, out Mode mode) { bool upperShift = false; mode = Mode.ASCII_ENCODE; do { int oneByte = bits.readBits(8); if (oneByte == 0) { return false; } else if (oneByte <= 128) { // ASCII data (ASCII value + 1) if (upperShift) { oneByte += 128; //upperShift = false; } result.Append((char)(oneByte - 1)); mode = Mode.ASCII_ENCODE; return true; } else if (oneByte == 129) { // Pad mode = Mode.PAD_ENCODE; return true; } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) int value = oneByte - 130; if (value < 10) { // padd with '0' for single digit values result.Append('0'); } result.Append(value); } else if (oneByte == 230) { // Latch to C40 encodation mode = Mode.C40_ENCODE; return true; } else if (oneByte == 231) { // Latch to Base 256 encodation mode = Mode.BASE256_ENCODE; return true; } else if (oneByte == 232) { // FNC1 result.Append((char)29); // translate as ASCII 29 } else if (oneByte == 233 || oneByte == 234) { // Structured Append, Reader Programming // Ignore these symbols for now //throw ReaderException.Instance; } else if (oneByte == 235) { // Upper Shift (shift to Extended ASCII) upperShift = true; } else if (oneByte == 236) { // 05 Macro result.Append("[)>\u001E05\u001D"); resultTrailer.Insert(0, "\u001E\u0004"); } else if (oneByte == 237) { // 06 Macro result.Append("[)>\u001E06\u001D"); resultTrailer.Insert(0, "\u001E\u0004"); } else if (oneByte == 238) { // Latch to ANSI X12 encodation mode = Mode.ANSIX12_ENCODE; return true; } else if (oneByte == 239) { // Latch to Text encodation mode = Mode.TEXT_ENCODE; return true; } else if (oneByte == 240) { // Latch to EDIFACT encodation mode = Mode.EDIFACT_ENCODE; return true; } else if (oneByte == 241) { // ECI Character // TODO(bbrown): I think we need to support ECI //throw ReaderException.Instance; // Ignore this symbol for now } else if (oneByte >= 242) { // Not to be used in ASCII encodation // ... but work around encoders that end with 254, latch back to ASCII if (oneByte != 254 || bits.available() != 0) { return false; } } } while (bits.available() > 0); mode = Mode.ASCII_ENCODE; return true; } /// <summary> /// See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 /// </summary> private static bool decodeC40Segment(BitSource bits, StringBuilder result) { // Three C40 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time bool upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return true; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return true; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else if (cValue < C40_BASIC_SET_CHARS.Length) { char c40char = C40_BASIC_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(c40char + 128)); upperShift = false; } else { result.Append(c40char); } } else { return false; } break; case 1: if (upperShift) { result.Append((char)(cValue + 128)); upperShift = false; } else { result.Append((char)cValue); } shift = 0; break; case 2: if (cValue < C40_SHIFT2_SET_CHARS.Length) { char c40char = C40_SHIFT2_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(c40char + 128)); upperShift = false; } else { result.Append(c40char); } } else if (cValue == 27) { // FNC1 result.Append((char)29); // translate as ASCII 29 } else if (cValue == 30) { // Upper Shift upperShift = true; } else { return false; } shift = 0; break; case 3: if (upperShift) { result.Append((char)(cValue + 224)); upperShift = false; } else { result.Append((char)(cValue + 96)); } shift = 0; break; default: return false; } } } while (bits.available() > 0); return true; } /// <summary> /// See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 /// </summary> private static bool decodeTextSegment(BitSource bits, StringBuilder result) { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time bool upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return true; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return true; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else if (cValue < TEXT_BASIC_SET_CHARS.Length) { char textChar = TEXT_BASIC_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(textChar + 128)); upperShift = false; } else { result.Append(textChar); } } else { return false; } break; case 1: if (upperShift) { result.Append((char)(cValue + 128)); upperShift = false; } else { result.Append((char)cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < C40_SHIFT2_SET_CHARS.Length) { char c40char = C40_SHIFT2_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(c40char + 128)); upperShift = false; } else { result.Append(c40char); } } else if (cValue == 27) { // FNC1 result.Append((char)29); // translate as ASCII 29 } else if (cValue == 30) { // Upper Shift upperShift = true; } else { return false; } shift = 0; break; case 3: if (cValue < TEXT_SHIFT3_SET_CHARS.Length) { char textChar = TEXT_SHIFT3_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(textChar + 128)); upperShift = false; } else { result.Append(textChar); } shift = 0; } else { return false; } break; default: return false; } } } while (bits.available() > 0); return true; } /// <summary> /// See ISO 16022:2006, 5.2.7 /// </summary> private static bool decodeAnsiX12Segment(BitSource bits, StringBuilder result) { // Three ANSI X12 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return true; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return true; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; if (cValue == 0) { // X12 segment terminator <CR> result.Append('\r'); } else if (cValue == 1) { // X12 segment separator * result.Append('*'); } else if (cValue == 2) { // X12 sub-element separator > result.Append('>'); } else if (cValue == 3) { // space result.Append(' '); } else if (cValue < 14) { // 0 - 9 result.Append((char)(cValue + 44)); } else if (cValue < 40) { // A - Z result.Append((char)(cValue + 51)); } else { return false; } } } while (bits.available() > 0); return true; } private static void parseTwoBytes(int firstByte, int secondByte, int[] result) { int fullBitValue = (firstByte << 8) + secondByte - 1; int temp = fullBitValue / 1600; result[0] = temp; fullBitValue -= temp * 1600; temp = fullBitValue / 40; result[1] = temp; result[2] = fullBitValue - temp * 40; } /// <summary> /// See ISO 16022:2006, 5.2.8 and Annex C Table C.3 /// </summary> private static bool decodeEdifactSegment(BitSource bits, StringBuilder result) { do { // If there is only two or less bytes left then it will be encoded as ASCII if (bits.available() <= 16) { return true; } for (int i = 0; i < 4; i++) { int edifactValue = bits.readBits(6); // Check for the unlatch character if (edifactValue == 0x1F) { // 011111 // Read rest of byte, which should be 0, and stop int bitsLeft = 8 - bits.BitOffset; if (bitsLeft != 8) { bits.readBits(bitsLeft); } return true; } if ((edifactValue & 0x20) == 0) { // no 1 in the leading (6th) bit edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value } result.Append((char)edifactValue); } } while (bits.available() > 0); return true; } /// <summary> /// See ISO 16022:2006, 5.2.9 and Annex B, B.2 /// </summary> private static bool decodeBase256Segment(BitSource bits, StringBuilder result, IList<byte[]> byteSegments) { // Figure out how long the Base 256 Segment is. int codewordPosition = 1 + bits.ByteOffset; // position is 1-indexed int d1 = unrandomize255State(bits.readBits(8), codewordPosition++); int count; if (d1 == 0) { // Read the remainder of the symbol count = bits.available() / 8; } else if (d1 < 250) { count = d1; } else { count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++); } // We're seeing NegativeArraySizeException errors from users. if (count < 0) { return false; } byte[] bytes = new byte[count]; for (int i = 0; i < count; i++) { // Have seen this particular error in the wild, such as at // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2 if (bits.available() < 8) { return false; } bytes[i] = (byte)unrandomize255State(bits.readBits(8), codewordPosition++); } byteSegments.Add(bytes); try { #if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || WINDOWS_PHONE80 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || WindowsCE) #if WindowsCE result.Append(Encoding.GetEncoding(1252).GetString(bytes, 0, bytes.Length)); #else result.Append(Encoding.GetEncoding("ISO-8859-1").GetString(bytes, 0, bytes.Length)); #endif #else result.Append(Encoding.GetEncoding("ISO-8859-1").GetString(bytes)); #endif } catch (Exception uee) { throw new InvalidOperationException("Platform does not support required encoding: " + uee); } return true; } /// <summary> /// See ISO 16022:2006, Annex B, B.2 /// </summary> private static int unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition) { int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; return tempVariable >= 0 ? tempVariable : tempVariable + 256; } } }
// 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 Roslyn.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Emit; using System.IO; namespace Microsoft.Cci { /// <summary> /// Represents a .NET assembly. /// </summary> internal interface IAssembly : IModule, IAssemblyReference { /// <summary> /// A list of the files that constitute the assembly. These are not the source language files that may have been /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well /// as any external resources. It corresponds to the File table of the .NET assembly file format. /// </summary> IEnumerable<IFileReference> GetFiles(EmitContext context); /// <summary> /// A set of bits and bit ranges representing properties of the assembly. The value of <see cref="Flags"/> can be set /// from source code via the AssemblyFlags assembly custom attribute. The interpretation of the property depends on the target platform. /// </summary> AssemblyFlags Flags { get; } /// <summary> /// The public part of the key used to encrypt the SHA1 hash over the persisted form of this assembly. Empty or null if not specified. /// This value is used by the loader to decrypt an encrypted hash value stored in the assembly, which it then compares with a freshly computed hash value /// in order to verify the integrity of the assembly. /// </summary> ImmutableArray<byte> PublicKey { get; } /// <summary> /// The contents of the AssemblySignatureKeyAttribute /// </summary> string SignatureKey { get; } AssemblyHashAlgorithm HashAlgorithm { get; } } /// <summary> /// A reference to a .NET assembly. /// </summary> internal interface IAssemblyReference : IModuleReference { AssemblyIdentity Identity { get; } Version AssemblyVersionPattern { get; } } /// <summary> /// An object that represents a .NET module. /// </summary> internal interface IModule : IUnit, IModuleReference { ModulePropertiesForSerialization Properties { get; } /// <summary> /// Used to distinguish which style to pick while writing native PDB information. /// </summary> /// <remarks> /// The PDB content for custom debug information is different between Visual Basic and CSharp. /// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where /// as VB only outputs namespace imports into the namespace scopes. /// C# defines forwards in that header, VB includes them into the scopes list. /// /// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module. /// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly. /// </remarks> bool GenerateVisualBasicStylePdb { get; } /// <summary> /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly /// followed by types forwarded to another assembly. /// </summary> ImmutableArray<ExportedType> GetExportedTypes(DiagnosticBag diagnostics); /// <summary> /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata /// with this assembly. /// </summary> IEnumerable<ICustomAttribute> AssemblyAttributes { get; } /// <summary> /// A list of objects representing persisted instances of pairs of security actions and sets of security permissions. /// These apply by default to every method reachable from the module. /// </summary> IEnumerable<SecurityAttribute> AssemblySecurityAttributes { get; } /// <summary> /// A list of the assemblies that are referenced by this module. /// </summary> IEnumerable<IAssemblyReference> GetAssemblyReferences(EmitContext context); /// <summary> /// A list of named byte sequences persisted with the assembly and used during execution, typically via .NET Framework helper classes. /// </summary> ImmutableArray<ManagedResource> GetResources(EmitContext context); /// <summary> /// CorLibrary assembly referenced by this module. /// </summary> IAssemblyReference GetCorLibrary(EmitContext context); /// <summary> /// The Assembly that contains this module. If this module is main module then this returns this. /// </summary> new IAssembly GetContainingAssembly(EmitContext context); /// <summary> /// The method that will be called to start execution of this executable module. /// </summary> IMethodReference PEEntryPoint { get; } IMethodReference DebugEntryPoint { get; } /// <summary> /// Returns zero or more strings used in the module. If the module is produced by reading in a CLR PE file, then this will be the contents /// of the user string heap. If the module is produced some other way, the method may return an empty enumeration or an enumeration that is a /// subset of the strings actually used in the module. The main purpose of this method is to provide a way to control the order of strings in a /// prefix of the user string heap when writing out a module as a PE file. /// </summary> IEnumerable<string> GetStrings(); /// <summary> /// Returns all top-level (not nested) types defined in the current module. /// </summary> IEnumerable<INamespaceTypeDefinition> GetTopLevelTypes(EmitContext context); /// <summary> /// The kind of metadata stored in this module. For example whether this module is an executable or a manifest resource file. /// </summary> OutputKind Kind { get; } /// <summary> /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata /// with this module. /// </summary> IEnumerable<ICustomAttribute> ModuleAttributes { get; } /// <summary> /// The name of the module. /// </summary> string ModuleName { get; } /// <summary> /// A list of the modules that are referenced by this module. /// </summary> IEnumerable<IModuleReference> ModuleReferences { get; } /// <summary> /// A list of named byte sequences persisted with the module and used during execution, typically via the Win32 API. /// A module will define Win32 resources rather than "managed" resources mainly to present metadata to legacy tools /// and not typically use the data in its own code. /// </summary> IEnumerable<IWin32Resource> Win32Resources { get; } /// <summary> /// An alternate form the Win32 resources may take. These represent the rsrc$01 and rsrc$02 section data and relocs /// from a COFF object file. /// </summary> ResourceSection Win32ResourceSection { get; } IAssembly AsAssembly { get; } ITypeReference GetPlatformType(PlatformType t, EmitContext context); bool IsPlatformType(ITypeReference typeRef, PlatformType t); IEnumerable<IReference> ReferencesInIL(out int count); /// <summary> /// Builds symbol definition to location map used for emitting token -> location info /// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj) /// </summary> MultiDictionary<DebugSourceDocument, DefinitionWithLocation> GetSymbolToLocationMap(); /// <summary> /// Assembly reference aliases (C# only). /// </summary> ImmutableArray<AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context); /// <summary> /// Linked assembly names to be stored to native PDB (VB only). /// </summary> IEnumerable<string> LinkedAssembliesDebugInfo { get; } /// <summary> /// Project level imports (VB only, TODO: C# scripts). /// </summary> ImmutableArray<UsedNamespaceOrType> GetImports(); /// <summary> /// Default namespace (VB only). /// </summary> string DefaultNamespace { get; } // An approximate number of method definitions that can // provide a basis for approximating the capacities of // various databases used during Emit. int HintNumberOfMethodDefinitions { get; } /// <summary> /// Number of debug documents in the module. /// Used to determine capacities of lists and indices when emitting debug info. /// </summary> int DebugDocumentCount { get; } Stream SourceLinkStream { get; } } internal struct DefinitionWithLocation { public readonly IDefinition Definition; public readonly uint StartLine; public readonly uint StartColumn; public readonly uint EndLine; public readonly uint EndColumn; public DefinitionWithLocation(IDefinition definition, int startLine, int startColumn, int endLine, int endColumn) { Debug.Assert(startLine >= 0); Debug.Assert(startColumn >= 0); Debug.Assert(endLine >= 0); Debug.Assert(endColumn >= 0); this.Definition = definition; this.StartLine = (uint)startLine; this.StartColumn = (uint)startColumn; this.EndLine = (uint)endLine; this.EndColumn = (uint)endColumn; } public override string ToString() { return string.Format( "{0} => start:{1}/{2}, end:{3}/{4}", this.Definition.ToString(), this.StartLine.ToString(), this.StartColumn.ToString(), this.EndLine.ToString(), this.EndColumn.ToString()); } } /// <summary> /// A reference to a .NET module. /// </summary> internal interface IModuleReference : IUnitReference { /// <summary> /// The Assembly that contains this module. May be null if the module is not part of an assembly. /// </summary> IAssemblyReference GetContainingAssembly(EmitContext context); } /// <summary> /// A unit of metadata stored as a single artifact and potentially produced and revised independently from other units. /// Examples of units include .NET assemblies and modules, as well C++ object files and compiled headers. /// </summary> internal interface IUnit : IUnitReference, IDefinition { } /// <summary> /// A reference to a instance of <see cref="IUnit"/>. /// </summary> internal interface IUnitReference : IReference, INamedEntity { } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Core.GroupManagementWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class ResourceOperationsExtensions { /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <param name='action'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceActionResult Action(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceName, string action, ResourceActionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ActionAsync(resourceGroupName, resourceProviderNamespace, fqResourceName, action, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <param name='action'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceActionResult> ActionAsync(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceName, string action, ResourceActionParameters parameters) { return operations.ActionAsync(resourceGroupName, resourceProviderNamespace, fqResourceName, action, parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceCreateOrUpdateResult CreateOrUpdate(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceName, ResourceCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).CreateOrUpdateAsync(resourceGroupName, resourceProviderNamespace, fqResourceName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceCreateOrUpdateResult> CreateOrUpdateAsync(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceName, ResourceCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, resourceProviderNamespace, fqResourceName, parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceName) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).DeleteAsync(resourceGroupName, resourceProviderNamespace, fqResourceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceName'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceName) { return operations.DeleteAsync(resourceGroupName, resourceProviderNamespace, fqResourceName, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceGetResult Get(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceId) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).GetAsync(resourceGroupName, resourceProviderNamespace, fqResourceId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceGetResult> GetAsync(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceId) { return operations.GetAsync(resourceGroupName, resourceProviderNamespace, fqResourceId, CancellationToken.None); } /// <summary> /// Gets the spend on the resource with the given resource Id. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceId'> /// Required. The resource Id. /// </param> /// <returns> /// The resource spend result /// </returns> public static ResourceGetSpendResult GetSpend(this IResourceOperations operations, string resourceId) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).GetSpendAsync(resourceId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the spend on the resource with the given resource Id. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceId'> /// Required. The resource Id. /// </param> /// <returns> /// The resource spend result /// </returns> public static Task<ResourceGetSpendResult> GetSpendAsync(this IResourceOperations operations, string resourceId) { return operations.GetSpendAsync(resourceId, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceType'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceListResult List(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceType) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListAsync(resourceGroupName, resourceProviderNamespace, fqResourceType); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceType'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceListResult> ListAsync(this IResourceOperations operations, string resourceGroupName, string resourceProviderNamespace, string fqResourceType) { return operations.ListAsync(resourceGroupName, resourceProviderNamespace, fqResourceType, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceListResult ListNext(this IResourceOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceListResult> ListNextAsync(this IResourceOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceType'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceListResult ListWithoutResourceGroup(this IResourceOperations operations, string resourceProviderNamespace, string fqResourceType) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListWithoutResourceGroupAsync(resourceProviderNamespace, fqResourceType); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Your documentation here. /// </param> /// <param name='fqResourceType'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceListResult> ListWithoutResourceGroupAsync(this IResourceOperations operations, string resourceProviderNamespace, string fqResourceType) { return operations.ListWithoutResourceGroupAsync(resourceProviderNamespace, fqResourceType, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.Serialization; namespace Stress.Data { public enum ErrorHandlingAction { // If you add an item here, remember to add it to all of the methods below DebugBreak, ThrowException } /// <summary> /// Static class containing methods to report errors. /// /// The StressTest executor will eat exceptions that are thrown and write them out to the console. In theory these should all be /// either harmless exceptions or product bugs, however at present there are a large number of test issues that will cause a flood /// of exceptions. Therefore if something actually bad happens (e.g. a known product bug is hit due to regression, or a major test /// programming error) this error would be easy to miss if it were reported just by throwing an exception. To solve this, we use /// this class for structured & consistent handling of errors. /// </summary> public static class DataStressErrors { private static void DebugBreak(string message, Exception exception) { // Print out the error before breaking to make debugging easier Console.WriteLine(message); if (exception != null) { Console.WriteLine(exception); } Debugger.Break(); } /// <summary> /// Reports that a product bug has been hit. The action that will be taken is configurable in the .config file. /// This can be used to check for regressions of known product bugs. /// </summary> /// <param name="description">A description of the product bug hit (e.g. title, bug number & database, more information)</param> /// <param name="exception">The exception that was thrown that indicates a product bug, or null if the product bug was detected without /// having thrown an exception</param> /// <returns>An exception that the caller should throw.</returns> public static Exception ProductError(string description, Exception exception = null) { switch (DataStressSettings.Instance.ActionOnProductError) { case ErrorHandlingAction.DebugBreak: DebugBreak("Hit product error: " + description, exception); return new ProductErrorException(description, exception); case ErrorHandlingAction.ThrowException: return new ProductErrorException(description, exception); default: throw UnhandledCaseError(DataStressSettings.Instance.ActionOnProductError); } } /// <summary> /// Reports that a non-fatal test error has been hit. The action that will be taken is configurable in the .config file. /// This should be used for test errors that do not prevent the test from running. /// </summary> /// <param name="description">A description of the error</param> /// <param name="exception">The exception that was thrown that indicates an error, or null if the error was detected without /// <returns>An exception that the caller should throw.</returns> public static Exception TestError(string description, Exception exception = null) { switch (DataStressSettings.Instance.ActionOnTestError) { case ErrorHandlingAction.DebugBreak: DebugBreak("Hit test error: " + description, exception); return new TestErrorException(description, exception); case ErrorHandlingAction.ThrowException: return new TestErrorException(description, exception); default: throw UnhandledCaseError(DataStressSettings.Instance.ActionOnTestError); } } /// <summary> /// Reports that a programming error in the test code has occurred. The action that will be taken is configurable in the .config file. /// This must strictly be used to report programming errors. It should not be in any way possible to see one of these errors unless /// you make an incorrect change to the code, for example having an unhandled case in a switch statement. /// </summary> /// <param name="description">A description of the error</param> /// <param name="exception">The exception that was thrown that indicates an error, or null if the error was detected without /// having thrown an exception</param> /// <returns>An exception that the caller should throw.</returns> private static Exception ProgrammingError(string description, Exception exception = null) { switch (DataStressSettings.Instance.ActionOnProgrammingError) { case ErrorHandlingAction.DebugBreak: DebugBreak("Hit programming error: " + description, exception); return new ProgrammingErrorException(description, exception); case ErrorHandlingAction.ThrowException: return new ProgrammingErrorException(description, exception); default: // If we are here then it's a programming error, but calling UnhandledCaseError here would cause an inifite loop. goto case ErrorHandlingAction.DebugBreak; } } /// <summary> /// Reports that an unhandled case in a switch statement in the test code has occurred. The action that will be taken is configurable /// as a programming error in the .config file. It should not be in any way possible to see one of these errors unless /// you make an incorrect change to the test code, for example having an unhandled case in a switch statement. /// </summary> /// <param name="unhandledValue">The value that was not handled in the switch statement</param> /// <returns>An exception that the caller should throw.</returns> public static Exception UnhandledCaseError<T>(T unhandledValue) { return ProgrammingError("Unhandled case in switch statement: " + unhandledValue); } /// <summary> /// Asserts that a condition is true. If the condition is false then throws a ProgrammingError. /// This must strictly be used to report programming errors. It should not be in any way possible to see one of these errors unless /// you make an incorrect change to the code, for example having an unhandled case in a switch statement. /// </summary> /// <param name="condition">A condition to assert</param> /// <param name="description">A description of the error</param> /// <exception cref="ProgrammingErrorException">if the condition is false</exception> public static void Assert(bool condition, string description) { if (!condition) { throw ProgrammingError(description); } } /// <summary> /// Reports that a fatal error has happened. This is an error that completely prevents the test from continuing, /// for example a setup failure. Ordinary programming errors should not be handled by this method. /// </summary> /// <param name="description">A description of the error</param> /// <returns>An exception that the caller should throw.</returns> public static Exception FatalError(string description) { Console.WriteLine("Fatal test error: {0}", description); Debugger.Break(); // Give the user a chance to debug Environment.FailFast("Fatal error. Exit."); return new Exception(); // Caller should throw this to indicate to the compiler that any code after the call is unreachable } #region Exception types // These exception types are provided so that they can be easily found in logs, i.e. just do a text search in the console // output log for "ProductErrorException" private class ProductErrorException : Exception { public ProductErrorException() : base() { } public ProductErrorException(string message) : base(message) { } public ProductErrorException(string message, Exception innerException) : base(message, innerException) { } } private class ProgrammingErrorException : Exception { public ProgrammingErrorException() : base() { } public ProgrammingErrorException(string message) : base(message) { } public ProgrammingErrorException(string message, Exception innerException) : base(message, innerException) { } } private class TestErrorException : Exception { public TestErrorException() : base() { } public TestErrorException(string message) : base(message) { } public TestErrorException(string message, Exception innerException) : base(message, innerException) { } } #endregion } }
// ---------------------------------------------------------------------------------- // // 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 System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using Commands.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.Table; using MS.Test.Common.MsTestLib; using StorageTestLib; using StorageBlob = Microsoft.WindowsAzure.Storage.Blob; namespace Commands.Storage.ScenarioTest.BVT { /// <summary> /// this class contain all the bvt cases for the full functional storage context such as local/connectionstring/namekey, anonymous and sas token are excluded. /// </summary> //TODO use the TestBase as the base class internal class CLICommonBVT { private static CloudBlobHelper CommonBlobHelper; private static CloudStorageAccount CommonStorageAccount; private static string CommonBlockFilePath; private static string CommonPageFilePath; //env connection string private static string SavedEnvString; public static string EnvKey; /// <summary> /// the storage account which is used to set up the unit tests. /// </summary> protected static CloudStorageAccount SetUpStorageAccount { get { return CommonStorageAccount; } set { CommonStorageAccount = value; } } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes public CLICommonBVT() { } //TODO remove it if it's useless public CLICommonBVT(CloudStorageAccount StorageAccount, TestContext testContext) { CommonStorageAccount = StorageAccount; testContextInstance = testContext; //init the blob helper for blob related operations CommonBlobHelper = new CloudBlobHelper(CommonStorageAccount); GenerateBvtTempFiles(); } /// <summary> /// Init test resources for bvt class /// </summary> /// <param name="testContext">TestContext object</param> [ClassInitialize()] public static void CLICommonBVTInitialize(TestContext testContext) { Test.Info(string.Format("{0} Class Initialize", testContext.FullyQualifiedTestClassName)); Test.FullClassName = testContext.FullyQualifiedTestClassName; EnvKey = Test.Data.Get("EnvContextKey"); SaveAndCleanSubScriptionAndEnvConnectionString(); //init the blob helper for blob related operations CommonBlobHelper = new CloudBlobHelper(CommonStorageAccount); //Clean Storage Context Test.Info("Clean storage context in PowerShell"); PowerShellAgent.CleanStorageContext(); // import module string moduleFilePath = Test.Data.Get("ModuleFilePath"); PowerShellAgent.ImportModule(moduleFilePath); GenerateBvtTempFiles(); } /// <summary> /// Save azure subscription and env connection string. So the current settings can't impact our tests. /// </summary> //TODO move to TestBase public static void SaveAndCleanSubScriptionAndEnvConnectionString() { Test.Info("Clean Azure Subscription and save env connection string"); //can't restore the azure subscription files PowerShellAgent.RemoveAzureSubscriptionIfExists(); //set env connection string //TODO A little bit trivial, move to CLITestBase class if (string.IsNullOrEmpty(EnvKey)) { EnvKey = Test.Data.Get("EnvContextKey"); } SavedEnvString = System.Environment.GetEnvironmentVariable(EnvKey); System.Environment.SetEnvironmentVariable(EnvKey, string.Empty); } /// <summary> /// Restore the previous subscription and env connection string before testing. /// </summary> public static void RestoreSubScriptionAndEnvConnectionString() { Test.Info("Restore env connection string and skip restore subscription"); System.Environment.SetEnvironmentVariable(EnvKey, SavedEnvString); } /// <summary> /// Generate temp files /// </summary> private static void GenerateBvtTempFiles() { CommonBlockFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName()); CommonPageFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName()); FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(CommonBlockFilePath)); FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(CommonPageFilePath)); // Generate block file and page file which are used for uploading Helper.GenerateMediumFile(CommonBlockFilePath, 1); Helper.GenerateMediumFile(CommonPageFilePath, 1); } /// <summary> /// Clean up test resources of bvt class /// </summary> [ClassCleanup()] public static void CLICommonBVTCleanup() { Test.Info(string.Format("BVT Test Class Cleanup")); RestoreSubScriptionAndEnvConnectionString(); } /// <summary> /// init test resources for one single unit test. /// </summary> [TestInitialize()] public void UnitTestInitialize() { Trace.WriteLine("Unit Test Initialize"); Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName); } /// <summary> /// clean up the test resources for one single unit test. /// </summary> [TestCleanup()] public void UnitTestCleanup() { Trace.WriteLine("Unit Test Cleanup"); Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName); } #endregion /// <summary> /// BVT case : for New-AzureStorageContainer /// </summary> [TestMethod] [TestCategory(Tag.BVT)] [TestCategory(PsTag.FastEnv)] public void NewContainerTest() { NewContainerTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Get-AzureStorageContainer /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void GetContainerTest() { GetContainerTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Remove-AzureStorageContainer /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void RemoveContainerTest() { RemoveContainerTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Set-AzureStorageContainerACL /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void SetContainerACLTest() { SetContainerACLTest(new PowerShellAgent()); } /// <summary> /// BVT case : for New-AzureStorageTable /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void NewTableTest() { NewTableTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Get-AzureStorageTable /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void GetTableTest() { GetTableTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Remove-AzureStorageTable /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void RemoveTableTest() { RemoveTableTest(new PowerShellAgent()); } /// <summary> /// BVT case : for New-AzureStorageQueue /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void NewQueueTest() { NewQueueTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Get-AzureStorageQueue /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void GetQueueTest() { GetQueueTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Remove-AzureStorageQueue /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void RemoveQueueTest() { RemoveQueueTest(new PowerShellAgent()); } /// <summary> /// BVT case : for Set-AzureStorageBlobContent /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void UploadBlobTest() { UploadBlobTest(new PowerShellAgent(), CommonBlockFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob); UploadBlobTest(new PowerShellAgent(), CommonPageFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob); } /// <summary> /// BVT case : for Get-AzureStorageBlob /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void GetBlobTest() { GetBlobTest(new PowerShellAgent(), CommonBlockFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob); GetBlobTest(new PowerShellAgent(), CommonPageFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob); } /// <summary> /// BVT case : for Get-AzureStorageBlobContent /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void DownloadBlobTest() { string downloadDirPath = Test.Data.Get("DownloadDir"); FileUtil.CreateDirIfNotExits(downloadDirPath); DownloadBlobTest(new PowerShellAgent(), CommonBlockFilePath, downloadDirPath, Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob); DownloadBlobTest(new PowerShellAgent(), CommonPageFilePath, downloadDirPath, Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob); } /// <summary> /// BVT case : for Remove-AzureStorageBlob /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void RemoveBlobTest() { RemoveBlobTest(new PowerShellAgent(), CommonBlockFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob); RemoveBlobTest(new PowerShellAgent(), CommonPageFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob); } /// <summary> /// BVT case : for Start-AzureStorageBlobCopy /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void StartCopyBlobUsingName() { StartCopyBlobTest(new PowerShellAgent(), false); } /// <summary> /// BVT case : for Start-AzureStorageBlobCopy /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void StartCopyBlobUsingUri() { StartCopyBlobTest(new PowerShellAgent(), true); } /// <summary> /// BVT case : for Get-AzureStorageBlobCopyState /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void GetBlobCopyStateTest() { CloudBlobUtil blobUtil = new CloudBlobUtil(CommonStorageAccount); blobUtil.SetupTestContainerAndBlob(); StorageBlob.ICloudBlob destBlob = CopyBlobAndWaitForComplete(blobUtil); try { Test.Assert(destBlob.CopyState.Status == StorageBlob.CopyStatus.Success, String.Format("The blob copy using storage client should be success, actually it's {0}", destBlob.CopyState.Status)); PowerShellAgent agent = new PowerShellAgent(); Test.Assert(agent.GetAzureStorageBlobCopyState(blobUtil.ContainerName, destBlob.Name, false), "Get copy state should be success"); int expectedStateCount = 1; Test.Assert(agent.Output.Count == expectedStateCount, String.Format("Expected to get {0} copy state, actually it's {1}", expectedStateCount, agent.Output.Count)); StorageBlob.CopyStatus copyStatus = (StorageBlob.CopyStatus)agent.Output[0]["Status"]; Test.Assert(copyStatus == StorageBlob.CopyStatus.Success, String.Format("The blob copy should be success, actually it's {0}", copyStatus)); Uri sourceUri = (Uri)agent.Output[0]["Source"]; string expectedUri = CloudBlobUtil.ConvertCopySourceUri(blobUtil.Blob.Uri.ToString()); Test.Assert(sourceUri.ToString() == expectedUri, String.Format("Expected source uri is {0}, actully it's {1}", expectedUri, sourceUri.ToString())); Test.Assert(!agent.GetAzureStorageBlobCopyState(blobUtil.ContainerName, blobUtil.BlobName, false), "Get copy state should be fail since the specified blob don't have any copy operation"); Test.Assert(agent.ErrorMessages.Count > 0, "Should return error message"); string errorMessage = "Can not find copy task on specified blob"; Test.Assert(agent.ErrorMessages[0].StartsWith(errorMessage), String.Format("Error message should start with {0}, and actually it's {1}", errorMessage, agent.ErrorMessages[0])); } finally { blobUtil.CleanupTestContainerAndBlob(); } } /// <summary> /// BVT case : for Stop-AzureStorageBlobCopy /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void StopCopyBlobTest() { CloudBlobUtil blobUtil = new CloudBlobUtil(CommonStorageAccount); blobUtil.SetupTestContainerAndBlob(); StorageBlob.ICloudBlob destBlob = CopyBlobAndWaitForComplete(blobUtil); try { PowerShellAgent agent = new PowerShellAgent(); string copyId = Guid.NewGuid().ToString(); Test.Assert(!agent.StopAzureStorageBlobCopy(blobUtil.ContainerName, blobUtil.BlobName, copyId, true), "Stop copy operation should be fail since the specified blob don't have any copy operation"); Test.Assert(agent.ErrorMessages.Count > 0, "Should return error message"); string errorMessage = String.Format("Can not find copy task on specified blob '{0}' in container '{1}'", blobUtil.BlobName, blobUtil.ContainerName); Test.Assert(agent.ErrorMessages[0].IndexOf(errorMessage) != -1, String.Format("Error message should contain {0}, and actually it's {1}", errorMessage, agent.ErrorMessages[0])); errorMessage = "There is currently no pending copy operation."; Test.Assert(!agent.StopAzureStorageBlobCopy(blobUtil.ContainerName, destBlob.Name, copyId, true), "Stop copy operation should be fail since the specified copy operation has finished"); Test.Assert(agent.ErrorMessages.Count > 0, "Should return error message"); Test.Assert(agent.ErrorMessages[0].IndexOf(errorMessage) != -1, String.Format("Error message should contain {0}, and actually it's {1}", errorMessage, agent.ErrorMessages[0])); } finally { blobUtil.CleanupTestContainerAndBlob(); } } internal StorageBlob.ICloudBlob CopyBlobAndWaitForComplete(CloudBlobUtil blobUtil) { string destBlobName = Utility.GenNameString("copystate"); StorageBlob.ICloudBlob destBlob = default(StorageBlob.ICloudBlob); Test.Info("Copy Blob using storage client"); if (blobUtil.Blob.BlobType == StorageBlob.BlobType.BlockBlob) { StorageBlob.CloudBlockBlob blockBlob = blobUtil.Container.GetBlockBlobReference(destBlobName); blockBlob.StartCopyFromBlob((StorageBlob.CloudBlockBlob)blobUtil.Blob); destBlob = blockBlob; } else { StorageBlob.CloudPageBlob pageBlob = blobUtil.Container.GetPageBlobReference(destBlobName); pageBlob.StartCopyFromBlob((StorageBlob.CloudPageBlob)blobUtil.Blob); destBlob = pageBlob; } CloudBlobUtil.WaitForCopyOperationComplete(destBlob); Test.Assert(destBlob.CopyState.Status == StorageBlob.CopyStatus.Success, String.Format("The blob copy using storage client should be success, actually it's {0}", destBlob.CopyState.Status)); return destBlob; } internal void StartCopyBlobTest(Agent agent, bool useUri) { CloudBlobUtil blobUtil = new CloudBlobUtil(CommonStorageAccount); blobUtil.SetupTestContainerAndBlob(); string copiedName = Utility.GenNameString("copied"); if(useUri) { //Set the blob permission, so the copy task could directly copy by uri StorageBlob.BlobContainerPermissions permission = new StorageBlob.BlobContainerPermissions(); permission.PublicAccess = StorageBlob.BlobContainerPublicAccessType.Blob; blobUtil.Container.SetPermissions(permission); } try { if(useUri) { Test.Assert(agent.StartAzureStorageBlobCopy(blobUtil.Blob.Uri.ToString(), blobUtil.ContainerName, copiedName, PowerShellAgent.Context), Utility.GenComparisonData("Start copy blob using source uri", true)); } else { Test.Assert(agent.StartAzureStorageBlobCopy(blobUtil.ContainerName, blobUtil.BlobName, blobUtil.ContainerName, copiedName), Utility.GenComparisonData("Start copy blob using blob name", true)); } Test.Info("Get destination blob in copy task"); StorageBlob.ICloudBlob blob = blobUtil.Container.GetBlobReferenceFromServer(copiedName); Test.Assert(blob != null, "Destination blob should exist after start copy. If not, please check it's a test issue or dev issue."); string sourceUri = CloudBlobUtil.ConvertCopySourceUri(blobUtil.Blob.Uri.ToString()); Test.Assert(blob.BlobType == blobUtil.Blob.BlobType, String.Format("The destination blob type should be {0}, actually {1}.", blobUtil.Blob.BlobType, blob.BlobType)); Test.Assert(blob.CopyState.Source.ToString().StartsWith(sourceUri), String.Format("The source of destination blob should start with {0}, and actually it's {1}", sourceUri, blob.CopyState.Source.ToString())); } finally { blobUtil.CleanupTestContainerAndBlob(); } } internal void NewContainerTest(Agent agent) { string NEW_CONTAINER_NAME = Utility.GenNameString("astoria-"); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Container, NEW_CONTAINER_NAME); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>{dic}; // delete container if it exists StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.DeleteIfExists(); try { //--------------New operation-------------- Test.Assert(agent.NewAzureStorageContainer(NEW_CONTAINER_NAME), Utility.GenComparisonData("NewAzureStorageContainer", true)); // Verification for returned values CloudBlobUtil.PackContainerCompareData(container, dic); agent.OutputValidation(comp); Test.Assert(container.Exists(), "container {0} should exist!", NEW_CONTAINER_NAME); } finally { // clean up container.DeleteIfExists(); } } internal void GetContainerTest(Agent agent) { string NEW_CONTAINER_NAME = Utility.GenNameString("astoria-"); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Container, NEW_CONTAINER_NAME); // create container if it does not exist StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.CreateIfNotExists(); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>> { dic }; try { //--------------Get operation-------------- Test.Assert(agent.GetAzureStorageContainer(NEW_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageContainer", true)); // Verification for returned values container.FetchAttributes(); dic.Add("CloudBlobContainer", container); CloudBlobUtil.PackContainerCompareData(container, dic); agent.OutputValidation(comp); } finally { // clean up container.DeleteIfExists(); } } internal void RemoveContainerTest(Agent agent) { string NEW_CONTAINER_NAME = Utility.GenNameString("astoria-"); // create container if it does not exist StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.CreateIfNotExists(); try { //--------------Remove operation-------------- Test.Assert(agent.RemoveAzureStorageContainer(NEW_CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageContainer", true)); Test.Assert(!container.Exists(), "container {0} should not exist!", NEW_CONTAINER_NAME); } finally { // clean up container.DeleteIfExists(); } } internal void SetContainerACLTest(Agent agent) { string NEW_CONTAINER_NAME = Utility.GenNameString("astoria-"); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Container, NEW_CONTAINER_NAME); comp.Add(dic); // create container if it does not exist StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.CreateIfNotExists(); try { StorageBlob.BlobContainerPublicAccessType[] accessTypes = new StorageBlob.BlobContainerPublicAccessType[] { StorageBlob.BlobContainerPublicAccessType.Blob, StorageBlob.BlobContainerPublicAccessType.Container, StorageBlob.BlobContainerPublicAccessType.Off }; // set PublicAccess as one value respetively foreach (var accessType in accessTypes) { //--------------Set operation-------------- Test.Assert(agent.SetAzureStorageContainerACL(NEW_CONTAINER_NAME, accessType), "SetAzureStorageContainerACL operation should succeed"); // Verification for returned values dic["PublicAccess"] = accessType; CloudBlobUtil.PackContainerCompareData(container, dic); agent.OutputValidation(comp); Test.Assert(container.GetPermissions().PublicAccess == accessType, "PublicAccess should be equal: {0} = {1}", container.GetPermissions().PublicAccess, accessType); } } finally { // clean up container.DeleteIfExists(); } } internal void NewTableTest(Agent agent) { string NEW_TABLE_NAME = Utility.GenNameString("Washington"); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Table, NEW_TABLE_NAME); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>> { dic }; // delete table if it exists CloudTable table = CommonStorageAccount.CreateCloudTableClient().GetTableReference(NEW_TABLE_NAME); table.DeleteIfExists(); try { //--------------New operation-------------- Test.Assert(agent.NewAzureStorageTable(NEW_TABLE_NAME), Utility.GenComparisonData("NewAzureStorageTable", true)); // Verification for returned values dic.Add("CloudTable", table); agent.OutputValidation(comp); Test.Assert(table.Exists(), "table {0} should exist!", NEW_TABLE_NAME); } finally { table.DeleteIfExists(); } } internal void GetTableTest(Agent agent) { string NEW_TABLE_NAME = Utility.GenNameString("Washington"); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Table, NEW_TABLE_NAME); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>> {dic}; // create table if it does not exist CloudTable table = CommonStorageAccount.CreateCloudTableClient().GetTableReference(NEW_TABLE_NAME); table.CreateIfNotExists(); dic.Add("CloudTable", table); try { //--------------Get operation-------------- Test.Assert(agent.GetAzureStorageTable(NEW_TABLE_NAME), Utility.GenComparisonData("GetAzureStorageTable", true)); // Verification for returned values agent.OutputValidation(comp); } finally { // clean up table.DeleteIfExists(); } } internal void RemoveTableTest(Agent agent) { string NEW_TABLE_NAME = Utility.GenNameString("Washington"); // create table if it does not exist CloudTable table = CommonStorageAccount.CreateCloudTableClient().GetTableReference(NEW_TABLE_NAME); table.CreateIfNotExists(); try { //--------------Remove operation-------------- Test.Assert(agent.RemoveAzureStorageTable(NEW_TABLE_NAME), Utility.GenComparisonData("RemoveAzureStorageTable", true)); Test.Assert(!table.Exists(), "queue {0} should not exist!", NEW_TABLE_NAME); } finally { // clean up table.DeleteIfExists(); } } internal void NewQueueTest(Agent agent) { string NEW_QUEUE_NAME = Utility.GenNameString("redmond-"); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Queue, NEW_QUEUE_NAME); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>{ dic }; CloudQueue queue = CommonStorageAccount.CreateCloudQueueClient().GetQueueReference(NEW_QUEUE_NAME); // delete queue if it exists queue.DeleteIfExists(); try { //--------------New operation-------------- Test.Assert(agent.NewAzureStorageQueue(NEW_QUEUE_NAME), Utility.GenComparisonData("NewAzureStorageQueue", true)); dic.Add("CloudQueue", queue); dic["ApproximateMessageCount"] = null; // Verification for returned values agent.OutputValidation(comp); Test.Assert(queue.Exists(), "queue {0} should exist!", NEW_QUEUE_NAME); } finally { // clean up queue.DeleteIfExists(); } } internal void GetQueueTest(Agent agent) { string NEW_QUEUE_NAME = Utility.GenNameString("redmond-"); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Queue, NEW_QUEUE_NAME); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>> { dic }; CloudQueue queue = CommonStorageAccount.CreateCloudQueueClient().GetQueueReference(NEW_QUEUE_NAME); // create queue if it does exist queue.CreateIfNotExists(); dic.Add("CloudQueue", queue); try { //--------------Get operation-------------- Test.Assert(agent.GetAzureStorageQueue(NEW_QUEUE_NAME), Utility.GenComparisonData("GetAzureStorageQueue", true)); // Verification for returned values queue.FetchAttributes(); agent.OutputValidation(comp); } finally { // clean up queue.DeleteIfExists(); } } internal void RemoveQueueTest(Agent agent) { string NEW_QUEUE_NAME = Utility.GenNameString("redmond-"); // create queue if it does exist CloudQueue queue = CommonStorageAccount.CreateCloudQueueClient().GetQueueReference(NEW_QUEUE_NAME); queue.CreateIfNotExists(); try { //--------------Remove operation-------------- Test.Assert(agent.RemoveAzureStorageQueue(NEW_QUEUE_NAME), Utility.GenComparisonData("RemoveAzureStorageQueue", true)); Test.Assert(!queue.Exists(), "queue {0} should not exist!", NEW_QUEUE_NAME); } finally { // clean up queue.DeleteIfExists(); } } /// <summary> /// Parameters: /// Block: /// True for BlockBlob, false for PageBlob /// </summary> internal void UploadBlobTest(Agent agent, string UploadFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType Type) { string NEW_CONTAINER_NAME = Utility.GenNameString("upload-"); string blobName = Path.GetFileName(UploadFilePath); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Blob, blobName); dic["BlobType"] = Type; comp.Add(dic); // create the container StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.CreateIfNotExists(); try { //--------------Upload operation-------------- Test.Assert(agent.SetAzureStorageBlobContent(UploadFilePath, NEW_CONTAINER_NAME, Type), Utility.GenComparisonData("SendAzureStorageBlob", true)); StorageBlob.ICloudBlob blob = CommonBlobHelper.QueryBlob(NEW_CONTAINER_NAME, blobName); CloudBlobUtil.PackBlobCompareData(blob, dic); // Verification for returned values agent.OutputValidation(comp); Test.Assert(blob != null && blob.Exists(), "blob " + blobName + " should exist!"); } finally { // cleanup container.DeleteIfExists(); } } /// <summary> /// Parameters: /// Block: /// True for BlockBlob, false for PageBlob /// </summary> internal void GetBlobTest(Agent agent, string UploadFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType Type) { string NEW_CONTAINER_NAME = Utility.GenNameString("upload-"); string blobName = Path.GetFileName(UploadFilePath); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Blob, blobName); dic["BlobType"] = Type; comp.Add(dic); // create the container StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.CreateIfNotExists(); try { bool bSuccess = false; // upload the blob file if (Type == Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob) bSuccess = CommonBlobHelper.UploadFileToBlockBlob(NEW_CONTAINER_NAME, blobName, UploadFilePath); else if (Type == Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob) bSuccess = CommonBlobHelper.UploadFileToPageBlob(NEW_CONTAINER_NAME, blobName, UploadFilePath); Test.Assert(bSuccess, "upload file {0} to container {1} should succeed", UploadFilePath, NEW_CONTAINER_NAME); //--------------Get operation-------------- Test.Assert(agent.GetAzureStorageBlob(blobName, NEW_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageBlob", true)); // Verification for returned values // get blob object using XSCL StorageBlob.ICloudBlob blob = CommonBlobHelper.QueryBlob(NEW_CONTAINER_NAME, blobName); blob.FetchAttributes(); CloudBlobUtil.PackBlobCompareData(blob, dic); dic.Add("ICloudBlob", blob); agent.OutputValidation(comp); } finally { // cleanup container.DeleteIfExists(); } } /// <summary> /// Parameters: /// Block: /// True for BlockBlob, false for PageBlob /// </summary> internal void DownloadBlobTest(Agent agent, string UploadFilePath, string DownloadDirPath, Microsoft.WindowsAzure.Storage.Blob.BlobType Type) { string NEW_CONTAINER_NAME = Utility.GenNameString("upload-"); string blobName = Path.GetFileName(UploadFilePath); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Blob, blobName); dic["BlobType"] = Type; comp.Add(dic); // create the container StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.CreateIfNotExists(); try { bool bSuccess = false; // upload the blob file if (Type == Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob) bSuccess = CommonBlobHelper.UploadFileToBlockBlob(NEW_CONTAINER_NAME, blobName, UploadFilePath); else if (Type == Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob) bSuccess = CommonBlobHelper.UploadFileToPageBlob(NEW_CONTAINER_NAME, blobName, UploadFilePath); Test.Assert(bSuccess, "upload file {0} to container {1} should succeed", UploadFilePath, NEW_CONTAINER_NAME); //--------------Download operation-------------- string downloadFilePath = Path.Combine(DownloadDirPath, blobName); Test.Assert(agent.GetAzureStorageBlobContent(blobName, downloadFilePath, NEW_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageBlobContent", true)); StorageBlob.ICloudBlob blob = CommonBlobHelper.QueryBlob(NEW_CONTAINER_NAME, blobName); CloudBlobUtil.PackBlobCompareData(blob, dic); // Verification for returned values agent.OutputValidation(comp); Test.Assert(Helper.CompareTwoFiles(downloadFilePath, UploadFilePath), String.Format("File '{0}' should be bit-wise identicial to '{1}'", downloadFilePath, UploadFilePath)); } finally { // cleanup container.DeleteIfExists(); } } /// <summary> /// Parameters: /// Block: /// True for BlockBlob, false for PageBlob /// </summary> internal void RemoveBlobTest(Agent agent, string UploadFilePath, Microsoft.WindowsAzure.Storage.Blob.BlobType Type) { string NEW_CONTAINER_NAME = Utility.GenNameString("upload-"); string blobName = Path.GetFileName(UploadFilePath); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Blob, blobName); dic["BlobType"] = Type; comp.Add(dic); // create the container StorageBlob.CloudBlobContainer container = CommonStorageAccount.CreateCloudBlobClient().GetContainerReference(NEW_CONTAINER_NAME); container.CreateIfNotExists(); try { bool bSuccess = false; // upload the blob file if (Type == Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob) bSuccess = CommonBlobHelper.UploadFileToBlockBlob(NEW_CONTAINER_NAME, blobName, UploadFilePath); else if (Type == Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob) bSuccess = CommonBlobHelper.UploadFileToPageBlob(NEW_CONTAINER_NAME, blobName, UploadFilePath); Test.Assert(bSuccess, "upload file {0} to container {1} should succeed", UploadFilePath, NEW_CONTAINER_NAME); //--------------Remove operation-------------- Test.Assert(agent.RemoveAzureStorageBlob(blobName, NEW_CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageBlob", true)); StorageBlob.ICloudBlob blob = CommonBlobHelper.QueryBlob(NEW_CONTAINER_NAME, blobName); Test.Assert(blob == null, "blob {0} should not exist!", blobName); } finally { // cleanup container.DeleteIfExists(); } } /// <summary> /// Create a container and then get it using powershell cmdlet /// </summary> /// <returns>A CloudBlobContainer object which is returned by PowerShell</returns> protected StorageBlob.CloudBlobContainer CreateAndPsGetARandomContainer() { string containerName = Utility.GenNameString("bvt"); StorageBlob.CloudBlobContainer container = SetUpStorageAccount.CreateCloudBlobClient().GetContainerReference(containerName); container.CreateIfNotExists(); try { PowerShellAgent agent = new PowerShellAgent(); Test.Assert(agent.GetAzureStorageContainer(containerName), Utility.GenComparisonData("GetAzureStorageContainer", true)); int count = 1; Test.Assert(agent.Output.Count == count, string.Format("get container should return only 1 container, actully it's {0}", agent.Output.Count)); return (StorageBlob.CloudBlobContainer)agent.Output[0]["CloudBlobContainer"]; } finally { // clean up container.DeleteIfExists(); } } } }
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL) #region License /* * ResponseStream.cs * * This code is derived from ResponseStream.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2015 sta.blockhead * * 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 #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.IO; using System.Text; namespace WebSocketSharp.Net { internal class ResponseStream : Stream { #region Private Fields private MemoryStream _body; private static readonly byte[] _crlf = new byte[] { 13, 10 }; private bool _disposed; private HttpListenerResponse _response; private bool _sendChunked; private Stream _stream; private Action<byte[], int, int> _write; private Action<byte[], int, int> _writeBody; private Action<byte[], int, int> _writeChunked; #endregion #region Internal Constructors internal ResponseStream ( Stream stream, HttpListenerResponse response, bool ignoreWriteExceptions) { _stream = stream; _response = response; if (ignoreWriteExceptions) { _write = writeWithoutThrowingException; _writeChunked = writeChunkedWithoutThrowingException; } else { _write = stream.Write; _writeChunked = writeChunked; } _body = new MemoryStream (); } #endregion #region Public Properties public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_disposed; } } public override long Length { get { throw new NotSupportedException (); } } public override long Position { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } #endregion #region Private Methods private bool flush (bool closing) { if (!_response.HeadersSent) { if (!flushHeaders (closing)) { if (closing) _response.CloseConnection = true; return false; } _sendChunked = _response.SendChunked; _writeBody = _sendChunked ? _writeChunked : _write; } flushBody (closing); if (closing && _sendChunked) { var last = getChunkSizeBytes (0, true); _write (last, 0, last.Length); } return true; } private void flushBody (bool closing) { using (_body) { var len = _body.Length; if (len > Int32.MaxValue) { _body.Position = 0; var buffLen = 1024; var buff = new byte[buffLen]; var nread = 0; while ((nread = _body.Read (buff, 0, buffLen)) > 0) _writeBody (buff, 0, nread); } else if (len > 0) { _writeBody (_body.GetBuffer (), 0, (int) len); } } _body = !closing ? new MemoryStream () : null; } private bool flushHeaders (bool closing) { using (var buff = new MemoryStream ()) { var headers = _response.WriteHeadersTo (buff); var start = buff.Position; var len = buff.Length - start; if (len > 32768) return false; if (!_response.SendChunked && _response.ContentLength64 != _body.Length) return false; _write (buff.GetBuffer (), (int) start, (int) len); _response.CloseConnection = headers["Connection"] == "close"; _response.HeadersSent = true; } return true; } private static byte[] getChunkSizeBytes (int size, bool final) { return Encoding.ASCII.GetBytes (String.Format ("{0:x}\r\n{1}", size, final ? "\r\n" : "")); } private void writeChunked (byte[] buffer, int offset, int count) { var size = getChunkSizeBytes (count, false); _stream.Write (size, 0, size.Length); _stream.Write (buffer, offset, count); _stream.Write (_crlf, 0, 2); } private void writeChunkedWithoutThrowingException (byte[] buffer, int offset, int count) { try { writeChunked (buffer, offset, count); } catch { } } private void writeWithoutThrowingException (byte[] buffer, int offset, int count) { try { _stream.Write (buffer, offset, count); } catch { } } #endregion #region Internal Methods internal void Close (bool force) { if (_disposed) return; _disposed = true; if (!force && flush (true)) { _response.Close (); } else { if (_sendChunked) { var last = getChunkSizeBytes (0, true); _write (last, 0, last.Length); } _body.Dispose (); _body = null; _response.Abort (); } _response = null; _stream = null; } internal void InternalWrite (byte[] buffer, int offset, int count) { _write (buffer, offset, count); } #endregion #region Public Methods public override IAsyncResult BeginRead ( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException (); } public override IAsyncResult BeginWrite ( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); return _body.BeginWrite (buffer, offset, count, callback, state); } public override void Close () { Close (false); } protected override void Dispose (bool disposing) { Close (!disposing); } public override int EndRead (IAsyncResult asyncResult) { throw new NotSupportedException (); } public override void EndWrite (IAsyncResult asyncResult) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); _body.EndWrite (asyncResult); } public override void Flush () { if (!_disposed && (_sendChunked || _response.SendChunked)) flush (false); } public override int Read (byte[] buffer, int offset, int count) { throw new NotSupportedException (); } public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException (); } public override void SetLength (long value) { throw new NotSupportedException (); } public override void Write (byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); _body.Write (buffer, offset, count); } #endregion } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.ObjectModel; using System.Globalization; using System.Xml; using System.Reflection; using System.Text; namespace System.Management.Automation { /// <summary> /// MamlNode is an xml node in MAML schema. Maml schema includes formatting oriented tags like para, list /// etc, which needs to be taken care of during display. As a result, xml node in Maml schema can't be /// converted into PSObject directly with XmlNodeAdapter. /// /// MamlNode class provides logic in converting formatting tags into the format acceptable by monad format /// and output engine. /// /// Following three kinds of formating tags are supported per our agreement with Maml team, /// 1. para, /// <para> /// para text here /// </para> /// 2. list, /// <list class="ordered|unordered"> /// <listItem> /// <para> /// listItem Text here /// </para> /// </listItem> /// </list> /// 3. definition list, /// <definitionList> /// <definitionListItem> /// <term> /// definition term text here /// </term> /// <definition> /// <para> /// definition text here /// </para> /// </definition> /// </definitionListItem> /// </definitionList> /// After processing, content of these three tags will be converted into textItem and its derivations, /// 1. para => paraTextItem /// <textItem class="paraTextItem"> /// <text>para text here</text> /// </textItem> /// 2. list => a list of listTextItem's (which can be ordered or unordered) /// <textItem class="unorderedListTextItem"> /// <tag>*</tag> /// <text>text for list item 1</text> /// </textItem> /// <textItem class="unorderedListTextItem"> /// <tag>*</tag> /// <text>text for list item 2</text> /// </textItem> /// 3. definitionList => a list of definitionTextItem's /// <definitionListItem> /// <term>definition term here</term> /// <definition>definition text here</definition> /// </definitionListItem> /// </summary> internal class MamlNode { /// <summary> /// Constructor for HelpInfo. /// </summary> internal MamlNode(XmlNode xmlNode) { _xmlNode = xmlNode; } private XmlNode _xmlNode; /// <summary> /// Underline xmlNode for this MamlNode object. /// </summary> /// <value></value> internal XmlNode XmlNode { get { return _xmlNode; } } private PSObject _mshObject; /// <summary> /// MshObject which is converted from XmlNode. /// </summary> /// <value></value> internal PSObject PSObject { get { if (_mshObject == null) { // There is no XSLT to convert docs to supported maml format // We dont want comments etc to spoil our format. // So remove all unsupported nodes before constructing help // object. RemoveUnsupportedNodes(_xmlNode); _mshObject = GetPSObject(_xmlNode); } return _mshObject; } } #region Conversion of xmlNode => PSObject /// <summary> /// Convert an xmlNode into an PSObject. There are four scenarios, /// 1. Null xml, this will return an PSObject wrapping a null object. /// 2. Atomic xml, which is an xmlNode with only one simple text child node /// <atomicXml attribute="value"> /// atomic xml text /// </atomicXml> /// In this case, an PSObject that wraps string "atomic xml text" will be returned with following properties /// attribute => name /// 3. Composite xml, which is an xmlNode with structured child nodes, but not a special case for Maml formating. /// <compositeXml attribute="attribute"> /// <singleChildNode> /// single child node text /// </singleChildNode> /// <dupChildNode> /// dup child node text 1 /// </dupChildNode> /// <dupChildNode> /// dup child node text 2 /// </dupChildNode> /// </compositeXml> /// In this case, an PSObject will base generated based on an inside PSObject, /// which in turn has following properties /// a. property "singleChildNode", with its value an PSObject wrapping string "single child node text" /// b. property "dupChildNode", with its value an PSObject array wrapping strings for two dupChildNode's /// The outside PSObject will have property, /// a. property "attribute", with its value an PSObject wrapping string "attribute" /// 4. Maml formatting xml, this is a special case for Composite xml, for example /// <description attribute="value"> /// <para> /// para 1 /// </para> /// <list> /// <listItem> /// <para> /// list item 1 /// </para> /// </listItem> /// <listItem> /// <para> /// list item 2 /// </para> /// </listItem> /// </list> /// <definitionList> /// <definitionListItem> /// <term> /// term 1 /// </term> /// <definition> /// definition list item 1 /// </definition> /// </definitionListItem> /// <definitionListItem> /// <term> /// term 2 /// </term> /// <definition> /// definition list item 2 /// </definition> /// </definitionListItem> /// </definitionList> /// </description> /// In this case, an PSObject based on an PSObject array will be created. The inside PSObject array /// will contain following items /// . a MamlParaTextItem based on "para 1" /// . a MamlUnorderedListItem based on "list item 1" /// . a MamlUnorderedListItem based on "list item 2" /// . a MamlDefinitionListItem based on "definition list item 1" /// . a MamlDefinitionListItem based on "definition list item 2" /// /// The outside PSObject will have a property /// attribute => "value" /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private PSObject GetPSObject(XmlNode xmlNode) { if (xmlNode == null) return new PSObject(); PSObject mshObject = null; if (IsAtomic(xmlNode)) { mshObject = new PSObject(xmlNode.InnerText.Trim()); } else if (IncludeMamlFormatting(xmlNode)) { mshObject = new PSObject(GetMamlFormattingPSObjects(xmlNode)); } else { mshObject = new PSObject(GetInsidePSObject(xmlNode)); // Add typeNames to this MSHObject and create views so that // the ouput is readable. This is done only for complex nodes. mshObject.TypeNames.Clear(); if (xmlNode.Attributes["type"] != null) { if (string.Compare(xmlNode.Attributes["type"].Value, "field", StringComparison.OrdinalIgnoreCase) == 0) mshObject.TypeNames.Add("MamlPSClassHelpInfo#field"); else if (string.Compare(xmlNode.Attributes["type"].Value, "method", StringComparison.OrdinalIgnoreCase) == 0) mshObject.TypeNames.Add("MamlPSClassHelpInfo#method"); } mshObject.TypeNames.Add("MamlCommandHelpInfo#" + xmlNode.LocalName); } if (xmlNode.Attributes != null) { foreach (XmlNode attribute in xmlNode.Attributes) { mshObject.Properties.Add(new PSNoteProperty(attribute.Name, attribute.Value)); } } return mshObject; } /// <summary> /// Get inside PSObject created based on inside nodes of xmlNode. /// /// The inside PSObject will be based on null. It will created one /// property per inside node grouping by node names. /// /// For example, for xmlNode like, /// <command> /// <name>get-item</name> /// <note>note 1</note> /// <note>note 2</note> /// </command> /// It will create an PSObject based on null, with following two properties /// . property 1: name="name" value=an PSObject to wrap string "get-item" /// . property 2: name="note" value=an PSObject array with following two PSObjects /// 1. PSObject wrapping string "note 1" /// 2. PSObject wrapping string "note 2" /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private PSObject GetInsidePSObject(XmlNode xmlNode) { Hashtable properties = GetInsideProperties(xmlNode); PSObject mshObject = new PSObject(); IDictionaryEnumerator enumerator = properties.GetEnumerator(); while (enumerator.MoveNext()) { mshObject.Properties.Add(new PSNoteProperty((string)enumerator.Key, enumerator.Value)); } return mshObject; } /// <summary> /// This is for getting inside properties of an XmlNode. Properties are /// stored in a hashtable with key as property name and value as property value. /// /// Inside node with same node names will be grouped into one property with /// property value as an array. /// /// For example, for xmlNode like, /// <command> /// <name>get-item</name> /// <note>note 1</note> /// <note>note 2</note> /// </command> /// It will create an PSObject based on null, with following two properties /// . property 1: name="name" value=an PSObject to wrap string "get-item" /// . property 2: name="note" value=an PSObject array with following two PSObjects /// 1. PSObject wrapping string "note 1" /// 2. PSObject wrapping string "note 2" /// /// Since we don't know whether an node name will be used more than once, /// We are making each property value is an array (PSObject[]) to start with. /// At the end, SimplifyProperties will be called to reduce PSObject[] containing /// only one element to PSObject itself. /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private Hashtable GetInsideProperties(XmlNode xmlNode) { Hashtable properties = new Hashtable(StringComparer.OrdinalIgnoreCase); if (xmlNode == null) return properties; if (xmlNode.ChildNodes != null) { foreach (XmlNode childNode in xmlNode.ChildNodes) { AddProperty(properties, childNode.LocalName, GetPSObject(childNode)); } } return SimplifyProperties(properties); } /// <summary> /// Removes unsupported child nodes recursively from the given /// xml node so that they wont spoil the format. /// </summary> /// <param name="xmlNode"> /// Node whose children are verified for maml. /// </param> private void RemoveUnsupportedNodes(XmlNode xmlNode) { // Start with the first child.. // We want to modify only children.. // The current node is taken care by the callee.. XmlNode childNode = xmlNode.FirstChild; while (childNode != null) { // We dont want Comments..so remove.. if (childNode.NodeType == XmlNodeType.Comment) { XmlNode nodeToRemove = childNode; childNode = childNode.NextSibling; // Remove this node and its children if any.. xmlNode.RemoveChild(nodeToRemove); } else { // Search children... RemoveUnsupportedNodes(childNode); childNode = childNode.NextSibling; } } } /// <summary> /// This is for adding a property into a property hashtable. /// /// As mentioned in comment of GetInsideProperties, property values stored in /// property hashtable is an array to begin with. /// /// The property value to be added is an mshObject whose base object can be an /// PSObject array itself. In that case, each PSObject in the array will be /// added separately into the property value array. This case can only happen when /// an node with maml formatting node inside is treated. The side effect of this /// is that the properties for outside mshObject will be lost. An example of this /// is that, /// <command> /// <description attrib1="value1"> /// <para></para> /// <list></list> /// <definitionList></definitionList> /// </description> /// </command> /// After the processing, PSObject corresponding to command will have an property /// with name "description" and a value of an PSObject array created based on /// maml formatting node inside "description" node. The attribute of description node /// "attrib1" will be lost. This seems to be OK with current practice of authoring /// monad command help. /// </summary> /// <param name="properties">Property hashtable.</param> /// <param name="name">Property name.</param> /// <param name="mshObject">Property value.</param> private static void AddProperty(Hashtable properties, string name, PSObject mshObject) { ArrayList propertyValues = (ArrayList)properties[name]; if (propertyValues == null) { propertyValues = new ArrayList(); properties[name] = propertyValues; } if (mshObject == null) return; if (mshObject.BaseObject is PSCustomObject || !mshObject.BaseObject.GetType().Equals(typeof(PSObject[]))) { propertyValues.Add(mshObject); return; } PSObject[] mshObjects = (PSObject[])mshObject.BaseObject; for (int i = 0; i < mshObjects.Length; i++) { propertyValues.Add(mshObjects[i]); } return; } /// <summary> /// This is for simplifying property value array of only one element. /// /// As mentioned in comments for GetInsideProperties, this is needed /// to reduce an array of only one PSObject into the PSObject itself. /// /// A side effect of this function is to turn property values from /// ArrayList into PSObject[]. /// </summary> /// <param name="properties"></param> /// <returns></returns> private static Hashtable SimplifyProperties(Hashtable properties) { if (properties == null) return null; Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase); IDictionaryEnumerator enumerator = properties.GetEnumerator(); while (enumerator.MoveNext()) { ArrayList propertyValues = (ArrayList)enumerator.Value; if (propertyValues == null || propertyValues.Count == 0) continue; if (propertyValues.Count == 1) { if (!IsMamlFormattingPSObject((PSObject)propertyValues[0])) { PSObject mshObject = (PSObject)propertyValues[0]; // Even for strings or other basic types, they need to be contained in PSObject in case // there is attributes for this object. result[enumerator.Key] = mshObject; continue; } } result[enumerator.Key] = propertyValues.ToArray(typeof(PSObject)); } return result; } /// <summary> /// An xmlNode is atomic if it contains no structured inside nodes. /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private static bool IsAtomic(XmlNode xmlNode) { if (xmlNode == null) return false; if (xmlNode.ChildNodes == null) return true; if (xmlNode.ChildNodes.Count > 1) return false; if (xmlNode.ChildNodes.Count == 0) return true; if (xmlNode.ChildNodes[0].GetType().Equals(typeof(XmlText))) return true; return false; } #endregion #region Maml formatting /// <summary> /// Check whether an xmlNode contains childnodes which is for /// maml formatting. /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private static bool IncludeMamlFormatting(XmlNode xmlNode) { if (xmlNode == null) return false; if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return false; foreach (XmlNode childNode in xmlNode.ChildNodes) { if (IsMamlFormattingNode(childNode)) { return true; } } return false; } /// <summary> /// Check whether a node is for maml formatting. This include following nodes, /// a. para /// b. list /// c. definitionList. /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private static bool IsMamlFormattingNode(XmlNode xmlNode) { if (xmlNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) return true; if (xmlNode.LocalName.Equals("list", StringComparison.OrdinalIgnoreCase)) return true; if (xmlNode.LocalName.Equals("definitionList", StringComparison.OrdinalIgnoreCase)) return true; return false; } /// <summary> /// Check whether an mshObject is created from a maml formatting node. /// </summary> /// <param name="mshObject"></param> /// <returns></returns> private static bool IsMamlFormattingPSObject(PSObject mshObject) { Collection<string> typeNames = mshObject.TypeNames; if (typeNames == null || typeNames.Count == 0) return false; return typeNames[typeNames.Count - 1].Equals("MamlTextItem", StringComparison.OrdinalIgnoreCase); } /// <summary> /// Convert an xmlNode containing maml formatting nodes into an PSObject array. /// /// For example, for node, /// <description attribute="value"> /// <para> /// para 1 /// </para> /// <list> /// <listItem> /// <para> /// list item 1 /// </para> /// </listItem> /// <listItem> /// <para> /// list item 2 /// </para> /// </listItem> /// </list> /// <definitionList> /// <definitionListItem> /// <term> /// term 1 /// </term> /// <definition> /// definition list item 1 /// </definition> /// </definitionListItem> /// <definitionListItem> /// <term> /// term 2 /// </term> /// <definition> /// definition list item 2 /// </definition> /// </definitionListItem> /// </definitionList> /// </description> /// In this case, an PSObject based on an PSObject array will be created. The inside PSObject array /// will contain following items /// . a MamlParaTextItem based on "para 1" /// . a MamlUnorderedListItem based on "list item 1" /// . a MamlUnorderedListItem based on "list item 2" /// . a MamlDefinitionListItem based on "definition list item 1" /// . a MamlDefinitionListItem based on "definition list item 2" /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private PSObject[] GetMamlFormattingPSObjects(XmlNode xmlNode) { ArrayList mshObjects = new ArrayList(); int paraNodes = GetParaMamlNodeCount(xmlNode.ChildNodes); int count = 0; // Don't trim the content if this is an "introduction" node. bool trim = !string.Equals(xmlNode.Name, "maml:introduction", StringComparison.OrdinalIgnoreCase); foreach (XmlNode childNode in xmlNode.ChildNodes) { if (childNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { ++count; PSObject paraPSObject = GetParaPSObject(childNode, count != paraNodes, trim: trim); if (paraPSObject != null) mshObjects.Add(paraPSObject); continue; } if (childNode.LocalName.Equals("list", StringComparison.OrdinalIgnoreCase)) { ArrayList listPSObjects = GetListPSObjects(childNode); for (int i = 0; i < listPSObjects.Count; i++) { mshObjects.Add(listPSObjects[i]); } continue; } if (childNode.LocalName.Equals("definitionList", StringComparison.OrdinalIgnoreCase)) { ArrayList definitionListPSObjects = GetDefinitionListPSObjects(childNode); for (int i = 0; i < definitionListPSObjects.Count; i++) { mshObjects.Add(definitionListPSObjects[i]); } continue; } // If we get here, there is some tags that is not supported by maml. WriteMamlInvalidChildNodeError(xmlNode, childNode); } return (PSObject[])mshObjects.ToArray(typeof(PSObject)); } /// <summary> /// Gets the number of para nodes. /// </summary> /// <param name="nodes"></param> /// <returns></returns> private int GetParaMamlNodeCount(XmlNodeList nodes) { int i = 0; foreach (XmlNode childNode in nodes) { if (childNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { if (childNode.InnerText.Trim().Equals(string.Empty)) { continue; } ++i; } } return i; } /// <summary> /// Write an error to helpsystem to indicate an invalid maml child node. /// </summary> /// <param name="node"></param> /// <param name="childNode"></param> private void WriteMamlInvalidChildNodeError(XmlNode node, XmlNode childNode) { ErrorRecord errorRecord = new ErrorRecord(new ParentContainsErrorRecordException("MamlInvalidChildNodeError"), "MamlInvalidChildNodeError", ErrorCategory.SyntaxError, null); errorRecord.ErrorDetails = new ErrorDetails(typeof(MamlNode).Assembly, "HelpErrors", "MamlInvalidChildNodeError", node.LocalName, childNode.LocalName, GetNodePath(node)); this.Errors.Add(errorRecord); } /// <summary> /// Write an error to help system to indicate an invalid child node count. /// </summary> /// <param name="node"></param> /// <param name="childNodeName"></param> /// <param name="count"></param> private void WriteMamlInvalidChildNodeCountError(XmlNode node, string childNodeName, int count) { ErrorRecord errorRecord = new ErrorRecord(new ParentContainsErrorRecordException("MamlInvalidChildNodeCountError"), "MamlInvalidChildNodeCountError", ErrorCategory.SyntaxError, null); errorRecord.ErrorDetails = new ErrorDetails(typeof(MamlNode).Assembly, "HelpErrors", "MamlInvalidChildNodeCountError", node.LocalName, childNodeName, count, GetNodePath(node)); this.Errors.Add(errorRecord); } private static string GetNodePath(XmlNode xmlNode) { if (xmlNode == null) return string.Empty; if (xmlNode.ParentNode == null) return "\\" + xmlNode.LocalName; return GetNodePath(xmlNode.ParentNode) + "\\" + xmlNode.LocalName + GetNodeIndex(xmlNode); } private static string GetNodeIndex(XmlNode xmlNode) { if (xmlNode == null || xmlNode.ParentNode == null) return string.Empty; int index = 0; int total = 0; foreach (XmlNode siblingNode in xmlNode.ParentNode.ChildNodes) { if (siblingNode == xmlNode) { index = total++; continue; } if (siblingNode.LocalName.Equals(xmlNode.LocalName, StringComparison.OrdinalIgnoreCase)) { total++; } } if (total > 1) { return "[" + index.ToString("d", CultureInfo.CurrentCulture) + "]"; } return string.Empty; } /// <summary> /// Convert a para node into an mshObject. /// /// For example, /// <para> /// para text /// </para> /// In this case, an PSObject of type "MamlParaTextItem" will be created with following property /// a. text="para text" /// </summary> /// <param name="xmlNode"></param> /// <param name="newLine"></param> /// <param name="trim"></param> /// <returns></returns> private static PSObject GetParaPSObject(XmlNode xmlNode, bool newLine, bool trim = true) { if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) return null; PSObject mshObject = new PSObject(); StringBuilder sb = new StringBuilder(); if (newLine && !xmlNode.InnerText.Trim().Equals(string.Empty)) { sb.AppendLine(xmlNode.InnerText.Trim()); } else { var innerText = xmlNode.InnerText; if (trim) { innerText = innerText.Trim(); } sb.Append(innerText); } mshObject.Properties.Add(new PSNoteProperty("Text", sb.ToString())); mshObject.TypeNames.Clear(); mshObject.TypeNames.Add("MamlParaTextItem"); mshObject.TypeNames.Add("MamlTextItem"); return mshObject; } /// <summary> /// Convert a list node into an PSObject array. /// /// For example, /// <list class="ordered"> /// <listItem> /// <para> /// text for list item 1 /// </para> /// </listItem> /// <listItem> /// <para> /// text for list item 2 /// </para> /// </listItem> /// </list> /// In this case, an array of PSObject, each of type "MamlOrderedListText" will be created with following /// two properties, /// a. tag=" 1. " or " 2. " /// b. text="text for list item 1" or "text for list item 2" /// In the case of unordered list, similar PSObject will created with type to be "MamlUnorderedListText" and tag="*" /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private ArrayList GetListPSObjects(XmlNode xmlNode) { ArrayList mshObjects = new ArrayList(); if (xmlNode == null) return mshObjects; if (!xmlNode.LocalName.Equals("list", StringComparison.OrdinalIgnoreCase)) return mshObjects; if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return mshObjects; bool ordered = IsOrderedList(xmlNode); int index = 1; foreach (XmlNode childNode in xmlNode.ChildNodes) { if (childNode.LocalName.Equals("listItem", StringComparison.OrdinalIgnoreCase)) { PSObject listItemPSObject = GetListItemPSObject(childNode, ordered, ref index); if (listItemPSObject != null) mshObjects.Add(listItemPSObject); continue; } // If we get here, there is some tags that is not supported by maml. WriteMamlInvalidChildNodeError(xmlNode, childNode); } return mshObjects; } /// <summary> /// Check whether a list is ordered or not. /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private static bool IsOrderedList(XmlNode xmlNode) { if (xmlNode == null) return false; if (xmlNode.Attributes == null || xmlNode.Attributes.Count == 0) return false; foreach (XmlNode attribute in xmlNode.Attributes) { if (attribute.Name.Equals("class", StringComparison.OrdinalIgnoreCase) && attribute.Value.Equals("ordered", StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// <summary> /// Convert an listItem node into an PSObject with property "tag" and "text" /// </summary> /// <param name="xmlNode"></param> /// <param name="ordered"></param> /// <param name="index"></param> /// <returns></returns> private PSObject GetListItemPSObject(XmlNode xmlNode, bool ordered, ref int index) { if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("listItem", StringComparison.OrdinalIgnoreCase)) return null; string text = string.Empty; if (xmlNode.ChildNodes.Count > 1) { WriteMamlInvalidChildNodeCountError(xmlNode, "para", 1); } foreach (XmlNode childNode in xmlNode.ChildNodes) { if (childNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { text = childNode.InnerText.Trim(); continue; } WriteMamlInvalidChildNodeError(xmlNode, childNode); } string tag = string.Empty; if (ordered) { tag = index.ToString("d2", CultureInfo.CurrentCulture); tag += ". "; index++; } else { tag = "* "; } PSObject mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty("Text", text)); mshObject.Properties.Add(new PSNoteProperty("Tag", tag)); mshObject.TypeNames.Clear(); if (ordered) { mshObject.TypeNames.Add("MamlOrderedListTextItem"); } else { mshObject.TypeNames.Add("MamlUnorderedListTextItem"); } mshObject.TypeNames.Add("MamlTextItem"); return mshObject; } /// <summary> /// Convert definitionList node into an array of PSObject, an for /// each definitionListItem node inside this node. /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private ArrayList GetDefinitionListPSObjects(XmlNode xmlNode) { ArrayList mshObjects = new ArrayList(); if (xmlNode == null) return mshObjects; if (!xmlNode.LocalName.Equals("definitionList", StringComparison.OrdinalIgnoreCase)) return mshObjects; if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return mshObjects; foreach (XmlNode childNode in xmlNode.ChildNodes) { if (childNode.LocalName.Equals("definitionListItem", StringComparison.OrdinalIgnoreCase)) { PSObject definitionListItemPSObject = GetDefinitionListItemPSObject(childNode); if (definitionListItemPSObject != null) mshObjects.Add(definitionListItemPSObject); continue; } // If we get here, we found some node that is not supported. WriteMamlInvalidChildNodeError(xmlNode, childNode); } return mshObjects; } /// <summary> /// Convert an definitionListItem node into an PSObject /// /// For example /// <definitionListItem> /// <term> /// term text /// </term> /// <definition> /// <para> /// definition text /// </para> /// </definition> /// </definitionListItem> /// In this case, an PSObject of type "definitionListText" will be created with following /// properties /// a. term="term text" /// b. definition="definition text" /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private PSObject GetDefinitionListItemPSObject(XmlNode xmlNode) { if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("definitionListItem", StringComparison.OrdinalIgnoreCase)) return null; string term = null; string definition = null; foreach (XmlNode childNode in xmlNode.ChildNodes) { if (childNode.LocalName.Equals("term", StringComparison.OrdinalIgnoreCase)) { term = childNode.InnerText.Trim(); continue; } if (childNode.LocalName.Equals("definition", StringComparison.OrdinalIgnoreCase)) { definition = GetDefinitionText(childNode); continue; } // If we get here, we found some node that is not supported. WriteMamlInvalidChildNodeError(xmlNode, childNode); } if (string.IsNullOrEmpty(term)) return null; PSObject mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty("Term", term)); mshObject.Properties.Add(new PSNoteProperty("Definition", definition)); mshObject.TypeNames.Clear(); mshObject.TypeNames.Add("MamlDefinitionTextItem"); mshObject.TypeNames.Add("MamlTextItem"); return mshObject; } /// <summary> /// Get the text for definition. The will treat some intermediate nodes like "definition" and "para" /// </summary> /// <param name="xmlNode"></param> /// <returns></returns> private string GetDefinitionText(XmlNode xmlNode) { if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("definition", StringComparison.OrdinalIgnoreCase)) return null; if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return string.Empty; if (xmlNode.ChildNodes.Count > 1) { WriteMamlInvalidChildNodeCountError(xmlNode, "para", 1); } string text = string.Empty; foreach (XmlNode childNode in xmlNode.ChildNodes) { if (childNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { text = childNode.InnerText.Trim(); continue; } WriteMamlInvalidChildNodeError(xmlNode, childNode); } return text; } #endregion #region Preformatted string processing /// <summary> /// This is for getting preformatted text from an xml document. /// /// Normally in xml document, preformatted text will be indented by /// a fix amount based on its position. The task of this function /// is to remove that fixed amount from the text. /// /// For example, in xml, /// <preformatted> /// void function() /// { /// // call some other function here; /// } /// </preformatted> /// we can find that the preformatted text are indented unanimously /// by 4 spaces because of its position in xml. /// /// After massaging in this function, the result text will be, /// /// void function /// { /// // call some other function here; /// } /// /// please notice that the indention is reduced. /// </summary> /// <param name="text"></param> /// <returns></returns> private static string GetPreformattedText(string text) { // we are assuming tabsize=4 here. // It is discouraged to use tab in preformatted text. string noTabText = text.Replace("\t", " "); string[] lines = noTabText.Split(Utils.Separators.Newline); string[] trimedLines = TrimLines(lines); if (trimedLines == null || trimedLines.Length == 0) return string.Empty; int minIndentation = GetMinIndentation(trimedLines); string[] shortedLines = new string[trimedLines.Length]; for (int i = 0; i < trimedLines.Length; i++) { if (IsEmptyLine(trimedLines[i])) { shortedLines[i] = trimedLines[i]; } else { shortedLines[i] = trimedLines[i].Remove(0, minIndentation); } } StringBuilder result = new StringBuilder(); for (int i = 0; i < shortedLines.Length; i++) { result.AppendLine(shortedLines[i]); } return result.ToString(); } /// <summary> /// Trim empty lines from the either end of an string array. /// </summary> /// <param name="lines">Lines to trim.</param> /// <returns>An string array with empty lines trimed on either end.</returns> private static string[] TrimLines(string[] lines) { if (lines == null || lines.Length == 0) return null; int i = 0; for (i = 0; i < lines.Length; i++) { if (!IsEmptyLine(lines[i])) break; } int start = i; if (start == lines.Length) return null; for (i = lines.Length - 1; i >= start; i--) { if (!IsEmptyLine(lines[i])) break; } int end = i; string[] result = new string[end - start + 1]; for (i = start; i <= end; i++) { result[i - start] = lines[i]; } return result; } /// <summary> /// Get minimum indentation of a paragraph. /// </summary> /// <param name="lines"></param> /// <returns></returns> private static int GetMinIndentation(string[] lines) { int minIndentation = -1; for (int i = 0; i < lines.Length; i++) { if (IsEmptyLine(lines[i])) continue; int indentation = GetIndentation(lines[i]); if (minIndentation < 0 || indentation < minIndentation) minIndentation = indentation; } return minIndentation; } /// <summary> /// Get indentation of a line, i.e., number of spaces /// at the beginning of the line. /// </summary> /// <param name="line"></param> /// <returns></returns> private static int GetIndentation(string line) { if (IsEmptyLine(line)) return 0; string leftTrimedLine = line.TrimStart(Utils.Separators.Space); return line.Length - leftTrimedLine.Length; } /// <summary> /// Test whether a line is empty. /// /// A line is empty if it contains only white spaces. /// </summary> /// <param name="line"></param> /// <returns></returns> private static bool IsEmptyLine(string line) { if (string.IsNullOrEmpty(line)) return true; string trimedLine = line.Trim(); if (string.IsNullOrEmpty(trimedLine)) return true; return false; } #endregion #region Error handling /// <summary> /// This is for tracking the set of errors happened during the parsing of /// maml text. /// </summary> /// <value></value> internal Collection<ErrorRecord> Errors { get; } = new Collection<ErrorRecord>(); #endregion } }
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 MatrixApi.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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; } } }
using System; using System.Reflection; /* * Regression tests for the mono JIT. * * Each test needs to be of the form: * * public static int test_<result>_<name> (); * * where <result> is an integer (the value that needs to be returned by * the method to make it pass. * <name> is a user-displayed name used to identify the test. * * The tests can be driven in two ways: * *) running the program directly: Main() uses reflection to find and invoke * the test methods (this is useful mostly to check that the tests are correct) * *) with the --regression switch of the jit (this is the preferred way since * all the tests will be run with optimizations on and off) * * The reflection logic could be moved to a .dll since we need at least another * regression test file written in IL code to have better control on how * the IL code looks. */ /* A comparison made to same variable. */ #pragma warning disable 1718 #if MOBILE class FloatTests #else class Tests #endif { #if !MOBILE public static int Main (string[] args) { return TestDriver.RunTests (typeof (Tests), args); } #endif public static int test_0_beq () { double a = 2.0; if (a != 2.0) return 1; return 0; } public static int test_0_bne_un () { double a = 2.0; if (a == 1.0) return 1; return 0; } public static int test_0_conv_r8 () { double a = 2; if (a != 2.0) return 1; return 0; } public static int test_0_conv_i () { double a = 2.0; int i = (int)a; if (i != 2) return 1; uint ui = (uint)a; if (ui != 2) return 2; short s = (short)a; if (s != 2) return 3; ushort us = (ushort)a; if (us != 2) return 4; byte b = (byte)a; if (b != 2) return 5; sbyte sb = (sbyte)a; if (sb != 2) return 6; /* MS.NET special cases these */ double d = Double.NaN; ui = (uint)d; if (ui != 0) return 7; d = Double.PositiveInfinity; ui = (uint)d; if (ui != 0) return 8; d = Double.NegativeInfinity; ui = (uint)d; if (ui != 0) return 9; return 0; } public static int test_5_conv_r4 () { int i = 5; float f = (float)i; return (int)f; } public static int test_0_conv_r4_m1 () { int i = -1; float f = (float)i; return (int)f + 1; } public static int test_5_double_conv_r4 () { double d = 5.0; float f = (float)d; return (int)f; } public static int test_5_float_conv_r8 () { float f = 5.0F; double d = (double)f; return (int)d; } public static int test_5_conv_r8 () { int i = 5; double f = (double)i; return (int)f; } public static int test_5_add () { double a = 2.0; double b = 3.0; return (int)(a + b); } public static int test_5_sub () { double a = 8.0; double b = 3.0; return (int)(a - b); } public static int test_24_mul () { double a = 8.0; double b = 3.0; return (int)(a * b); } public static int test_4_div () { double a = 8.0; double b = 2.0; return (int)(a / b); } public static int test_2_rem () { double a = 8.0; double b = 3.0; return (int)(a % b); } public static int test_2_neg () { double a = -2.0; return (int)(-a); } public static int test_46_float_add_spill () { // we overflow the FP stack double a = 1; double b = 2; double c = 3; double d = 4; double e = 5; double f = 6; double g = 7; double h = 8; double i = 9; return (int)(1.0 + (a + (b + (c + (d + (e + (f + (g + (h + i))))))))); } public static int test_4_float_sub_spill () { // we overflow the FP stack double a = 1; double b = 2; double c = 3; double d = 4; double e = 5; double f = 6; double g = 7; double h = 8; double i = 9; return -(int)(1.0 - (a - (b - (c - (d - (e - (f - (g - (h - i))))))))); ////// -(int)(1.0 - (1 - (2 - (3 - (4 - (5 - (6 - (7 - (8 - 9))))))))); } public static int test_362880_float_mul_spill () { // we overflow the FP stack double a = 1; double b = 2; double c = 3; double d = 4; double e = 5; double f = 6; double g = 7; double h = 8; double i = 9; return (int)(1.0 * (a * (b * (c * (d * (e * (f * (g * (h * i))))))))); } public static int test_4_long_cast () { long a = 1000; double d = (double)a; long b = (long)d; if (b != 1000) return 0; a = -1; d = (double)a; b = (long)d; if (b != -1) return 1; return 4; } public static int test_4_ulong_cast () { ulong a = 1000; double d = (double)a; ulong b = (ulong)d; if (b != 1000) return 0; a = 0xffffffffffffffff; float f = (float)a; if (!(f > 0f)) return 1; return 4; } public static int test_4_single_long_cast () { long a = 1000; float d = (float)a; long b = (long)d; if (b != 1000) return 0; a = -1; d = (float)a; b = (long)d; if (b != -1) return 1; return 4; } public static int test_0_lconv_to_r8 () { long a = 150; double b = (double) a; if (b != 150.0) return 1; return 0; } public static int test_0_lconv_to_r4 () { long a = 3000; float b = (float) a; if (b != 3000.0F) return 1; return 0; } static void doit (double value, out long m) { m = (long) value; } public static int test_0_ftol_clobber () { long m; doit (1.3, out m); if (m != 1) return 2; return 0; } public static int test_0_rounding () { long ticks = 631502475130080000L; long ticksperday = 864000000000L; double days = (double) ticks / ticksperday; if ((int)days != 730905) return 1; return 0; } /* FIXME: This only works on little-endian machines */ /* static unsafe int test_2_negative_zero () { int result = 0; double d = -0.0; float f = -0.0f; byte *ptr = (byte*)&d; if (ptr [7] == 0) return result; result ++; ptr = (byte*)&f; if (ptr [3] == 0) return result; result ++; return result; } */ public static int test_16_float_cmp () { double a = 2.0; double b = 1.0; int result = 0; bool val; val = a == a; if (!val) return result; result++; val = (a != a); if (val) return result; result++; val = a < a; if (val) return result; result++; val = a > a; if (val) return result; result++; val = a <= a; if (!val) return result; result++; val = a >= a; if (!val) return result; result++; val = b == a; if (val) return result; result++; val = b < a; if (!val) return result; result++; val = b > a; if (val) return result; result++; val = b <= a; if (!val) return result; result++; val = b >= a; if (val) return result; result++; val = a == b; if (val) return result; result++; val = a < b; if (val) return result; result++; val = a > b; if (!val) return result; result++; val = a <= b; if (val) return result; result++; val = a >= b; if (!val) return result; result++; return result; } public static int test_15_float_cmp_un () { double a = Double.NaN; double b = 1.0; int result = 0; bool val; val = a == a; if (val) return result; result++; val = a < a; if (val) return result; result++; val = a > a; if (val) return result; result++; val = a <= a; if (val) return result; result++; val = a >= a; if (val) return result; result++; val = b == a; if (val) return result; result++; val = b < a; if (val) return result; result++; val = b > a; if (val) return result; result++; val = b <= a; if (val) return result; result++; val = b >= a; if (val) return result; result++; val = a == b; if (val) return result; result++; val = a < b; if (val) return result; result++; val = a > b; if (val) return result; result++; val = a <= b; if (val) return result; result++; val = a >= b; if (val) return result; result++; return result; } public static int test_15_float_branch () { double a = 2.0; double b = 1.0; int result = 0; if (!(a == a)) return result; result++; if (a < a) return result; result++; if (a > a) return result; result++; if (!(a <= a)) return result; result++; if (!(a >= a)) return result; result++; if (b == a) return result; result++; if (!(b < a)) return result; result++; if (b > a) return result; result++; if (!(b <= a)) return result; result++; if (b >= a) return result; result++; if (a == b) return result; result++; if (a < b) return result; result++; if (!(a > b)) return result; result++; if (a <= b) return result; result++; if (!(a >= b)) return result; result++; return result; } public static int test_15_float_branch_un () { double a = Double.NaN; double b = 1.0; int result = 0; if (a == a) return result; result++; if (a < a) return result; result++; if (a > a) return result; result++; if (a <= a) return result; result++; if (a >= a) return result; result++; if (b == a) return result; result++; if (b < a) return result; result++; if (b > a) return result; result++; if (b <= a) return result; result++; if (b >= a) return result; result++; if (a == b) return result; result++; if (a < b) return result; result++; if (a > b) return result; result++; if (a <= b) return result; result++; if (a >= b) return result; result++; return result; } public static int test_0_float_precision () { float f1 = 3.40282346638528859E+38f; float f2 = 3.40282346638528859E+38f; float PositiveInfinity = 1.0f / 0.0f; float f = f1 + f2; return f == PositiveInfinity ? 0 : 1; } static double VALUE = 0.19975845134874831D; public static int test_0_float_conversion_reduces_double_precision () { double d = (float)VALUE; if (d != 0.19975845515727997d) return 1; return 0; } /* This doesn't work with llvm */ /* public static int test_0_long_to_double_conversion () { long l = 9223372036854775807L; long conv = (long)((double)l); if (conv != -9223372036854775808L) return 1; return 0; } */ public static int INT_VAL = 0x13456799; public static int test_0_int4_to_float_convertion () { double d = (double)(float)INT_VAL; if (d != 323315616) return 1; return 0; } public static int test_0_int8_to_float_convertion () { double d = (double)(float)(long)INT_VAL; if (d != 323315616) return 1; return 0; } }
// // 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 System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Store; using Microsoft.WindowsAzure.Management.Store.Models; namespace Microsoft.WindowsAzure.Management.Store { /// <summary> /// Provides REST operations for working with Store add-ins from the /// Windows Azure store service. /// </summary> internal partial class AddOnOperations : IServiceOperations<StoreManagementClient>, Microsoft.WindowsAzure.Management.Store.IAddOnOperations { /// <summary> /// Initializes a new instance of the AddOnOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal AddOnOperations(StoreManagementClient client) { this._client = client; } private StoreManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Store.StoreManagementClient. /// </summary> public StoreManagementClient Client { get { return this._client; } } /// <summary> /// The Create Store Item operation creates Windows Azure Store entries /// in a Windows Azure subscription. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service to which this store item /// will be assigned. /// </param> /// <param name='resourceName'> /// Required. The name of this resource. /// </param> /// <param name='addOnName'> /// Required. The add on name. /// </param> /// <param name='parameters'> /// Required. Parameters used to specify how the Create procedure will /// function. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> BeginCreatingAsync(string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (addOnName == null) { throw new ArgumentNullException("addOnName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Plan == null) { throw new ArgumentNullException("parameters.Plan"); } if (parameters.Type == null) { throw new ArgumentNullException("parameters.Type"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("addOnName", addOnName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/CloudServices/" + cloudServiceName.Trim() + "/resources/" + parameters.Type.Trim() + "/" + resourceName.Trim() + "/" + addOnName.Trim(); 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 httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(resourceElement); XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); typeElement.Value = parameters.Type; resourceElement.Add(typeElement); XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); planElement.Value = parameters.Plan; resourceElement.Add(planElement); if (parameters.PromotionCode != null) { XElement promotionCodeElement = new XElement(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure")); promotionCodeElement.Value = parameters.PromotionCode; resourceElement.Add(promotionCodeElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Delete Store Item operation deletes Windows Azure Store entries /// that re provisioned for a subscription. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service to which this store item /// will be assigned. /// </param> /// <param name='resourceProviderNamespace'> /// Required. The namespace in which this store item resides. /// </param> /// <param name='resourceProviderType'> /// Required. The type of store item to be deleted. /// </param> /// <param name='resourceProviderName'> /// Required. The name of this resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> BeginDeletingAsync(string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (resourceProviderType == null) { throw new ArgumentNullException("resourceProviderType"); } if (resourceProviderName == null) { throw new ArgumentNullException("resourceProviderName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("resourceProviderType", resourceProviderType); tracingParameters.Add("resourceProviderName", resourceProviderName); Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/CloudServices/" + cloudServiceName.Trim() + "/resources/" + resourceProviderNamespace.Trim() + "/" + resourceProviderType.Trim() + "/" + resourceProviderName.Trim(); 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.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Create Store Item operation creates Windows Azure Store entries /// in a Windows Azure subscription. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service to which this store item /// will be assigned. /// </param> /// <param name='resourceName'> /// Required. The name of this resource. /// </param> /// <param name='addOnName'> /// Required. The add on name. /// </param> /// <param name='parameters'> /// Required. Parameters used to specify how the Create procedure will /// function. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> CreateAsync(string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters, CancellationToken cancellationToken) { StoreManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("addOnName", addOnName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.AddOns.BeginCreatingAsync(cloudServiceName, resourceName, addOnName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// The Delete Store Item operation deletes Windows Azure Storeentries /// that are provisioned for a subscription. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service to which this store item /// will be assigned. /// </param> /// <param name='resourceProviderNamespace'> /// Required. The namespace in which this store item resides. /// </param> /// <param name='resourceProviderType'> /// Required. The type of store item to be deleted. /// </param> /// <param name='resourceProviderName'> /// Required. The name of this resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> DeleteAsync(string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName, CancellationToken cancellationToken) { StoreManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("resourceProviderType", resourceProviderType); tracingParameters.Add("resourceProviderName", resourceProviderName); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.AddOns.BeginDeletingAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// The Update Store Item operation creates Windows Azure Store entries /// in a Windows Azure subscription. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service to which this store item /// will be assigned. /// </param> /// <param name='resourceName'> /// Required. The name of this resource. /// </param> /// <param name='addOnName'> /// Required. The addon name. /// </param> /// <param name='parameters'> /// Required. Parameters used to specify how the Create procedure will /// function. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> UpdateAsync(string cloudServiceName, string resourceName, string addOnName, AddOnUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (addOnName == null) { throw new ArgumentNullException("addOnName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Plan == null) { throw new ArgumentNullException("parameters.Plan"); } if (parameters.Type == null) { throw new ArgumentNullException("parameters.Type"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("addOnName", addOnName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/CloudServices/" + cloudServiceName.Trim() + "/resources/" + parameters.Type.Trim() + "/" + resourceName.Trim() + "/" + addOnName.Trim(); 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 httpRequest.Headers.TryAddWithoutValidation("If-Match", "*"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(resourceElement); XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); typeElement.Value = parameters.Type; resourceElement.Add(typeElement); XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); planElement.Value = parameters.Plan; resourceElement.Add(planElement); if (parameters.PromotionCode != null) { XElement promotionCodeElement = new XElement(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure")); promotionCodeElement.Value = parameters.PromotionCode; resourceElement.Add(promotionCodeElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using J2N.Threading; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Util { /* * 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. */ [TestFixture] public class TestDoubleBarrelLRUCache : LuceneTestCase { private void TestCache(DoubleBarrelLRUCache<CloneableInteger, object> cache, int n) { object dummy = new object(); for (int i = 0; i < n; i++) { cache.Put(new CloneableInteger(i), dummy); } // access every 2nd item in cache for (int i = 0; i < n; i += 2) { Assert.IsNotNull(cache.Get(new CloneableInteger(i))); } // add n/2 elements to cache, the ones that weren't // touched in the previous loop should now be thrown away for (int i = n; i < n + (n / 2); i++) { cache.Put(new CloneableInteger(i), dummy); } // access every 4th item in cache for (int i = 0; i < n; i += 4) { Assert.IsNotNull(cache.Get(new CloneableInteger(i))); } // add 3/4n elements to cache, the ones that weren't // touched in the previous loops should now be thrown away for (int i = n; i < n + (n * 3 / 4); i++) { cache.Put(new CloneableInteger(i), dummy); } // access every 4th item in cache for (int i = 0; i < n; i += 4) { Assert.IsNotNull(cache.Get(new CloneableInteger(i))); } } [Test] public virtual void TestLRUCache() { const int n = 100; TestCache(new DoubleBarrelLRUCache<CloneableInteger, object>(n), n); } private class CacheThread : ThreadJob { private readonly TestDoubleBarrelLRUCache outerInstance; private readonly CloneableObject[] objs; private readonly DoubleBarrelLRUCache<CloneableObject, object> c; private readonly DateTime endTime; internal volatile bool failed; public CacheThread(TestDoubleBarrelLRUCache outerInstance, DoubleBarrelLRUCache<CloneableObject, object> c, CloneableObject[] objs, DateTime endTime) { this.outerInstance = outerInstance; this.c = c; this.objs = objs; this.endTime = endTime; } public override void Run() { try { long count = 0; long miss = 0; long hit = 0; int limit = objs.Length; while (true) { CloneableObject obj = objs[(int)((count / 2) % limit)]; object v = c.Get(obj); if (v == null) { c.Put(new CloneableObject(obj), obj); miss++; } else { Assert.True(obj == v); hit++; } if ((++count % 10000) == 0) { if (DateTime.Now.CompareTo(endTime) > 0) { break; } } } outerInstance.AddResults(miss, hit); } catch (Exception t) { failed = true; throw new Exception(t.Message, t); } } } internal long totMiss, totHit; internal virtual void AddResults(long miss, long hit) { totMiss += miss; totHit += hit; } [Test] public virtual void TestThreadCorrectness() { const int NUM_THREADS = 4; const int CACHE_SIZE = 512; int OBJ_COUNT = 3 * CACHE_SIZE; DoubleBarrelLRUCache<CloneableObject, object> c = new DoubleBarrelLRUCache<CloneableObject, object>(1024); CloneableObject[] objs = new CloneableObject[OBJ_COUNT]; for (int i = 0; i < OBJ_COUNT; i++) { objs[i] = new CloneableObject(new object()); } CacheThread[] threads = new CacheThread[NUM_THREADS]; DateTime endTime = DateTime.Now.AddSeconds(1); for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new CacheThread(this, c, objs, endTime); threads[i].Start(); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].Join(); Assert.False(threads[i].failed); } //System.out.println("hits=" + totHit + " misses=" + totMiss); } private class CloneableObject : DoubleBarrelLRUCache.CloneableKey { private readonly object value; public CloneableObject(object value) { this.value = value; } public override bool Equals(object other) { if (other.GetType().Equals(typeof (CloneableObject))) return this.value.Equals(((CloneableObject) other).value); else return false; } public override int GetHashCode() { return value.GetHashCode(); } public override object Clone() { return new CloneableObject(value); } } protected internal class CloneableInteger : DoubleBarrelLRUCache.CloneableKey { internal int? value; public CloneableInteger(int? value) { this.value = value; } public override bool Equals(object other) { return this.value.Equals(((CloneableInteger)other).value); } public override int GetHashCode() { return value.GetHashCode(); } public override object Clone() { return new CloneableInteger(value); } } } }
namespace Azure.Messaging.EventHubs { public partial class EventData { public EventData(System.ReadOnlyMemory<byte> eventBody) { } protected EventData(System.ReadOnlyMemory<byte> eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { } public System.ReadOnlyMemory<byte> Body { get { throw null; } } public System.IO.Stream BodyAsStream { get { throw null; } } public System.DateTimeOffset EnqueuedTime { get { throw null; } } public long Offset { get { throw null; } } public string PartitionKey { get { throw null; } } public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public long SequenceNumber { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, object> SystemProperties { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnection : System.IAsyncDisposable { protected EventHubConnection() { } public EventHubConnection(string connectionString) { } public EventHubConnection(string connectionString, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public EventHubConnection(string connectionString, string eventHubName) { } public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { } public EventHubConnection(string connectionString, string eventHubName, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnectionOptions { public EventHubConnectionOptions() { } public System.Net.IWebProxy Proxy { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsTransportType TransportType { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProperties { protected internal EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { } public System.DateTimeOffset CreatedOn { get { throw null; } } public string Name { get { throw null; } } public string[] PartitionIds { get { throw null; } } } public partial class EventHubsException : System.Exception { public EventHubsException(bool isTransient, string eventHubName) { } public EventHubsException(bool isTransient, string eventHubName, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason, System.Exception innerException) { } public EventHubsException(bool isTransient, string eventHubName, string message, System.Exception innerException) { } public EventHubsException(string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public string EventHubName { get { throw null; } } public bool IsTransient { get { throw null; } } public override string Message { get { throw null; } } public Azure.Messaging.EventHubs.EventHubsException.FailureReason Reason { get { throw null; } } public override string ToString() { throw null; } public enum FailureReason { GeneralError = 0, ClientClosed = 1, ConsumerDisconnected = 2, ResourceNotFound = 3, MessageSizeExceeded = 4, QuotaExceeded = 5, ServiceBusy = 6, ServiceTimeout = 7, ServiceCommunicationProblem = 8, } } public enum EventHubsRetryMode { Fixed = 0, Exponential = 1, } public partial class EventHubsRetryOptions { public EventHubsRetryOptions() { } public Azure.Messaging.EventHubs.EventHubsRetryPolicy CustomRetryPolicy { get { throw null; } set { } } public System.TimeSpan Delay { get { throw null; } set { } } public System.TimeSpan MaximumDelay { get { throw null; } set { } } public int MaximumRetries { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryMode Mode { get { throw null; } set { } } public System.TimeSpan TryTimeout { get { throw null; } set { } } } public abstract partial class EventHubsRetryPolicy { protected EventHubsRetryPolicy() { } public abstract System.TimeSpan? CalculateRetryDelay(System.Exception lastException, int attemptCount); public abstract System.TimeSpan CalculateTryTimeout(int attemptCount); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public enum EventHubsTransportType { AmqpTcp = 0, AmqpWebSockets = 1, } public partial class PartitionProperties { protected internal PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { } public long BeginningSequenceNumber { get { throw null; } } public string EventHubName { get { throw null; } } public string Id { get { throw null; } } public bool IsEmpty { get { throw null; } } public long LastEnqueuedOffset { get { throw null; } } public long LastEnqueuedSequenceNumber { get { throw null; } } public System.DateTimeOffset LastEnqueuedTime { get { throw null; } } } } namespace Azure.Messaging.EventHubs.Consumer { public partial class EventHubConsumerClient : System.IAsyncDisposable { public const string DefaultConsumerGroupName = "$Default"; protected EventHubConsumerClient() { } public EventHubConsumerClient(string consumerGroup, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString) { } public EventHubConsumerClient(string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName) { } public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(bool startReadingAtEarliestEvent, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions = null, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConsumerClientOptions { public EventHubConsumerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EventPosition : System.IEquatable<Azure.Messaging.EventHubs.Consumer.EventPosition> { private object _dummy; private int _dummyPrimitive; public static Azure.Messaging.EventHubs.Consumer.EventPosition Earliest { get { throw null; } } public static Azure.Messaging.EventHubs.Consumer.EventPosition Latest { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.EventPosition other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromEnqueuedTime(System.DateTimeOffset enqueuedTime) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromOffset(long offset, bool isInclusive = true) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromSequenceNumber(long sequenceNumber, bool isInclusive = true) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LastEnqueuedEventProperties : System.IEquatable<Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties> { public LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; } public System.DateTimeOffset? EnqueuedTime { get { throw null; } } public System.DateTimeOffset? LastReceivedTime { get { throw null; } } public long? Offset { get { throw null; } } public long? SequenceNumber { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionContext { protected internal PartitionContext(string partitionId) { } public string PartitionId { get { throw null; } } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct PartitionEvent { private object _dummy; private int _dummyPrimitive; public PartitionEvent(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data) { throw null; } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } } public partial class ReadEventOptions { public ReadEventOptions() { } public int CacheEventCount { get { throw null; } set { } } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Primitives { public partial class EventProcessorCheckpoint { public EventProcessorCheckpoint() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition StartingPosition { get { throw null; } set { } } } public partial class EventProcessorOptions { public EventProcessorOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public Azure.Messaging.EventHubs.Processor.LoadBalancingStrategy LoadBalancingStrategy { get { throw null; } set { } } public System.TimeSpan LoadBalancingUpdateInterval { get { throw null; } set { } } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public System.TimeSpan PartitionOwnershipExpirationInterval { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventProcessorPartition { public EventProcessorPartition() { } public string PartitionId { get { throw null; } protected internal set { } } } public partial class EventProcessorPartitionOwnership { public EventProcessorPartitionOwnership() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public System.DateTimeOffset LastModifiedTime { get { throw null; } set { } } public string OwnerIdentifier { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public string Version { get { throw null; } set { } } } public abstract partial class EventProcessor<TPartition> where TPartition : Azure.Messaging.EventHubs.Primitives.EventProcessorPartition, new() { protected EventProcessor() { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string Identifier { get { throw null; } } public bool IsRunning { get { throw null; } protected set { } } protected Azure.Messaging.EventHubs.EventHubsRetryPolicy RetryPolicy { get { throw null; } } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ClaimOwnershipAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership> desiredOwnership, System.Threading.CancellationToken cancellationToken); protected internal virtual Azure.Messaging.EventHubs.EventHubConnection CreateConnection() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint>> ListCheckpointsAsync(System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ListOwnershipAsync(System.Threading.CancellationToken cancellationToken); protected virtual System.Threading.Tasks.Task OnInitializingPartitionAsync(TPartition partition, System.Threading.CancellationToken cancellationToken) { throw null; } protected virtual System.Threading.Tasks.Task OnPartitionProcessingStoppedAsync(TPartition partition, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken) { throw null; } protected abstract System.Threading.Tasks.Task OnProcessingErrorAsync(System.Exception exception, TPartition partition, string operationDescription, System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task OnProcessingEventBatchAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> events, TPartition partition, System.Threading.CancellationToken cancellationToken); protected virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties(string partitionId) { throw null; } public virtual void StartProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StartProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual void StopProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StopProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiver : System.IAsyncDisposable { protected PartitionReceiver() { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition InitialPosition { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public string PartitionId { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.TimeSpan maximumWaitTime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiverOptions { public PartitionReceiverOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public System.TimeSpan? DefaultMaximumReceiveWaitTime { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Processor { public enum LoadBalancingStrategy { Balanced = 0, Greedy = 1, } public partial class PartitionClosingEventArgs { public PartitionClosingEventArgs(string partitionId, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public string PartitionId { get { throw null; } } public Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason Reason { get { throw null; } } } public partial class PartitionInitializingEventArgs { public PartitionInitializingEventArgs(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition defaultStartingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessErrorEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessErrorEventArgs(string partitionId, string operation, System.Exception exception, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public System.Exception Exception { get { throw null; } } public string Operation { get { throw null; } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessEventArgs(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task> updateCheckpointImplementation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public bool HasEvent { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } public System.Threading.Tasks.Task UpdateCheckpointAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public enum ProcessingStoppedReason { Shutdown = 0, OwnershipLost = 1, } } namespace Azure.Messaging.EventHubs.Producer { public partial class CreateBatchOptions : Azure.Messaging.EventHubs.Producer.SendEventOptions { public CreateBatchOptions() { } public long? MaximumSizeInBytes { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public sealed partial class EventDataBatch : System.IDisposable { internal EventDataBatch() { } public int Count { get { throw null; } } public long MaximumSizeInBytes { get { throw null; } } public long SizeInBytes { get { throw null; } } public void Dispose() { } public bool TryAdd(Azure.Messaging.EventHubs.EventData eventData) { throw null; } } public partial class EventHubProducerClient : System.IAsyncDisposable { protected EventHubProducerClient() { } public EventHubProducerClient(Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString) { } public EventHubProducerClient(string connectionString, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public EventHubProducerClient(string connectionString, string eventHubName) { } public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString, string eventHubName, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(Azure.Messaging.EventHubs.Producer.CreateBatchOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(Azure.Messaging.EventHubs.Producer.EventDataBatch eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, Azure.Messaging.EventHubs.Producer.SendEventOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProducerClientOptions { public EventHubProducerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class SendEventOptions { public SendEventOptions() { } public string PartitionId { get { throw null; } set { } } public string PartitionKey { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Microsoft.Extensions.Azure { public static partial class EventHubClientBuilderExtensions { public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClientWithNamespace<TBuilder>(this TBuilder builder, string consumerGroup, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClientWithNamespace<TBuilder>(this TBuilder builder, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // classes dda_line_interpolator, dda2_line_interpolator // //---------------------------------------------------------------------------- using System; namespace MatterHackers.Agg { //===================================================dda_line_interpolator public sealed class dda_line_interpolator { private int m_y; private int m_inc; private int m_dy; //int m_YShift; private int m_FractionShift; //-------------------------------------------------------------------- public dda_line_interpolator(int FractionShift) { m_FractionShift = FractionShift; } //-------------------------------------------------------------------- public dda_line_interpolator(int y1, int y2, int count, int FractionShift) { m_FractionShift = FractionShift; m_y = (y1); m_inc = (((y2 - y1) << m_FractionShift) / (int)(count)); m_dy = (0); } //-------------------------------------------------------------------- //public void operator ++ () public void Next() { m_dy += m_inc; } //-------------------------------------------------------------------- //public void operator -- () public void Prev() { m_dy -= m_inc; } //-------------------------------------------------------------------- //public void operator += (int n) public void Next(int n) { m_dy += m_inc * (int)n; } //-------------------------------------------------------------------- //public void operator -= (int n) public void Prev(int n) { m_dy -= m_inc * (int)n; } //-------------------------------------------------------------------- public int y() { return m_y + (m_dy >> (m_FractionShift)); } // - m_YShift)); } public int dy() { return m_dy; } } //=================================================dda2_line_interpolator public sealed class dda2_line_interpolator { private enum save_size_e { save_size = 2 }; //-------------------------------------------------------------------- public dda2_line_interpolator() { } //-------------------------------------------- Forward-adjusted line public dda2_line_interpolator(int y1, int y2, int count) { m_cnt = (count <= 0 ? 1 : count); m_lft = ((y2 - y1) / m_cnt); m_rem = ((y2 - y1) % m_cnt); m_mod = (m_rem); m_y = (y1); if (m_mod <= 0) { m_mod += count; m_rem += count; m_lft--; } m_mod -= count; } //-------------------------------------------- Backward-adjusted line public dda2_line_interpolator(int y1, int y2, int count, int unused) { m_cnt = (count <= 0 ? 1 : count); m_lft = ((y2 - y1) / m_cnt); m_rem = ((y2 - y1) % m_cnt); m_mod = (m_rem); m_y = (y1); if (m_mod <= 0) { m_mod += count; m_rem += count; m_lft--; } } //-------------------------------------------- Backward-adjusted line public dda2_line_interpolator(int y, int count) { m_cnt = (count <= 0 ? 1 : count); m_lft = ((y) / m_cnt); m_rem = ((y) % m_cnt); m_mod = (m_rem); m_y = (0); if (m_mod <= 0) { m_mod += count; m_rem += count; m_lft--; } } /* //-------------------------------------------------------------------- public void save(save_data_type* data) { data[0] = m_mod; data[1] = m_y; } //-------------------------------------------------------------------- public void load(save_data_type* data) { m_mod = data[0]; m_y = data[1]; } */ //-------------------------------------------------------------------- //public void operator++() public void Next() { m_mod += m_rem; m_y += m_lft; if (m_mod > 0) { m_mod -= m_cnt; m_y++; } } //-------------------------------------------------------------------- //public void operator--() public void Prev() { if (m_mod <= m_rem) { m_mod += m_cnt; m_y--; } m_mod -= m_rem; m_y -= m_lft; } //-------------------------------------------------------------------- public void adjust_forward() { m_mod -= m_cnt; } //-------------------------------------------------------------------- public void adjust_backward() { m_mod += m_cnt; } //-------------------------------------------------------------------- public int mod() { return m_mod; } public int rem() { return m_rem; } public int lft() { return m_lft; } //-------------------------------------------------------------------- public int y() { return m_y; } private int m_cnt; private int m_lft; private int m_rem; private int m_mod; private int m_y; } //---------------------------------------------line_bresenham_interpolator public sealed class line_bresenham_interpolator { private int m_x1_lr; private int m_y1_lr; private int m_x2_lr; private int m_y2_lr; private bool m_ver; private int m_len; private int m_inc; private dda2_line_interpolator m_interpolator; public enum subpixel_scale_e { subpixel_shift = 8, subpixel_scale = 1 << subpixel_shift, subpixel_mask = subpixel_scale - 1 } //-------------------------------------------------------------------- public static int line_lr(int v) { return v >> (int)subpixel_scale_e.subpixel_shift; } //-------------------------------------------------------------------- public line_bresenham_interpolator(int x1, int y1, int x2, int y2) { m_x1_lr = (line_lr(x1)); m_y1_lr = (line_lr(y1)); m_x2_lr = (line_lr(x2)); m_y2_lr = (line_lr(y2)); m_ver = (Math.Abs(m_x2_lr - m_x1_lr) < Math.Abs(m_y2_lr - m_y1_lr)); if (m_ver) { m_len = (int)Math.Abs(m_y2_lr - m_y1_lr); } else { m_len = (int)Math.Abs(m_x2_lr - m_x1_lr); } m_inc = (m_ver ? ((y2 > y1) ? 1 : -1) : ((x2 > x1) ? 1 : -1)); m_interpolator = new dda2_line_interpolator(m_ver ? x1 : y1, m_ver ? x2 : y2, (int)m_len); } //-------------------------------------------------------------------- public bool is_ver() { return m_ver; } public int len() { return m_len; } public int inc() { return m_inc; } //-------------------------------------------------------------------- public void hstep() { m_interpolator.Next(); m_x1_lr += m_inc; } //-------------------------------------------------------------------- public void vstep() { m_interpolator.Next(); m_y1_lr += m_inc; } //-------------------------------------------------------------------- public int x1() { return m_x1_lr; } public int y1() { return m_y1_lr; } public int x2() { return line_lr(m_interpolator.y()); } public int y2() { return line_lr(m_interpolator.y()); } public int x2_hr() { return m_interpolator.y(); } public int y2_hr() { return m_interpolator.y(); } } }
#region License /* * Copyright (C) 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Threading; using Java.Util.Concurrent.Helpers; namespace Java.Util.Concurrent.Locks { /// <summary> /// A reentrant mutual exclusion <see cref="ILock"/> with the same basic /// behavior and semantics as the implicit monitor lock accessed using /// <c>lock</c> statements, but with extended capabilities. /// </summary> /// <remarks> /// <para> /// A <see cref="ReentrantLock"/> is <b>owned</b> by the thread last /// successfully locking, but not yet unlocking it. A thread invoking /// <see cref="Lock()"/> will return, successfully acquiring the lock, when /// the lock is not owned by another thread. The method will return /// immediately if the current thread already owns the lock. This can /// be checked using methods <see cref="IsHeldByCurrentThread"/>, and /// <see cref="HoldCount"/>. /// </para> /// <para> /// The constructor for this class accepts an optional /// <b>fairness</b> parameter. When set <c>true</c>, under /// contention, locks favor granting access to the longest-waiting /// thread. Otherwise this lock does not guarantee any particular /// access order. Programs using fair locks accessed by many threads /// may display lower overall throughput (i.e., are slower; often much /// slower) than those using the default setting, but have smaller /// variances in times to obtain locks and guarantee lack of /// starvation. Note however, that fairness of locks does not guarantee /// fairness of thread scheduling. Thus, one of many threads using a /// fair lock may obtain it multiple times in succession while other /// active threads are not progressing and not currently holding the /// lock. /// Also note that the untimed <see cref="TryLock()"/> method does not /// honor the fairness setting. It will succeed if the lock /// is available even if other threads are waiting. /// </para> /// <para> /// It is recommended practice to <b>always</b> immediately follow a call /// to <see cref="Lock()"/> with a <c>try</c> block or make user of /// the <c>using</c> keyward in C#, most typically in a before/after /// construction such as: /// /// <code> /// class X { /// private ReentrantLock lock = new ReentrantLock(); /// // ... /// /// public void m() { /// lock.Lock(); // block until condition holds /// try { /// // ... method body /// } finally { /// lock.Unlock() /// } /// } /// } /// </code> /// </para> /// <para> /// In addition to implementing the <see cref="ILock"/> interface, this /// class defines methods <see cref="IsLocked"/> and /// <see cref="GetWaitQueueLength"/> , as well as some associated /// <c>protected</c> access methods that may be useful for /// instrumentation and monitoring. /// </para> /// <para> /// Serialization of this class behaves in the same way as built-in /// locks: a deserialized lock is in the unlocked state, regardless of /// its state when serialized. /// </para> /// <para> /// This lock supports a maximum of 2147483648 recursive locks by /// the same thread. /// </para> /// </remarks> /// <author>Doug Lea</author> /// <author>Dawid Kurzyniec</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu (.NET)</author> [Serializable] public class ReentrantLock : ILock, IDisposable, ConditionVariable.IExclusiveLock { #region Internal Helper Classes /// <summary> /// Base of synchronization control for this lock. Subclassed /// into fair and nonfair versions below. /// </summary> [Serializable] private abstract class Sync { [NonSerialized] protected Thread _owner; [NonSerialized] protected int _holds; internal Thread Owner { get { lock (this) return _owner; } } public int HoldCount { get { lock (this) return IsHeldByCurrentThread ? _holds : 0; } } public bool IsHeldByCurrentThread { get { lock (this) return Thread.CurrentThread == _owner; } } public bool IsLocked { get { lock (this) return _owner != null; } } public bool TryLock() { Thread caller = Thread.CurrentThread; lock (this) return GetHold(caller); } public virtual bool HasQueuedThreads { get { throw new NotSupportedException("Use FAIR version"); } } public virtual int QueueLength { get { throw new NotSupportedException("Use FAIR version"); } } public virtual ICollection<Thread> QueuedThreads { get { throw new NotSupportedException("Use FAIR version"); } } public virtual bool IsQueued(Thread thread) { throw new NotSupportedException("Use FAIR version"); } public abstract void Lock(); public abstract bool IsFair { get; } public abstract void LockInterruptibly(); public abstract bool TryLock(TimeSpan timespan); public abstract void Unlock(); protected bool GetHold(Thread caller) { if (_owner == null) { _owner = caller; _holds = 1; return true; } if (caller == _owner) { int holds = _holds; if (++holds < 0) throw new SystemException("Maximum lock count exceeded"); _holds = holds; return true; } return false; } } [Serializable] private sealed class NonfairSync : Sync { public override bool IsFair { get { return false; } } /// <summary> /// Performs lock. Try immediate barge, backing up to normal acquire on failure. /// </summary> public override void Lock() { Thread caller = Thread.CurrentThread; lock (this) { if (GetHold(caller)) return; bool wasInterrupted = false; try { while (true) { try { Monitor.Wait(this); } catch (ThreadInterruptedException) { wasInterrupted = true; // no need to notify; if we were signalled, we // will act as signalled, ignoring the // interruption } if (_owner == null) { _owner = caller; _holds = 1; return; } } } finally { if (wasInterrupted) Thread.CurrentThread.Interrupt(); } } } public override void LockInterruptibly() { Thread caller = Thread.CurrentThread; lock (this) { if (GetHold(caller)) return; try { do { Monitor.Wait(this); } while (_owner != null); _owner = caller; _holds = 1; return; } catch (ThreadInterruptedException e) { if (_owner == null) Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(e); } } } public override bool TryLock(TimeSpan durationToWait) { Thread caller = Thread.CurrentThread; lock (this) { if (GetHold(caller)) return true; if (durationToWait.Ticks <= 0) return false; DateTime deadline = DateTime.UtcNow.Add(durationToWait); try { for (;;) { Monitor.Wait(this, durationToWait); if (_owner == null) { _owner = caller; _holds = 1; return true; } durationToWait = deadline.Subtract(DateTime.UtcNow); if ( durationToWait.Ticks <= 0) return false; } } catch (ThreadInterruptedException e) { if (_owner == null ) Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(e); } } } public override void Unlock() { lock (this) { if (Thread.CurrentThread != _owner) { throw new SynchronizationLockException("Not owner"); } if (--_holds == 0) { _owner = null; Monitor.Pulse(this); } } } } [Serializable] private sealed class FairSync : Sync, IQueuedSync, IDeserializationCallback { [NonSerialized] private IWaitQueue _wq = new FIFOWaitQueue(); public override bool IsFair { get { return true; } } public bool Recheck(WaitNode node) { Thread caller = Thread.CurrentThread; lock (this) { if(GetHold(caller)) return true; _wq.Enqueue(node); return false; } } public void TakeOver(WaitNode node) { lock (this) { Debug.Assert(_holds == 1 && _owner == Thread.CurrentThread); _owner = node.Owner; } } public override void Lock() { Thread caller = Thread.CurrentThread; lock (this) { if(GetHold(caller)) return; } WaitNode n = new WaitNode(); n.DoWaitUninterruptibly(this); } public override void LockInterruptibly() { Thread caller = Thread.CurrentThread; lock (this) { if (GetHold(caller)) return; } WaitNode n = new WaitNode(); n.DoWait(this); } public override bool TryLock(TimeSpan timespan) { Thread caller = Thread.CurrentThread; lock (this) { if (GetHold(caller)) return true; } WaitNode n = new WaitNode(); return n.DoTimedWait(this, timespan); } private WaitNode GetSignallee(Thread caller) { lock (this) { if (caller != _owner) { throw new SynchronizationLockException("Not owner"); } if (_holds >= 2) // current thread will keep the lock { --_holds; return null; } WaitNode w = _wq.Dequeue(); if (w == null) // if none, clear for new arrivals { _owner = null; _holds = 0; } return w; } } public override void Unlock() { Thread caller = Thread.CurrentThread; for (;; ) { WaitNode w = GetSignallee(caller); if (w == null) return; // no one to signal if (w.Signal(this)) return; // notify if still waiting, else skip } } public override bool HasQueuedThreads { get { lock (this) { return _wq.HasNodes; } } } public override int QueueLength { get { lock (this) { return _wq.Length; } } } public override ICollection<Thread> QueuedThreads { get { lock (this) { return _wq.WaitingThreads; } } } public override bool IsQueued(Thread thread) { lock (this) { return _wq.IsWaiting(thread); } } #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) { lock (this) { _wq = new FIFOWaitQueue(); } } #endregion } #endregion private readonly Sync sync; /// <summary> /// Queries the number of holds on this lock by the current thread. /// /// <p/> /// A thread has a hold on a lock for each lock action that is not /// matched by an unlock action. /// /// <p/> /// The hold count information is typically only used for testing and /// debugging purposes. For example, if a certain section of code should /// not be entered with the lock already held then we can assert that /// fact: /// /// <code> /// class X { /// ReentrantLock lock = new ReentrantLock(); /// // ... /// public void m() { /// Debug.Assert( lock.HoldCount() == 0 ); /// lock.Lock(); /// try { /// // ... method body /// } finally { /// lock.Unlock(); /// } /// } /// } /// </code> /// </summary> /// <returns> /// The number of holds on this lock by the current thread, /// or zero if this lock is not held by the current thread. /// </returns> public virtual int HoldCount { get { return sync.HoldCount; } } /// <summary> /// Queries if this lock is held by the current thread. /// /// <p/> /// This method is typically used for debugging and /// testing. For example, a method that should only be called while /// a lock is held can assert that this is the case: /// /// <code> /// class X { /// ReentrantLock lock = new ReentrantLock(); /// // ... /// /// public void m() { /// Debug.Assert( lock.IsHeldByCurrentThread ); /// // ... method body /// } /// } /// </code> /// /// <p/> /// It can also be used to ensure that a reentrant lock is used /// in a non-reentrant manner, for example: /// /// <code> /// class X { /// ReentrantLock lock = new ReentrantLock(); /// // ... /// /// public void m() { /// Debug.Assert( !lock.IsHeldByCurrentThread ); /// lock.Lock(); /// try { /// // ... method body /// } finally { /// lock.Unlock(); /// } /// } /// } /// </code> /// </summary> /// <returns> <c>true</c> if current thread holds this lock and /// <c>false</c> otherwise. /// </returns> public virtual bool IsHeldByCurrentThread { get { return sync.IsHeldByCurrentThread; } } /// <summary> /// Queries if this lock is held by any thread. This method is /// designed for use in monitoring of the system state, /// not for synchronization control. /// </summary> /// <returns> <c>true</c> if any thread holds this lock and /// <c>false</c> otherwise. /// </returns> public virtual bool IsLocked { get { return sync.IsLocked; } } /// <summary> Returns <c>true</c> if this lock has fairness set true.</summary> /// <returns> <c>true</c> if this lock has fairness set true. /// </returns> public virtual bool IsFair { get { return sync.IsFair; } } /// <summary> /// Returns the thread that currently owns this lock, or /// <c>null</c> if not owned. Note that the owner may be /// momentarily <c>null</c> even if there are threads trying to /// acquire the lock but have not yet done so. This method is /// designed to facilitate construction of subclasses that provide /// more extensive lock monitoring facilities. /// </summary> /// <returns> the owner, or <c>null</c> if not owned. /// </returns> protected internal virtual Thread Owner { get { return sync.Owner; } } /// <summary> /// Returns an estimate of the number of threads waiting to /// acquire this lock. The value is only an estimate because the number of /// threads may change dynamically while this method traverses /// internal data structures. This method is designed for use in /// monitoring of the system state, not for synchronization /// control. /// </summary> /// <returns> the estimated number of threads waiting for this lock /// </returns> public virtual int QueueLength { get { return sync.QueueLength; } } /// <summary> Creates an instance of <see cref="Spring.Threading.Locks.ReentrantLock"/>. /// This is equivalent to using <tt>ReentrantLock(false)</tt>. /// </summary> public ReentrantLock() : this(false) { } /// <summary> /// Creates an instance of <see cref="Spring.Threading.Locks.ReentrantLock"/> with the /// given fairness policy. /// </summary> /// <param name="fair"><c>true</c> if this lock will be fair, else <c>false</c> /// </param> public ReentrantLock(bool fair) { sync = fair ? (Sync) new FairSync() : new NonfairSync(); } /// <summary> /// Acquires the lock and returns an <see cref="IDisposable"/> that /// can be used to unlock when disposed. /// </summary> /// <remarks> /// <para> /// Acquires the lock if it is not held by another thread and returns /// immediately, setting the lock hold count to one. /// </para> /// <para> /// If the <see cref="Thread.CurrentThread">current thread</see> /// already holds the lock then the hold count is incremented by one and /// the method returns immediately. /// </para> /// <para> /// If the lock is held by another thread then the /// current thread becomes disabled for thread scheduling /// purposes and lies dormant until the lock has been acquired, /// at which time the lock hold count is set to one. /// </para> /// <example> /// Below is a typical use of <see cref="Lock"/> /// <code language="c#"> /// ReentrantLock reentrantLock = ...; /// /// using(reentrantLock.Lock()) /// { /// // locked /// } /// // unlocked. /// </code> /// it is equvilant to /// <code language="c#"> /// ReentrantLock reentrantLock = ...; /// /// reentrantLock.Lock(); /// try { /// // locked /// } /// finally /// { /// reentrantLock.Unlock(); /// } /// // unlocked /// </code> /// </example> /// </remarks> /// <returns> /// An <see cref="IDisposable"/> object that unlocks current /// <see cref="ReentrantLock"/> when it is disposed. /// </returns> /// <seealso cref="LockInterruptibly"/> public virtual IDisposable Lock() { sync.Lock(); return this; } /// <summary> /// Acquires the lock unless <see cref="System.Threading.Thread.Interrupt()"/> is called on the current thread /// /// <p/> /// Acquires the lock if it is not held by another thread and returns /// immediately, setting the lock hold count to one. /// /// <p/> /// If the current thread already holds this lock then the hold count /// is incremented by one and the method returns immediately. /// /// <p/> /// If the lock is held by another thread then the /// current thread becomes disabled for thread scheduling /// purposes and lies dormant until one of two things happens: /// /// <list type="bullet"> /// <item>The lock is acquired by the current thread</item> /// <item>Some other thread calls <see cref="System.Threading.Thread.Interrupt()"/> on the current thread.</item> /// </list> /// /// <p/>If the lock is acquired by the current thread then the lock hold /// count is set to one. /// /// <p/>If the current thread: /// /// <list type="bullet"> /// <item>has its interrupted status set on entry to this method</item> /// <item><see cref="System.Threading.Thread.Interrupt()"/> is called while acquiring the lock</item> /// </list> /// /// then <see cref="System.Threading.ThreadInterruptedException"/> is thrown and the current thread's /// interrupted status is cleared. /// /// <p/> /// In this implementation, as this method is an explicit interruption /// point, preference is given to responding to the interrupt over normal or reentrant /// acquisition of the lock. /// </summary> /// <exception cref="System.Threading.ThreadInterruptedException">if the current thread is interrupted</exception> /// /// <summary> /// Acquires the lock unless <see cref="Thread.Interrupt()"/> is called /// on the current thread. Returns an <see cref="IDisposable"/> that /// can be used to unlock if the lock is sucessfully obtained. /// </summary> /// <remarks> /// <para> /// Acquires the lock if it is not held by another thread and returns /// immediately, setting the lock hold count to one. /// </para> /// <para> /// If the current thread already holds this lock then the hold count /// is incremented by one and the method returns immediately. /// </para> /// <para> /// If the lock is held by another thread then the /// current thread becomes disabled for thread scheduling /// purposes and lies dormant until one of two things happens: /// </para> /// <list type="bullet"> /// <item> /// The lock is acquired by the current thread. /// </item> /// <item> /// Some other thread calls <see cref="Thread.Interrupt()"/> on the current thread. /// </item> /// </list> /// <para> /// If the lock is acquired by the current thread then the lock hold /// count is set to one. /// </para> /// <para> /// If the current thread: /// </para> /// <list type="bullet"> /// <item>has its interrupted status set on entry to this method</item> /// <item><see cref="Thread.Interrupt()"/> is called while acquiring the lock</item> /// </list> /// <para> /// then <see cref="ThreadInterruptedException"/> is thrown and the current thread's /// interrupted status is cleared. /// </para> /// <para> /// In this implementation, as this method is an explicit interruption /// point, preference is given to responding to the interrupt over normal or reentrant /// acquisition of the lock. /// </para> /// <example> /// Below is a typical use of <see cref="LockInterruptibly"/> /// <code language="c#"> /// ReentrantLock reentrantLock = ...; /// /// using(reentrantLock.LockInterruptibly()) /// { /// // locked /// } /// // unlocked. /// </code> /// it is equvilant to /// <code language="c#"> /// ReentrantLock reentrantLock = ...; /// /// reentrantLock.LockInterruptibly(); /// try { /// // locked /// } /// finally /// { /// reentrantLock.Unlock(); /// } /// // unlocked /// </code> /// </example> /// </remarks> /// <returns> /// An <see cref="IDisposable"/> object that unlocks current /// <see cref="ReentrantLock"/> when it is disposed. /// </returns> /// <exception cref="ThreadInterruptedException"> /// If the current thread is interrupted. /// </exception> /// <seealso cref="Lock"/> public virtual IDisposable LockInterruptibly() { sync.LockInterruptibly(); return this; } /// <summary> /// Acquires the lock only if it is not held by another thread at the time /// of invocation. /// /// <p/> /// Acquires the lock if it is not held by another thread and /// returns immediately with the value <c>true</c>, setting the /// lock hold count to one. Even when this lock has been set to use a /// fair ordering policy, a call to <see cref="Spring.Threading.Locks.ReentrantLock.TryLock()"/> <b>will</b> /// immediately acquire the lock if it is available, whether or not /// other threads are currently waiting for the lock. /// This &quot;barging&quot; behavior can be useful in certain /// circumstances, even though it breaks fairness. If you want to honor /// the fairness setting for this lock, then use /// <see cref="Spring.Threading.Locks.ReentrantLock.TryLock(TimeSpan)"/> /// which is almost equivalent (it also detects interruption). /// /// <p/> /// If the current thread /// already holds this lock then the hold count is incremented by one and /// the method returns <c>true</c>. /// /// <p/> /// If the lock is held by another thread then this method will return /// immediately with the value <c>false</c>. /// /// </summary> /// <returns> <c>true</c> if the lock was free and was acquired by the /// current thread, or the lock was already held by the current thread, /// <c>false</c> otherwise. /// </returns> public virtual bool TryLock() { return sync.TryLock(); } /// <summary> /// Acquires the lock if it is not held by another thread within the given /// waiting time and <see cref="System.Threading.Thread.Interrupt()"/> hasn't been called on the current thread /// /// <p/> /// Acquires the lock if it is not held by another thread and returns /// immediately with the value <c>true</c>, setting the lock hold count /// to one. If this lock has been set to use a fair ordering policy then /// an available lock <b>will not</b> be acquired if any other threads /// are waiting for the lock. This is in contrast to the <see cref="Spring.Threading.Locks.ReentrantLock.TryLock()"/> /// method. If you want a timed <see cref="Spring.Threading.Locks.ReentrantLock.TryLock()"/> that does permit barging on /// a fair lock then combine the timed and un-timed forms together: /// /// <code> /// if (lock.TryLock() || lock.TryLock(timeSpan) ) { ... } /// </code> /// /// <p/> /// If the current thread /// already holds this lock then the hold count is incremented by one and /// the method returns <c>true</c>. /// /// <p/> /// If the lock is held by another thread then the /// current thread becomes disabled for thread scheduling /// purposes and lies dormant until one of three things happens: /// /// <list type="bullet"> /// <item>The lock is acquired by the current thread</item> /// <item>Some other thread calls <see cref="System.Threading.Thread.Interrupt()"/> the current thread</item> /// <item>The specified waiting time elapses</item> /// </list> /// /// <p/> /// If the lock is acquired then the value <c>true</c> is returned and /// the lock hold count is set to one. /// /// <p/>If the current thread: /// <list type="bullet"> /// <item>has its interrupted status set on entry to this method</item> /// <item>has <see cref="System.Threading.Thread.Interrupt()"/> called on it while acquiring the lock</item> /// </list> /// /// then <see cref="System.Threading.ThreadInterruptedException"/> is thrown and the current thread's /// interrupted status is cleared. /// /// <p/> /// If the specified waiting time elapses then the value <c>false</c> /// is returned. If the time is less than or equal to zero, the method will not wait at all. /// /// <p/> /// In this implementation, as this method is an explicit interruption /// point, preference is given to responding to the interrupt over normal or reentrant /// acquisition of the lock, and over reporting the elapse of the waiting /// time. /// /// </summary> /// <param name="timeSpan">the <see cref="System.TimeSpan"/> to wait for the lock</param> /// <returns> <c>true</c> if the lock was free and was acquired by the /// current thread, or the lock was already held by the current thread; and /// <c>false</c> if the waiting time elapsed before the lock could be /// acquired. /// </returns> /// <throws> InterruptedException if the current thread is interrupted </throws> /// <throws> NullPointerException if unit is null </throws> /// <exception cref="System.NullReferenceException">If <paramref name="timeSpan"/> is null</exception> /// <exception cref="System.Threading.ThreadInterruptedException">If the current thread is interrupted</exception> public virtual bool TryLock(TimeSpan timeSpan) { return sync.TryLock(timeSpan); } /// <summary> /// Attempts to release this lock. /// <p/> /// If the current thread is the /// holder of this lock then the hold count is decremented. If the /// hold count is now zero then the lock is released. If the /// current thread is not the holder of this lock then <see cref="System.InvalidOperationException"/> is thrown. /// </summary> /// <exception cref="System.Threading.SynchronizationLockException">if the current thread does not hold this lock.</exception> public virtual void Unlock() { sync.Unlock(); } /// <summary> /// Returns a <see cref="Spring.Threading.Locks.ICondition"/> instance for use with this /// <see cref="Spring.Threading.Locks.ILock"/> instance. /// /// <p/> /// The returned <see cref="Spring.Threading.Locks.ICondition"/> instance supports the same /// usages as do the <see cref="System.Threading.Monitor"/> methods <see cref="System.Threading.Monitor.Wait(object)"/>, /// <see cref="System.Threading.Monitor.Pulse(object)"/>, and <see cref="System.Threading.Monitor.PulseAll(object)"/>) when used with the built-in /// monitor lock. /// <list type="bullet"> /// <item> /// If this lock is not held when either /// <see cref="Spring.Threading.Locks.ICondition.Await()"/> or <see cref="Spring.Threading.Locks.ICondition.Signal()"/> /// methods are called, then an <see cref="System.InvalidOperationException"/> is thrown.</item> /// <item>When the condition <see cref="Spring.Threading.Locks.ICondition"/>await() waiting} /// methods are called the lock is released and, before they /// return, the lock is reacquired and the lock hold count restored /// to what it was when the method was called.</item> /// <item>If <see cref="System.Threading.Thread.Interrupt()"/> is called while /// waiting then the wait will terminate, an <see cref="System.Threading.ThreadInterruptedException"/> /// and the thread's interrupted status will be cleared.</item> /// <item> Waiting threads are signalled in FIFO order</item> /// <item> /// The ordering of lock reacquisition for threads returning /// from waiting methods is the same as for threads initially /// acquiring the lock, which is in the default case not specified, /// but for <b>fair</b> locks favors those threads that have been /// waiting the longest.</item> /// </list> /// </summary> /// <returns> the ICondition object /// </returns> public virtual ICondition NewCondition() { return IsFair ? new FIFOConditionVariable(this) : new ConditionVariable(this); } /// <summary> /// Queries whether any threads are waiting to acquire this lock. Note that /// because cancellations may occur at any time, a <c>true</c> /// return does not guarantee that any other thread will ever /// acquire this lock. This method is designed primarily for use in /// monitoring of the system state. /// </summary> /// <returns> <c>true</c>if there may be other threads waiting to acquire /// the lock, <c>false</c> otherwise. /// </returns> public bool HasQueuedThreads { get { return sync.HasQueuedThreads; } } /// <summary> /// Queries whether the <paramref name="thread"/> is waiting to acquire this /// lock. Note that because cancellations may occur at any time, a /// <c>true</c> return does not guarantee that this thread /// will ever acquire this lock. This method is designed primarily for use /// in monitoring of the system state. /// </summary> /// <param name="thread">the <see cref="System.Threading.Thread"/> instance. /// </param> /// <returns> <c>true</c> if the given thread is queued waiting for this lock, <c>false</c> otherwise. /// </returns> /// <throws> NullPointerException if thread is null </throws> /// <exception cref="System.NullReferenceException">if <paramref name="thread"/> is null.</exception> public bool IsQueuedThread(Thread thread) { return sync.IsQueued(thread); } /// <summary> /// Returns a collection containing threads that may be waiting to /// acquire this lock. Since the actual set of threads may change /// dynamically while constructing this result, the returned /// collection is only a best-effort estimate. The elements of the /// returned collection are in no particular order. This method is /// designed to facilitate construction of subclasses that provide /// more extensive monitoring facilities. /// </summary> /// <returns> collection of threads /// </returns> public virtual ICollection<Thread> QueuedThreads { get { return sync.QueuedThreads; } } /// <summary> /// Queries whether any threads are waiting on the <paramref name="condition"/> /// associated with this lock. Note that because timeouts and /// interrupts may occur at any time, a <c>true</c> return does /// not guarantee that a future <tt>signal</tt> will awaken any /// threads. This method is designed primarily for use in /// monitoring of the system state. /// </summary> /// <param name="condition">the condition</param> /// <returns> <c>true</c> if there are any waiting threads.</returns> /// <exception cref="System.NullReferenceException">if the <paramref name="condition"/> is null</exception> /// <exception cref="System.ArgumentException">if the <paramref name="condition"/> is not associated with this lock</exception> public virtual bool HasWaiters(ICondition condition) { return AsConditionVariable(condition).HasWaiters; } /// <summary> /// Returns an estimate of the number of threads waiting on the /// <paramref name="condition"/> associated with this lock. Note that because /// timeouts and interrupts may occur at any time, the estimate /// serves only as an upper bound on the actual number of waiters. /// This method is designed for use in monitoring of the system /// state, not for synchronization control. /// </summary> /// <param name="condition">the condition</param> /// <returns> the estimated number of waiting threads.</returns> /// <exception cref="System.NullReferenceException">if the <paramref name="condition"/> is null</exception> /// <exception cref="System.ArgumentException">if the <paramref name="condition"/> is not associated with this lock</exception> public virtual int GetWaitQueueLength(ICondition condition) { return AsConditionVariable(condition).WaitQueueLength; } /// <summary> /// Returns a collection containing those threads that may be /// waiting on the <paramref name="condition"/> associated with this lock. /// Because the actual set of threads may change dynamically while /// constructing this result, the returned collection is only a /// best-effort estimate. The elements of the returned collection /// are in no particular order. This method is designed to /// facilitate construction of subclasses that provide more /// extensive condition monitoring facilities. /// </summary> /// <param name="condition">the condition</param> /// <returns> the collection of threads waiting on <paramref name="condition"/></returns> /// <exception cref="System.NullReferenceException">if the <paramref name="condition"/> is null</exception> /// <exception cref="System.ArgumentException">if the <paramref name="condition"/> is not associated with this lock</exception> protected virtual ICollection<Thread> GetWaitingThreads(ICondition condition) { return AsConditionVariable(condition).WaitingThreads; } /// <summary> /// Returns a string identifying this lock, as well as its lock /// state. The state, in brackets, includes either the string /// 'Unlocked' or the string 'Locked by' /// followed by the <see cref="System.Threading.Thread.Name"/> of the owning thread. /// </summary> /// <returns> a string identifying this lock, as well as its lock state.</returns> public override string ToString() { Thread o = Owner; return base.ToString() + ((o == null) ? "[Unlocked]" : "[Locked by thread " + o.Name + "]"); } private ConditionVariable AsConditionVariable(ICondition condition) { if (condition == null) throw new ArgumentNullException(nameof(condition)); ConditionVariable condVar = condition as ConditionVariable; if (condVar == null) throw new ArgumentException("not owner"); if (condVar.Lock != this) throw new ArgumentException("not owner"); return condVar; } #region IDisposable Members void IDisposable.Dispose() { sync.Unlock(); } #endregion } }
#region BSD License /* Copyright (c) 2011, Clarius Consulting 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 Clarius Consulting 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. */ #endregion namespace OctoHook.Diagnostics { using System; using System.Diagnostics; /// <summary> /// Provides usability overloads for tracing to a <see cref="ITracer"/>. /// </summary> /// <nuget id="Tracer.Interfaces" /> static partial class ITracerExtensions { #region Critical overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given message; /// </summary> public static void Critical(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Critical, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given format string and arguments. /// </summary> public static void Critical(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Critical, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given exception and message. /// </summary> public static void Critical(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Critical, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Critical"/> with the given exception, format string and arguments. /// </summary> public static void Critical(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Critical, exception, format, args); } #endregion #region Error overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given message; /// </summary> public static void Error(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Error, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given format string and arguments. /// </summary> public static void Error(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Error, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given exception and message. /// </summary> public static void Error(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Error, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Error"/> with the given exception, format string and arguments. /// </summary> public static void Error(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Error, exception, format, args); } #endregion #region Warn overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given message; /// </summary> public static void Warn(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Warning, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given format string and arguments. /// </summary> public static void Warn(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Warning, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given exception and message. /// </summary> public static void Warn(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Warning, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Warning"/> with the given exception, format string and arguments. /// </summary> public static void Warn(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Warning, exception, format, args); } #endregion #region Info overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given message; /// </summary> public static void Info(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Information, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given format string and arguments. /// </summary> public static void Info(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Information, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given exception and message. /// </summary> public static void Info(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Information, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Information"/> with the given exception, format string and arguments. /// </summary> public static void Info(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Information, exception, format, args); } #endregion #region Verbose overloads /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given message; /// </summary> public static void Verbose(this ITracer tracer, object message) { tracer.Trace(TraceEventType.Verbose, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given format string and arguments. /// </summary> public static void Verbose(this ITracer tracer, string format, params object[] args) { tracer.Trace(TraceEventType.Verbose, format, args); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given exception and message. /// </summary> public static void Verbose(this ITracer tracer, Exception exception, object message) { tracer.Trace(TraceEventType.Verbose, exception, message); } /// <summary> /// Traces an event of type <see cref="TraceEventType.Verbose"/> with the given exception, format string and arguments. /// </summary> public static void Verbose(this ITracer tracer, Exception exception, string format, params object[] args) { tracer.Trace(TraceEventType.Verbose, exception, format, args); } #endregion } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Annotations; using NodaTime.Globalization; using NodaTime.Text.Patterns; using NodaTime.Utility; using System.Globalization; using System.Text; namespace NodaTime.Text { /// <summary> /// Represents a pattern for parsing and formatting <see cref="OffsetDateTime"/> values. /// </summary> /// <threadsafety> /// When used with a read-only <see cref="CultureInfo" />, this type is immutable and instances /// may be shared freely between threads. We recommend only using read-only cultures for patterns, although this is /// not currently enforced. /// </threadsafety> [Immutable] // Well, assuming an immutable culture... public sealed class OffsetDateTimePattern : IPattern<OffsetDateTime> { internal static readonly OffsetDateTime DefaultTemplateValue = new LocalDateTime(2000, 1, 1, 0, 0).WithOffset(Offset.Zero); /// <summary> /// Gets an invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC. /// </summary> /// <remarks> /// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'sso&lt;G&gt;". This pattern is available as the "G" /// standard pattern (even though it is invariant). /// </remarks> /// <value>An invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC.</value> public static OffsetDateTimePattern GeneralIso => Patterns.GeneralIsoPatternImpl; /// <summary> /// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC. /// </summary> /// <remarks> /// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo&lt;G&gt;". This will round-trip any values /// in the ISO calendar, and is available as the "o" standard pattern. /// </remarks> /// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC.</value> public static OffsetDateTimePattern ExtendedIso => Patterns.ExtendedIsoPatternImpl; /// <summary> /// Gets an invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC /// as hours and minutes only. /// </summary> /// <remarks> /// The minutes part of the offset is always included, but any sub-minute component /// of the offset is lost. An offset of zero is formatted as 'Z', but all of 'Z', '+00:00' and '-00:00' are parsed /// the same way. The RFC 3339 meaning of '-00:00' is not supported by Noda Time. /// Note that parsing is case-sensitive (so 'T' and 'Z' must be upper case). /// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo&lt;Z+HH:mm&gt;". /// </remarks> /// <value>An invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC /// as hours and minutes only.</value> public static OffsetDateTimePattern Rfc3339 => Patterns.Rfc3339PatternImpl; /// <summary> /// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond) /// including offset from UTC and calendar ID. /// </summary> /// <remarks> /// The returned pattern corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo&lt;G&gt; '('c')'". This will round-trip any value in any calendar, /// and is available as the "r" standard pattern. /// </remarks> /// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond) /// including offset from UTC and calendar ID.</value> public static OffsetDateTimePattern FullRoundtrip => Patterns.FullRoundtripPatternImpl; /// <summary> /// Class whose existence is solely to avoid type initialization order issues, most of which stem /// from needing NodaFormatInfo.InvariantInfo... /// </summary> internal static class Patterns { internal static readonly OffsetDateTimePattern GeneralIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'sso<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly OffsetDateTimePattern ExtendedIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly OffsetDateTimePattern Rfc3339PatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<Z+HH:mm>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly OffsetDateTimePattern FullRoundtripPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> '('c')'", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly PatternBclSupport<OffsetDateTime> BclSupport = new PatternBclSupport<OffsetDateTime>("G", fi => fi.OffsetDateTimePatternParser); } private readonly IPattern<OffsetDateTime> pattern; /// <summary> /// Gets the pattern text for this pattern, as supplied on creation. /// </summary> /// <value>The pattern text for this pattern, as supplied on creation.</value> public string PatternText { get; } // Visible for testing /// <summary> /// Gets the localization information used in this pattern. /// </summary> internal NodaFormatInfo FormatInfo { get; } /// <summary> /// Gets the value used as a template for parsing: any field values unspecified /// in the pattern are taken from the template. /// </summary> /// <value>The value used as a template for parsing.</value> public OffsetDateTime TemplateValue { get; } private OffsetDateTimePattern(string patternText, NodaFormatInfo formatInfo, OffsetDateTime templateValue, IPattern<OffsetDateTime> pattern) { this.PatternText = patternText; this.FormatInfo = formatInfo; this.TemplateValue = templateValue; this.pattern = pattern; } /// <summary> /// Parses the given text value according to the rules of this pattern. /// </summary> /// <remarks> /// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as /// the argument being null are wrapped in a parse result. /// </remarks> /// <param name="text">The text value to parse.</param> /// <returns>The result of parsing, which may be successful or unsuccessful.</returns> public ParseResult<OffsetDateTime> Parse([SpecialNullHandling] string text) => pattern.Parse(text); /// <summary> /// Formats the given offset date/time as text according to the rules of this pattern. /// </summary> /// <param name="value">The offset date/time to format.</param> /// <returns>The offset date/time formatted according to this pattern.</returns> public string Format(OffsetDateTime value) => pattern.Format(value); /// <summary> /// Formats the given value as text according to the rules of this pattern, /// appending to the given <see cref="StringBuilder"/>. /// </summary> /// <param name="value">The value to format.</param> /// <param name="builder">The <c>StringBuilder</c> to append to.</param> /// <returns>The builder passed in as <paramref name="builder"/>.</returns> public StringBuilder AppendFormat(OffsetDateTime value, StringBuilder builder) => pattern.AppendFormat(value, builder); /// <summary> /// Creates a pattern for the given pattern text, format info, and template value. /// </summary> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="formatInfo">The format info to use in the pattern</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <returns>A pattern for parsing and formatting offset date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> private static OffsetDateTimePattern Create(string patternText, NodaFormatInfo formatInfo, OffsetDateTime templateValue) { Preconditions.CheckNotNull(patternText, nameof(patternText)); Preconditions.CheckNotNull(formatInfo, nameof(formatInfo)); var pattern = new OffsetDateTimePatternParser(templateValue).ParsePattern(patternText, formatInfo); return new OffsetDateTimePattern(patternText, formatInfo, templateValue, pattern); } /// <summary> /// Creates a pattern for the given pattern text, culture, and template value. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="cultureInfo">The culture to use in the pattern</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <returns>A pattern for parsing and formatting local date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static OffsetDateTimePattern Create(string patternText, [ValidatedNotNull] CultureInfo cultureInfo, OffsetDateTime templateValue) => Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), templateValue); /// <summary> /// Creates a pattern for the given pattern text in the invariant culture, using the default /// template value of midnight January 1st 2000 at an offset of 0. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <returns>A pattern for parsing and formatting local date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static OffsetDateTimePattern CreateWithInvariantCulture(string patternText) => Create(patternText, NodaFormatInfo.InvariantInfo, DefaultTemplateValue); /// <summary> /// Creates a pattern for the given pattern text in the current culture, using the default /// template value of midnight January 1st 2000 at an offset of 0. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. Note that the current culture /// is captured at the time this method is called - it is not captured at the point of parsing /// or formatting values. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <returns>A pattern for parsing and formatting local date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static OffsetDateTimePattern CreateWithCurrentCulture(string patternText) => Create(patternText, NodaFormatInfo.CurrentInfo, DefaultTemplateValue); /// <summary> /// Creates a pattern for the same original localization information as this pattern, but with the specified /// pattern text. /// </summary> /// <param name="patternText">The pattern text to use in the new pattern.</param> /// <returns>A new pattern with the given pattern text.</returns> public OffsetDateTimePattern WithPatternText(string patternText) => Create(patternText, FormatInfo, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// localization information. /// </summary> /// <param name="formatInfo">The localization information to use in the new pattern.</param> /// <returns>A new pattern with the given localization information.</returns> private OffsetDateTimePattern WithFormatInfo(NodaFormatInfo formatInfo) => Create(PatternText, formatInfo, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// culture. /// </summary> /// <param name="cultureInfo">The culture to use in the new pattern.</param> /// <returns>A new pattern with the given culture.</returns> public OffsetDateTimePattern WithCulture([ValidatedNotNull] CultureInfo cultureInfo) => WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo)); /// <summary> /// Creates a pattern for the same original pattern text and culture as this pattern, but with /// the specified template value. /// </summary> /// <param name="newTemplateValue">The template value to use in the new pattern.</param> /// <returns>A new pattern with the given template value.</returns> public OffsetDateTimePattern WithTemplateValue(OffsetDateTime newTemplateValue) => Create(PatternText, FormatInfo, newTemplateValue); /// <summary> /// Creates a pattern like this one, but with the template value modified to use /// the specified calendar system. /// </summary> /// <remarks> /// <para> /// Care should be taken in two (relatively rare) scenarios. Although the default template value /// is supported by all Noda Time calendar systems, if a pattern is created with a different /// template value and then this method is called with a calendar system which doesn't support that /// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields, /// it's possible that the new template value will not be suitable for all values. /// </para> /// </remarks> /// <param name="calendar">The calendar system to convert the template value into.</param> /// <returns>A new pattern with a template value in the specified calendar system.</returns> public OffsetDateTimePattern WithCalendar(CalendarSystem calendar) => WithTemplateValue(TemplateValue.WithCalendar(calendar)); } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; namespace UnrealBuildTool { class MacPlatform : UEBuildPlatform { public override bool CanUseXGE() { return false; } public override bool CanUseDistcc() { return true; } protected override SDKStatus HasRequiredManualSDKInternal() { return SDKStatus.Valid; } /** * Register the platform with the UEBuildPlatform class */ protected override void RegisterBuildPlatformInternal() { // Register this build platform for Mac Log.TraceVerbose(" Registering for {0}", UnrealTargetPlatform.Mac.ToString()); UEBuildPlatform.RegisterBuildPlatform(UnrealTargetPlatform.Mac, this); UEBuildPlatform.RegisterPlatformWithGroup(UnrealTargetPlatform.Mac, UnrealPlatformGroup.Unix); UEBuildPlatform.RegisterPlatformWithGroup(UnrealTargetPlatform.Mac, UnrealPlatformGroup.Apple); } /** * Retrieve the CPPTargetPlatform for the given UnrealTargetPlatform * * @param InUnrealTargetPlatform The UnrealTargetPlatform being build * * @return CPPTargetPlatform The CPPTargetPlatform to compile for */ public override CPPTargetPlatform GetCPPTargetPlatform(UnrealTargetPlatform InUnrealTargetPlatform) { switch (InUnrealTargetPlatform) { case UnrealTargetPlatform.Mac: return CPPTargetPlatform.Mac; } throw new BuildException("MacPlatform::GetCPPTargetPlatform: Invalid request for {0}", InUnrealTargetPlatform.ToString()); } /** * Get the extension to use for the given binary type * * @param InBinaryType The binrary type being built * * @return string The binary extenstion (ie 'exe' or 'dll') */ public override string GetBinaryExtension(UEBuildBinaryType InBinaryType) { switch (InBinaryType) { case UEBuildBinaryType.DynamicLinkLibrary: return ".dylib"; case UEBuildBinaryType.Executable: return ""; case UEBuildBinaryType.StaticLibrary: return ".a"; case UEBuildBinaryType.Object: return ".o"; case UEBuildBinaryType.PrecompiledHeader: return ".gch"; } return base.GetBinaryExtension(InBinaryType); } /** * Get the extension to use for debug info for the given binary type * * @param InBinaryType The binary type being built * * @return string The debug info extension (i.e. 'pdb') */ public override string GetDebugInfoExtension(UEBuildBinaryType InBinaryType) { return BuildConfiguration.bGeneratedSYMFile || BuildConfiguration.bUsePDBFiles ? ".dsym" : ""; } public override void ModifyNewlyLoadedModule(UEBuildModule InModule, TargetInfo Target) { if (Target.Platform == UnrealTargetPlatform.Mac) { bool bBuildShaderFormats = UEBuildConfiguration.bForceBuildShaderFormats; if (!UEBuildConfiguration.bBuildRequiresCookedData) { if (InModule.ToString() == "TargetPlatform") { bBuildShaderFormats = true; } } // allow standalone tools to use target platform modules, without needing Engine if (UEBuildConfiguration.bForceBuildTargetPlatforms) { InModule.AddDynamicallyLoadedModule("MacTargetPlatform"); InModule.AddDynamicallyLoadedModule("MacNoEditorTargetPlatform"); InModule.AddDynamicallyLoadedModule("MacClientTargetPlatform"); InModule.AddDynamicallyLoadedModule("MacServerTargetPlatform"); InModule.AddDynamicallyLoadedModule("AllDesktopTargetPlatform"); } if (bBuildShaderFormats) { // InModule.AddDynamicallyLoadedModule("ShaderFormatD3D"); InModule.AddDynamicallyLoadedModule("ShaderFormatOpenGL"); } } } /** * Setup the target environment for building * * @param InBuildTarget The target being built */ public override void SetUpEnvironment(UEBuildTarget InBuildTarget) { InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_MAC=1"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_APPLE=1"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WITH_TTS=0"); InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WITH_SPEECH_RECOGNITION=0"); if(!InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Contains("WITH_DATABASE_SUPPORT=0") && !InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Contains("WITH_DATABASE_SUPPORT=1")) { InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WITH_DATABASE_SUPPORT=0"); } } /** * Whether this platform should create debug information or not * * @param InPlatform The UnrealTargetPlatform being built * @param InConfiguration The UnrealTargetConfiguration being built * * @return bool true if debug info should be generated, false if not */ public override bool ShouldCreateDebugInfo(UnrealTargetPlatform Platform, UnrealTargetConfiguration Configuration) { return true; } public override void ResetBuildConfiguration(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration) { UEBuildConfiguration.bCompileSimplygon = false; UEBuildConfiguration.bCompileICU = true; } public override void ValidateBuildConfiguration(CPPTargetConfiguration Configuration, CPPTargetPlatform Platform, bool bCreateDebugInfo) { if (BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac) { // @todo: Temporarily disable precompiled header files when building remotely due to errors BuildConfiguration.bUsePCHFiles = false; } BuildConfiguration.bCheckExternalHeadersForModification = BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac; BuildConfiguration.bCheckSystemHeadersForModification = BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac; BuildConfiguration.ProcessorCountMultiplier = MacToolChain.GetAdjustedProcessorCountMultiplier(); BuildConfiguration.bUseSharedPCHs = false; BuildConfiguration.bUsePDBFiles = bCreateDebugInfo && Configuration != CPPTargetConfiguration.Debug && Platform == CPPTargetPlatform.Mac; // we always deploy - the build machines need to be able to copy the files back, which needs the full bundle BuildConfiguration.bDeployAfterCompile = true; } public override void ValidateUEBuildConfiguration() { if (ProjectFileGenerator.bGenerateProjectFiles && !ProjectFileGenerator.bGeneratingRocketProjectFiles) { // When generating non-Rocket project files we need intellisense generator to include info from all modules, including editor-only third party libs UEBuildConfiguration.bCompileLeanAndMeanUE = false; } } /** * Whether the platform requires the extra UnityCPPWriter * This is used to add an extra file for UBT to get the #include dependencies from * * @return bool true if it is required, false if not */ public override bool RequiresExtraUnityCPPWriter() { return true; } /** * Return whether we wish to have this platform's binaries in our builds */ public override bool IsBuildRequired() { return false; } /** * Return whether we wish to have this platform's binaries in our CIS tests */ public override bool IsCISRequired() { return false; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.DDF { using System; using System.Text; using System.Collections.Generic; using NPOI.Util; /// <summary> /// Escher array properties are the most wierd construction ever invented /// with all sorts of special cases. I'm hopeful I've got them all. /// @author Glen Stampoultzis (glens at superlinksoftware.com) /// </summary> public class EscherArrayProperty : EscherComplexProperty, IEnumerable<byte[]> { /** * The size of the header that goes at the * start of the array, before the data */ private const int FIXED_SIZE = 3 * 2; /** * Normally, the size recorded in the simple data (for the complex * data) includes the size of the header. * There are a few cases when it doesn't though... */ private bool sizeIncludesHeaderSize = true; /** * When Reading a property from data stream remeber if the complex part is empty and Set this flag. */ private bool emptyComplexPart = false; public EscherArrayProperty(short id, byte[] complexData) : base(id, CheckComplexData(complexData)) { emptyComplexPart = complexData.Length == 0; } public EscherArrayProperty(short propertyNumber, bool isBlipId, byte[] complexData) : base(propertyNumber, isBlipId, CheckComplexData(complexData)) { } private static byte[] CheckComplexData(byte[] complexData) { if (complexData == null || complexData.Length == 0) complexData = new byte[6]; return complexData; } public int NumberOfElementsInArray { get { if (emptyComplexPart) { return 0; } return LittleEndian.GetUShort(_complexData, 0); } set { int expectedArraySize = value * GetActualSizeOfElements(SizeOfElements) + FIXED_SIZE; if (expectedArraySize != _complexData.Length) { byte[] newArray = new byte[expectedArraySize]; Array.Copy(_complexData, 0, newArray, 0, _complexData.Length); _complexData = newArray; } LittleEndian.PutShort(_complexData, 0, (short)value); } } public int NumberOfElementsInMemory { get { return LittleEndian.GetUShort(_complexData, 2); } set { int expectedArraySize = value * GetActualSizeOfElements(this.SizeOfElements) + FIXED_SIZE; if (expectedArraySize != _complexData.Length) { byte[] newArray = new byte[expectedArraySize]; Array.Copy(_complexData, 0, newArray, 0, expectedArraySize); _complexData = newArray; } LittleEndian.PutShort(_complexData, 2, (short)value); } } public short SizeOfElements { get { return LittleEndian.GetShort(_complexData, 4); } set { LittleEndian.PutShort(_complexData, 4, (short)value); int expectedArraySize = NumberOfElementsInArray * GetActualSizeOfElements(SizeOfElements) + FIXED_SIZE; if (expectedArraySize != _complexData.Length) { // Keep just the first 6 bytes. The rest is no good to us anyway. byte[] newArray = new byte[expectedArraySize]; Array.Copy(_complexData, 0, newArray, 0, 6); _complexData = newArray; } } } /// <summary> /// Gets the element. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> public byte[] GetElement(int index) { int actualSize = GetActualSizeOfElements(SizeOfElements); byte[] result = new byte[actualSize]; Array.Copy(_complexData, FIXED_SIZE + index * actualSize, result, 0, result.Length); return result; } /// <summary> /// Sets the element. /// </summary> /// <param name="index">The index.</param> /// <param name="element">The element.</param> public void SetElement(int index, byte[] element) { int actualSize = GetActualSizeOfElements(SizeOfElements); Array.Copy(element, 0, _complexData, FIXED_SIZE + index * actualSize, actualSize); } /// <summary> /// Retrieves the string representation for this property. /// </summary> /// <returns></returns> public override String ToString() { String nl = Environment.NewLine; StringBuilder results = new StringBuilder(); results.Append(" {EscherArrayProperty:" + nl); results.Append(" Num Elements: " + NumberOfElementsInArray + nl); results.Append(" Num Elements In Memory: " + NumberOfElementsInMemory + nl); results.Append(" Size of elements: " + SizeOfElements + nl); for (int i = 0; i < NumberOfElementsInArray; i++) { results.Append(" Element " + i + ": " + HexDump.ToHex(GetElement(i)) + nl); } results.Append("}" + nl); return "propNum: " + PropertyNumber + ", propName: " + EscherProperties.GetPropertyName(PropertyNumber) + ", complex: " + IsComplex + ", blipId: " + IsBlipId + ", data: " + nl + results.ToString(); } public override String ToXml(String tab) { StringBuilder builder = new StringBuilder(); builder.Append(tab).Append("<").Append(GetType().Name).Append(" id=\"0x").Append(HexDump.ToHex(Id)) .Append("\" name=\"").Append(Name).Append("\" blipId=\"") .Append(IsBlipId.ToString().ToLower()).Append("\">\n"); for (int i = 0; i < NumberOfElementsInArray; i++) { builder.Append("\t").Append(tab).Append("<Element>").Append(HexDump.ToHex(GetElement(i))).Append("</Element>\n"); } builder.Append(tab).Append("</").Append(GetType().Name).Append(">\n"); return builder.ToString(); } /// <summary> /// We have this method because the way in which arrays in escher works /// is screwed for seemly arbitary reasons. While most properties are /// fairly consistent and have a predictable array size, escher arrays /// have special cases. /// </summary> /// <param name="data">The data array containing the escher array information</param> /// <param name="offset">The offset into the array to start Reading from.</param> /// <returns>the number of bytes used by this complex property.</returns> public int SetArrayData(byte[] data, int offset) { if (emptyComplexPart) { _complexData = new byte[0]; } else { short numElements = LittleEndian.GetShort(data, offset); //short numReserved = LittleEndian.GetShort(data, offset + 2); // numReserved short sizeOfElements = LittleEndian.GetShort(data, offset + 4); int arraySize = GetActualSizeOfElements(sizeOfElements) * numElements; if (arraySize == _complexData.Length) { // The stored data size in the simple block excludes the header size _complexData = new byte[arraySize + 6]; sizeIncludesHeaderSize = false; } Array.Copy(data, offset, _complexData, 0, _complexData.Length); } return _complexData.Length; } /// <summary> /// Serializes the simple part of this property. ie the first 6 bytes. /// Needs special code to handle the case when the size doesn't /// include the size of the header block /// </summary> /// <param name="data"></param> /// <param name="pos"></param> /// <returns></returns> public override int SerializeSimplePart(byte[] data, int pos) { LittleEndian.PutShort(data, pos, Id); int recordSize = _complexData.Length; if (!sizeIncludesHeaderSize) { recordSize -= 6; } LittleEndian.PutInt(data, pos + 2, recordSize); return 6; } /// <summary> /// Sometimes the element size is stored as a negative number. We /// negate it and shift it to Get the real value. /// </summary> /// <param name="sizeOfElements">The size of elements.</param> /// <returns></returns> public static int GetActualSizeOfElements(short sizeOfElements) { if (sizeOfElements < 0) return (short)((-sizeOfElements) >> 2); else return sizeOfElements; } public IEnumerator<byte[]> GetEnumerator() { return new EscherArrayEnumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } private class EscherArrayEnumerator : IEnumerator<byte[]> { EscherArrayProperty dataHolder; public EscherArrayEnumerator(EscherArrayProperty eap) { dataHolder = eap; } private int idx = -1; public byte[] Current { get { if (idx < 0 || idx > dataHolder.NumberOfElementsInArray) throw new IndexOutOfRangeException(); return dataHolder.GetElement(idx); } } public void Dispose() { throw new NotImplementedException(); } object System.Collections.IEnumerator.Current { get { return this.Current; } } public bool MoveNext() { idx++; return (idx < dataHolder.NumberOfElementsInArray); } public void Reset() { throw new NotImplementedException(); } } } }
// 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.Threading; using System.IO; using System.Collections; using System.Reflection; namespace System.Diagnostics { internal static class TraceInternal { private class TraceProvider : DebugProvider { public override void Fail(string message, string detailMessage) { TraceInternal.Fail(message, detailMessage); } public override void OnIndentLevelChanged(int indentLevel) { lock (TraceInternal.critSec) { foreach (TraceListener listener in Listeners) { listener.IndentLevel = indentLevel; } } } public override void OnIndentSizeChanged(int indentSize) { lock (TraceInternal.critSec) { foreach (TraceListener listener in Listeners) { listener.IndentSize = indentSize; } } } public override void Write(string message) { TraceInternal.Write(message); } public override void WriteLine(string message) { TraceInternal.WriteLine(message); } } private static volatile string s_appName = null; private static volatile TraceListenerCollection s_listeners; private static volatile bool s_autoFlush; private static volatile bool s_useGlobalLock; private static volatile bool s_settingsInitialized; // this is internal so TraceSource can use it. We want to lock on the same object because both TraceInternal and // TraceSource could be writing to the same listeners at the same time. internal static readonly object critSec = new object(); public static TraceListenerCollection Listeners { get { InitializeSettings(); if (s_listeners == null) { lock (critSec) { if (s_listeners == null) { // This is where we override default DebugProvider because we know // for sure that we have some Listeners to write to. Debug.SetProvider(new TraceProvider()); // In the absence of config support, the listeners by default add // DefaultTraceListener to the listener collection. s_listeners = new TraceListenerCollection(); TraceListener defaultListener = new DefaultTraceListener(); defaultListener.IndentLevel = Debug.IndentLevel; defaultListener.IndentSize = Debug.IndentSize; s_listeners.Add(defaultListener); } } } return s_listeners; } } internal static string AppName { get { if (s_appName == null) { s_appName = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty; } return s_appName; } } public static bool AutoFlush { get { InitializeSettings(); return s_autoFlush; } set { InitializeSettings(); s_autoFlush = value; } } public static bool UseGlobalLock { get { InitializeSettings(); return s_useGlobalLock; } set { InitializeSettings(); s_useGlobalLock = value; } } public static int IndentLevel { get { return Debug.IndentLevel; } set { Debug.IndentLevel = value; } } public static int IndentSize { get { return Debug.IndentSize; } set { Debug.IndentSize = value; } } public static void Indent() { Debug.IndentLevel++; } public static void Unindent() { Debug.IndentLevel--; } public static void Flush() { if (s_listeners != null) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Flush(); } } else { listener.Flush(); } } } } } public static void Close() { if (s_listeners != null) { // Use global lock lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Close(); } } } } public static void Assert(bool condition) { if (condition) return; Fail(string.Empty); } public static void Assert(bool condition, string message) { if (condition) return; Fail(message); } public static void Assert(bool condition, string message, string detailMessage) { if (condition) return; Fail(message, detailMessage); } public static void Fail(string message) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Fail(message); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Fail(message); if (AutoFlush) listener.Flush(); } } else { listener.Fail(message); if (AutoFlush) listener.Flush(); } } } } public static void Fail(string message, string detailMessage) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Fail(message, detailMessage); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Fail(message, detailMessage); if (AutoFlush) listener.Flush(); } } else { listener.Fail(message, detailMessage); if (AutoFlush) listener.Flush(); } } } } private static void InitializeSettings() { if (!s_settingsInitialized) { // we should avoid 2 threads altering the state concurrently for predictable behavior // though it may not be strictly necessary at present lock (critSec) { if (!s_settingsInitialized) { s_autoFlush = DiagnosticsConfiguration.AutoFlush; s_useGlobalLock = DiagnosticsConfiguration.UseGlobalLock; s_settingsInitialized = true; } } } } // This method refreshes all the data from the configuration file, so that updated to the configuration file are mirrored // in the System.Diagnostics.Trace class internal static void Refresh() { lock (critSec) { s_settingsInitialized = false; s_listeners = null; Debug.IndentSize = DiagnosticsConfiguration.IndentSize; } InitializeSettings(); } public static void TraceEvent(TraceEventType eventType, int id, string format, params object[] args) { TraceEventCache EventCache = new TraceEventCache(); if (UseGlobalLock) { lock (critSec) { if (args == null) { foreach (TraceListener listener in Listeners) { listener.TraceEvent(EventCache, AppName, eventType, id, format); if (AutoFlush) listener.Flush(); } } else { foreach (TraceListener listener in Listeners) { listener.TraceEvent(EventCache, AppName, eventType, id, format, args); if (AutoFlush) listener.Flush(); } } } } else { if (args == null) { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.TraceEvent(EventCache, AppName, eventType, id, format); if (AutoFlush) listener.Flush(); } } else { listener.TraceEvent(EventCache, AppName, eventType, id, format); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.TraceEvent(EventCache, AppName, eventType, id, format, args); if (AutoFlush) listener.Flush(); } } else { listener.TraceEvent(EventCache, AppName, eventType, id, format, args); if (AutoFlush) listener.Flush(); } } } } } public static void Write(string message) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(message); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(message); if (AutoFlush) listener.Flush(); } } else { listener.Write(message); if (AutoFlush) listener.Flush(); } } } } public static void Write(object value) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(value); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(value); if (AutoFlush) listener.Flush(); } } else { listener.Write(value); if (AutoFlush) listener.Flush(); } } } } public static void Write(string message, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(message, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(message, category); if (AutoFlush) listener.Flush(); } } else { listener.Write(message, category); if (AutoFlush) listener.Flush(); } } } } public static void Write(object value, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(value, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(value, category); if (AutoFlush) listener.Flush(); } } else { listener.Write(value, category); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(string message) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(message); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(message); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(message); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(object value) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(value); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(value); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(value); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(string message, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(message, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(message, category); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(message, category); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(object value, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(value, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(value, category); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(value, category); if (AutoFlush) listener.Flush(); } } } } public static void WriteIf(bool condition, string message) { if (condition) Write(message); } public static void WriteIf(bool condition, object value) { if (condition) Write(value); } public static void WriteIf(bool condition, string message, string category) { if (condition) Write(message, category); } public static void WriteIf(bool condition, object value, string category) { if (condition) Write(value, category); } public static void WriteLineIf(bool condition, string message) { if (condition) WriteLine(message); } public static void WriteLineIf(bool condition, object value) { if (condition) WriteLine(value); } public static void WriteLineIf(bool condition, string message, string category) { if (condition) WriteLine(message, category); } public static void WriteLineIf(bool condition, object value, string category) { if (condition) WriteLine(value, category); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is where we group together all the runtime export calls. // using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime { internal static class RuntimeExports { // // internal calls for allocation // [RuntimeExport("RhNewObject")] public unsafe static object RhNewObject(EETypePtr pEEType) { EEType* ptrEEType = (EEType*)pEEType.ToPointer(); #if FEATURE_64BIT_ALIGNMENT if (ptrEEType->RequiresAlign8) { if (ptrEEType->IsValueType) return InternalCalls.RhpNewFastMisalign(ptrEEType); if (ptrEEType->IsFinalizable) return InternalCalls.RhpNewFinalizableAlign8(ptrEEType); return InternalCalls.RhpNewFastAlign8(ptrEEType); } else #endif // FEATURE_64BIT_ALIGNMENT { if (ptrEEType->IsFinalizable) return InternalCalls.RhpNewFinalizable(ptrEEType); return InternalCalls.RhpNewFast(ptrEEType); } } [RuntimeExport("RhNewArray")] public unsafe static object RhNewArray(EETypePtr pEEType, int length) { EEType* ptrEEType = (EEType*)pEEType.ToPointer(); #if FEATURE_64BIT_ALIGNMENT if (ptrEEType->RequiresAlign8) { return InternalCalls.RhpNewArrayAlign8(ptrEEType, length); } else #endif // FEATURE_64BIT_ALIGNMENT { return InternalCalls.RhpNewArray(ptrEEType, length); } } [RuntimeExport("RhBox")] public unsafe static object RhBox(EETypePtr pEEType, void* pData) { EEType* ptrEEType = (EEType*)pEEType.ToPointer(); object result; // If we're boxing a Nullable<T> then either box the underlying T or return null (if the // nullable's value is empty). if (ptrEEType->IsNullable) { // The boolean which indicates whether the value is null comes first in the Nullable struct. if (!*(bool*)pData) return null; // Switch type we're going to box to the Nullable<T> target type and advance the data pointer // to the value embedded within the nullable. pData = (byte*)pData + ptrEEType->GetNullableValueOffset(); ptrEEType = ptrEEType->GetNullableType(); } #if FEATURE_64BIT_ALIGNMENT if (ptrEEType->RequiresAlign8) { result = InternalCalls.RhpNewFastMisalign(ptrEEType); } else #endif // FEATURE_64BIT_ALIGNMENT { result = InternalCalls.RhpNewFast(ptrEEType); } InternalCalls.RhpBox(result, pData); return result; } // this serves as a kind of union where: // - the field o is used if the struct wraps a reference type // - the field p is used together with pointer arithmetic if the struct is a valuetype public struct Hack_o_p { internal Object o; internal IntPtr p; } [RuntimeExport("RhBoxAny")] public unsafe static object RhBoxAny(ref Hack_o_p data, EETypePtr pEEType) { EEType* ptrEEType = (EEType*)pEEType.ToPointer(); if (ptrEEType->IsValueType) { // HACK: we would really want to take the address of o here, // but the rules of the C# language don't let us do that, // so we arrive at the same result by taking the address of p // and going back one pointer-sized unit fixed (IntPtr* pData = &data.p) return RhBox(pEEType, pData - 1); } else return data.o; } private unsafe static bool UnboxAnyTypeCompare(EEType *pEEType, EEType *ptrUnboxToEEType) { bool result = false; if (pEEType->CorElementType == ptrUnboxToEEType->CorElementType) { result = TypeCast.AreTypesEquivalentInternal(pEEType, ptrUnboxToEEType); if (!result) { // Enum's and primitive types should pass the UnboxAny exception cases // if they have an exactly matching cor element type. switch (ptrUnboxToEEType->CorElementType) { case TypeCast.CorElementType.ELEMENT_TYPE_I1: case TypeCast.CorElementType.ELEMENT_TYPE_U1: case TypeCast.CorElementType.ELEMENT_TYPE_I2: case TypeCast.CorElementType.ELEMENT_TYPE_U2: case TypeCast.CorElementType.ELEMENT_TYPE_I4: case TypeCast.CorElementType.ELEMENT_TYPE_U4: case TypeCast.CorElementType.ELEMENT_TYPE_I8: case TypeCast.CorElementType.ELEMENT_TYPE_U8: case TypeCast.CorElementType.ELEMENT_TYPE_I: case TypeCast.CorElementType.ELEMENT_TYPE_U: result = true; break; } } } return result; } [RuntimeExport("RhUnboxAny")] public unsafe static void RhUnboxAny(object o, ref Hack_o_p data, EETypePtr pUnboxToEEType) { EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer(); if (ptrUnboxToEEType->IsValueType) { // HACK: we would really want to take the address of o here, // but the rules of the C# language don't let us do that, // so we arrive at the same result by taking the address of p // and going back one pointer-sized unit fixed (IntPtr* pData = &data.p) { bool isValid = false; if (ptrUnboxToEEType->IsNullable) isValid = (o == null) || TypeCast.AreTypesEquivalentInternal(o.EEType, ptrUnboxToEEType->GetNullableType()); else if (o != null) { isValid = UnboxAnyTypeCompare(o.EEType, ptrUnboxToEEType); } if (!isValid) { // Throw the invalid cast exception defined by the classlib, using the input unbox EEType* // to find the correct classlib. ExceptionIDs exID = o == null ? ExceptionIDs.NullReference : ExceptionIDs.InvalidCast; IntPtr addr = ptrUnboxToEEType->GetAssociatedModuleAddress(); Exception e = EH.GetClasslibException(exID, addr); BinderIntrinsics.TailCall_RhpThrowEx(e); } InternalCalls.RhUnbox(o, pData - 1, ptrUnboxToEEType); } } else { if (o == null || (TypeCast.IsInstanceOf(o, ptrUnboxToEEType) != null)) { data.o = o; } else { IntPtr addr = ptrUnboxToEEType->GetAssociatedModuleAddress(); Exception e = EH.GetClasslibException(ExceptionIDs.InvalidCast, addr); BinderIntrinsics.TailCall_RhpThrowEx(e); } } } #if CORERT // // Unbox helpers with RyuJIT conventions // [RuntimeExport("RhUnbox2")] static public unsafe void* RhUnbox2(EETypePtr pUnboxToEEType, Object obj) { EEType * ptrUnboxToEEType = (EEType *)pUnboxToEEType.ToPointer(); if (obj.EEType != ptrUnboxToEEType) { // We allow enums and their primtive type to be interchangable if (obj.EEType->CorElementType != ptrUnboxToEEType->CorElementType) { IntPtr addr = ptrUnboxToEEType->GetAssociatedModuleAddress(); Exception e = EH.GetClasslibException(ExceptionIDs.InvalidCast, addr); BinderIntrinsics.TailCall_RhpThrowEx(e); } } fixed (void* pObject = &obj.m_pEEType) { // CORERT-TODO: This code has GC hole - the method return type should really be byref. // Requires byref returns in C# to fix cleanly (https://github.com/dotnet/roslyn/issues/118) return (IntPtr*)pObject + 1; } } [RuntimeExport("RhUnboxNullable")] static public unsafe void RhUnboxNullable(ref Hack_o_p data, EETypePtr pUnboxToEEType, Object obj) { EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer(); // HACK: we would really want to take the address of o here, // but the rules of the C# language don't let us do that, // so we arrive at the same result by taking the address of p // and going back one pointer-sized unit fixed (IntPtr* pData = &data.p) { if ((obj != null) && (obj.EEType != ptrUnboxToEEType->GetNullableType())) { IntPtr addr = ptrUnboxToEEType->GetAssociatedModuleAddress(); Exception e = EH.GetClasslibException(ExceptionIDs.InvalidCast, addr); BinderIntrinsics.TailCall_RhpThrowEx(e); } InternalCalls.RhUnbox(obj, pData - 1, ptrUnboxToEEType); } } #endif // CORERT [RuntimeExport("RhArrayStoreCheckAny")] static public unsafe void RhArrayStoreCheckAny(object array, ref Hack_o_p data) { if (array == null) { return; } Debug.Assert(array.EEType->IsArray, "first argument must be an array"); EEType* arrayElemType = array.EEType->RelatedParameterType; if (arrayElemType->IsValueType) { return; } TypeCast.CheckArrayStore(array, data.o); } [RuntimeExport("RhBoxAndNullCheck")] static public unsafe bool RhBoxAndNullCheck(ref Hack_o_p data, EETypePtr pEEType) { EEType* ptrEEType = (EEType*)pEEType.ToPointer(); if (ptrEEType->IsValueType) return true; else return data.o != null; } #pragma warning disable 169 // The field 'System.Runtime.RuntimeExports.Wrapper.o' is never used. private class Wrapper { private Object _o; } #pragma warning restore 169 [RuntimeExport("RhAllocLocal")] public unsafe static object RhAllocLocal(EETypePtr pEEType) { EEType* ptrEEType = (EEType*)pEEType.ToPointer(); if (ptrEEType->IsValueType) { #if FEATURE_64BIT_ALIGNMENT if (ptrEEType->RequiresAlign8) return InternalCalls.RhpNewFastMisalign(ptrEEType); #endif return InternalCalls.RhpNewFast(ptrEEType); } else return new Wrapper(); } [RuntimeExport("RhMemberwiseClone")] public unsafe static object RhMemberwiseClone(object src) { object objClone; if (src.EEType->IsArray) objClone = RhNewArray(new EETypePtr((IntPtr)src.EEType), src.GetArrayLength()); else objClone = RhNewObject(new EETypePtr((IntPtr)src.EEType)); InternalCalls.RhpCopyObjectContents(objClone, src); return objClone; } [RuntimeExport("RhpReversePInvokeBadTransition")] public static void RhpReversePInvokeBadTransition(IntPtr returnAddress) { EH.FailFastViaClasslib( RhFailFastReason.IllegalNativeCallableEntry, null, returnAddress); } // EEType interrogation methods. [RuntimeExport("RhGetRelatedParameterType")] public static unsafe EETypePtr RhGetRelatedParameterType(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return new EETypePtr((IntPtr)pEEType->RelatedParameterType); } [RuntimeExport("RhGetNonArrayBaseType")] public static unsafe EETypePtr RhGetNonArrayBaseType(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return new EETypePtr((IntPtr)pEEType->NonArrayBaseType); } [RuntimeExport("RhGetComponentSize")] public static unsafe ushort RhGetComponentSize(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->ComponentSize; } [RuntimeExport("RhGetBaseSize")] public static unsafe uint RhGetBaseSize(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->BaseSize; } [RuntimeExport("RhGetNumInterfaces")] public static unsafe uint RhGetNumInterfaces(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return (uint)pEEType->NumInterfaces; } [RuntimeExport("RhGetInterface")] public static unsafe EETypePtr RhGetInterface(EETypePtr ptrEEType, uint index) { EEType* pEEType = ptrEEType.ToPointer(); // The convoluted pointer arithmetic into the interface map below (rather than a simply array // dereference) is because C# will generate a 64-bit multiply for the lookup by default. This // causes us a problem on x86 because it uses a helper that's mapped directly into the CRT via // import magic and that technique doesn't work with the way we link this code into the runtime // image. Since we don't need a 64-bit multiply here (the classlib is trusted code) we manually // perform the calculation. EEInterfaceInfo* pInfo = (EEInterfaceInfo*)((byte*)pEEType->InterfaceMap + (index * (uint)sizeof(EEInterfaceInfo))); return new EETypePtr((IntPtr)pInfo->InterfaceType); } [RuntimeExport("RhSetInterface")] public static unsafe void RhSetInterface(EETypePtr ptrEEType, int index, EETypePtr ptrInterfaceEEType) { EEType* pEEType = ptrEEType.ToPointer(); EEType* pInterfaceEEType = ptrInterfaceEEType.ToPointer(); pEEType->InterfaceMap[index].InterfaceType = pInterfaceEEType; } [RuntimeExport("RhIsDynamicType")] public static unsafe bool RhIsDynamicType(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->IsDynamicType; } [RuntimeExport("RhHasCctor")] public static unsafe bool RhHasCctor(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->HasCctor; } [RuntimeExport("RhIsValueType")] public static unsafe bool RhIsValueType(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->IsValueType; } [RuntimeExport("RhIsInterface")] public static unsafe bool RhIsInterface(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->IsInterface; } [RuntimeExport("RhIsArray")] public static unsafe bool RhIsArray(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->IsArray; } [RuntimeExport("RhIsString")] public static unsafe bool RhIsString(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); // String is currently the only non-array type with a non-zero component size. return (pEEType->ComponentSize == sizeof(char)) && !pEEType->IsArray; } [RuntimeExport("RhIsNullable")] public static unsafe bool RhIsNullable(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->IsNullable; } [RuntimeExport("RhGetNullableType")] public static unsafe EETypePtr RhGetNullableType(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return new EETypePtr((IntPtr)pEEType->GetNullableType()); } [RuntimeExport("RhHasReferenceFields")] public static unsafe bool RhHasReferenceFields(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->HasReferenceFields; } [RuntimeExport("RhGetCorElementType")] public static unsafe byte RhGetCorElementType(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return (byte)pEEType->CorElementType; } public enum RhEETypeClassification { Regular, // Object, String, Int32 Array, // String[] Generic, // List<Int32> GenericTypeDefinition, // List<T> UnmanagedPointer, // void* } [RuntimeExport("RhGetEETypeClassification")] public static unsafe RhEETypeClassification RhGetEETypeClassification(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); if (pEEType->IsArray) return RhEETypeClassification.Array; if (pEEType->IsGeneric) return RhEETypeClassification.Generic; if (pEEType->IsGenericTypeDefinition) return RhEETypeClassification.GenericTypeDefinition; if (pEEType->IsPointerTypeDefinition) return RhEETypeClassification.UnmanagedPointer; return RhEETypeClassification.Regular; } [RuntimeExport("RhGetEETypeHash")] public static unsafe uint RhGetEETypeHash(EETypePtr ptrEEType) { EEType* pEEType = ptrEEType.ToPointer(); return pEEType->HashCode; } [RuntimeExport("RhGetCurrentThreadStackTrace")] [MethodImpl(MethodImplOptions.NoInlining)] // Ensures that the RhGetCurrentThreadStackTrace frame is always present public static unsafe int RhGetCurrentThreadStackTrace(IntPtr[] outputBuffer) { fixed (IntPtr* pOutputBuffer = outputBuffer) return RhpGetCurrentThreadStackTrace(pOutputBuffer, (uint)((outputBuffer != null) ? outputBuffer.Length : 0)); } [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern int RhpGetCurrentThreadStackTrace(IntPtr* pOutputBuffer, uint outputBufferLength); // Worker for RhGetCurrentThreadStackTrace. RhGetCurrentThreadStackTrace just allocates a transition // frame that will be used to seed the stack trace and this method does all the real work. // // Input: outputBuffer may be null or non-null // Return value: positive: number of entries written to outputBuffer // negative: number of required entries in outputBuffer in case it's too small (or null) // Output: outputBuffer is filled in with return address IPs, starting with placing the this // method's return address into index 0 // // NOTE: We don't want to allocate the array on behalf of the caller because we don't know which class // library's objects the caller understands (we support multiple class libraries with multiple root // System.Object types). [NativeCallable(EntryPoint = "RhpCalculateStackTraceWorker", CallingConvention = CallingConvention.Cdecl)] private static unsafe int RhpCalculateStackTraceWorker(IntPtr * pOutputBuffer, uint outputBufferLength) { uint nFrames = 0; bool success = true; StackFrameIterator frameIter = new StackFrameIterator(); bool isValid = frameIter.Init(null); Debug.Assert(isValid, "Missing RhGetCurrentThreadStackTrace frame"); // Note that the while loop will skip RhGetCurrentThreadStackTrace frame while (frameIter.Next()) { if (nFrames < outputBufferLength) pOutputBuffer[nFrames] = new IntPtr(frameIter.ControlPC); else success = false; nFrames++; } return success ? (int)nFrames : -(int)nFrames; } // The GC conservative reporting descriptor is a special structure of data that the GC // parses to determine whether there are specific regions of memory that it should not // collect or move around. // During garbage collection, the GC will inspect the data in this structure, and verify that: // 1) _magic is set to the magic number (also hard coded on the GC side) // 2) The reported region is valid (checks alignments, size, within bounds of the thread memory, etc...) // 3) The ConservativelyReportedRegionDesc pointer must be reported by a frame which does not make a pinvoke transition. // 4) The value of the _hash field is the computed hash of _regionPointerLow with _regionPointerHigh // 5) The region must be IntPtr aligned, and have a size which is also IntPtr aligned // If all conditions are satisfied, the region of memory starting at _regionPointerLow and ending at // _regionPointerHigh will be conservatively reported. // This can only be used to report memory regions on the current stack and the structure must itself // be located on the stack. public struct ConservativelyReportedRegionDesc { internal const ulong MagicNumber64 = 0x87DF7A104F09E0A9UL; internal const uint MagicNumber32 = 0x4F09E0A9; internal UIntPtr _magic; internal UIntPtr _regionPointerLow; internal UIntPtr _regionPointerHigh; internal UIntPtr _hash; } [RuntimeExport("RhInitializeConservativeReportingRegion")] public static unsafe void RhInitializeConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc, void* bufferBegin, int cbBuffer) { Debug.Assert((((int)bufferBegin) & (sizeof(IntPtr) - 1)) == 0, "Buffer not IntPtr aligned"); Debug.Assert((cbBuffer & (sizeof(IntPtr) - 1)) == 0, "Size of buffer not IntPtr aligned"); UIntPtr regionPointerLow = (UIntPtr)bufferBegin; UIntPtr regionPointerHigh = (UIntPtr)(((byte*)bufferBegin) + cbBuffer); // Setup pointers to start and end of region regionDesc->_regionPointerLow = regionPointerLow; regionDesc->_regionPointerHigh = regionPointerHigh; // Activate the region for processing #if BIT64 ulong hash = ConservativelyReportedRegionDesc.MagicNumber64; hash = ((hash << 13) ^ hash) ^ (ulong)regionPointerLow; hash = ((hash << 13) ^ hash) ^ (ulong)regionPointerHigh; regionDesc->_hash = new UIntPtr(hash); regionDesc->_magic = new UIntPtr(ConservativelyReportedRegionDesc.MagicNumber64); #else uint hash = ConservativelyReportedRegionDesc.MagicNumber32; hash = ((hash << 13) ^ hash) ^ (uint)regionPointerLow; hash = ((hash << 13) ^ hash) ^ (uint)regionPointerHigh; regionDesc->_hash = new UIntPtr(hash); regionDesc->_magic = new UIntPtr(ConservativelyReportedRegionDesc.MagicNumber32); #endif } // Disable conservative reporting [RuntimeExport("RhDisableConservativeReportingRegion")] public static unsafe void RhDisableConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc) { regionDesc->_magic = default(UIntPtr); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Web.Mvc; using EPiBootstrapArea.Providers; using EPiServer; using EPiServer.Core; using EPiServer.Web.Mvc.Html; using HtmlAgilityPack; namespace EPiBootstrapArea { public class BootstrapAwareContentAreaRenderer : ContentAreaRenderer { private IEnumerable<DisplayModeFallback> _fallbacks; private IContent _currentContent; private Action<HtmlNode, ContentAreaItem, IContent> _elementStartTagRenderCallback; public BootstrapAwareContentAreaRenderer(IEnumerable<DisplayModeFallback> fallbacks) { _fallbacks = fallbacks ?? throw new ArgumentNullException(nameof(fallbacks)); } public string ContentAreaTag { get; private set; } public string DefaultContentAreaDisplayOption { get; private set; } protected void SetElementStartTagRenderCallback(Action<HtmlNode, ContentAreaItem, IContent> callback) { _elementStartTagRenderCallback = callback; } internal void SetDisplayOptions(List<DisplayModeFallback> displayOptions) { _fallbacks = displayOptions; } public override void Render(HtmlHelper htmlHelper, ContentArea contentArea) { if(contentArea == null || contentArea.IsEmpty) { return; } // capture given CA tag (should be contentArea.Tag, but EPiServer is not filling that property) ContentAreaTag = htmlHelper.ViewData["tag"] as string; if(htmlHelper.ViewData.ModelMetadata.AdditionalValues.ContainsKey($"{nameof(DefaultDisplayOptionMetadataProvider)}__DefaultDisplayOption")) { DefaultContentAreaDisplayOption = htmlHelper.ViewData.ModelMetadata.AdditionalValues[$"{nameof(DefaultDisplayOptionMetadataProvider)}__DefaultDisplayOption"] as string; } var viewContext = htmlHelper.ViewContext; TagBuilder tagBuilder = null; if(!IsInEditMode(htmlHelper) && ShouldRenderWrappingElement(htmlHelper)) { tagBuilder = new TagBuilder(GetContentAreaHtmlTag(htmlHelper, contentArea)); AddNonEmptyCssClass(tagBuilder, viewContext.ViewData["cssclass"] as string); if(ConfigurationContext.Current.AutoAddRow) { AddNonEmptyCssClass(tagBuilder, "row"); } viewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); } RenderContentAreaItems(htmlHelper, contentArea.FilteredItems); if(tagBuilder == null) { return; } viewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.EndTag)); } protected override void RenderContentAreaItems(HtmlHelper htmlHelper, IEnumerable<ContentAreaItem> contentAreaItems) { var isRowSupported = htmlHelper.GetFlagValueFromViewData("rowsupport"); var addRowMarkup = ConfigurationContext.Current.RowSupportEnabled && isRowSupported.HasValue && isRowSupported.Value; // there is no need to proceed if row rendering support is disabled if(!addRowMarkup) { base.RenderContentAreaItems(htmlHelper, contentAreaItems); return; } var rowRender = new RowRenderer(); rowRender.Render(contentAreaItems, htmlHelper, GetContentAreaItemTemplateTag, GetColumnWidth, base.RenderContentAreaItems); } protected override void RenderContentAreaItem( HtmlHelper htmlHelper, ContentAreaItem contentAreaItem, string templateTag, string htmlTag, string cssClass) { var originalWriter = htmlHelper.ViewContext.Writer; var tempWriter = new StringWriter(); htmlHelper.ViewContext.Writer = tempWriter; try { htmlHelper.ViewContext.ViewData[Constants.BlockIndexViewDataKey] = (int?)htmlHelper.ViewContext.ViewData[Constants.BlockIndexViewDataKey] + 1 ?? 0; var content = contentAreaItem.GetContent(); // persist selected DisplayOption for content template usage (if needed there of course) using(new ContentAreaItemContext(htmlHelper.ViewContext.ViewData, contentAreaItem)) { // NOTE: if content area was rendered with tag (Html.PropertyFor(m => m.Area, new { tag = "..." })) // this tag is overridden if editor chooses display option for the block // therefore - we need to persist original CA tag and ask kindly EPiServer to render block template in original CA tag context var tag = string.IsNullOrEmpty(ContentAreaTag) ? templateTag : ContentAreaTag; base.RenderContentAreaItem(htmlHelper, contentAreaItem, tag, htmlTag, cssClass); var contentItemContent = tempWriter.ToString(); var hasEditContainer = htmlHelper.GetFlagValueFromViewData(Constants.HasEditContainerKey); // we need to render block if we are in Edit mode if(IsInEditMode(htmlHelper) && (hasEditContainer == null || hasEditContainer.Value)) { originalWriter.Write(contentItemContent); return; } ProcessItemContent(contentItemContent, contentAreaItem, content, htmlHelper, originalWriter); } } finally { // restore original writer to proceed further with rendering pipeline htmlHelper.ViewContext.Writer = originalWriter; } } private void ProcessItemContent(string contentItemContent, ContentAreaItem contentAreaItem, IContent content, HtmlHelper htmlHelper, TextWriter originalWriter) { HtmlNode blockContentNode = null; var shouldStop = CallbackOnItemNode(contentItemContent, contentAreaItem, content, ref blockContentNode); if(shouldStop) return; shouldStop = RenderItemContainer(contentItemContent, htmlHelper, originalWriter, ref blockContentNode); if(shouldStop) return; shouldStop = ControlItemVisibility(contentItemContent, content, originalWriter, ref blockContentNode); if(shouldStop) return; // finally we just render whole body if (blockContentNode == null) { PrepareNodeElement(ref blockContentNode, contentItemContent); } if (blockContentNode != null) { originalWriter.Write(blockContentNode.OuterHtml); } } protected override string GetContentAreaItemCssClass(HtmlHelper htmlHelper, ContentAreaItem contentAreaItem) { return GetItemCssClass(htmlHelper, contentAreaItem); } internal string GetItemCssClass(HtmlHelper htmlHelper, ContentAreaItem contentAreaItem) { var tag = GetContentAreaItemTemplateTag(htmlHelper, contentAreaItem); var baseClasses = base.GetContentAreaItemCssClass(htmlHelper, contentAreaItem); return $"block {GetTypeSpecificCssClasses(contentAreaItem)}{(!string.IsNullOrEmpty(GetCssClassesForTag(contentAreaItem, tag)) ? " " +GetCssClassesForTag(contentAreaItem, tag) : "")}{(!string.IsNullOrEmpty(tag) ? " " + tag : "")}{(!string.IsNullOrEmpty(baseClasses) ? baseClasses : "")}"; } protected override string GetContentAreaItemTemplateTag(HtmlHelper htmlHelper, ContentAreaItem contentAreaItem) { return ContentAreaItemTemplateTagCore(htmlHelper, contentAreaItem); } internal string ContentAreaItemTemplateTagCore(HtmlHelper htmlHelper, ContentAreaItem contentAreaItem) { var templateTag = base.GetContentAreaItemTemplateTag(htmlHelper, contentAreaItem); if (!string.IsNullOrEmpty(templateTag)) { return templateTag; } // let's try to find default display options - when set to "Automatic" (meaning that tag is empty for the content) var currentContent = GetCurrentContent(contentAreaItem); var attribute = currentContent?.GetOriginalType().GetCustomAttribute<DefaultDisplayOptionAttribute>(); if (attribute != null) { return attribute.DisplayOption; } // no default display option set in block definition using attributes // let's try to find - maybe developer set default one on CA definition return !string.IsNullOrEmpty(DefaultContentAreaDisplayOption) ? DefaultContentAreaDisplayOption : templateTag; } protected virtual IContent GetCurrentContent(ContentAreaItem contentAreaItem) { if(_currentContent == null || !_currentContent.ContentLink.CompareToIgnoreWorkID(contentAreaItem.ContentLink)) { _currentContent = contentAreaItem.GetContent(); } return _currentContent; } internal int GetColumnWidth(string tag) { var fallback = _fallbacks.FirstOrDefault(f => f.Tag == tag); return fallback?.LargeScreenWidth ?? 12; } internal string GetCssClassesForTag(ContentAreaItem contentAreaItem, string tagName) { if(string.IsNullOrWhiteSpace(tagName)) { tagName = ContentAreaTags.FullWidth; } // this is special case for skipping any CSS class calculations if (tagName.Equals(ContentAreaTags.None)) { return string.Empty; } var extraTagInfo = string.Empty; // try to find default display option only if CA was rendered with tag // passed in tag is equal with tag used to render content area - block does not have any display option set explicitly if(!string.IsNullOrEmpty(ContentAreaTag) && tagName.Equals(ContentAreaTag)) { // we also might have defined default display options for particular CA tag (Html.PropertyFor(m => m.ContentArea, new { tag = ... })) var currentContent = GetCurrentContent(contentAreaItem); var defaultAttribute = currentContent?.GetOriginalType() .GetCustomAttributes<DefaultDisplayOptionForTagAttribute>() .FirstOrDefault(a => a.Tag == ContentAreaTag); if(defaultAttribute != null) { tagName = defaultAttribute.DisplayOption; extraTagInfo = tagName; } } var fallback = _fallbacks.FirstOrDefault(f => f.Tag == tagName) ?? _fallbacks.FirstOrDefault(f => f.Tag == ContentAreaTags.FullWidth); if(fallback == null) return string.Empty; return $"{GetCssClassesForItem(fallback)}{(string.IsNullOrEmpty(extraTagInfo) ? string.Empty : $" {extraTagInfo}")}"; } // TODO: get rid of this static internal method and refactor to some sort of formatter / class builder / whatever // needed only for unittest to access this out of constructor - as there are lot of ceremony going on with injections (want to skip that). internal static string GetCssClassesForItem(DisplayModeFallback fallback) { var largeScreenClass = string.IsNullOrEmpty(fallback.LargeScreenCssClassPattern) ? "col-lg-" + fallback.LargeScreenWidth : fallback.LargeScreenCssClassPattern.TryFormat(fallback.LargeScreenWidth); var mediumScreenClass = string.IsNullOrEmpty(fallback.MediumScreenCssClassPattern) ? "col-md-" + fallback.MediumScreenWidth : fallback.MediumScreenCssClassPattern.TryFormat(fallback.MediumScreenWidth); var smallScreenClass = string.IsNullOrEmpty(fallback.SmallScreenCssClassPattern) ? "col-sm-" + fallback.SmallScreenWidth : fallback.SmallScreenCssClassPattern.TryFormat(fallback.SmallScreenWidth); var xsmallScreenClass = string.IsNullOrEmpty(fallback.ExtraSmallScreenCssClassPattern) ? "col-xs-" + fallback.ExtraSmallScreenWidth : fallback.ExtraSmallScreenCssClassPattern.TryFormat(fallback.ExtraSmallScreenWidth); return string.Join(" ", new[] { largeScreenClass, mediumScreenClass, smallScreenClass, xsmallScreenClass }.Where(s => !string.IsNullOrEmpty(s))); } private static string GetTypeSpecificCssClasses(ContentAreaItem contentAreaItem) { var content = contentAreaItem.GetContent(); var cssClass = content?.GetOriginalType().Name.ToLowerInvariant() ?? string.Empty; // ReSharper disable once SuspiciousTypeConversion.Global var customClassContent = content as ICustomCssInContentArea; if(customClassContent != null && !string.IsNullOrWhiteSpace(customClassContent.ContentAreaCssClass)) { cssClass += $" {customClassContent.ContentAreaCssClass}"; } return cssClass; } private void PrepareNodeElement(ref HtmlNode node, string contentItemContent) { if(node != null) { return; } var doc = new HtmlDocument(); doc.Load(new StringReader(contentItemContent)); node = doc.DocumentNode.ChildNodes.FirstOrDefault(); } private bool CallbackOnItemNode(string contentItemContent, ContentAreaItem contentAreaItem, IContent content, ref HtmlNode blockContentNode) { // should we process start element node via callback? if(_elementStartTagRenderCallback == null) { return false; } PrepareNodeElement(ref blockContentNode, contentItemContent); if(blockContentNode == null) { return true; } // pass node to callback for some fancy modifications (if any) _elementStartTagRenderCallback.Invoke(blockContentNode, contentAreaItem, content); return false; } private bool RenderItemContainer(string contentItemContent, HtmlHelper htmlHelper, TextWriter originalWriter, ref HtmlNode blockContentNode) { // do we need to control item container visibility? var renderItemContainer = htmlHelper.GetFlagValueFromViewData("hasitemcontainer"); if(renderItemContainer.HasValue && !renderItemContainer.Value) { PrepareNodeElement(ref blockContentNode, contentItemContent); if(blockContentNode != null) { originalWriter.Write(blockContentNode.InnerHtml); return true; } } return false; } private bool ControlItemVisibility(string contentItemContent, IContent content, TextWriter originalWriter, ref HtmlNode blockContentNode) { // can block be converted to IControlVisibility? so then we might need to control block rendering as such // ReSharper disable once SuspiciousTypeConversion.Global var visibilityControlledContent = content as IControlVisibility; if(visibilityControlledContent == null) { return false; } PrepareNodeElement(ref blockContentNode, contentItemContent); if (blockContentNode == null) { return false; } if(string.IsNullOrEmpty(blockContentNode.InnerHtml.Trim(null)) && visibilityControlledContent.HideIfEmpty) { return true; } originalWriter.Write(blockContentNode.OuterHtml); return true; } } }
//----------------------------------------------------------------------- // <copyright file="SmallBlockMemoryStream.cs" company="Microsoft"> // Copyright 2011 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. // </copyright> // <summary> // Contains code for the SmallBlockMemoryStream class. // </summary> //----------------------------------------------------------------------- namespace Microsoft.WindowsAzure.StorageClient { using System; using System.Collections.Generic; using System.IO; /// <summary> /// This class provides MemoryStream-like behavior but uses a list of blocks rather than a single piece of bufferBlocks. /// </summary> internal class SmallBlockMemoryStream : Stream { /// <summary> /// The default block size. /// </summary> private const long DefaultBlockSize = 1024 * 1024; // 1MB /// <summary> /// The size of the block. /// </summary> private readonly long blockSize; /// <summary> /// The underlying bufferBlocks for the stream. /// </summary> private List<byte[]> bufferBlocks = new List<byte[]>(); /// <summary> /// The currently used length. /// </summary> private long length; /// <summary> /// The total capacity of the stream. /// </summary> private long capacity; /// <summary> /// The current position. /// </summary> private long position; /// <summary> /// Initializes a new instance of the SmallBlockMemoryStream class with default 64KB block size and no reserved space. /// </summary> public SmallBlockMemoryStream() : this(DefaultBlockSize) { } /// <summary> /// Initializes a new instance of the SmallBlockMemoryStream class with provided block size and no reserved space. /// </summary> /// <param name="blockSize">The size of blocks to use.</param> public SmallBlockMemoryStream(long blockSize) : this(blockSize, 0) { } /// <summary> /// Initializes a new instance of the SmallBlockMemoryStream class. /// </summary> /// <param name="blockSize">The size of blocks to use.</param> /// <param name="reservedSize">The amount of memory to reserve.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="blockSize"/> is zero or negative.</exception> public SmallBlockMemoryStream(long blockSize, long reservedSize) { if (blockSize <= 0) { throw new ArgumentOutOfRangeException("blockSize", "BlockSize must be a positive, non-zero value"); } this.blockSize = blockSize; this.Reserve(reservedSize); } /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> /// <value>Is <c>true</c> if the stream supports reading; otherwise, <c>false</c>.</value> public override bool CanRead { get { return true; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> /// <value>Is true if the stream supports seeking; otherwise, false.</value> public override bool CanSeek { get { return true; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> /// <value>Is true if the stream supports writing; otherwise, false.</value> public override bool CanWrite { get { return true; } } /// <summary> /// Gets the currently written length. /// </summary> public override long Length { get { return this.length; } } /// <summary> /// Represents the current position in the stream. /// </summary> /// <exception cref="ArgumentException">Thrown if position is outside the stream size</exception> public override long Position { get { return this.position; } set { this.Seek(value, SeekOrigin.Begin); } } /// <summary> /// Copies the specified amount of data from internal buffers to the buffer and advances the position. /// </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> /// <exception cref="System.ArgumentException">The offset subtracted from the buffer length is less than count.</exception> /// <exception cref="System.ArgumentNullException">The buffer is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">The offset or count is negative.</exception> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Offset must be positive"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Count must be positive"); } if ((buffer.Length - offset) < count) { throw new ArgumentException("Offset and count are beyond the buffer size", "count"); } return this.ReadInternal(buffer, offset, count); } /// <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 System.IO.SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="ArgumentException">Thrown if <paramref name="offset"/> is invalid for SeekOrigin.</exception> public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: if (offset < 0) { throw new ArgumentException("Attempting to seek before the start of the stream", "origin"); } if (offset > this.length) { throw new ArgumentException("Attempting to seek past the end of the stream", "origin"); } this.position = offset; break; case SeekOrigin.Current: if (this.position + offset < 0) { throw new ArgumentException("Attempting to seek before the start of the stream", "origin"); } if (this.position + offset > this.length) { throw new ArgumentException("Attempting to seek past the end of the stream", "origin"); } this.position += offset; break; case SeekOrigin.End: if (this.length + offset < 0) { throw new ArgumentException("Attempting to seek before the start of the stream", "origin"); } if (offset > 0) { throw new ArgumentException("Attempting to seek past the end of the stream", "origin"); } this.position = this.length + offset; break; } return this.position; } /// <summary> /// Sets the length of the current stream. (preallocating the bufferBlocks). /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="ArgumentOutOfRangeException">If the <paramref name="value"/> is negative.</exception> public override void SetLength(long value) { this.Reserve(value); this.length = 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> /// <exception cref="System.ArgumentException">Offset subtracted from the buffer length is less than count. </exception> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="buffer"/> is null</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="offset"/> or <paramref name="count"/> is negative</exception> public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Offset must be positive"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Count must be positive"); } if ((buffer.Length - offset) < count) { throw new ArgumentException("Offset subtracted from the buffer length is less than count", "offset"); } // Grow the buffer if more space is needed if (this.position + count > this.capacity) { this.Reserve(this.position + count); } this.WriteInternal(buffer, offset, count); // Adjust the length to be the max of currently written data. this.length = Math.Max(this.length, this.position); } /// <summary> /// Does not perform any operation as it's an in-memory stream. /// </summary> public override void Flush() { } /// <summary> /// Ensures that the amount of bufferBlocks is greater than or equal to the required size. /// Does not trim the size. /// </summary> /// <param name="requiredSize">The required size.</param> /// <exception cref="ArgumentOutOfRangeException">If the <paramref name="requiredSize"/> is negative.</exception> private void Reserve(long requiredSize) { if (requiredSize < 0) { throw new ArgumentOutOfRangeException("requiredSize", "The size must be positive"); } while (requiredSize > this.capacity) { this.AddBlock(); } } /// <summary> /// Adds another block to the underlying bufferBlocks. /// </summary> private void AddBlock() { this.bufferBlocks.Add(new byte[this.blockSize]); this.capacity += this.blockSize; } /// <summary> /// Copies the specified amount of data from internal buffers to the buffer and advances the position. /// </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> private int ReadInternal(byte[] buffer, int offset, int count) { // Maximum amount you can read is from current spot to the end. int readLength = (int)Math.Min(this.Length - this.Position, count); int leftToRead = readLength; while (leftToRead != 0) { int blockPosition; byte[] currentBlock; this.GetCurrentBlock(out blockPosition, out currentBlock); // Copy the block int blockReadLength = Math.Min(leftToRead, currentBlock.Length - blockPosition); Buffer.BlockCopy(currentBlock, blockPosition, buffer, offset, blockReadLength); this.AdvancePosition(ref offset, ref leftToRead, blockReadLength); } return readLength; } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// (Requires the stream to be of sufficient size for writing). /// </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> private void WriteInternal(byte[] buffer, int offset, int count) { while (count != 0) { int blockPosition; byte[] currentBlock; this.GetCurrentBlock(out blockPosition, out currentBlock); // Copy the block int blockWriteLength = Math.Min(count, currentBlock.Length - blockPosition); Buffer.BlockCopy(buffer, offset, currentBlock, blockPosition, blockWriteLength); this.AdvancePosition(ref offset, ref count, blockWriteLength); } } /// <summary> /// Advances the current position of the stream and adjust the offset and remainder based on the amount completed. /// </summary> /// <param name="offset">The current offset in the external buffer.</param> /// <param name="leftToProcess">The amount of data left to process.</param> /// <param name="amountProcessed">The amount of data processed.</param> private void AdvancePosition(ref int offset, ref int leftToProcess, int amountProcessed) { // Advance the position in the stream and in the destination buffer this.position += amountProcessed; offset += amountProcessed; leftToProcess -= amountProcessed; } /// <summary> /// Calculate the block for the current position. /// </summary> /// <param name="blockPosition">The position within a block.</param> /// <param name="currentBlock">The block reference itself.</param> private void GetCurrentBlock(out int blockPosition, out byte[] currentBlock) { // Calculate the block and position in a block int blockID = (int)(this.position / this.blockSize); blockPosition = (int)(this.position % this.blockSize); currentBlock = this.bufferBlocks[blockID]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Net.Http { internal readonly struct CurlResponseHeaderReader { private const string HttpPrefix = "HTTP/"; private readonly HeaderBufferSpan _span; public CurlResponseHeaderReader(IntPtr buffer, ulong size) { Debug.Assert(buffer != IntPtr.Zero); Debug.Assert(size <= int.MaxValue); _span = new HeaderBufferSpan(buffer, (int)size).Trim(); } public bool ReadStatusLine(HttpResponseMessage response) { if (!_span.StartsWithHttpPrefix()) { return false; } int index = HttpPrefix.Length; int majorVersion = _span.ReadInt(ref index); CheckResponseMsgFormat(majorVersion != 0); CheckResponseMsgFormat(index < _span.Length); int minorVersion; if (_span[index] == '.') { index++; CheckResponseMsgFormat(index < _span.Length && _span[index] >= '0' && _span[index] <= '9'); minorVersion = _span.ReadInt(ref index); } else { minorVersion = 0; } CheckResponseMsgFormat(_span.SkipSpace(ref index)); // Parse status code. int statusCode = _span.ReadInt(ref index); CheckResponseMsgFormat(statusCode >= 100 && statusCode < 1000); bool foundSpace = _span.SkipSpace(ref index); CheckResponseMsgFormat(index <= _span.Length); CheckResponseMsgFormat(foundSpace || index == _span.Length); // Set the response HttpVersion. response.Version = (majorVersion == 1 && minorVersion == 1) ? HttpVersion.Version11 : (majorVersion == 1 && minorVersion == 0) ? HttpVersion.Version10 : (majorVersion == 2 && minorVersion == 0) ? HttpVersion.Version20 : HttpVersion.Unknown; response.StatusCode = (HttpStatusCode)statusCode; // Try to use a known reason phrase instead of allocating a new string. HeaderBufferSpan reasonPhraseSpan = _span.Slice(index); string knownReasonPhrase = HttpStatusDescription.Get(response.StatusCode); response.ReasonPhrase = reasonPhraseSpan.EqualsOrdinal(knownReasonPhrase) ? knownReasonPhrase : reasonPhraseSpan.ToString(); return true; } public bool ReadHeader(out string headerName, out string headerValue) { int index = 0; while (index < _span.Length && ValidHeaderNameChar(_span[index])) { index++; } if (index > 0) { // For compatability, skip past any whitespace before the colon, even though // the RFC suggests there shouldn't be any. int headerNameLength = index; while (index < _span.Length && IsWhiteSpaceLatin1(_span[index])) { index++; } CheckResponseMsgFormat(index < _span.Length); CheckResponseMsgFormat(_span[index] == ':'); HeaderBufferSpan headerNameSpan = _span.Slice(0, headerNameLength); if (!HttpKnownHeaderNames.TryGetHeaderName(headerNameSpan.Buffer, headerNameSpan.Length, out headerName)) { headerName = headerNameSpan.ToString(); } CheckResponseMsgFormat(headerName.Length > 0); index++; headerValue = _span.Slice(index).Trim().ToString(); return true; } headerName = null; headerValue = null; return false; } private static void CheckResponseMsgFormat(bool condition) { if (!condition) { throw new HttpRequestException(SR.net_http_invalid_response); } } private static bool ValidHeaderNameChar(byte c) { const string invalidChars = "()<>@,;:\\\"/[]?={}"; return c > ' ' && !invalidChars.Contains((char)c); } internal static bool IsWhiteSpaceLatin1(byte c) { // SPACE // U+0009 = <control> HORIZONTAL TAB // U+000a = <control> LINE FEED // U+000b = <control> VERTICAL TAB // U+000c = <control> FORM FEED // U+000d = <control> CARRIAGE RETURN // U+0085 = <control> NEXT LINE // U+00a0 = NO-BREAK SPACE return c == ' ' || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085'; } private unsafe readonly struct HeaderBufferSpan { private readonly byte* _pointer; public readonly int Length; public static readonly HeaderBufferSpan Empty = default(HeaderBufferSpan); public HeaderBufferSpan(IntPtr pointer, int length) : this((byte*)pointer, length) { } public HeaderBufferSpan(byte* pointer, int length) { Debug.Assert(pointer != null); Debug.Assert(length >= 0); _pointer = pointer; Length = length; } public IntPtr Buffer => new IntPtr(_pointer); public byte this[int index] { get { Debug.Assert(index >= 0 && index < Length); return _pointer[index]; } } public HeaderBufferSpan Trim() { if (Length == 0) { return Empty; } int index = 0; while (index < Length && IsWhiteSpaceLatin1(_pointer[index])) { index++; } int end = Length - 1; while (end >= index && IsWhiteSpaceLatin1(_pointer[end])) { end--; } byte* pointer = _pointer + index; int length = end - index + 1; return new HeaderBufferSpan(pointer, length); } public bool StartsWithHttpPrefix() { if (Length < HttpPrefix.Length) { return false; } return (_pointer[0] == 'H' || _pointer[0] == 'h') && (_pointer[1] == 'T' || _pointer[1] == 't') && (_pointer[2] == 'T' || _pointer[2] == 't') && (_pointer[3] == 'P' || _pointer[3] == 'p') && (_pointer[4] == '/'); } public int ReadInt(ref int index) { int value = 0; for (; index < Length; index++) { byte c = _pointer[index]; if (c < '0' || c > '9') { break; } value = (value * 10) + (c - '0'); } return value; } public bool SkipSpace(ref int index) { bool foundSpace = false; for (; index < Length; index++) { if (_pointer[index] == ' ' || _pointer[index] == '\t') { foundSpace = true; } else { break; } } return foundSpace; } public bool EqualsOrdinal(string value) { if (value == null) { return false; } if (Length != value.Length) { return false; } for (int i = 0; i < Length; i++) { if (_pointer[i] != value[i]) { return false; } } return true; } public HeaderBufferSpan Slice(int startIndex) { return Slice(startIndex, Length - startIndex); } public HeaderBufferSpan Slice(int startIndex, int length) { Debug.Assert(startIndex >= 0); Debug.Assert(length >= 0); Debug.Assert(startIndex <= Length - length); if (length == 0) { return Empty; } if (startIndex == 0 && length == Length) { return this; } return new HeaderBufferSpan(_pointer + startIndex, length); } public override string ToString() { return Length == 0 ? string.Empty : HttpRuleParser.DefaultHttpEncoding.GetString(_pointer, Length); } } } }
// 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 System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class GetTypedObjectForIUnknownTests { public static IEnumerable<object> GetTypedObjectForIUnknown_RoundtrippableType_TestData() { yield return new object(); yield return 10; yield return "string"; yield return new NonGenericClass(); yield return new NonGenericStruct(); yield return Int32Enum.Value1; MethodInfo method = typeof(GetTypedObjectForIUnknownTests).GetMethod(nameof(NonGenericMethod)); Delegate d = method.CreateDelegate(typeof(NonGenericDelegate)); yield return d; } public static IEnumerable<object[]> GetTypedObjectForIUnknown_TestData() { foreach (object o in GetTypedObjectForIUnknown_RoundtrippableType_TestData()) { yield return new object[] { o, o.GetType() }; yield return new object[] { o, typeof(GenericClass<>).GetTypeInfo().GenericTypeParameters[0] }; yield return new object[] { o, typeof(int).MakeByRefType() }; Type baseType = o.GetType().BaseType; while (baseType != null) { yield return new object[] { o, baseType }; baseType = baseType.BaseType; } } yield return new object[] { new ClassWithInterface(), typeof(NonGenericInterface) }; yield return new object[] { new StructWithInterface(), typeof(NonGenericInterface) }; yield return new object[] { new GenericClass<string>(), typeof(object) }; yield return new object[] { new Dictionary<string, int>(), typeof(object) }; yield return new object[] { new GenericStruct<string>(), typeof(object) }; yield return new object[] { new GenericStruct<string>(), typeof(ValueType) }; yield return new object[] { new int[] { 10 }, typeof(object) }; yield return new object[] { new int[] { 10 }, typeof(Array) }; yield return new object[] { new int[][] { new int[] { 10 } }, typeof(object) }; yield return new object[] { new int[][] { new int[] { 10 } }, typeof(Array) }; yield return new object[] { new int[,] { { 10 } }, typeof(object) }; yield return new object[] { new int[,] { { 10 } }, typeof(Array) }; yield return new object[] { new KeyValuePair<string, int>("key", 10), typeof(object) }; yield return new object[] { new KeyValuePair<string, int>("key", 10), typeof(ValueType) }; } [Theory] [MemberData(nameof(GetTypedObjectForIUnknown_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_ValidPointer_ReturnsExpected(object o, Type type) { IntPtr ptr = Marshal.GetIUnknownForObject(o); try { Assert.Equal(o, Marshal.GetTypedObjectForIUnknown(ptr, type)); } finally { Marshal.Release(ptr); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void GetTypedObjectForIUnknown_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetTypedObjectForIUnknown(IntPtr.Zero, typeof(int))); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_ZeroUnknown_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("pUnk", () => Marshal.GetTypedObjectForIUnknown(IntPtr.Zero, typeof(int))); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_NullType_ThrowsArgumentNullException() { IntPtr iUnknown = Marshal.GetIUnknownForObject(new object()); try { AssertExtensions.Throws<ArgumentNullException>("t", () => Marshal.GetTypedObjectForIUnknown(iUnknown, null)); } finally { Marshal.Release(iUnknown); } } public static IEnumerable<object[]> GetTypedObjectForIUnknown_Invalid_TestData() { yield return new object[] { typeof(GenericClass<string>) }; yield return new object[] { typeof(GenericStruct<string>) }; yield return new object[] { typeof(GenericInterface<string>) }; yield return new object[] { typeof(GenericClass<>) }; #if !netstandard // TODO: Enable for netstandard2.1 AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); yield return new object[] { typeBuilder }; #endif } [Theory] [MemberData(nameof(GetTypedObjectForIUnknown_Invalid_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_InvalidType_ThrowsArgumentException(Type type) { IntPtr ptr = Marshal.GetIUnknownForObject(new object()); try { AssertExtensions.Throws<ArgumentException>("t", () => Marshal.GetTypedObjectForIUnknown(ptr, type)); } finally { Marshal.Release(ptr); } } public static IEnumerable<object[]> GetTypedObjectForIUnknownType_UncastableObject_TestData() { yield return new object[] { new object(), typeof(AbstractClass) }; yield return new object[] { new object(), typeof(NonGenericClass) }; yield return new object[] { new object(), typeof(NonGenericStruct) }; yield return new object[] { new object(), typeof(NonGenericStruct) }; yield return new object[] { new object(), typeof(NonGenericInterface) }; yield return new object[] { new NonGenericClass(), typeof(IFormattable) }; yield return new object[] { new ClassWithInterface(), typeof(IFormattable) }; yield return new object[] { new object(), typeof(int).MakePointerType() }; AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); Type collectibleType = typeBuilder.CreateType(); yield return new object[] { new object(), collectibleType }; } [Theory] [MemberData(nameof(GetTypedObjectForIUnknownType_UncastableObject_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_UncastableObject_ThrowsInvalidCastException(object o, Type type) { IntPtr ptr = Marshal.GetIUnknownForObject(o); try { Assert.Throws<InvalidCastException>(() => Marshal.GetTypedObjectForIUnknown(ptr, type)); } finally { Marshal.Release(ptr); } } public static IEnumerable<object[]> GetTypedObjectForIUnknown_ArrayObjects_TestData() { yield return new object[] { new int[] { 10 } }; yield return new object[] { new int[][] { new int[] { 10 } } }; yield return new object[] { new int[,] { { 10 } } }; } [Theory] [MemberData(nameof(GetTypedObjectForIUnknown_ArrayObjects_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_ArrayType_ThrowsBadImageFormatException(object o) { IntPtr ptr = Marshal.GetIUnknownForObject(o); try { Assert.Throws<BadImageFormatException>(() => Marshal.GetTypedObjectForIUnknown(ptr, o.GetType())); } finally { Marshal.Release(ptr); } } public class ClassWithInterface : NonGenericInterface { } public struct StructWithInterface : NonGenericInterface { } public static void NonGenericMethod(int i) { } public delegate void NonGenericDelegate(int i); public enum Int32Enum : int { Value1, Value2 } } }
/* * Copyright (c) 2013 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * 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. * * This code is modified MiniJSON.cs * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace SimpleJSON { /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> internal static class Json { /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="obj">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append((bool)value ? "true" : "false"); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(new string((char)value, 1)); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: builder.Append(c); break; } } builder.Append('\"'); } void SerializeOther(object value) { // NOTE: decimals lose precision during serialization. // They always have, I'm just letting you know. // Previously floats and doubles lost precision too. if (value is float) { builder.Append(((float)value).ToString("R")); } else if (value is int || value is uint || value is long || value is sbyte || value is byte || value is short || value is ushort || value is ulong) { builder.Append(value); } else if (value is double || value is decimal) { builder.Append(Convert.ToDouble(value).ToString("R")); } else { SerializeString(value.ToString()); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Dummy implementations of non-portable interop methods that just throw PlatformNotSupportedException namespace System.Runtime.InteropServices { public static partial class Marshal { [System.Security.SecurityCriticalAttribute] public static int AddRef(System.IntPtr pUnk) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static bool AreComObjectsAvailableForCleanup() { return false; } [System.Security.SecurityCriticalAttribute] public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, object o) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static System.IntPtr CreateAggregatedObject<T>(System.IntPtr pOuter, T o) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static object CreateWrapperOfType(object o, System.Type t) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static int FinalReleaseComObject(object o) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static System.IntPtr GetComInterfaceForObject(object o, System.Type T) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static System.IntPtr GetComInterfaceForObject(object o, System.Type T, System.Runtime.InteropServices.CustomQueryInterfaceMode mode) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static System.IntPtr GetComInterfaceForObject<T, TInterface>(T o) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static System.IntPtr GetIUnknownForObject(object o) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static void GetNativeVariantForObject(object obj, System.IntPtr pDstNativeVariant) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static void GetNativeVariantForObject<T>(T obj, System.IntPtr pDstNativeVariant) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static object GetObjectForIUnknown(System.IntPtr pUnk) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static object GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static T GetObjectForNativeVariant<T>(System.IntPtr pSrcNativeVariant) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static object[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static T[] GetObjectsForNativeVariants<T>(System.IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static int GetStartComSlot(System.Type t) { throw new PlatformNotSupportedException(); } public static System.Type GetTypeFromCLSID(System.Guid clsid) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static object GetUniqueObjectForIUnknown(System.IntPtr unknown) { throw new PlatformNotSupportedException(); } public static bool IsComObject(object o) { return false; } [System.Security.SecurityCriticalAttribute] public static int QueryInterface(System.IntPtr pUnk, ref System.Guid iid, out System.IntPtr ppv) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static int Release(System.IntPtr pUnk) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static int ReleaseComObject(object o) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static void ZeroFreeBSTR(System.IntPtr s) { throw new PlatformNotSupportedException(); } } public class DispatchWrapper { public DispatchWrapper(object obj) { throw new PlatformNotSupportedException(); } public object WrappedObject { get { throw new PlatformNotSupportedException(); } } } public static class ComEventsHelper { [System.Security.SecurityCriticalAttribute] public static void Combine(object rcw, System.Guid iid, int dispid, System.Delegate d) { throw new PlatformNotSupportedException(); } [System.Security.SecurityCriticalAttribute] public static System.Delegate Remove(object rcw, System.Guid iid, int dispid, System.Delegate d) { throw new PlatformNotSupportedException(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Billing.V1.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedCloudCatalogClientSnippets { /// <summary>Snippet for ListServices</summary> public void ListServicesRequestObject() { // Snippet: ListServices(ListServicesRequest, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = CloudCatalogClient.Create(); // Initialize request argument(s) ListServicesRequest request = new ListServicesRequest { }; // Make the request PagedEnumerable<ListServicesResponse, Service> response = cloudCatalogClient.ListServices(request); // Iterate over all response items, lazily performing RPCs as required foreach (Service item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListServicesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Service item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Service> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Service item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListServicesAsync</summary> public async Task ListServicesRequestObjectAsync() { // Snippet: ListServicesAsync(ListServicesRequest, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = await CloudCatalogClient.CreateAsync(); // Initialize request argument(s) ListServicesRequest request = new ListServicesRequest { }; // Make the request PagedAsyncEnumerable<ListServicesResponse, Service> response = cloudCatalogClient.ListServicesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Service item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListServicesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Service item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Service> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Service item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListServices</summary> public void ListServices() { // Snippet: ListServices(string, int?, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = CloudCatalogClient.Create(); // Make the request PagedEnumerable<ListServicesResponse, Service> response = cloudCatalogClient.ListServices(); // Iterate over all response items, lazily performing RPCs as required foreach (Service item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListServicesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Service item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Service> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Service item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListServicesAsync</summary> public async Task ListServicesAsync() { // Snippet: ListServicesAsync(string, int?, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = await CloudCatalogClient.CreateAsync(); // Make the request PagedAsyncEnumerable<ListServicesResponse, Service> response = cloudCatalogClient.ListServicesAsync(); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Service item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListServicesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Service item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Service> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Service item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSkus</summary> public void ListSkusRequestObject() { // Snippet: ListSkus(ListSkusRequest, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = CloudCatalogClient.Create(); // Initialize request argument(s) ListSkusRequest request = new ListSkusRequest { ParentAsServiceName = ServiceName.FromService("[SERVICE]"), StartTime = new Timestamp(), EndTime = new Timestamp(), CurrencyCode = "", }; // Make the request PagedEnumerable<ListSkusResponse, Sku> response = cloudCatalogClient.ListSkus(request); // Iterate over all response items, lazily performing RPCs as required foreach (Sku item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSkusResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Sku item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Sku> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Sku item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSkusAsync</summary> public async Task ListSkusRequestObjectAsync() { // Snippet: ListSkusAsync(ListSkusRequest, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = await CloudCatalogClient.CreateAsync(); // Initialize request argument(s) ListSkusRequest request = new ListSkusRequest { ParentAsServiceName = ServiceName.FromService("[SERVICE]"), StartTime = new Timestamp(), EndTime = new Timestamp(), CurrencyCode = "", }; // Make the request PagedAsyncEnumerable<ListSkusResponse, Sku> response = cloudCatalogClient.ListSkusAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Sku item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSkusResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Sku item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Sku> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Sku item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSkus</summary> public void ListSkus() { // Snippet: ListSkus(string, string, int?, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = CloudCatalogClient.Create(); // Initialize request argument(s) string parent = "services/[SERVICE]"; // Make the request PagedEnumerable<ListSkusResponse, Sku> response = cloudCatalogClient.ListSkus(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Sku item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSkusResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Sku item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Sku> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Sku item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSkusAsync</summary> public async Task ListSkusAsync() { // Snippet: ListSkusAsync(string, string, int?, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = await CloudCatalogClient.CreateAsync(); // Initialize request argument(s) string parent = "services/[SERVICE]"; // Make the request PagedAsyncEnumerable<ListSkusResponse, Sku> response = cloudCatalogClient.ListSkusAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Sku item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSkusResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Sku item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Sku> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Sku item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSkus</summary> public void ListSkusResourceNames() { // Snippet: ListSkus(ServiceName, string, int?, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = CloudCatalogClient.Create(); // Initialize request argument(s) ServiceName parent = ServiceName.FromService("[SERVICE]"); // Make the request PagedEnumerable<ListSkusResponse, Sku> response = cloudCatalogClient.ListSkus(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Sku item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSkusResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Sku item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Sku> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Sku item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSkusAsync</summary> public async Task ListSkusResourceNamesAsync() { // Snippet: ListSkusAsync(ServiceName, string, int?, CallSettings) // Create client CloudCatalogClient cloudCatalogClient = await CloudCatalogClient.CreateAsync(); // Initialize request argument(s) ServiceName parent = ServiceName.FromService("[SERVICE]"); // Make the request PagedAsyncEnumerable<ListSkusResponse, Sku> response = cloudCatalogClient.ListSkusAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Sku item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSkusResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Sku item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Sku> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Sku item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }